Commit graph

48 commits

Author SHA1 Message Date
Huang Xin
119bf28011
feat(sync): sync reading speed across devices (#8023)
Reading speed stayed on the device that measured it, so each device
showed only its own languages and history. It now syncs through
Readest Cloud like the page events, behind the same stats sync switch.

A device pushes one row per book, language and unit for each quarter
hour it read in, keyed by its first sample there: about four rows per
hour of reading instead of one per page, so the server table needs no
archive. Two devices never share a key, and a row only grows while its
quarter hour lasts, so the server keeps the longer copy. Pulled rows
are kept apart from this device's own samples (a `remote` flag), so a
device's own row coming back meets its first sample's key and is
ignored. Deleting a book's statistics deletes its speed on every
device: the pull flags rows that started before the book's deleted_at.
Merging moves the source's speed, its own and pulled, to the target.
A server without speed sync still syncs and merges the pages.

Server: migration 036 adds stat_speeds with RLS and the
upsert_stat_speeds merge RPC; /api/sync/speeds pages its pull on the
(updated_at, book_hash, start_time_ms) keyset. Deploy both before
releasing clients that push speed.

Tests: speedSync covers the push (one row per quarter hour, sent again
only when it grows, pulled rows never sent back), the pull (counted
once, own rows and deleted books skipped, keyset paging, a minute of
overlap) and the merge; sync-speeds covers the route; ReadingStats
covers the dialog's pull. Removing each behavior fails its test on an
assertion: without the echo guard the totals read count 340 for 270,
without skipping deleted rows 370 for 270; pushing pulled rows changes
the pushed rows; without the changed-quarter check the push runs twice
for once; without the merge push "expected to be called with
arguments"; without the route's flag ['x', 1000, false] for true;
without the dialog's pull "expected to be called at least once". The
related suites (53 files, 641 tests), lint and format pass. The new
local SQL gives the same results on Turso 0.6.0-pre.9 (native app) and
0.6.0-pre.28.

Verified end to end on a self-hosted Supabase (repo migrations, 036
applied) with dev-web and three browser profiles on one account. Device
A, holding Sep-Nov history, pushed 10 rows; a fresh device B then showed
the same English 180 words/min and Chinese 249 characters/min as A.
After B read three pages of Alice, both showed English 203 words/min
(+25.5% this month), matching the server's sum. After Alice's
statistics were deleted, A and a newly signed-in device C showed only
Chinese.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:49:36 +08:00
Huang Xin
94653dc741
feat(sync): limit the Free plan to 3 devices, with a list to sign them out (#7945)
* feat(sync): limit the Free plan to 3 devices, with a list to sign them out

A Free account (no subscription or purchase, and not self-hosted) that is
already signed in on three other devices can't finish signing in on a
fourth. The login page lists those devices instead, each with Sign Out.
Signing one out finishes the sign-in; Cancel or Go Back ends the new
session. Every plan can see its devices and sign them out under Devices in
the profile's Manage Sync view.

Devices come from the account's Supabase sessions, grouped by the kind of
device their user agent names (Chrome on macOS, Readest on Pixel 7,
KOReader on Kindle Paperwhite 5), so a device holding several sessions
counts once. Only devices signed in before this session count, so the
first three are never sent away by later ones. An error skips the check
rather than block a sign-in.

- Migration 035 adds list_user_sessions and delete_user_sessions, callable
  by the service role only. Apply it to production before this merges;
  until then the check is skipped and the list stays hidden.
- GET /api/auth/sessions lists the devices with the plan's limit and
  whether this one is over it; DELETE signs another device out.
- The auth-proxy Worker forwards User-Agent, so password sign-ins and
  refreshes record the device instead of the Worker. It needs a redeploy.
- handleAuthCallback also checks the session supabase-js took from the
  URL. On web it clears the hash before the callback page runs, so web
  OAuth and magic links went straight to the library.

Verified:
- Each new test failed before the change and passes with it:
  auth-page-device-limit.test.tsx ("Unable to find an element with the
  text: Chrome on macOS"), helpers/auth.test.ts URL-session case (expected
  navigate to be called with '/auth'), auth-proxy.test.ts (expected null
  to be 'KOReader/v2025.08'), device-limit-access.test.ts (getDeviceLimit
  is not a function), syncDevices.test.ts and auth-sessions-route.test.ts
  (modules missing).
- Related suites: 115 files, 1513 tests passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase (GoTrue v2.185) with
  migration 035, 13/13 end-to-end checks: a fourth device is held;
  signing out KOReader finishes the sign-in and deletes its session;
  Manage Sync names this device and signs another out; Cancel ends the
  new session; a magic link is held on /auth. Screens checked in light,
  dark, e-ink and at 360px wide.
- anon and authenticated get "permission denied" on both functions;
  GoTrue rewrites a session's user_agent on every refresh.

Not run: the Tauri desktop and mobile apps, RTL, the full pnpm test.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(sync): keep a held sign-in out of the app until a device signs out

Answers the CodeRabbit review of #7945.

- AuthProvider published every session the SDK reported, so a sign-in held
  at the device limit was signed in for the rest of the app, and again
  after a restart. A new Free plan sign-in (no stored user, or another
  account) now waits for the device check and is published only when let
  in; a device already signed in is published as before, unchecked.
- A device sign-out that answers after Cancel or Go Back no longer signs in
  the session they ended.
- DELETE /api/auth/sessions answers from the one read it makes, so a
  second read that fails after the sign-out can't report it as failed.
- A held callback goes to /auth?redirect=<destination>, so a held password
  recovery still reaches /auth/recovery.
- A device that signs in again keeps its place from its first sign-in, so
  the held fourth device can't push one of the first three out.
- Tibetan: "{{limit}} and above" is now "at most {{limit}}".
- Migration 035 turns off check_function_bodies: on a fresh self-hosted
  database it runs before GoTrue has created auth.sessions, and failed.

Verified:
- New tests failed before the fix and pass with it:
  auth-context-device-limit.test.tsx (expected the check to be called with
  'held-token'), auth-page-device-limit.test.tsx after-Cancel case
  (expected login not to be called, called once), auth-sessions-route
  (expected 500 to be 200), helpers/auth.test.ts recovery case (expected
  navigate with '/auth?redirect=%2Fauth%2Frecovery'), syncDevices.test.ts
  sign-in-again case on the old cutoff (expected true to be false).
- auth-context-logout.test.tsx mocks the device check: its token has no
  plan claim, so it read as a Free sign-in and fetched the live API.
- Related suites: 187 files, 2278 tests passed. pnpm lint clean.
- 035 applied on a database before GoTrue started (it failed there before),
  then list_user_sessions answered once GoTrue had migrated; anon is still
  refused.
- dev-web against a local self-hosted Supabase, 15/15 end-to-end checks,
  now including that no token or user is stored while held. Reloading the
  app during a hold leaves it signed out, and opening sign-in again shows
  the device list.

Not run: the Tauri desktop and mobile apps.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(sync): drop a device check that answers after Go Back or Sign Out

Answers CodeRabbit's second review of #7945.

- Go Back now abandons a Free plan sign-in whose device check is still
  running, as it already did for one that is held: it signs the session
  out, and the check's answer neither signs in nor shows the device list.
  A check answering after the page unmounts is dropped too.
- AuthProvider doesn't publish a session whose device check answers while
  Sign Out is running.

Verified:
- New tests failed before the fix and pass with it:
  auth-page-device-limit.test.tsx ("abandons a sign-in whose device check
  is still running on Go Back": expected signOut with { scope: 'local' },
  not called) and auth-context-device-limit.test.tsx ("does not sign in
  when the device check answers during Sign Out": expected 'new-token' to
  be null).
- Related suites: 187 files, 2280 tests passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase: 15/15 end-to-end checks
  and both reload-during-hold checks pass again.

Not run: the Tauri desktop and mobile apps.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(sync): keep the refresh token of a sign-in let in after a hold

Answers CodeRabbit's third review of #7945.

AuthProvider never publishes a sign-in held at the device limit, and
login() stores only the token and user. Once a device was signed out and
the held sign-in finished, nothing stored refresh_token until the next
token refresh, so an offline launch before then found none and signed
the user out. The login page now stores it when it finishes a sign-in.

Verified:
- auth-page-device-limit.test.tsx ("finishes signing in once a device is
  signed out") now checks refresh_token: it failed before with "expected
  null to be 'free-refresh'" and passes with the fix.
- Auth page, AuthContext and auth helper suites: 14 files, 81 tests
  passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase, 16/16 end-to-end checks,
  now including that token and refresh_token are stored once the held
  sign-in is let in.

Not run: the Tauri desktop and mobile apps.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(sync): open the recovery form after a held reset link in the app

Answers CodeRabbit's follow-ups on #7945.

In the desktop and mobile apps a sign-in link arrives as a deep link,
handled on the login page, whose onDeviceLimit did nothing. Once a device
was signed out, the held sign-in went to the page's redirect or /library,
so a password reset link never reached /auth/recovery. The page now keeps
the destination the callback would have opened under the limit, goes
there when the sign-in is let in, and forgets it on Cancel or Go Back.

Adds a test for the other follow-up, a device check started by a token
refresh while the list is open that answers after Cancel. The guard from
2f02f8275 already drops it.

Verified:
- auth-page-device-limit.test.tsx:
  - "opens the recovery form once a held password reset link is let in"
    delivers the link through onOpenUrl. Before the fix it failed with
    replace called with '/library', not '/auth/recovery'.
  - "forgets a cancelled reset link when signing in again" fails with
    "expected ... '/library'" when Cancel doesn't clear the destination.
  - "drops a device check that answers after Cancel" fails with login
    called once when the 2f02f8275 guard is taken out.
- Related suites: 187 files, 2283 tests passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase: 16/16 end-to-end checks
  and both reload-during-hold checks pass, so the web path is unchanged.

Not run: the deep link itself in the Tauri desktop and mobile apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): ignore a reset link's device check that answers after Cancel

Answers CodeRabbit's fourth review of #7945.

A deep link's own device check runs after the page's, so it can answer
after Cancel or Go Back. It then still stored the link's destination, and
the next sign-in on the same page followed it, to the recovery form for a
password reset link. The callback now drops the destination when the
sign-in was abandoned since the link arrived.

Verified:
- auth-page-device-limit.test.tsx ("forgets a reset link whose device
  check answers after Cancel") holds the link's check until after Cancel.
  Before the fix it failed with replace not called with '/library'.
- Auth page, AuthContext and auth helper suites: 14 files, 85 tests
  passed. pnpm lint clean.

Not run: the deep link in the Tauri desktop and mobile apps, and dev-web,
which never runs this callback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): tie a held sign-in's checks and destination to its session

Answers CodeRabbit's follow-ups on #7945.

- A deep link's destination is kept when the link arrives, not when its
  own device check answers. The device list can show first, and a device
  signed out before that check answered sent a reset link to /library.
  The callback no longer writes it, so a late answer after Cancel can't
  either. The destination is used only when a held sign-in is let in, so
  a sign-in under the limit goes where it did before.
- Every auth event on the login page moves the sign-in on. A device check
  or sign-out started for an older session is dropped when it answers.
  When the session ends, the page goes back to the sign-in form.

Verified:
- New tests in auth-page-device-limit.test.tsx failed before the fix:
  - "opens the recovery form when a device is signed out before the link
    check answers": replace not called with '/auth/recovery'.
  - "drops a device check when the session ends while it runs": login
    called once.
  - "signs in only the newer session when one replaces it during the
    check": login called for the replaced session.
- Auth page, AuthContext and auth helper suites pass. pnpm lint clean.
- dev-web against a local self-hosted Supabase: 16/16 end-to-end checks.

Not run: the deep link in the Tauri desktop and mobile apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): let a new sign-in into the app only on the server's answer

Found re-running the end-to-end checks for #7945. Reloading the app while
a sign-in was held let it in. The reload aborted AuthProvider's device
check, which was still running. The check fails open, so AuthProvider
published the session just before the page unloaded. After the reload
the stored user matched, so the device was never checked again. It
reproduced 3 of 3 runs, and 1 of 3 on the previous head.

AuthProvider now publishes a new Free plan sign-in only when the server
answers that it is let in. The sign-in screens still sign in on their own
answer, which fails open. The web callback's branch for tokens that
supabase-js took from the URL relied on AuthProvider to publish, so it
now signs in itself.

Verified:
- auth-context-device-limit.test.tsx ("does not sign in when the device
  check fails") failed before with "expected 'new-token' to be null".
  helpers/auth.test.ts ("signs in a session supabase-js already took
  from the URL") failed with login not called.
- Related suites: 187 files, 2289 tests passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase:
  - 16/16 end-to-end checks.
  - The reload-during-hold check passes 3 of 3, including a run where the
    browser aborted the check.
  - A magic link under the limit lands signed in on /library, also with
    /api/auth/sessions answering 500. Without the callback's login() the
    500 case landed signed out.

Not run: the Tauri desktop and mobile apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): finish a held sign-in with its newest session, drop links after Cancel

Answers CodeRabbit's follow-ups on #7945.

- A token refresh while the device list shows left the old session on
  screen, and a device sign-out then signed in that session and its spent
  refresh token. The page now keeps the newest session it heard of. A
  device check answers only for that session, and a held sign-in finishes
  with it.
- In the desktop and mobile apps, a link's own device check fails open.
  When it failed after Cancel, the callback still signed in and navigated.
  Its login and navigate now do nothing once the sign-in was abandoned.
  This needs a counter that only abandoning moves, since the callback's
  own setSession fires an auth event. The newest session handles
  replacement.

Verified:
- New tests in auth-page-device-limit.test.tsx failed before the fix:
  - "finishes with the refreshed session when a device is signed out
    meanwhile": login called with 'free-token', not 'refreshed-token'.
  - "does not sign in a link whose own check lets it in after Cancel":
    login called once. It fails again with the callback guard taken out.
  - "opens the recovery form for a reset link under the limit, as
    before" passes with and without the guard.
- Related suites: 187 files, 2292 tests passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase:
  - 16/16 end-to-end checks.
  - Reload during a hold: 3 of 3 stay signed out, two with the check
    aborted.
  - Magic link under the limit signs in, also with /api/auth/sessions
    answering 500.

Not run: the deep link in the Tauri desktop and mobile apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): apply a device sign-out's answer only to the account that asked

Answers CodeRabbit's follow-up on #7945.

A held sign-in finishes with the newest session the page heard of, so a
token refresh carries over. If another account signed in while a device
sign-out was pending (from another tab, say), the answer for the first
account signed in the second before its own device check had answered.
The answer now applies only when the newest session is the same user.

Verified:
- auth-page-device-limit.test.tsx ("does not sign in another account on
  a sign-out answered for the first") failed before with login called
  once. The refresh case ("finishes with the refreshed session...") still
  passes.
- Auth page, AuthContext and auth helper suites: 14 files, 94 tests
  passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase: 16/16 end-to-end checks,
  including a held sign-in finishing through a device sign-out. The
  reload-during-hold check passes too.

Not run: the Tauri desktop and mobile apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): keep the refresh token when the auth callback signs in itself

Answers CodeRabbit's review of a6a5d6cfa on #7945.

AuthProvider stores nothing for a new sign-in whose device check failed
(a6a5d6cfa), and login() stores only the token and user. When both device
checks failed and the callback signed in itself, refresh_token was never
stored. An offline launch whose INITIAL_SESSION is null then found no
refresh token and signed the user out. Both of the callback's sign-in
branches (tokens in the link, or taken from the URL by supabase-js) now
store it, as the login page does.

Verified:
- helpers/auth.test.ts: "should login and navigate to next URL on
  successful auth" and "signs in a session supabase-js already took from
  the URL" now check refresh_token. Before the fix they failed with
  "expected null to be 'good-refresh'" and "... 'url-refresh'".
- Related suites: 187 files, 2293 tests passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase:
  - A magic link under the limit stores token, user and refresh_token,
    also with /api/auth/sessions answering 500.
  - 16/16 end-to-end checks.
  - The reload-during-hold check passes, with the check aborted.

Not run: the Tauri desktop and mobile apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): keep the SDK's refresh token, not the link's, after a callback

ba3a6cf8e stored the refresh token from the sign-in link when the auth
callback signed in itself. If the link's access token had expired,
setSession refreshed it, and that spent the link's refresh token. The
stored one could then never restore the sign-in. The callback now stores
the refresh token of the SDK's session, which still works.

CodeQL flagged ba3a6cf8e (js/clear-text-storage-of-sensitive-data,
alert 161) for storing a value parsed from the callback URL. The app
already keeps its refresh token in localStorage, as AuthProvider does on
main, and that key now comes from the SDK's session as everywhere else.

Verified:
- helpers/auth.test.ts ("should login and navigate to next URL on
  successful auth") now has getSession return a rotated refresh token.
  Before the fix it failed with "expected 'good-refresh' to be
  'rotated-refresh'".
- Related suites: 187 files, 2293 tests passed. pnpm lint clean.
- dev-web against a local self-hosted Supabase: a magic link under the
  limit stores token, user and refresh_token, also with
  /api/auth/sessions answering 500. 16/16 end-to-end checks.

Not run: the Tauri desktop and mobile apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): keep a callback's refresh token only for the account it signed in

Answers CodeRabbit's review of 499b39262 on #7945.

The auth callback reads the SDK's session after its device check, to keep
a refresh token that setSession may have rotated. A second deep link can
replace that session during the check. The first callback then stored
the other account's refresh token next to its own token and user. It now
keeps the token only when the SDK's session is the same user. It compares
user ids, since a rotated session has a new access token.

Verified:
- helpers/auth.test.ts ("doesn't keep the refresh token of another
  account's session") failed before with "expected 'other-refresh' to be
  null". The rotated-token case still passes.
- Related suites: 187 files, 2294 tests passed. pnpm lint clean.

Not run: this branch in a browser. dev-web never takes it, since
supabase-js takes the tokens from the URL first. Not run in the Tauri
apps either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(plans): list the number of devices on each plan (owner: Free plan Number of devices: 3; other plan limitations Number of devices: Unlimited)

The plan cards' What's Included box gets a Number of Devices row: 3 on
Free, Unlimited on Plus and Pro. Lifetime has no limits box, so no row.
The Free value comes from FREE_PLAN_DEVICE_LIMIT, which moves to
services/constants so the card and the server check read one number.

PlanCard now passes string values through _(): plan.ts builds its
limits with stubTranslation, so "Unlimited" stayed English. The
existing values ('500 MB', '10K') have no translation and pass through
unchanged.

Verified:
- plan.test.ts "lists the number of devices for the <plan> plan"
  fails without plan.ts (expected undefined to be 3 / 'Unlimited').
- PlanCardLimits.test.tsx fails without the PlanCard change: expected
  'Anzahl der GeräteUnlimited' to be 'Anzahl der GeräteUnbegrenzt'.
- dev-web: the row on each card in light, dark, e-ink, German and at
  390px; German reads "Anzahl der Geräte 3 / Unbegrenzt".
- Translations for both keys in all 34 locales.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): line the Devices list up with Manage Sync's categories (owner: Manage sync page the indent is wrong)

The Devices list used the settings BoxedList: a white card with an
invisible border and dividers inset by the row padding, under a
bordered list whose dividers run edge to edge. It now uses the same
list as the categories above it (border-base-300, rounded-lg, px-4
py-3 rows, text-sm title, text-xs line). The auth page's Device limit
reached panel shares the component and looks the same.

Both lists get eink-bordered, so e-ink shows the same border on each;
the categories list had none before.

Verified on dev-web: both lists span the same edges with 16px row
padding at 1024px (112-912) and 390px (24-366), in light, dark and
e-ink; the 16 device-limit end-to-end checks pass. No unit test: the
change is styling only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-26 05:26:52 +01:00
Huang Xin
f4929c7c1e
feat(gift): gift cards for a year of Readest Plus or Pro (#7930)
* feat(gift): add gift_cards migration and types

SQL checked on a throwaway Postgres 15: migration re-runs cleanly; claim sweep,
unconfirmed-email skip, email immutability trigger, reassign (true unclaimed,
false claimed) and email lookup all pass. db-bootstrap-migrations test passes.

Co-Authored-By: Claude Code (Claude Sonnet 5.5) <noreply@anthropic.com>

* feat(gift): codes, validation, product ids and gift timeline

Co-Authored-By: Claude Code (Claude Sonnet 5.5) <noreply@anthropic.com>

* fix(gift): skip queued Pro cards when placing Plus cards

Co-Authored-By: Claude Code (Claude Sonnet 5.5) <noreply@anthropic.com>

* feat(gift): count redeemed gifts in resolveUserPlan

Co-Authored-By: Claude Code (Claude Sonnet 5.5) <noreply@anthropic.com>

* feat(gift): create, activate, claim, edit and refund gift cards

Server operations for gift cards. Activation is idempotent on the payment
reference and survives races between the webhook, the client's verify, store
notifications and restores: a lost race (a unique violation on the reference,
or a draft no longer pending) runs the lookups once more, so the draft is
merged into the card the winner made. A draft is only merged into the same
buyer's card. Claims by email and by code are one conditional update on an
active, unclaimed card, so the first wins; each claim re-syncs the
recipient's plan through resolveUserPlan. markPaymentRefunded now marks the
gift card refunded and re-syncs the recipient. Sent cards never carry the
redeemer's identity.

Verified: the three new test files (35 tests) failed before the code existed
(module not found; refund tests failed on "expected 'active' to be
'refunded'"). Seventeen mutations of the new code (drop the buyer filter,
the redeemed_by/status/pending conditions, the retry, the claim at
activation, the email guard, the draft delete, the merge buyer check, ...)
each fail a named test. stripe-webhook-refund and
stripe-payment-refund-state pass; apple/google notification mocks gained a
gift_cards update branch. Full suite: 1388 files passed, 4 skipped.
pnpm lint: clean (one pre-existing info).

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): a card stays claimed after its recipient's account is deleted

redeemed_by is ON DELETE SET NULL, so a recipient deleting their account
re-opened the card: claimable again by code or by the cron sweep (a new
year each time), its code shown to the buyer again, and its email settable.
"Claimed" now means redeemed_at IS NOT NULL everywhere: the claim update,
the draft merge, buyer edits, the Sent status and code visibility, and in
034 the claim sweep, reassign_gift_email and the guard trigger.

Also, per review:
- activateGiftCard throws 'gift card belongs to another buyer' rather than
  returning a card with the same payment reference that another buyer owns.
- toSentGiftCard is exported so routes never return raw rows.
- updateSentGiftCard treats the card's own email as not touching the email;
  a different email is still 'email_locked'.
- 034: recipient_email must be stored lower(btrim()); gift_cards_guard sets
  search_path = ''; reassign_gift_email returns false for a NULL or blank
  email and turns its flag off after the update.

Verified: the 4 new or changed tests failed before the change (expected a
claimed card back to be null; promise resolved instead of rejecting;
'email_locked' instead of the edited card; toSentGiftCard not a function)
and pass after. Mutations putting redeemed_by back in the claim, merge,
edit, status and code checks, dropping the buyer throw and dropping the
same-email fallback each fail a named test. Throwaway Postgres 15: the
migration runs twice cleanly; Task 1's checks plus the normalized-email
CHECK, guard search_path, blank/NULL reassign, flag reset, deleted
recipient left unclaimable by the sweep (even when the address signs up
again), reassign false and email unsettable on that card all pass. The
pre-fix 034 fails the email CHECK and the sweep checks. gift-server,
gift-claim, gift-refund and db-bootstrap-migrations: 46 passed. Full
suite: 1388 files passed. pnpm lint clean (one pre-existing info).

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): Stripe, App Store and Play purchases create gift cards

Each payment path records its `payments` row exactly as before, then turns a
gift payment into an active card through `activateGiftCard`:

- Stripe `createOrUpdatePayment`: a product with `metadata.gift` activates
  the draft named by `session.metadata.giftCardId` when the intent is paid,
  and revokes the card when the charge is refunded. An unpaid intent does
  nothing. Plan and storage purchases are untouched.
- App Store / Play `createOrUpdatePayment` take an optional `giftCardId`; a
  gift product with status `active` activates on its original transaction id
  or purchase token. ONE_TIME_CHARGE and restore re-verifies send no draft
  and make a card with an empty message.
- Both verify routes accept `giftCardId: z.string().uuid().optional()`; a
  malformed id is a 400.
- Checkout: a gift session returns to `/user?section=gifts`.
- `/api/stripe/plans` leaves gift products out; the new public
  `/api/gift/prices` lists their one-time prices as `GiftPrice[]`.

Verified:
- New tests in gift-payment-paths.test.ts and stripe-plans-route.test.ts
  failed before the change (11 assertion failures; the plans file failed on
  the missing prices route). Hand-reverting the plans gift filter, the gift
  price tier check and the Stripe paid-status gate fails "leaves gift
  products out of the plan list", "returns { tier, productId, price,
  currency } only for gift products" and "an unpaid Stripe gift session does
  not activate" on assertions; restored, all 23 pass.
- pnpm test: 1389 files passed, 4 skipped (17071 tests passed).
- pnpm lint (tsc + Biome): clean.
- Not run: iap-verify.test.ts needs ENABLE_IAP_API_TESTS and live store
  credentials, so it is skipped. No real Stripe/App Store/Play purchase was
  made; that is Task 9.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): refuse a malformed checkout giftCardId; pin Play consume order

The checkout route copied the client's `metadata.giftCardId` into the Stripe
session unchecked. `gift_cards.id` is a uuid, so a non-UUID id (or a number,
which Stripe stringifies) was paid for, then failed the draft lookup on every
webhook retry and every `/api/stripe/check`, and no card was ever made. The
route now answers 400 unless the id is absent or a UUID string (the verify
routes' rule), and the gift return URLs follow that validated id.

New tests also pin the order on Play: the card is recorded before the
purchase is consumed. A failed activation answers 500 on both store verify
routes and leaves the Play purchase unconsumed. A Play restore re-verify with
no draft still makes a card.

Verified:
- "checkout answers a non-UUID string giftCardId with 400" and "checkout
  answers a number giftCardId with 400" failed before the fix (expected 200
  to be 400) and pass after it.
- The store tests guard behavior that already held, so I mutated the code
  instead of reverting it. Swallowing activation errors in both IAP servers
  fails "a failed App Store activation answers 500" and "a failed Play
  activation answers 500 and leaves the purchase unconsumed" (expected 200 to
  be 500). Consuming before recording fails "Google verify activates and
  consumes a gift product" (expected 2 to be less than 0). Restored, all pass.
- pnpm test --run gift-payment-paths, stripe-checkout-error-detail,
  google-iap-verify-consume: 3 files, 34 tests passed. All of
  src/__tests__/app/api and src/__tests__/libs/payment: 40 files passed,
  1 skipped.
- pnpm lint (tsc + Biome): clean.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): gift card API routes and reconcile cron

Tested: gift-routes and gift-reconcile tests (16) fail on missing modules before, pass after; full suite 17092 passed; pnpm lint clean.
Not run: the cron on a deployed Worker.

Co-Authored-By: Claude Code (Claude Sonnet 5.5) <noreply@anthropic.com>

* feat(gift): client library; gift holders buy through checkout, not the portal

Tests: gift-client, plan, plans-comparison, account-actions fail before the change and pass after; full suite and lint pass.

Co-Authored-By: Claude Code (Claude Sonnet 5.5) <noreply@anthropic.com>

* feat(gift): gift card design and the Gift Cards view

The card is an ID-1 shaped object: a soft sky (Plus) or violet (Pro)
two-stop gradient with a faint ruled-page texture, a bookmark ribbon
hanging from the top edge, the tier large, the message in an italic
serif (dir=auto) and To/From along the bottom. It keeps its palette in
dark themes with a hairline rim; under e-ink it is paper, ink, a 1px
border and an outlined ribbon. Ink is tier-950 and tier-900, both AA on
the darker gradient stop.

The Gift Cards view, opened from a new Gift Cards button or by
section=gifts / gift=<code>, has the composer with a live preview, the
received cards with their dates, the redeem form and the sent cards
with copy, add-email (confirmed, set once) and edit actions. Buying
creates a draft, then pays through Stripe (embedded on Tauri, redirect
on web) or the store, verifying with the draft id. A returning Stripe
session is checked before the list loads. The account page and login
claim email gifts and refresh the session when one was claimed; a gift
link opened signed out comes back to the view after sign-in.

Verified: the 11 brief tests plus auth-context-gift-claim (3) and the
signed-out gift redirect pass. Each was checked failing on its behavior
assertion with the behavior removed by hand (no slice -> length 301;
code shown for refunded; save without confirmation; unawaited session
check; draft id dropped from checkout and verify; generic redeem error;
missing dir/data-tier/To-From guard; redirect without the gift).
pnpm test: 1395 files, 17117 tests pass. pnpm lint: clean (1
pre-existing info). Not run: visual checks in a browser (Task 9).

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): IAP builds sell gifts through the store only; a charged buyer is never told it failed

- The Gift Cards view gets useIAP = appService.hasIAP. iapAvailable starts
  false while the store is checked, so Stripe prices showed (and a Buy tap
  opened Stripe checkout) inside App Store and Play builds; a store that
  reports unavailable now leaves no prices and Buy disabled. Prices are
  cleared whenever useIAP changes.
- Once the store has charged, a failed verify says the payment was
  received and to use Restore Purchase, and reloads the list, instead of
  "Failed to buy the gift card".
- A returning Stripe session is checked once: session_id leaves the URL
  after the check, so reopening the view doesn't check and announce it again.
- Buy stays busy after a web redirect to Stripe, so a second tap can't make
  a second draft and session.
- "Plus" / "Pro" go through _().

Verified: new tests "an IAP build with no store products shows no price
and never uses Stripe", "a failed verify after the store charged says the
payment was received", the gift-cards-view page test (useIAP true while
iapAvailable is false), plus assertions for the session_id replace and
busy-after-redirect. With each fix removed by hand, each failed on its
behavior assertion (e.g. `expected "vi.fn()" to not be called with
arguments: [ false ]`, `expected false to be true`); restored, all pass.
src/__tests__/app/user and src/__tests__/context: 16 files, 111 tests
pass. pnpm lint: clean (1 pre-existing info).

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* test(gift): redeem the deleted-subscription gift relative to the real clock

The test resolves the plan at the real now, but redeemed its gift on a fixed
2026-10-01, so it would start failing on 2027-10-01 when that gift ends.

Verified with a setup file that shifts Date to 2027-12-01 and 2031-01-01:
before, 'keeps Plus from an active gift when the Stripe subscription is
deleted' failed (expected 'free' to be 'plus'); after, all 16 pass at both
dates and on the real clock. The other 25 gift test files pass at both dates.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(stripe): grant a delayed bank payment when its money arrives

An ACH or SEPA checkout is still processing at checkout.session.completed, so
neither a gift card nor a storage add-on was granted then, and nothing ran
createOrUpdatePayment again once the payment cleared. The webhook now handles
checkout.session.async_payment_succeeded for a payment-mode session the way
the completed event does: it records the payment again, which re-reads the
intent, recomputes storage and activates the gift card.

The Stripe webhook endpoint must be subscribed to this event type.

Tests (gift-payment-paths.test.ts, 'Stripe delayed payments'): without the
case, 'async_payment_succeeded for a gift session activates the card' failed
(expected sessions.retrieve to be called with 'cs_1') and the storage test
failed (expected undefined to match the payment row). Both pass with it, as do
the existing webhook cancel and refund tests.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): never fail a paid or committed gift over the recipient's side

activateGiftCard handed the card to its recipient inside the buyer's call, so
a failed email lookup, claim or recipient plan sync threw after the card was
already live. On Google Play the verify route then answered 500 before
consuming, and Play refunds an unconsumed purchase after three days while the
card stays live. A redeem by code had the same shape: the claim committed,
the sync threw, the route answered 500 and a retry said the code was used.

The claim for the recipient after activation, and the plan sync after a
claim (by code or email) and after a refund revocation, are now best-effort:
they log and carry on. The activation itself and the claim's own conditional
update still throw. The cron's email sweep and its redeemed_at / refunded
updated_at windows repair the plan.

Tests, each failing before the change:
- gift-server.test.ts 'activateGiftCard once the card is live': returns the
  card when the recipient lookup, the claim or the plan sync fails, and a
  refund still revokes when the sync fails (all: promise rejected instead of
  resolving).
- gift-claim.test.ts 'redeem by code returns the card when the plan sync
  fails' (promise rejected "stripe unavailable").
- gift-payment-paths.test.ts 'a live Play gift is consumed even when handing
  it to its recipient fails', through the real activation (expected 500 to
  be 200).

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): page the cron's read of claimed cards

reconcileGiftCards loaded every active, claimed card in one select with no
order or range. PostgREST caps a response at max-rows (1000 on Supabase), so
once there are more claimed cards than that, recipients past the slice never
get their end-of-gift sync. The read is now ordered by id and fetched in
pages of RECONCILE_PAGE_SIZE (1000) until a short page.

The refunded-card read is left as one select: it is bounded by the cron's
2-hour updated_at window.

The in-memory Supabase fake now supports range() and caps a select at
max-rows (1000) the way PostgREST does.

Test: gift-reconcile.test.ts 'syncs recipients beyond the first page of
claimed cards' (RECONCILE_PAGE_SIZE + 1 recipients whose gift just ended)
failed with 'expected 1000 to be 1001' on the single select and passes with
paging.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): a gift-only holder can buy any tier; the chip is theirs alone

Owner rule: a gift holder can buy any plan at any time. A Pro gift set the
plan to Pro, so the Plus card counted as below it and showed no button. For a
gift-only holder every paid subscription tier (Plus, Pro) is now upgradable;
their own tier keeps the gift chip and its Subscribe button. Users without a
gift, and gift holders who also pay, are unchanged.

The 'Gift, until {{date}}' chip showed to someone who also pays for that
tier, where it reads as their paid plan ending. It now shows only to a
gift-only holder; anyone else sees Current Plan.

Tests (plans-comparison.test.tsx), each failing before the change:
- 'a gift-only holder can subscribe to a tier below their gift' (unable to
  find 'Upgrade to Plus Plan').
- 'a gift holder who also pays for the tier sees Current Plan, not the gift
  chip' (unable to find 'Current Plan').
'a lower tier stays without a button for a paying subscriber' guards the
unchanged case and passes before and after.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): don't point iOS gift buyers at Restore Purchase

When the verify call fails after the store has charged, the toast told the
buyer to use Restore Purchase, but StoreKit never restores a consumable, so
on iOS that does nothing. It now says only: 'Payment received. Your gift
card will appear here shortly.' The store notification still makes the card.

Test: gift-cards-section.test.tsx 'a failed verify after the store charged
says the payment was received' failed on the old message (toast called with
'..., or use Restore Purchase.') and passes with the new one.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): take a gift link's code out of the URL once it is read

A /user?gift=CODE link kept the code in the URL, browser history and
analytics after it was redeemed, and filled the form again on every reload.
The account page now reads the code once into state and replaces the URL
with the app router, keeping section=gifts so a reload still opens the Gift
Cards view. The redeem form keeps the code it was given, and the signed-out
handoff to the login page carries the saved code rather than re-reading the
now stripped URL.

Tests:
- gift-cards-view.test.tsx 'takes a gift link code out of the URL and keeps
  it in the redeem form' failed before the change (replace never called with
  '/user?section=gifts'). With the strip but a code re-read from the URL it
  fails on 'initialCode: undefined'.
- signed-out-login-handoff.test.tsx 'keeps a gift link as the redirect' now
  lets the mocked replace change the params; with a re-read code it fails
  (the redirect loses the code). Both pass with the change.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): a null checkout metadata is no gift; fix the plan button comment

The Stripe checkout route read metadata.giftCardId, so a body with
metadata: null threw a TypeError instead of going through validation. It
reads metadata?.giftCardId now: null metadata is no gift card, and the
checkout proceeds as a plan purchase.

The PlanActionButton comment still said its secondary button routes to the
Stripe portal; for a gift-only holder it goes to checkout.

Test: gift-payment-paths.test.ts 'checkout treats a null metadata as no
giftCardId' failed with 'TypeError: Cannot read properties of null (reading
"giftCardId")' and passes with the change.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): residual review fixes for redeem, Android recovery and lower-tier label

Co-Authored-By: Claude Code (Claude Sonnet 5.5) <noreply@anthropic.com>

* chore(i18n): gift card strings

44 new strings for the gift card view, the card itself and the
gift-aware plan cards, translated into all 34 shipped locales. Each
locale keeps its file's existing form of address (formal Sie / uw /
您 where the file uses it) and its existing terms for Plan, Restore
Purchase and Upgrade. Checked: no __STRING_NOT_TRANSLATED__ left,
every file parses, re-running i18n:extract changes nothing, and every
{{placeholder}} in a key appears in its translations.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): keep the card's message inside a ruled middle at every width

The card keeps ID-1 proportions while its text is in rem, and the message
clamp was picked from character count alone. On cards under ~380px a
long message ran over the title and the To/From row, with the ellipsis
hidden. Changes, all in the gift components:

- The message sits in a bounded middle area (flex-1, min-h-0, overflow
  hidden). Its line clamp is measured from that area's height, so the
  last line and its ellipsis always land inside the card. Cards under
  16rem of content set every message at text-xs (container query).
- The size counts lines as well as characters, so a short letter with
  line breaks is set small enough to keep its sign-off.
- The ruled lines sit only behind the message, one under each line
  (em-based, matching leading-snug), instead of across the header.
- The composer preview shows To, From and message placeholders faintly
  until the buyer types.
- A sent card's face follows the message while it is edited and takes
  the PATCH response at once, so the saved text shows even if the
  reload fails.
- E-ink: the ribbon is an outline open at the top with inset sides; the
  unselected tier radio gets a base-content ring.
- RTL messages are not italicized; the n / 300 counter is dir=ltr.
- The tier options stack below 21.25rem and the recipient email input
  shrinks so its label stays on one line at 320px.
- Dark mode: the hairline is drawn over the page (bg-clip-padding).
- The card uses the Readest app icon instead of a generic book icon.

Verified:
- New tests, each failing before the change: gift-card.test.tsx "sizes
  the message by its lines as well as its length" (expected 'text-base'
  to be 'text-xs'); gift-cards-section.test.tsx placeholders (unable to
  find "Their name"), counter dir (expected null to be 'ltr'), sent
  edit (unable to find "Happy reading"); gift-card-layout.browser.test
  at 320/360/375 px (message top 93.25 < title bottom 111) and the
  six-line letter at 390 px (scrollHeight 154 > clientHeight 67).
  All pass now.
- pnpm test: 1398 files passed. pnpm lint: clean apart from an existing
  info in nativePageTurn.ts. pnpm format:check: clean.
- A local screenshot pass in Chromium for light, dark, e-ink, e-ink dark
  and RTL at 320-1280 px: no message overlapping title or names.
- Not run: WebKit/iOS and Android devices, the Tauri app.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): a clothbound gift card that turns over to its bookplate (owner: "I would like a vintage design", chose A)

The card is now an old cloth-bound book. The cover is navy cloth for Plus
and oxblood for Pro, with gilt stamping: a double-rule frame, an engraved
open book with a ribbon after the Readest icon, READEST, the plan and the
year in Roman numerals. Turning it over opens the cover: marbled endpaper
with an "Ex dono" bookplate that carries To, the message and the sender.

Clicking or tapping the card, or Enter or Space on its Turn over button,
turns it over with a 3D flip and a short lift; the button sits over the
card, so screen readers still read the face. Reduced motion and e-ink
swap the sides without moving. The composer shows the bookplate while
the buyer writes and the cover when they pick a plan; Edit message on a
sent card shows the bookplate. On e-ink the card is paper, ink and 1px
rules, with the spine kept as a rule. Italics and spaced capitals apply
only to scripts that take them, so Arabic, Hebrew, Indic, Thai, Tibetan,
CJK and Hangul stay upright and joined. The message is set in card
widths with an 11px floor, so a 300-character message now fits whole
from a 390px phone up.

Verified:
- gift-card.test.tsx: written first. Against the old card 6 of 8 failed,
  e.g. "expected 'text-base' to be 'large'" and no "Turn over" button;
  all 10 pass now.
- gift-cards-section.test.tsx: the preview turns with focus and plan
  picks, and Edit message shows the bookplate.
- gift-card-layout.browser.test.tsx (Chromium): the message stays between
  To and the signature inside the bookplate at 320-1280px, and a
  300-character message is shown whole at 390 and 1280px.
- Screenshots in Chromium of both sides in light, dark, e-ink, e-ink
  dark, RTL (Arabic labels) and RTL dark at 320, 390 and 1280px, the
  turn mid-flip, and the Gift Cards view.
- pnpm test (1398 files, 17200 tests), pnpm lint, pnpm format:check.
- i18n: "Ex dono" and "Turn over" in all 34 locales.

Not run: WebKit/iOS rendering (the marbling filter is inline, which
WebKit needs), Android's serif fallback, e-ink on a device.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): hide the card's turned-away face in WebKit too

WebKit drew the bookplate, mirrored, over the cover of every card at
rest: it draws a face's positioned children through
`backface-visibility: hidden`, so the plate, the marbling and the
vignette all showed through. The face turned away is now hidden
outright, and the faces swap as the turn passes edge-on, about 100ms
into its curve. Reduced motion and e-ink swap them at once, as before.

Verified:
- gift-card-layout.browser.test.tsx samples a pixel of the card at rest
  and once turned, and now runs in WebKit as well (added to
  vitest.browser.webkit.config.mts). In WebKit without the fix it fails
  with "cover's navy cloth at rest, got rgb(244,236,216)"; with it, 10/10
  pass in WebKit and in Chromium.
- WebKit screenshots of a full turn: cover at rest, the bookplate after
  turning, the cover again after turning back.
- Bisected in WebKit first: hiding the bookplate, or turning the
  vignette solid red, showed the escape was every positioned child, and
  only `visibility: hidden` on the turned-away face stopped it.
- gift-card.test.tsx and gift-cards-section.test.tsx, pnpm lint,
  pnpm format:check.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): hint under a received card that its message is on the back (owner: "add a small hint under received cards")

A recipient sees the card's cover first and might never turn it over to
the bookplate with the message. A received card that carries a message
now says "Turn the card over to read the message" under its status. A
card with no message shows no hint, since the back holds nothing to
read. The wording names no tap or click, so it reads the same on touch,
mouse and keyboard. It uses the secondary-text style, at full opacity on
e-ink, and is translated in all 34 locales.

Verified:
- received-gift-list.test.tsx failed without the change on the hint
  assertion for the card with a message, and passes with it.
- Screenshots in light, dark, e-ink, e-ink dark and RTL (Arabic) at
  320, 390 and 1280 px.
- pnpm test: 1407 files / 17258 tests pass; pnpm lint and
  pnpm format:check clean.

Not run: a real device.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): allow 'readest' as a gift card provider (owner: "add 'readest' so that in the future we may have a dashboard to generate gift cards")

Cards that Readest issues itself, with no payment behind them, can now be
stored with provider 'readest'. The migration's CHECK and the row type
both allow it. The payment path still records only stripe, apple or
google, and no code branches on a stored card's provider, so such a card
redeems and lists like any other. The dashboard itself is not built here.

Verified on a local Postgres 15:
- The previous migration rejects a 'readest' row with
  gift_cards_provider_check. The new one accepts it and still rejects
  an unknown provider.
- The new migration runs twice without errors.
- pnpm test: 1407 files / 17258 tests pass; pnpm lint and
  pnpm format:check clean.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): sell gift cards from On-Demand Purchase; the account action only redeems (owner: "Add a new Gift Card button in On-Demand Purchase, after the Full Customization button")

The Lifetime card gets a Gift Card tile after Full Customization, in each
of its states. It opens the give view: the composer, then the cards you
bought (Sent). The account action is renamed Redeem Gift Card (owner:
"rename it to \"Redeem Gift Card\"") and opens the redeem view: the redeem
form, then the cards you were given (owner: "Received. Keep it in the
redeem view.").

A gift link opens the redeem view, and the URL it leaves behind
(section=redeem) reopens it on a reload. A returning gift checkout still
opens the give view (section=gifts), so the checkout URLs are unchanged.
The tile shows even when no one-time products load: the give view is
where bought cards are managed. The redeem view fetches no prices.

Four new strings are translated in all 34 locales; "Gift Cards" and the
combined description are no longer used and were dropped by i18n:extract.

Verified:
- 12 new tests fail without the change, on assertions naming it: no
  "Gift Card" button in the Lifetime card (4), no "Redeem Gift Card"
  button, the give view still showing the redeem form, no "Redeem Gift
  Card" heading, the gift link replacing the URL with section=gifts, and
  the page passing no view or tile handler (4). All pass with it.
- pnpm lint, pnpm format:check and pnpm test (17417 passed) pass.
- Screenshots of the Lifetime card in Chromium at 400 and 900 px, in
  light, dark, e-ink and RTL, with Full Customization for sale and owned.

Not run: the two views in the running app. They keep the existing
components and are checked by the tests above.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): price the Gift Card tile and set every On-Demand tile alike (owner: "Gift Card also has a price on it (starts from $49.99)")

On-Demand Purchase:
- Full Customization, unlocked or coming soon, now uses the same tile and
  type as the products beside it (text-sm name, text-xs price) instead of
  the smaller chip text. Unlocked keeps its price as the anchor.
- The Gift Card tile shows "From" and the lowest gift price. With no gift
  prices loaded it shows the name alone, at the height of the other tiles.
- The page loads the gift prices once, for the tile and the buy view, from
  the store on an IAP build and from Stripe otherwise. The buy view no
  longer fetches its own.

The buy view drops its "Gift Card" and "Give a Gift" titles; the tile that
opens it already names it. The description line stays above the composer.

New string "From {{price}}", translated in all 34 locales.

Verified:
- Without the change, 13 tests fail on their assertions:
  plans-comparison (lowest gift price, unlocked price, Full Customization
  type in both states), gift-cards-view (one fetch, shared with the tile
  and the buy view), gift-cards-section (sells at the page's prices; no
  titles).
- pnpm lint exit 0; pnpm format:check exit 0 (after formatting one test
  file); pnpm test 1412 files, 17424 passed, 16 skipped.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): an unlocked Full Customization goes last in On-Demand Purchase (owner: "When Full Customization is unlocked, put it at the end of the products")

Owned, it sits below the Gift Card tile, after everything that can still be
bought, and keeps its price. For sale or coming soon it stays where it was,
above the Gift Card tile.

Verified:
- New test "an unlocked Full Customization moves to the end, after the Gift
  Card" fails without the change (expected +0 to be truthy: the tile came
  before the Gift Card) and passes with it.
- plans-comparison 23 passed; pnpm lint exit 0; pnpm format:check exit 0.
  The full suite ran on the next commit, which includes this one.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): buy first, write the card after, on a page that says what the plan includes (owner: "go with B and say what Plus or Pro includes, try optimize the conversion rate")

The gift buy page was a form: the account block, then To, From, Message
and a recipient email, with Buy about two screens down on a phone. Now:

- No account block on the buy page (owner: "we don't need the user avatar
  section"). The redeem view and the plans keep it.
- The card preview, the Plus/Pro choice, then what the picked plan
  includes, from the plan cards' own lists (no new strings): the storage
  line takes its size, and "Includes All Free Plan Benefits" is left off.
- Buy is the page's one brand-colour call to action (DESIGN.md 4.2), full
  width, right under the plan. Under it: "One payment, no subscription",
  "Write the card after you pay", "Their year starts when they redeem it".
- Nothing to fill in before paying. The draft goes out blank, signed with
  the buyer's name. After any way back from paying (store, embedded or
  redirected Stripe checkout), the newest card in Sent opens on its
  bookplate with the To/From/Message editor, scrolled into view.
- The recipient email moves to Sent's "Add recipient email", which now
  carries the Hide My Email advice the buy form had.
- On wide screens the buy column is capped at max-w-md and centred.

Three new strings, translated in all 34 locales; "Optional" is no longer
used and was dropped by extraction.

Verified:
- Without the change, 4 tests fail on their assertions: the buy view
  shows the account block; the give view has text boxes; the picked plan's
  benefits are missing; the card just bought doesn't open for writing.
  The Hide My Email check failed until the advice moved to Sent.
- pnpm lint exit 0; pnpm format:check exit 0 (after formatting one file);
  pnpm test 1412 files, 17429 passed, 16 skipped. This run includes the
  previous commit (unlocked Full Customization last).

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* docs(gift): a gift card product's Stripe metadata now follows the storage packs (owner: "Update the metadata for the gift card, refer to the metadata for the 10 gb pack in Stripe")

The Stripe test-mode gift products now carry plan: purchase and
feature: gift beside their gift tier, the shape of the 10 GB pack
(feature: storage, plan: purchase, storageGB: 10). The comment said a gift
product has no plan; it now says what the metadata holds and that only the
gift key is read.

Checked: no code path changes. /api/stripe/plans still drops any product
with a gift key (dev-web lists 5 plans, no gift); /api/gift/prices still
returns both tiers; a payment row's metadata has no storageGB, so 0 GB,
and its feature is not "customization", so no unlock.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): keep the buy page clear of the fixed back button

With the account block gone, the buy page's first line sat against the
fixed header (64px on phones, 84px under macOS traffic lights; the page
starts content at 40px). The buy view now pads 48px more.

Verified on the Xiaomi 13 (live preview of the same padding) in light,
dark, e-ink and RTL: the line clears the back arrow and Buy stays on the
first screen (top 650px of 872px). pnpm lint exit 0; format:check exit 0;
user page tests 134 passed.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* feat(gift): a headline for the buy page and the Readest icon on the card (owner: "we need a better header")

- The buy page opens with "The gift of reading" in the card's serif, the
  card's fleuron in gold (base-content on e-ink), then "Give someone a year
  of Readest Plus or Pro".
- The cover carries the Readest icon in place of the engraved open book
  (owner: "Can we use the Readest icon on the card or design the icon on
  the card?"). Full colour, like a pasted cover picture, and greyscale on
  e-ink. Its transparent margin is taken back so the cover keeps its
  height and the plan line stays clear of the year. On the Xiaomi I also
  tried a gold-tinted icon; it read flat next to the foil.
- The storage benefit reads "5 GB Cloud Sync Storage" (owner: "don't use
  the •").
- No Terms/Privacy line on the buy page (owner: "the line is already
  present in the user page"). The plans and the redeem view keep it. A gift
  card is a one-time purchase, so the store rule that puts those links by a
  subscription's buy button doesn't apply.

New string "The gift of reading", translated in all 34 locales.

Verified:
- Without the change, 4 tests fail on their assertions: the cover has no
  Readest icon; the buy view has no "The gift of reading" heading; the
  storage line isn't "5 GB Cloud Sync Storage"; the buy view shows the
  legal line.
- pnpm lint exit 0; pnpm format:check exit 0; pnpm test 1412 files,
  17433 passed, 16 skipped; gift-card-layout browser test 10 passed.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* docs(gift): note the giftDays key the Stripe gift products now carry (owner: "should we encode the 1 year in the metadata of stripe produce for the gift cards")

The live gift card products (created today) and the test ones carry
giftDays: "365" beside plan, feature and gift, so a future half-year or
two-year card can say its length the way a storage pack says storageGB.
Nothing reads it yet: a card still takes gift_cards.days' default of 365,
and the card prints "1 year". The type says so.

Checked: pnpm lint exit 0; pnpm format:check exit 0. Type and comment
only.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): a Full Customization tile you can't tap is quieter than the ones you can (owner: "the unlocked full customization has darker color for other clickable products, this is counterintuitive")

Unlocked and Coming Soon used the tier's Current Plan colour (emerald-100
fill, emerald-900 text), darker than the emerald-50 tiles you can buy, so
the one tile that does nothing looked the most tappable. Both are now an
outline with muted text and no fill (border-base-content/15,
text-base-content/60), which holds in light, dark and e-ink.

Verified: the new test (both states) fails without the change ("expected
... not to match /bg-emerald-/") and passes with it; user page tests 140
passed; pnpm lint exit 0; format:check exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): a long message steps down a size when the card's font runs wide (owner: "fix the CI")

CI's WebKit lane failed "a 300-character message is shown whole at 390px"
(expected 121 to be less than or equal to 107). It isn't WebKit: the card
asks for Iowan Old Style, Palatino or Georgia, and Linux has none of them,
so WebKit there sets it in a wide default serif. Measured locally, the same
message at a phone-width card takes 6 of 7 lines in Iowan or Times, all 7 in
Georgia, and 8 in Verdana, in Chromium and WebKit alike.

Real phones hit it too. On the Xiaomi 13 the card's font stack resolves to
Android's serif, and the message measures 1592px against Georgia's 1547px,
so a full-length message lost its last line to the ellipsis.

messageSize still guesses the size from the length. After layout, if the
clamped paragraph still overflows, the card steps down one size for that
message, as far as a new xsmall (max(10px, 2.7cqw)), the only place the
message goes below 11px.

Verified:
- New browser test "a 300-character message is shown whole at 390px in a
  wide fallback font" (Verdana forced) fails without the change in
  Chromium with CI's own error, expected 121 to be less than or equal to
  107, and passes with it in Chromium and WebKit (11 of 11 each).
- User page unit tests 140 passed; pnpm lint exit 0; format:check exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): log with constant messages, not interpolated ones (owner: "fix the CI")

CodeQL flagged js/tainted-format-string at gift/server.ts: the refund log
put a payment reference into console.error's first argument, which Node
treats as a format string, so a value holding "%s" would garble the line.
The two other gift log lines built the same way (a claim's column and user
id, a card id) change too. Each now logs a constant message and passes the
values as an object.

Checked: no test asserts on these messages; payment and API tests 497
passed; pnpm lint exit 0. CodeQL reruns on the push.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): the gift views keep the newest load, a failed check's session, and the plan after a redemption

From the CodeRabbit review of #7930:
- An older, slower load landing after a newer one put back what a save or a
  redemption had just changed. Only the newest load now updates the view.
- A payment check that failed (network, not "unpaid") still took the
  session out of the URL, so a reload couldn't check it again and the card
  never opened for writing. A failed check now keeps it.
- When the opening load failed there was no plan to compare against, so a
  redemption never refreshed the page's plan. It now does.

Verified: each new test fails without its change (router.replace called on
a failed check; the Received list gone after the older load lands;
onPlanChanged called 0 times) and passes
with it. User page tests pass; pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): wait for the gift status before the billing portal, and offer Subscribe only with a product

From the CodeRabbit review of #7930:
- A plan holder tapping a tier before the gift status loaded (or when it
  failed) was sent to the billing portal, even when a gift alone set the
  plan and there was no subscription to change. The page now asks for the
  status first, and says it couldn't load rather than guess.
- A gift-only holder saw an enabled Subscribe button that did nothing for a
  tier whose product hadn't loaded. It now needs a product.
- Test only: the page tests' mocked AuthContext.refresh was a new function
  each render, which re-ran the page's claim effect without end (274 gift
  loads in 50 ms; "loads the gift info once" now pins one). It is stable
  now, like the real useCallback.

Verified: "asks for the gift status before sending a plan holder to the
billing portal" fails without the change (fetchGiftCards called 1 time, the
portal opened) and passes with it; "a gift-only holder gets no Subscribe
for a tier with no product loaded" fails without it. pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): tile prices at full ink on e-ink, and the message fit check on every resize

From the CodeRabbit review of #7930:
- The On-Demand Purchase prices drew at 80% opacity on e-ink: the theme's
  e-ink rules flatten colours, not opacity. Now not-eink:opacity-80.
- The card reran its message fit check only when the bookplate's line count
  changed. A narrower card can wrap onto a line more at the same count, and
  the last line stayed under the ellipsis. The check now runs on every
  resize too.

Verified: the new browser test fails without the change (opacity '0.8' on
e-ink) and passes with it; the new card test fails without the change (no
step down after a same-count resize) and passes with it. Card layout browser
test 11 passed. pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(i18n): say the gift year starts at redemption in Chinese

"对方兑换后一年才开始计算" can read as "counting starts a year after they
redeem". Now "一年从对方兑换时算起" (zh-TW "一年從對方兌換時算起"): the
year counts from when they redeem. From the CodeRabbit review of #7930.

Checked by reading against the English, Japanese and French.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* test(payment): a gift refund test checks the stored payment row

The test asserted the recorded payments write, which the test database
records even when it matches no row, and matched it as a subset. A filter
that excluded the payment would still pass. It now seeds the payment and
checks it ends up refunded. From the CodeRabbit review of #7930.

Checked: with a stray .eq('status', 'pending') added to
markPaymentRefunded's update, the new assertion fails (expected
'succeeded' to be 'refunded') where the old one passed; restored, it
passes.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): a refund whose recipient plan sync fails fails the call, so the provider retries

revokeGiftCardForPayment logged a failed recipient sync and returned. The
cron then retried only while the refund was inside its two-hour window, so a
sync that failed throughout (a long database or Stripe outage) left the
recipient on the refunded tier for good. From the CodeRabbit review of #7930.

Every caller is a refund webhook (Stripe charge.refunded, App Store
REFUND/REVOKE, Play voided) or Stripe's refunded-session branch, and each
answers 500 on a throw, so the provider redelivers for days. Each
redelivery re-runs the refund update, whose BEFORE UPDATE trigger re-stamps
updated_at and reopens the cron's window. The card is refunded either way.
This takes back part of 157acb24f's best-effort sync, whose reasons (Play
consumption at activation, "code already used" at redeem) don't apply to a
refund webhook.

Verified: "a refund revokes the card, then fails the call when the
recipient's plan sync fails" fails without the change (promise resolved
instead of rejecting) and passes with it. Payment and API tests pass.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): the cron re-syncs a recipient whose stored plan is below their gift

A claim whose plan sync failed through the whole two-hour window was never
retried: the next boundary is the gift's end. Every plan write goes through
resolveUserPlan, which counts the gift, so a stored plan below the
recipient's gift plan can only be a missed sync. The cron now reads the
stored plans of current gift holders (200 ids a query) and re-syncs those
below their gift; once a sync lands they no longer match. A holder with no
plans row is left alone. From the CodeRabbit review of #7930.

Not covered: a gift's end whose sync fails for the whole window leaves the
recipient on the ended tier; a stored plan above the gift may be a paid plan,
so that direction needs a durable marker.

Verified: "syncs a recipient whose stored plan is below their gift, outside
the window" fails without the change (expected [] to deeply equal
['stale']) and passes with it; "leaves a recipient whose stored plan
already covers the gift" guards against endless re-syncs.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): an App Store gift charge follows Apple's live state before activating

The ONE_TIME_CHARGE notification recorded every one-time purchase as active.
If a gift's first charge notification and the app's verify both failed, and
the buyer was refunded before any payment row existed, the REFUND found
nothing to revoke and answered 200; Apple's later retry of the charge then
activated a redeemable card for a refunded purchase. From the CodeRabbit
review of #7930.

For gift products the handler now re-reads the transaction from Apple, as
the app's verify does: revoked means expired, no card. A failed read throws,
so Apple retries. It runs only where the verifier can see the transaction
(it reads one environment), and storage add-ons, which have the same gap
from before this PR, are left for their own change.

Verified: "a ONE_TIME_CHARGE for a gift Apple has since refunded does not
activate" and "a gift charge whose live check fails throws, so Apple
retries" fail without the change and pass with it; "a ONE_TIME_CHARGE for a
gift still paid activates after the live check" passes. Payment and API
tests 502 passed; pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): after paying, open the card this purchase paid for, and say only what's true

From CodeRabbit's second review of #7930:
- The card that opened for writing was the newest in Sent, which is wrong
  when another device bought one moments later. The store and the embedded
  checkout know which draft they paid for and now open that one; a
  redirected Stripe checkout returns with only its session, so it still
  opens the newest.
- "Your gift card is ready" showed even when the reload after paying failed
  (beside "Failed to load gift cards"). It no longer does.
- An embedded checkout that completed but couldn't be checked left the
  buyer on Buy with no word. It now says "Payment received. Your gift card
  will appear here shortly."; the webhook still activates the card.

Verified: each new or changed test fails without the change (a card bought
elsewhere opened instead; the ready toast shown; no toast after the failed
check) and passes with it. User page tests 152 passed; pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): the bookplate imprint at full ink on e-ink, Upgrade only with a product, and the newest gift status

From CodeRabbit's second review of #7930:
- The bookplate's "Readest · MMXXVI" imprint drew at 80% opacity on e-ink;
  the e-ink rules flatten colours, not opacity. Now not-eink:opacity-80.
- An Upgrade button showed for a tier whose product hadn't loaded and did
  nothing when tapped. Every Upgrade/Subscribe button now needs a product,
  not only the gift-only one.
- The account page's gift status took whichever load answered last, so an
  older answer could put back a stale "gift only" and send a gift holder to
  the billing portal. Only the newest load sets it now.

Verified: each new test fails without its change (opacity '0.8' on e-ink;
the Upgrade button present; the portal opened) and passes with it. Card
layout browser test 12 passed; user page tests 152 passed; pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): an App Store gift Apple reports revoked takes back a card already made

Stripe already revokes a gift card when its payment is refunded; Apple's
payment write only skipped activation, so a card made earlier stayed
active. Now a revocation date on the purchase (from the app's verify or a
charge notification's live check) revokes the card, a no-op when there is
none; a failed recipient sync throws, so Apple retries. From CodeRabbit's
second review of #7930.

Also from that review, test only: the payment-before-activation order
assertions now first check the payment write exists (indexOf is -1, which
passed, when there was none), and the no-draft ONE_TIME_CHARGE test runs
through the live check as production does.

Verified: "a ONE_TIME_CHARGE for a gift Apple has since refunded revokes a
card it already made" and "a revoked gift charge whose recipient sync fails
throws, so Apple retries" fail without the change and pass with it.
Payment and API tests 509 passed; pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): saving a recipient email answers with the saved card when the claim fails

The email is saved and locked before the card is handed to an existing
account, but a failed hand-over answered the save with a 500, so the buyer
saw "Failed to update the gift card" for an email that had been saved. The
claim is now best-effort here as it is at activation (one helper for both);
the cron's email sweep claims the card within minutes. From CodeRabbit's
second review of #7930.

Verified: "adding an email returns the saved card when the claim fails"
fails without the change (promise rejected "claim failed") and passes with
it.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): the cron pages by id and retries a gift's end that failed through the window

From CodeRabbit's second review of #7930:
- Claimed cards were read by offset, so a card leaving the active set
  between pages (a refund) shifted the next page and skipped a card. Pages
  now start after the last id read.
- A gift end whose plan sync failed through the whole two-hour window left
  the recipient on the ended tier, including when Pro ends while a Plus
  gift carries on. For seven days after a gift ends, a stored plan still on
  that tier and above the gift now is re-synced. A paying recipient whose
  gift only started isn't touched; one who pays for the very tier that
  ended is re-synced for those seven days and keeps the paid plan.

Verified: "reads every claimed card when one leaves the active set between
pages", "re-syncs a recipient whose gift ended outside the window while
plans still has it" and "re-syncs when a Pro gift ended outside the window
and a Plus gift carries on" fail without the change and pass with it; "leaves
a recipient whose stored plan already covers the gift" and the new
past-the-lookback case still pass. pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): a gift bought in a store's sandbox is a test card no one can claim (owner chose "Test cards")

App Store Connect sends sandbox notifications (TestFlight, App Review) to
the production endpoint, and the charge handler activated a gift card for
them: a free, redeemable year of Plus or Pro for anyone with TestFlight. A
Play license tester's purchase is free the same way. From CodeRabbit's
second review of #7930.

A gift bought with a sandbox purchase on the production server is now a
test card:
- gift_cards gets test boolean NOT NULL DEFAULT false (034 isn't applied
  in production yet; an ADD COLUMN IF NOT EXISTS covers re-runs), set at
  activation from both stores' purchase environment.
- Every claim skips it: the code and email claim's update, and the cron's
  email sweep in SQL. Redeeming its code answers test_card: "This is a test
  card and can't be redeemed."
- The buyer still sees it in Sent, as "Test card, can't be redeemed", with
  no email action, so App Review sees the whole purchase. Development
  servers keep sandbox purchases real.

Two new strings, translated in all 34 locales.

Verified: each new test fails without the change (no test flag from a
sandbox charge or a Play test purchase; the code claimed; the route said
invalid_or_used; no label, the email action shown, the generic error) and
passes with it. Payment, API and user page tests 668 passed; pnpm lint
exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): the redeem form and Sent editors hold what they sent and show they're working

From CodeRabbit's third review of #7930:
- Redeem: the code field is read-only while its request is out, so a code
  typed meanwhile isn't cleared or blamed for the first one's answer;
  editing the code clears the last error; the button shows a spinner and
  aria-busy.
- Sent: the email confirmation step has Back, which returns to the address
  as typed (after a failed save too); Save and Confirm show a spinner and
  aria-busy and ignore a second press; a save closes only the editor it
  began in, not one opened while it was on its way.

Verified: each new test fails without the change (input editable while
pending; the error kept; no Back; aria-busy missing and the new editor
closed by the old save) and passes with it. User page tests 158 passed;
pnpm lint exit 0.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

* fix(gift): match account emails case-insensitively in the claim SQL; stricter gift tests

From CodeRabbit's third review of #7930:
- gift_user_id_for_email and the cron's email sweep compared the card's
  lowercase email with auth.users.email as stored; accounts from before
  GoTrue lowercased emails can hold mixed case and never matched. Both now
  compare lower(u.email). Migration 034 changes, so production re-runs it
  (already on the PR's checklist; every statement is idempotent).
- Tests: a failed Stripe gift activation is checked at the webhook (500,
  after the payment write), not only at the helper; the route tests reset
  the claimed-email arguments; the redeemed Sent card carries a code the UI
  must hide; the test database stamps updated_at on every gift card update,
  as the guard trigger does, and a redelivered refund is shown to bring its
  recipient back into the cron's window.

Checked: the webhook test fails when the route answers 200 to the error
(expected 200 to be 500); the redeemed-code test fails when every
non-refunded code shows. The SQL change was checked by reading; the
migration isn't run in tests. Payment, API and user page tests 674 passed.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>

---------

Co-authored-by: Claude Code (Claude Sonnet 5.5) <noreply@anthropic.com>
2026-11-25 20:19:07 +01:00
Huang Xin
045beb4d1a
feat(crosspoint): sync CrossPoint 2.0 clippings with Readest highlights (#7317)
* feat(crosspoint): sync CrossPoint 2.0 clippings with Readest highlights

CrossPoint 2.0's Sync Clippings first probes
{KOSync server}/api/v1/clippings/{document} for sync_version 2, and stops
the whole sync, progress included, when the probe fails. Readest's KOSync
endpoint had no such route, so a reader signed in with the Readest plugin
showed "Could Not Sync Clippings" and stopped syncing progress once the
setting was on.

- /api/crosspoint/api/v1/clippings/{document} serves the clippings API
  (sync_version 2, cursor paging, tombstones). A clipping is a book_notes
  highlight whose new `crosspoint` column holds the reader's anchor (spine
  plus a code-point range), the way xpointer0/xpointer1 hold KOReader's.
  Only items the firmware can decode are sent, up to the 256 an X3/X4
  holds per book. A rewritten copy (Optimize EPUB) syncs as the library
  book it is linked to, and its first clippings move to that book when
  its progress upload links it.
- Readest apps turn a clipping into a CFI when they open the book, and
  give each EPUB highlight a CrossPoint anchor when they push it (tried
  once a session). Moving a highlight's range drops the old anchors.
- Migration 033 adds book_notes.crosspoint (nullable jsonb). Apply it
  before the web deploy.
- Plugin README: CrossPoint 2.0 names and requirements, and highlights.

Fails without the change: useNotesSync-crosspoint (4 of 5, e.g. "turns a
clipping a reader synced into a highlight at its CFI"), transform "carries
the anchor in the crosspoint column, both ways", useAnnotationEditor "a
moved range drops the KOReader and CrossPoint anchors of the old one"
(expected the old xpointer to be undefined), and the route test "moves a
rewritten copy's clippings to the library book it gets linked to". The
clippings route tests can't run without the route.

Verified on a real X4 (CrossPoint 2.0.0) with Sync Clippings on: the
probe and uploads answer 200, a reader clipping shows in Readest on its
words, a Readest highlight shows on the X4, and deletions go both ways.

Reported by itsthisjustin (CrossPoint).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(crosspoint): sync a document a reader names by its file name

A reader set to match documents by file name (CrossPoint's default, and
the alternate lookup of its Smart Sync) sends md5 of the book's file
name, as KOReader does. Since #7237 Readest keeps the name a book was
imported under (books.original_filename), and #7253 digests it the same
way in Readest's own KOSync client.

Progress, clippings and reading sessions now resolve such a document to
the library book imported under that name, link it on first sight like a
rewritten copy, and move clippings saved under the name's id to the book.
When two books were imported under one name, the most recently read one
wins. A document that is a book's own id is never looked up by name, and
an NFD spelling of the name does not match.

Fails without the change: 5 of the 6 tests in "a document named by its
file name", e.g. "syncs it as the library book imported under that name,
linked on first sight" (the link write and the library book's queries
never happen). The sixth, a name no book has, passed before too.

Not run on a device: the books in the test library were imported before
#7237 and have no original_filename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(crosspoint): page the file-name lookup, and retry a failed clipping move

From CodeRabbit's review of this PR:

- The lookup of the book imported under a file name read the user's books
  in one request, and PostgREST answers at most 1000 rows (db-max-rows),
  so a match past them was never found. It now pages through them by
  book_hash.
- A copy was linked before its clippings moved to the library book, and a
  failed move only logged a warning. Every later request followed the
  link, so those clippings stayed under the copy's id for good. They now
  move first, and a failed move fails that sync, leaving the copy
  unlinked so the next sync tries again.

Fails without the change: "finds the book past the first 1000 imported
under a name" (no link written: expected [ …(20) ] to deeply equal
ArrayContaining{…}), and "links a copy only once its clippings have
moved, so a failed move is tried again" (expected 200 to be 500).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:22:58 +01:00
Huang Xin
b58728c29a
feat(vocabulary): vocabulary builder and Learning/Mastered marks for Word Lens (#7284)
* feat(vocabulary): entry model, sentence extraction and merge

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): revive a word looked up after a delete on a stale device

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(vocabulary): local store, file persistence and backup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(wordlens): hint Learning words and skip Mastered words

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(dictionary): Learning and Mastered chips, capture lookups to Vocabulary

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sync): vocabulary table and sync route

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sync): sync vocabulary across devices

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(vocabulary): export to Anki and CSV

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(vocabulary): hint sources from dictionaries and the AI context dictionary

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(vocabulary): vocabulary builder window

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(i18n): vocabulary strings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): resolve the sync endpoint on use, not at import

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): save the lookup's sentence from its own paragraph with spacing kept

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): take a dictionary hint from the first definition, not the entry header

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): save a hint on Enter inside the Dialog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(wordlens): re-render hints after the selection clears, keeping the dictionary open

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): leave ruby hints out of saved sentences, dedupe a sentence across CFIs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): keep book text in its own direction under an RTL interface

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): a lookup never overrides a Learning or Mastered mark from another device

A word first looked up on a device stamped modifiedAt with the current
time, so its empty state beat a mark set elsewhere in the merge. Lookups
now carry modifiedAt 0. Selections with no letters get no chips or entry.
The migration moves to 032 (031 is taken on main).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): keep syncing past a bad row and cap saved sentences

A rejected row failed the whole push, and the push's failure skipped the
pull, so one bad word stopped vocabulary sync on that device. The server
now skips malformed rows and reports them, the client clears them, and a
failed push no longer prevents the pull. Sentences are cut to a window
around the word and pushes go in batches of 50.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): rebuild from the server when the local word list is lost

The pull cursor lives on the device apart from vocabulary.json. With the
file missing or unreadable, the cursor still claimed everything was
pulled, so the words never came back. Sync now starts over when the file
held no words, trusts the cursor again after that full pull, and keeps a
copy of an unreadable file before it is saved over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): show typed hints as written; harden sentence capture and IME Enter

A saved hint went through the pack gloss cleaner, which cut it at a comma
or slash. A range the sentence reader couldn't handle could throw inside
the annotator; it now falls back to the selected text. WebKit's
IME-confirming Enter (keyCode 229) no longer saves the hint early.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(api): keep /api/sync/vocabulary off language detection and DOMPurify

The vocabulary route syncs on every book open, so it joins the hot routes
that #7274 keeps light. It passes as written: the route imports only the
Supabase client, access check, CORS and the vocabulary entry/wire modules.
Checked the case can fail: with `import '@/utils/sanitize'` added to the
route it fails with `expected [ 'dompurify' ] to deeply equal []`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(vocabulary): describe lookup capture without naming another reader

Comment-only change; no behavior to test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): drop the lookbehind from export bolding; guard CSV cells against formulas

CodeRabbit on #7284. boldWord used (?<!…), which WebKit before 16.4 rejects
and which failed the build's check:lookbehind-regex (build_web_app). It now
consumes the boundary before the word in a capture group. CSV text cells that
start with = + - @ tab or CR get a leading apostrophe, so a spreadsheet won't
run book text or a hint as a formula.

Tests that fail without it (export.test.ts): 'bolds whole words without
lookbehind support' (RegExp throwing on lookbehind, as old WebKit does) and
'stops spreadsheet apps from running a cell as a formula'. pnpm build-web +
pnpm check:all: no lookbehind in chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): cap a saved sentence when the selection itself is over the limit

CodeRabbit on #7284. With a selection of 300+ characters the window half was 0
and pre.slice(-0) kept the whole text before it. Such a selection is now cut
to the limit on its own.

Test that fails without it (entry.test.ts): 'caps a selection longer than the
limit' (expected 414 to be less than or equal to 302).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): keep unpushed words pending when the word file loads

CodeRabbit on #7284. load() merged the file into memory with mergeEntries,
which drops the dirty flag, so a word restored from a backup or looked up
before the file loaded was never pushed. Either side being dirty now keeps
the merged word dirty, as applyRemote already does.

Test that fails without it (vocabulary-store.test.ts): 'keeps unpushed
changes pending when the file loads over them' (expected undefined to be
true).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(api): keep database errors out of /api/sync/vocabulary responses

CodeRabbit on #7284. The route returned PostgREST error messages to the
client; it now logs them and returns a fixed message. A since_ts that isn't
a timestamp gets a 400 before any query.

Tests that fail without it (sync-vocabulary.test.ts): 'rejects a since_ts
that is not a timestamp before querying' (expected 200 to be 400) and the two
'keeps database error details out of …' cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): run one more sync when one is asked for mid-sync

CodeRabbit on #7284. A debounced sync that fired while a sync was running
got the running promise back, so words changed after its push snapshot
waited for the next change. It now sets a flag and the running sync makes
one more pass. Fake timers in the sync tests are restored in afterEach.

Test that fails without it (vocabularySync.test.ts): 'runs once more when a
sync is asked for while one is running' (pull called 1 time, expected 2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(wordlens): wait to draw hints when a selection starts while the pack loads

CodeRabbit on #7284. whenSelectionClears guarded only the start of a refresh;
a selection made while the gloss index or OpenCC loaded still had hints
drawn under it, which can close the dictionary popup. The draw step now goes
through whenSelectionClears and is dropped if a newer refresh ran.

Tests (wordlens-section.test.ts): 'waits to draw hints when a selection
starts while the pack loads' fails without it (expected [ '尼莫' ] to deeply
equal []); 'drops a waiting draw once a newer refresh has run' guards the
generation check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(reader): give the Learning/Mastered chips a 32px hit target and focus ring

CodeRabbit on #7284, per DESIGN.md (32px minimum hit target, the canonical
focus-visible ring). Styling only. Checked on dev-web in Chrome: both chips
measure 32px high in the dictionary popup, and Learning toggles on and off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): drop the context when a selection leaves no room for it

CodeRabbit on #7284. A 299-character selection skipped the over-limit cut,
but the window half was still 0, and pre.slice(-0) kept the whole prefix.
Context is now dropped whenever the half window is 0.

Test that fails without it (entry.test.ts): 'caps the context when the
selection leaves no room for it' (expected 701 to be less than or equal to
302).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): break merge ties on the display word too

CodeRabbit on #7284. Two lookup-only copies of a word (same modifiedAt, state
and hint) could keep "Serendipity" or "serendipity" depending on argument
order, so devices and the server could show different forms. The tie key now
ends with the display word.

Test that fails without it (entry.test.ts): 'keeps the same display word
whatever the argument order' (expected 'Serendipity' to be 'serendipity').

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): save pulled words to the data file before moving the cursor

CodeRabbit on #7284. The pull saved its cursor right after applying a page,
while the file write waited for the 500 ms save delay; quitting in between
left the cursor past rows the file never got, and later pulls start from the
cursor. The store gains flush(), and the pull awaits it before each cursor
write.

Test that fails without it (vocabularySync.test.ts): 'writes the pulled words
to the data file before moving the cursor' (expected [ [] ] to deeply equal
[ [ 'en:a' ] ]).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(wordlens): defer a whole hint refresh while text is selected

CodeRabbit on #7284. The section-load refresh (and any other caller) cleared
hints before checking the selection, which unwraps the <ruby> under it and
can close the dictionary popup. refreshSectionGlosses now defers itself until
the selection clears; its generation bump drops any older pending draw.

Test that fails without it (wordlens-section.test.ts): 'leaves drawn hints
alone until a live selection clears' (expected [] to deeply equal ['尼莫']).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(reader): save a new sentence for the same word while the dictionary stays open

CodeRabbit on #7284. Lookup capture ran only when the word changed, so
selecting the same word in another sentence with the popup still mounted
saved nothing. It now also runs when the occurrence's book or sentence
changes; repeat sentences are still deduplicated by the store.

Test that fails without it (DictionaryVocabularyChips.test.tsx): 'records a
new sentence for the same word while the popup stays open'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vocabulary): write the word file one save at a time, and never mid-load

CodeRabbit on #7284: flush() cleared the save timer but not a save already
writing, so that older write could land over the list flush() had just
saved, after the pull had moved its cursor. Writes now run through one
chain, each saving the list as it is when it starts.

The same race reached backup restore, which wrote the file directly while a
delayed save could still land over it. Backup and restore now flush first.
A save that ran while the file was still loading wrote the partial list in
memory over the file; saves now wait until it has loaded, and load saves
the merged list when words were recorded before it finished.

Tests that fail without it:
- vocabulary-store.test.ts 'flush saves the newest list even while a delayed
  save is still writing' (expected [ 'en:first' ] to include 'en:second')
- vocabulary-store.test.ts 'saves a word looked up while the file is loading,
  without dropping the file': without the loaded check, expected [ 'en:new' ]
  to deeply equal [ 'en:new', 'en:old' ]; without the save after load,
  expected [ 'en:old' ] to deeply equal [ 'en:new', 'en:old' ]
- backup-vocabulary.test.ts 'includes a word saved moments ago…' (expected []
  to include 'en:fresh') and 'keeps restored words when an earlier save
  finishes during the restore' (restored word overwritten)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(vocabulary): sync the restore race test on flush instead of a delay

CodeRabbit on #7284: a fixed 50 ms wait didn't show the restore was blocked
on the stalled save, so the test could pass or fail on timing. It now
releases the stalled save only once the restore has called flush(), and
always releases it so a failure can't stall later tests.

Checked it still catches the bug: with restore's flush() removed it fails
with 'expected "flush" to be called at least once'; with it, 3 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:04:02 +01:00
Huang Xin
d5e10369b4
fix(library): preserve original filenames and use PDF filename titles (#7237)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / test_web_browser (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* fix(library): preserve import filenames and use PDF filename titles

Save each imported file's original basename, including its extension, on
the local Book record. Use the filename stem as the PDF display title while
preserving embedded metadata and the sourceTitle used to locate managed
files. Retain the original filename when re-importing a managed copy.

Regression evidence: before the fix, import-metahash and
import-docx-conversion had 13 assertion failures for missing
originalFilename fields and PDF titles still reading PowerPoint
Presentation. Both suites pass with the change.

Verified:
- Full unit suite: 1220 files passed, 4 skipped; 14648 tests passed,
  16 skipped (before updating to origin/main a2dd013a4).
- On origin/main a2dd013a4: six import suites plus useProgressSync,
  7 files / 124 tests passed.
- pnpm lint passed; formatting and git diff --check passed.
- Real web app: imported Device_Manual_V2.1.pdf with embedded title
  PowerPoint Presentation; filename title and originalFilename persisted
  after reload.
- Windows desktop not tested. Linux CEF verification was incomplete:
  the reused binary rendered a blank frontend in the isolated harness.

Reported by xiongshaowei on GitHub.
Refs #7230.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve question marks in import basenames

Derive local basenames without the URL helper's query stripping. For local
path imports use the supplied path, since NativeFile.name may already have
been shortened by that helper. Remote and provider imports retain their
resolved file names and URL fallback behavior.

The new File and path regression cases fail before this change with
originalFilename/title 'manual' instead of 'manual?rev1.pdf'/'manual?rev1'.
They now pass and verify two revisions remain separate library records.
A URL query fallback test also passes. Six import suites: 82 tests passed.
pnpm lint and formatting passed. The pre-push hook reruns the full suite.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): retain filename provenance across import and sync

Keep literal POSIX backslashes in import basenames and PDF identity, while
recognizing explicit Windows paths. Strip queries only from web URL fallback
names and preserve explicitly resolved filenames.

When a cloud-restored PDF lacks its original filename, reimporting its exact
managed path preserves the stored title and metadata hash. File sync fills
missing original filenames without changing titles, storage paths, or clocks.

Verification: four importer regressions failed first (URL fallback, two
backslash input forms, and cloud-restored managed copy). Three sync assertions
failed first for missing provenance and repair detection. All 232 tests across
11 affected suites pass with the fixes. pnpm lint, Biome formatting, and git
diff --check pass. Real web imports and reload retain three distinct filename
titles, original basenames, and embedded metadata. Windows desktop was not
tested; the earlier isolated Linux CEF harness remained blank. The full suite
runs again in the pre-push hook.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): exclude URL fragments from import fallback names

Remove the fragment before deriving the fallback name for a remote file,
while keeping explicitly resolved filenames unchanged.

Verification: the new fragment regression failed first because originalFilename
was manual.pdf#page=2 instead of manual.pdf. All 94 tests across the importer
metadata and web service suites pass, including query-plus-fragment and explicit
question-mark/hash filename cases. pnpm lint, formatting, and git diff --check
pass. Full unit tests run in the pre-push hook. Native device verification was
not repeated for this web URL fallback change.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): decode remote basenames after parsing the URL path

Derive a web remote file's fallback name from its final pathname segment before
decoding. This excludes queries and fragments, decodes reserved characters, and
preserves encoded backslashes as filename characters. Keep the encoded spelling
when pathname bytes cannot be decoded as UTF-8. Explicit filenames bypass this.

Verification: six new URL cases failed before the fix, covering C++, a slash
inside the query, malformed query/path bytes, and two encoded backslash names.
All 100 tests in the importer metadata and web service suites now pass. pnpm
lint, Biome formatting, and git diff --check pass. The full suite runs in the
pre-push hook. Native device verification was not repeated for this web fallback.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* test(library): cover Android provider display names on import

Verify opaque Android content URIs resolve the provider display name through
Tauri basename, for both external-storage and staged-provider file paths.
Verify importBook uses that resolved File.name for originalFilename, PDF title,
and salted identity instead of parsing the document identifier.

Verification: all 114 tests across the import metadata, web service, and native
service suites pass, as do pnpm lint, formatting, and git diff --check. This is
coverage of the existing basename flow, so no production behavior changed.
Android native basename was inspected and queries OpenableColumns.DISPLAY_NAME.
UI verification could not run against the available emulator because its
existing development WebView shows an unavailable URL. The full unit suite runs
in the pre-push hook.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve resolved filenames as atomic basenames

Do not split a resolved File.name again during original filename capture.
Local path basenames were already extracted, while a decoded URL segment may
contain a slash that belongs to its filename identity.

Verification: the two-file URL regression failed first with one/part.pdf reduced
to part.pdf and a different salted hash. It now passes and verifies two live
records with distinct filename titles and metadata hashes. All 138 tests across
eight import/native suites pass. pnpm lint, formatting, and git diff --check
pass. The full suite runs in the pre-push hook. Device UI checks were not
repeated for this filename capture change.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): simplify import filename handling (owner: refactor and simplify it)

Replace nested filename selection with explicit URI and local-path branches.
Resolve the managed-copy title/hash exception in one block instead of spreading
it across a boolean and three ternaries. Use the resolved title directly and
avoid PDF stem processing for non-PDF imports.

Verification: this is a control-flow refactor with no intended behavior change.
All 138 tests across eight import/native suites pass both before and after.
pnpm lint, Biome formatting, and git diff --check pass. Existing regressions
cover provider names, local special characters, Windows paths, decoded URLs,
conversion, and managed-copy identity. Full tests run again in the pre-push
hook. Device UI checks were not repeated for this refactor.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): share URL filename parsing across native and web imports

Reuse the URL pathname basename decoder in native and web filesystems. Native
URL fallbacks now exclude fragments and query separators and preserve decoded
filename characters, while explicit names remain unchanged. Use the existing
platform-aware path normalizer for managed-copy comparisons.

Verification: the new native URL and case-variant managed-copy regressions
failed before the fixes. All 146 tests across eight affected import/native
suites pass. pnpm lint, formatting, and git diff --check pass. Full tests run
in the pre-push hook. Device UI checks were not repeated; prior platform
verification limitations remain recorded on the PR.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): keep extensionless PDF downloads distinct

Use the existing file hash as the PDF identity salt when a remote URL does
not provide a .pdf filename. Keep the query-free title and original filename.
This prevents distinct query-selected downloads with identical metadata from
replacing one another's managed files.

Verified: the new extensionless-download regression failed before the fix
(expected two live books, received one), then all 147 affected tests passed.
pnpm lint passed with one unrelated informational notice; diff check passed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): retain extensionless PDF identity on reimport

Select the PDF identity salt from the preserved original filename rather than
the current input URL. Extensionless imports keep content-based identity when
the same files are reopened from local managed paths.

Verified: the extended two-download regression first failed because both
metadata hashes changed to the shared download stem. The correction preserves
both hashes, original names and live records without removing managed files.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): persist import provenance through cloud sync (owner: Can we simplify it?)

Add nullable books.original_filename, database mappings and blank-fill sync
merging so imported provenance survives cloud restoration and old clients.
Migration 031 must be applied before deploying the updated server.

Simplify PDF title/identity selection into three direct cases and normalize
the name once. Keep fallback metadata stable on managed-copy reimport and
refresh stale batch metadata keys after successful imports.

Verified: new regressions failed first for stale index keys, sanitized PDF
fallback titles, transform round trips and cloud filename merging. All 242
related tests pass, as do TypeScript, Biome lint and formatting checks. Actual
web imports, local reimports and reload preserve names and separate identities.
Migration applied twice successfully in isolated PostgreSQL, preserving null
legacy rows and round-tripping a Unicode filename. No live database changed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): resolve import filenames in openFile (owner: hide the filename parsing in openFile)

Have native and web filesystem openFile return a File whose name is the resolved
basename. Keep URL and Android provider resolution at that boundary and share
literal local-path basename parsing between the filesystem implementations.
The importer now reads fileobj.name without parsing the source path again.

Verified: eight new filesystem assertions failed before the changes for full
web paths, literal POSIX backslashes, question marks and percent-encoded-looking
local or supplied names. All 252 affected tests pass, as do TypeScript and Biome
lint. Existing importer mocks now provide resolved basenames; the obsolete
empty-name filesystem fallback test was removed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): resolve relative Windows import basenames

Normalize native Windows separators before extracting a local basename, so
relative and drive-relative paths satisfy the openFile name contract while
POSIX backslashes remain literal.

Verified: relative and root-relative Windows regression cases failed first
with directory components in File.name. The same POSIX relative name remains
literal. All 139 filesystem/importer tests and TypeScript/Biome lint pass.
Windows UI was not exercised on this Linux host.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve PDF identity and edited titles (owner: just use the origin filename as the default title)

Use the filename stem only as the initial PDF display title. Preserve stored
PDF titles and metadata hashes on exact-file reimport, and leave existing
books without filename provenance as they are. Keep the original content
hash and new-import metadata-hash calculations, removing content-salt and
managed-copy identity migration branches and their index maintenance.

Verified: two new regressions failed first because reimport replaced edited
or legacy titles and metadata hashes. All 81 importer tests now pass; lint
and whitespace checks pass. In the real web app, importing a PDF, editing
its title through Book Details, reloading, reimporting, and reloading again
preserved the edited bookshelf title, original filename, and both hashes.
Native UI was not repeated for this title-only simplification.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): clarify native filename branches (owner: Why the change is so ugly?)

Resolve URL and provider names within their early-return branches, then
select the local filename. Remove the overwritten mutable filename and
nested platform/path ternary while preserving existing naming behavior.

Verified with 141 passing native/web filesystem and importer tests, plus
TypeScript, Biome lint, and git diff --check. This is a control-flow cleanup;
no behavior change or new regression test is introduced. Native UI was not
repeated for this refactor.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-02 11:52:20 +01:00
Huang Xin
85db6faf49
fix(opds): allow trusted private catalogs at runtime (#7225)
Add the server-only READEST_TRUSTED_PRIVATE_HOSTS exact hostname allowlist
for self-hosted OPDS catalogs. Read it at request time, recheck redirects,
and preserve private-address and DNS checks for unlisted destinations.
Let self-hosted catalog forms submit LAN URLs and document Docker setup.

Verified: 113 focused and neighboring proxy tests passed; pnpm lint,
Biome formatting, pnpm build-web and Docker Compose configuration passed.
The same production build denied private hosts by default, then allowed
GET/HEAD with a runtime-only allowlist after restart. A fresh browser
added the LAN catalog and opened its publication feed.

Without the fix, the new OPDS proxy tests returned 400 instead of 200,
and the self-hosted catalog form never called validateOPDSURL.

Full-suite verification is unresolved: the default run had 4 timeouts
and a TTS timer teardown error; the 4-worker rerun had 6 timeouts and
4 worker startup failures. An unchanged-main comparison reproduced a
ControlPanelUpdateReset timeout. Related reliability tracking: #7217.
No Docker image build or reporter deployment verification was performed.

Reported by YorrickBao on GitHub.
Fixes #7105

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-01 17:26:53 +01:00
Huang Xin
bc7a5bfa54
feat(sync): record each book's synced read-aloud packs in its config (#7190)
* feat(sync): record each book's synced read-aloud packs in its config

Every Read Aloud open listed every sync destination for the book's audio,
including books that have none. The packs each destination holds now
travel in the book's config (BookConfig.ttsPacks, by destination id), which
every device already fetches when it opens the book:

- An open lists a destination only when the record names a pack this
  device lacks, or the destination was never recorded. A book without
  audio, once recorded, makes no request.
- A push needs no listing when every downloaded pack is already recorded
  there. With something to upload it still lists first, which checks the
  destination still takes the book (Readest Cloud) and skips what a peer
  uploaded.
- After a listing, the record for that destination is replaced with what
  it found (a declining destination as empty) and saved to the local
  config file at once.

The record merges as a union and never bumps updatedAt, so recording audio
cannot move reading progress: in config.json as its own envelope key, in
the Readest Cloud pull, and on the server, which grafts the union onto the
row whichever side wins it. Readest Cloud stores it in a new
book_configs.tts_packs column (migration 030).

Verified:
- Tests that fail without the change: engine.test.ts "makes no request
  when every pack is already recorded there" (`expected 1 to be +0`);
  tts-book-cache-store.test.ts "an open pulls nothing when every
  destination is recorded and nothing is missing" and "records what each
  listed destination holds, a declining one as empty"; merge.test.ts
  "unions both sides even when the remote config is older"; wire.test.ts
  "buildRemotePayload carries the synced read-aloud packs outside
  config"; transform.test.ts "round-trips the packs each destination
  holds"; sync-tts-packs-merge.test.ts (resolveTTSPacksMerge is new);
  useProgressSync.test.tsx "adds the read-aloud packs a peer recorded,
  without bumping updatedAt".
- dev-web, WebDAV only, request counter in the page: the first open of a
  book listed WebDAV once (404); after a reload, opening and starting Read
  Aloud made no audio-sync request; downloading a chapter listed once,
  created the folder and uploaded the pack; the config.json pushed to
  WebDAV carried `"ttsPacks":{"webdav":["1-4f4d1ca4.mp3"]}`; the next open
  made no audio-sync request.
- Not run in the app: the Readest Cloud half. dev-web uses the production
  database, which does not have migration 030 yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): never skip a push on the recorded read-aloud packs

Review finding (CodeRabbit): the record of each destination's packs only
grows by merging, so after a book's audio is purged from a destination
(the book removed from Readest Cloud) it still names those packs. A push
trusting it skipped the listing, so the device holding the audio never
uploaded them again, even after the book was uploaded again.

The record now only lets an open skip its pull. A device with downloaded
audio lists each destination once per open before pushing, as before the
record existed, and that listing corrects the record. A book without
downloaded audio still makes no request.

Verified: engine.test.ts "still uploads a recorded pack the destination no
longer holds" failed with the push still taking the record (`expected +0
to be 1`); with the parameter gone, tts-book-cache-store.test.ts "the push
never trusts the record, so purged packs are uploaded again" pins that the
round no longer hands it over (fails with the old call, `expected
"vi.fn()" to be called with arguments: [ Array(4) ]`). pnpm test (1217
files, 14485 tests), pnpm lint and pnpm format:check pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): keep pack records another sync merged while a round ran

Review finding (CodeRabbit): a sync round read the book's ttsPacks when it
started and wrote back that copy plus what it listed. The reader's
open-time pull can merge a peer's record while the round awaits its
listings, and the write-back dropped it. The round now starts from the
config as it is when it commits and replaces only the destinations it
listed.

Verified: tts-book-cache-store.test.ts "keeps an entry another sync merged
while the round ran" fails without the change (`expected "vi.fn()" to be
called with arguments: [ 'hash-rec6', { ttsPacks: { …(2) } } ]`). pnpm test
(1217 files, 14486 tests), pnpm lint and pnpm format:check pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): keep a pack merged into a destination while a round listed it

Review finding (CodeRabbit): a round replaced each listed destination's
record with its listing, so a peer's pack merged into that destination
after the listing began was dropped, and the next open skipped pulling
it. The listing now supersedes only the entries the round started with;
entries added since are kept.

Verified: tts-book-cache-store.test.ts "keeps a pack merged into a
destination while the round listed it" fails without the change
(`expected "vi.fn()" to be called with arguments: [ 'hash-rec7', …(1) ]`).
pnpm test (1217 files, 14487 tests), pnpm lint and pnpm format:check pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 04:01:24 +01:00
Huang Xin
5d2a939c28
fix(storage): check the quota after reserving the row and keep clients off files writes (#6820)
* fix(storage): reserve upload quota atomically and cap public image uploads

Check the storage quota and record the file row in one database call
(reserve_storage_upload, migration 029) that serialises a user's
reservations with an advisory lock and sums live file sizes under it, so
concurrent upload requests can no longer each pass against the same usage.
A reservation is released if signing the upload URL fails.

Require a positive integer fileSize on every upload path, and cap the
unmetered public cover/temp image uploads at 20 MiB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(storage): report re-upload usage without double counting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(storage): check the quota after reserving the row (owner: optimize the upload quota check instead of adding another layer)

The `files` row an upload writes is already its reservation, and the
trigger on `files` adds its size to `plans.storage_usage_bytes` in the
same transaction. So instead of migration 029's locked RPC, the upload
route now inserts the row first, reads the counter, and deletes the row
and returns 403 if it is over quota. Every accepted request checked after
its own row committed, so the last one to check counted all the others:
concurrent uploads can no longer pass against the same usage. A row is
also dropped if signing fails, and a re-upload of an existing key adds
nothing and is not re-checked. The fileSize validation and the 20 MiB
cap on cover and temp uploads stay.

Share import gets the same check. A fresh import used the token's frozen
usage claim, and restoring a soft-deleted copy was never checked at all;
both now check the counter once the row is live and undo it if over.

Migration 029 now revokes INSERT/UPDATE/DELETE/TRUNCATE on `files` from
anon and authenticated and adds CHECK (file_size >= 0). Only the API
routes write `files`, through the service role, but the grants let a
signed-in user write their own rows through the REST API directly:
insert a negative size, edit a size, or delete a row and keep its object.
init/schema.sql matches it for new installs.

Verified:
- storage-upload-quota.test.ts and share-import-quota.test.ts run
  against main's routes fail 12 and 2 cases: three concurrent uploads
  reach 608174080 bytes against a 524289000 limit; fileSize -1 and
  -107374182400 return 200 and leave a row; a failed signing leaves its
  row; a re-upload is counted twice; over-quota share imports and
  restores return 200 instead of 402. All pass with this change.
- Migration 029 applied twice to a local Postgres 15 `files` table with
  prod's policies and ALL granted to anon/authenticated: before it, a
  signed-in user set their own row's file_size to -5; after it, their
  insert, update and delete fail with "permission denied for table
  files", their select still works, and the service role cannot insert
  a negative size.
- pnpm test (1167 files passed), pnpm lint, pnpm format:check.
- Not run: an end-to-end upload in the app, or a concurrent burst
  against a real database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(storage): fail closed when the storage usage read fails

Both quota checks fell back to the token's frozen usage claim on any
error reading `plans`, so a transient database error let an upload or
share import pass on stale usage. Only a missing row (PGRST116) or a
missing `plans` table, as on self-hosted servers (PGRST205, or 42P01 from
older PostgREST), now falls back. Any other error returns 500 and undoes
the reservation: the upload deletes its new row, and share import
deletes a fresh row or soft-deletes a restored one again.

Raised by CodeRabbit on #6820.

Verified: the new cases in storage-upload-quota.test.ts and
share-import-quota.test.ts ("fails closed ... when the usage read
fails") fail on the previous head with "expected 200 to be 500" and pass
now; the fallback cases cover all three codes. pnpm test (1167 files
passed), pnpm lint, pnpm format:check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:29:27 +02:00
Huang Xin
385889d57d
feat(sync): sync the import-time page count across devices (#6775)
#6662 records a book's page count at import, but only on the importing
device. Other devices got a count only once someone opened the book, and a
cloud-only book could not be counted locally at all.

- Add a nullable books.page_count column (migration 028) and map it both ways.
  A pulled row without a count leaves the key off, so the pull merge keeps the
  local value.
- The server merge keeps the row winner's count and falls back to the other
  side's, so a push without one (old clients, the KOReader and Calibre
  plugins, devices that never counted the book) never erases it, and a server
  row missing a count gets it filled in without a date-read reorder.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:45:34 +02:00
Huang Xin
9bafc11120
feat(tts): custom OpenAI-compatible TTS services (#6746)
* feat(tts): custom OpenAI-compatible TTS services with BYOK

Closes #258.

Adds Settings > TTS > Custom TTS Services (premium, Full Customization):
users configure one or more OpenAI-compatible speech services (base URL,
API key, model, voices, optional instructions). Each service's voices
appear as their own group in the Read Aloud voice picker for every book
language.

- OpenAICompatibleSpeechProvider posts to {baseUrl}/audio/speech (mp3)
  behind BufferedTTSClient, so rate, caching and chapter downloads work
  as for other engines; highlighting is sentence-level (no word timings).
- 401/403/404 end the session, other 4xx skip the sentence, 429/5xx
  retry.
- SpeechProvider gains optional groupVoices (per-service voice groups)
  and cacheScope (model/baseUrl/instructions fold into the cache key so
  edits never replay stale audio).
- Services sync as the new custom_tts replica kind with the API key
  encrypted, with its own Manage Sync category; backups strip the key
  unless credentials are included.

Requires migration 027_replica_custom_tts.sql (replica kind allowlist)
to be deployed before clients ship.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(tts): voice picker that lists every engine dependably

Custom TTS services:
- Voices come from the service: GET {baseUrl}/audio/voices (names or
  {id, name} objects); a service without a listing gets the standard
  OpenAI voices. The editor no longer asks for voice names and Test
  reports how many voices the service offers.
- Custom voices are multilingual (lang `mul`): the picked voice is
  remembered and used for every language. Before, a pick never took
  effect and the first voice always spoke.

Readest Voice:
- Listed for every reader: `GET /api/tts/readest?all=1` returns the whole
  catalog with each voice's tier, and voices the reader's plan lacks are
  shown disabled. Without `all` the route answers released apps as
  before.
- Treated as always on: listing reads the catalog only and never checks
  the voice worker, and the app answers from the last list it received,
  refreshing it in the background, so a failed or slow request never
  hides the engine.
- A voice the plan lacks is never picked automatically, even a remembered
  one. Plus voices list before Pro ones, each by name.
- Dev builds use the production API for Readest Voice, which a local
  server cannot serve.

Voice picker:
- Groups ordered custom services, Readest Voice, Edge TTS, system, Web
  (after a book's own narration).
- An accordion: at most one group open, starting on the group of the
  voice in use, which stays marked and named while folded. The sheet
  keeps one height while folding.
- Badges (Plus, Pro, Multilingual, Expressive) align to the row end;
  Edge's Multilingual/Expressive suffixes become badges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(tts): a Readest voice the plan lacks leads to the upgrade

Tapping a greyed-out Readest voice opens the plans on the user page, or
sign-in for a signed-out reader, instead of doing nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(tts): list a custom service's voices by the book language

Kokoro names its voices by language (af_ American English, zf_ Mandarin,
...): those voices are offered only for books in their language, while a
voice without one (OpenAI's) still reads any language. A voice list that
states a language (lang or language) is used as given. A remembered custom
voice yields to the default engine for a book none of its service's voices
can read, as Readest Voice does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): sync a cleared custom TTS key and pick voices across services

- A cleared API key is saved as '' rather than undefined, so it syncs and
  other devices drop their copy instead of keeping the old key.
- The fallback voice for a language is looked up across every voice group,
  not only the first: a custom service without a voice for the book's
  language no longer hides one another service has.
- The auth page browser test mocks the new getReadestVoiceAPIBaseUrl.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): Readest Voice is available to every reader

The engine's init reported success only when the plan unlocked a voice,
so signed-out and free readers lost the whole engine. It now always
initializes; a voice the plan lacks stays listed but disabled and is
gated where it is picked or played (setVoice, setLang, the language
fallback, and the server). Opening the picker warms a worker only for
a reader with a playable Readest voice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:33:28 +02:00
esmaeelE
7893fa9167
Support handwriting annotation (#6674)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* Add handwriting annotations with optional BOOX pen support (#3673)

- services/handwriting: platform-neutral ink model (normalized,
  page-relative coords, versioned schema), coordinate transform,
  canvas renderer, editor with undo/redo/erase, capability detection,
  and BookConfig persistence (device-local, excluded from cloud sync
  like the existing paired-audiobook field). 44 unit tests.
- Generic pointer-event backend works everywhere (web/desktop/iOS/
  non-BOOX Android); BOOX raw-drawing is an additive fast path chosen
  automatically via detectPenCapabilities().
- Native bridge: query_pen_capabilities/start_raw_drawing/
  stop_raw_drawing/set_raw_drawing_enabled commands added to
  tauri-plugin-native-bridge (Rust: commands/mobile/desktop/lib/
  build.rs + permissions).
- BOOX Pen SDK isolated behind a new Gradle 'pen' flavor dimension
  (genericPen default / booxPen opt-in) so default/FOSS builds never
  add BOOX's Maven repo or dependency; rationale and build docs in
  android/README-pen.md. PenInputController interface keeps every
  Onyx SDK type out of NativeBridgePlugin.kt.
- Reader UI: HandwritingOverlay/Canvas/Toolbar + useHandwriting hook,
  mounted in BooksGrid next to FoliateViewer. PDF pages are keyed
  precisely by page index; EPUB ink is anchored per-section (documented
  limitation: reflow has no fixed page).

Verified: tsc --noEmit clean, biome clean, full handwriting test
suite green (44/44).

NOT verified (no Android SDK/NDK or BOOX hardware in this
environment): android/src/booxPen/** has not been compiled — see
android/README-pen.md for what to check before shipping the booxPen
flavor. The Rust plugin changes have not been built with cargo/tauri
CLI (not installed here) but follow the existing refresh_eink_screen
command's pattern exactly across every layer they touch.

* add handwritten

* chore(android): update icons and add Android build docs

- Regenerate app icons with pnpm tauri icon
- Simplify ic_launcher.xml via tauri android init
- Add ANDROID_BUILD.md with build instructions

* docs(android): document build fixes for Android APK build

- Java 21 requirement (Gradle 8.14.3 fails on Java 25)
- AGP downgraded from 8.11.0 to 8.7.3
- Aliyun Maven mirror for offline Google repo access
- buildToolsVersion 35.0.0 pinning
- compileSdk warning suppression

* test(browser): update annotation popup screenshots for added handwriting tool

* chore: drop Android icon regeneration and local build doc from PR

* fix(test): restore upstream ExportMarkdownDialog test and add getConfig mock

* refactor(handwriting): rework ink anchoring, persistence and BOOX pen path

Ink placement:
- Key fixed-layout ink by section index instead of the location counter,
  which collided for adjacent PDF pages.
- Anchor reflowable ink to the page-start CFI and reuse any stored anchor
  inside the visible range, so ink no longer repeats on every page of a
  chapter.
- Normalize fixed-layout ink to the page frame, so it follows zoom and pan.
- Disable handwriting in scrolled mode.

Persistence:
- Clearing the last inked page now sticks (the store merges partials).
- Imports update the store before the live editor reloads.
- Save on committed edits only, debounced to disk; simplify strokes on
  commit instead of on export.
- Ink written by a newer schema is never overwritten.

UI:
- Enter via View menu > Handwriting Mode; drop the always-visible floating
  button and the selection-popup tool.
- Single toolbar below the safe-area inset; no color swatches on B&W e-ink.
- The Notebook falls back to Notes when the Handwriting tab has nothing to
  show; rows are labelled by chapter and sorted in reading order.
- JSON export works for books that only have ink.
- Drop the restyle feature.

BOOX:
- Run the pen SDK on the WebView with density scaling, close the previous
  session on restart, and deliver each stroke on pen-up with normalized
  pressure.
- Only use raw drawing when an EMR pen digitizer is present, so pen-less
  readers keep finger drawing.
- Make the opt-in booxPen flavor build: repository in the app module,
  support-library exclusion, libc++ pickFirst, no stripping of prebuilt SDK
  libraries, and R8 rules.
- Remove the unused set_raw_drawing_enabled command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): tap ink to edit it; show every anchor on a reflowed page

- A single tap on existing ink enters handwriting mode instead of turning
  the page. Single clicks now carry their main-window position so overlays
  can hit-test them.
- A reflowed page shows the ink of every anchor in its visible range, not
  just one, so a smaller font no longer hides ink drawn on the next page.
  Eraser, Clear Page and Undo cover all of them as one step; new strokes
  go to the page's primary anchor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): pin reflowable ink to the content it marks

Ink in reflowable books was stored in page coordinates, so any font,
spacing or margin change left it over the wrong text. Each stroke is now
bound to content and re-placed from the current layout:

- Ink over text or images binds to the range of words and elements it
  covers (underlines bind to the line above) and is stored normalized to
  that range's box. Re-fitting to the new box keeps its shape and topology
  through font size, font family, line height and margin changes.
- Margin ink binds to the nearest character and scales uniformly; strokes
  written in one burst share an anchor so a note stays in one piece.
- Reflowable ink is keyed per section; the notebook labels rows by the
  chapter of the inked text and jumps straight to it.
- Fixed-layout ink stays normalized to the page, which already tracks
  zoom and pan.

This replaces the page-start anchors and the multi-anchor workaround.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): drawings as annotations; shape-aware morphing

Each drawing is now an `ink` booknote: listed with the other annotations
in the left sidebar (pen icon and the text it marks), navigable and
deletable there. A reflowable book gets one note per anchor, a fixed-layout
book one per page. Ink notes travel by file sync; Readest Cloud has no field
for stroke data yet, so they are kept out of its push. The notebook's
Handwriting tab and the separate handwriting import/export are removed; a
notebook canvas is left for a follow-up.

Pinned ink now morphs by its shape:
- flow (underline, strike-through): follows its words, split per line on a
  re-wrap; marks are resampled so they stay continuous.
- box (circle, box, scribble): fitted to the content it encloses, so an
  edge brushing the next line no longer widens it to the whole line.
- span (bar or bracket beside a paragraph): stretched along its lines,
  kept at its distance from the text edge.
- rigid (margin notes): moves and scales with the nearest character.
Boxes are measured within one column, so a range wrapping onto the next
page can no longer blow a drawing up across two pages.

Ink also shows in scrolled mode (read-only) for every loaded section or
page, and follows a PDF pinch live instead of jumping when it commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): redesign drawing mode; one annotation per session

- Drawing starts from a pen button in the reader header (the View menu
  item is gone; tapping existing ink still opens it for editing).
- While drawing, the reader's header and footer give way to the mode's own
  bars: a top bar (Drawing, Done) and a bottom dock with the pen (color and
  size in a popover), eraser, undo, redo and page turning. Nothing can cover
  Done any more.
- Strokes still save as they are drawn, but everything drawn in one visit
  to drawing mode is one annotation in the sidebar, instead of one per
  stroke. Each stroke keeps its own text anchor (or page in fixed layout).
- A short underline that encloses nothing binds to the word it marks,
  rather than to whichever character happened to be nearest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): draw in scrolled mode

Scrolled views show several sections (or PDF pages) at once, so drawing
was limited to paginated mode. Each finished stroke and eraser sweep is now
routed to the section or page it is drawn over, pinned with that section's
text anchoring (or normalized to that PDF page), while the live stroke
draws over the per-section ink layers. Undo follows the page last drawn
on, and the dock's arrows scroll a screen at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): stronger strokes and room for the drawing bars

Pen widths are heavier (default 0.006 of the page width) and a finger
stroke no longer carries pressure: touch reports contact size, not
pressure, which thinned every finger stroke. Ordinary pen pressure now
draws the full pen width, so existing strokes render stronger too.

Drawing mode lives in the reader view state, and the viewer reserves
the top bar and dock bands in its margins (paged) and scroll padding
(scrolled) while it is on, the way the TTS mini player does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): draw committed strokes as smoothly as live ones

A stroke was simplified on commit to within a pixel and then drawn as a
polyline, so small loops turned angular and pressure changed in steps
once the pen lifted. Keep points to a fifth of a pixel and wherever the
pressure changes, and draw strokes as quadratic curves through the
samples. Also add the drawingEnabled view state to two test fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): fill pen strokes as one antialiased outline

A pen stroke was stroked as many short pieces of different widths. Each
piece antialiased its own edge with round caps, so at every joint the soft
edges blended twice and the width stepped, which read as a jagged edge
next to native ink. Trace the stroke's outline around samples every 1.5px,
with the width interpolated along the curve, and fill it once. A single
contour has no inner edges for the rasterizer to blend, and points where
the inner side of a tight turn would fold back are skipped so no hole
opens there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): start every drawing session with the pen

The eraser toggle outlived the drawing session, so turning drawing back on
after erasing left the eraser active and the first strokes wiped ink
instead of drawing, which looked like strokes were not being recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): keep a Pencil stroke drawn right after a tap

iOS WebKit read a quick tap followed by a drag as its own double-tap or
text-selection gesture and withheld that touch from the page entirely, so
the stroke never reached the canvas. touch-action: none only stops panning
and zooming. The drawing surface now cancels the default of its touch
events, which leaves the touch sequence to the page while pointer events
still arrive, and is unselectable with no callout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): draw from the instant annotation tools, save from the dock

Draw moves from its own header button into the header's instant
annotation tools. The top drawing bar is gone: its Done becomes a save
icon as the dock's last button, and only the dock's band is reserved
below the text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): add a marker tool beside the pen

A marker draws a broad translucent band of even width with flat ends, for
highlighting what is under it. It is stroked as one path, so it does not
darken where it crosses itself, while separate marks still mix where they
cross. It ignores pressure, keeps its own highlighter colors and widths,
and the eraser sizes itself to one marker band instead of three. The dock
shows pen, marker and eraser side by side; tapping the active tool opens
its options. Marker ink is stored with tool: 'marker'; pen ink is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): match the pen and marker buttons to the rest of the dock

The tool buttons used a different icon set and a wider pill with a color
dot and caret. They now use the dock's line icons in the same square
button, with the active tool's ink color as a thin band under its icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sidebar): lead each annotation with an icon for its kind

Bookmarks, highlights, notes and drawings each start with a small round
badge, so the kind of an item reads at a glance. The badge carries the
kind's name for screen readers and replaces the inline pencil drawings
used to show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): save a drawing and keep drawing; close from the dock

Save now finishes the current drawing as one annotation and stays in
drawing mode, so the next strokes start a new annotation, with a short
toast when there was ink to save. A Close button at the end of the dock
leaves drawing mode. Strokes are still saved as they are drawn, so
neither discards anything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sync): sync handwriting strokes through Readest Cloud

Adds an ink jsonb column to book_notes (migration 026, folded into the
base schema) and carries ink notes through the notes sync instead of
leaving them to file sync only.

- The sync transform maps strokes to and from the column. Other notes
  never send the key, so an upsert does not clear stored strokes, and a
  pulled row without strokes carries no key, so merging it cannot wipe
  strokes held locally.
- Drawings are pushed when they change and never get an xpointer, which
  keeps every KOReader plugin version from importing one as a highlight.
- Committed points are rounded to 1/10000 of the page (pressure to
  1/100), which more than halves what each drawing stores and syncs.

The column has to exist before a server running this code receives a
drawing, so apply the migration to the database first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Readest Agent <agent@readest.local>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 21:31:38 +02:00
Huang Xin
8076905ce5
feat(translation): custom translation providers with a prompt library (#6582)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(translation): custom translation providers with a prompt library

Users can add their own translation backends and use them anywhere Readest
translates (inline translation, the translator popup, the updater):

- OpenAI-compatible LLM (OpenAI, DeepSeek, OpenRouter, SiliconFlow, Gemini,
  Ollama, LM Studio, ...): base URL + key + model. Concurrent paragraph
  requests are coalesced into numbered batches; a reply with the wrong block
  count falls back to one request per paragraph. Reasoning blocks are stripped.
- DeepL with the user's own Free/Pro key (app only; DeepL sends no CORS
  headers).

AI translators use a prompt library: a built-in Default prompt plus named
user prompts with {{sourceLang}} {{targetLang}} {{bookTitle}} {{bookAuthor}}
placeholders, chosen per book. Output-format rules are appended by code, and
the cache key folds in the model and the rendered prompt so edits yield fresh
translations.

Requests go straight from the device through getAIFetch; custom providers
never touch the Readest translation quota. Providers and prompts sync as the
custom_translator / translation_prompt replica kinds under one "Translators"
category, with apiKey encrypted; backups strip the key unless credentials are
included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(translation): address review on custom translators

- Strip only a leading <think> block so a quoted </think> survives.
- Make the DeepL 429 retry wait abortable and cap Retry-After at 10s.
- Associate the editor labels with their inputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(translation): load the AI SDK lazily in the custom LLM translator

The reader imports the translator registry unconditionally, and the AI SDK
pulls in Node-only modules at import time, which broke the browser test that
imports useTextTranslation. Load ai + @ai-sdk/openai-compatible once, on
first use. Also drop the DeepL retry-wait abort listener once the wait ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(translation): stop the LLM request timeout once the reply arrives

tauriFetch cancels its request from the signal's abort listener and leaves
that call's rejection unhandled. With AbortSignal.timeout, the timer fired
60 s after every finished request and raised "The resource id ... is
invalid". The timeout is now a cleared timer on an AbortController.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(translation): make custom translators a premium feature

Custom translators follow the other premium features (isCustomizationAllowed:
Plus, Pro, Full Customization, or a self-hosted deployment). The check reads
the session token, so a reader never treats a premium user as free while the
plan loads.

- Settings: the Custom Translators row shows a Premium badge and routes free
  users to the plans page and signed-out users to sign-in.
- Runtime: custom providers carry premiumRequired; isTranslatorAvailable
  excludes them without premium, so inline translation, the popup and the
  updater fall back to a built-in provider. The dropdowns list them as
  "Name (Premium)", disabled, and the Prompt row is hidden.
- NavigationRow gains an optional badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(translation): customizable font, style, size and color for translated text

Language settings gain a Translated Text group: Font (the book's, or the
reader's serif, sans-serif or monospace font), Font Style (normal, italic,
bold, bold italic), Font Size (relative to the paragraph) and Text Color.
The rules go on .translation-target-block, so translated TOC entries keep
their look, and the defaults leave translations styled like the book.

The color is saved when the picker closes, not on every drag tick, and the
settings are not rewritten for a profile saved before these keys existed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(translation): give the popup layout browser test a decodable token

The premium check for custom translators decodes the session token, and
'test-token' is not a JWT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(translation): relabel the popup's providers when the session changes

The popup derived provider labels and disabled flags only when the
translator list changed, so a sign-in or a token refresh that changed
premium eligibility left "(Premium)" or "(Login Required)" stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(translation): accept batch markers followed by text on the same line

Small local models such as gemma3 reply "[1]Translation…" instead of
putting the marker on its own line. The strict split rejected every such
batch and re-sent each paragraph on its own, so a batch cost one wasted
request. The block count and 1..n order checks still guard the split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(translation): start translating when it is switched on in Settings

The reader's translation hook only re-runs when the viewSettings object
changes. Settings saved Enable Translation in place, so the book stayed
untranslated until it was reopened. Publish a new object, as the toolbar
toggle and the provider and prompt selects already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(translation): batch 4 paragraphs per LLM request, 4 requests in flight

Measured against deepseek-flash and a local gemma3 with the reader's
scheduling on 16 paragraphs: batches of up to 8 with 2 in flight made the
first paragraph wait 2-4x longer than smaller batches, while total time
was unchanged and smaller batches cost only a few percent more prompt
tokens. 4 x 4 roughly halves the wait for the first translation and keeps
half of batching's request savings for rate-limited free tiers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sync): allow the custom_translator and translation_prompt replica kinds in the database

The replica API accepted the two new kinds, but the replicas_kind_allowlist
CHECK did not, so every pushed row would have failed to insert. Migration
025 extends the CHECK (NOT VALID, then VALIDATE, as in 023), and a test now
fails when KIND_ALLOWLIST holds a kind the latest migration does not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 13:58:02 +02:00
Huang Xin
9703d46113
feat(crosspoint): plugin updates, version display, and sync for optimized EPUBs (#6592)
* feat(crosspoint): check for plugin updates from the web settings card

The Readest card on CrossPoint's web Settings page shows the installed
plugin version and a Check for update button. Like the KOReader plugin,
it reads latest.json from download.readest.com through the device relay.
Update streams the release zip to the SD card, unpacks it with the JSZip
the device already serves, and writes each file into the plugin's folder,
manifest.json last, so an update cut short is offered again.

CrossPoint never shows a plugin's version on the reader, so the release
job now stamps it at the start of device.json's description, which the
reader's plugin list shows under Readest. The committed manifest version
becomes 0.0.1, so a copy made from the repo is offered the release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(crosspoint): keep syncing books rewritten by Optimize EPUB

CrossPoint's File Manager can optimize an EPUB on upload. That rewrites
the file, so its KOReader partial MD5 no longer matches the Readest book,
and progress sync and reading statistics lost track of it.

Sign-in now turns on KOReader Sync's Send metadata, so progress uploads
carry the book's title and authors. An upload under an unknown document
id links it to the one library EPUB with that title (the first author
breaks ties), stored in the new crosspoint_documents table (migration
025), without moving Readest's position back on that first upload.
Progress reads, progress uploads and reading sessions then follow the
link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(crosspoint): fail instead of syncing a copy under its own id on a database error

A failed link lookup, library query or link write counted as "not
linked", so a linked copy's reading session was recorded under the
copy's own hash, a progress read answered 404, and a progress upload
was saved under the copy's hash and acknowledged. The link helpers now
report the error like a query, and the routes answer 500 so the reader
retries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(crosspoint): compare every library book with a copy's title

The title lookup stopped at 20 rows in no particular order, so with more
books sharing a title it could miss Readest's own file or a second book
that fits, and link a copy it should have left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 13:37:10 +02:00
Huang Xin
54c089f362
feat(crosspoint): Readest plugin for CrossPoint e-readers (#6547)
* feat: Readest plugin for CrossPoint e-readers

Adds an SD-card plugin for CrossPoint firmware (Xteink X3/X4) that signs in
to Readest from the reader's web settings page, lets the reader browse,
search and download the EPUBs in the user's Readest cloud library, and adds
each on-device reading session to Readest reading statistics.

The device pages its catalog by number, so a new GET /api/library/books
lists the caller's uploaded EPUBs a page at a time. It returns one lookahead
row past per_page: CrossPoint requests page_size + 1 rows and drops the last
one, so stepping pages by the requested row count would skip a book per
page. Each item links to the existing /api/storage/download route.

The firmware renews tokens with a password grant, so the password is stored
on the SD card, JSON-escaped for the firmware's raw template substitution
and kept in dotfiles the reader's web server refuses to serve. Reading
sessions post statPages only, keyed by the partial MD5 the firmware already
computes, which is the book_hash Readest uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(crosspoint): sync reading progress through CrossPoint's KOReader Sync

Readest now acts as the KOSync server for the CrossPoint plugin, so reading
progress syncs between CrossPoint and Readest without configuring a sync
server. Signing in on the plugin's card mints a per-device key and points
the reader's built-in KOReader Sync at /api/crosspoint with binary document
matching, so books match by the partial MD5 Readest uses as book_hash.

The KOSync-compatible routes read and write the same book_configs row the
apps already sync: a push stores the XPointer, scaled progress and a fresh
updated_at, and keeps the library row's progress current like /api/sync; a
pull returns the XPointer Readest last synced. Readest apps apply it when
they open the book.

Device keys live in a new table (migration 024), stored as sha256 of the
md5 KOSync clients send, readable only by the service role. The reader's
web API never returns the KOSync password, so the plugin keeps the key's
random id in its non-secret account file and revokes by id at sign-out.
Sign-out only clears KOReader Sync settings that still point at Readest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(crosspoint): ask before replacing a KOReader Sync server, email username

The plugin card gains a "Sync reading progress" checkbox. It starts on when
KOReader Sync isn't set up on the reader or already points at Readest, so
the default stays zero-config, and off when the user set up another server,
naming that server. Signing in with it off leaves KOReader Sync alone (and
revokes this reader's key if it had one); sign-out shares the same logic.

The KOSync username is now the account email, a label for the reader's
settings: the server authenticates a device by its key alone, so the
setting stays readable and survives an email change. key_hash becomes
unique.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(crosspoint): sign readers in with a device code and a per-device key

The plugin stored the account password on the SD card, and anyone on the
reader's network could rewrite device.json through the device's
unauthenticated plugin-fs endpoint to send that password elsewhere. Readers
now sign in with a code their owner approves on the new /link page and get
their own revocable key, never a password. The key authenticates the
catalog, downloads, reading sessions and KOReader Sync, under
/api/crosspoint.

- Device sign-in: /device/code, /device/token and /device/approve, an OAuth
  device grant. The reader shows the code and a QR of the link; the plugin's
  web card runs the same flow and also points KOReader Sync at Readest.
- Reading sessions are spread over the pages they covered in the book's
  Readest page count, or in 1% steps until a Readest app paginates the
  book. Reading-speed estimates leave out events longer than a page visit.
  Unrecordable sessions are acknowledged rather than refused, since the
  reader's event queue stops at the first failed delivery.
- Progress pushes keep the percentage for unpaginated books, never
  overwrite a newer config, and never pull back a position the reader has
  not seen. Key lookup failures are server errors, not 401s.
- The plugin records keys before handing them out, retries revocations
  that failed, revokes before clearing the card at sign-out, and serializes
  sign-in and sign-out.
- Catalog: stable order by date added, literal search, clamped paging,
  and titles that can be saved as file names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(crosspoint): keep an approved sign-in when minting its key fails, list untitled books

- device/token claimed the approved code before inserting the key, so a
  failed insert threw the approval away and the owner had to start over.
  The claimed row now goes back on failure.
- books.title is nullable; an untitled book made the whole catalog page
  fail. It is listed under its hash instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(release): attach the CrossPoint plugin zip to releases

Like the calibre and KOReader plugins: stamp the release version into
manifest.json and upload Readest-<version>.crosspoint-plugin.zip, which
holds the readest/ folder to copy to the SD card, with the install guide
inside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 12:48:25 +02:00
Huang Xin
63bb079760
feat(library): add configurable bookshelves (#6329)
* feat(library): add configurable bookshelves and migrate preferences

* fix(bookshelves): harden offline persistence and replica sync

* fix(library): refine bookshelf editing layout and selection

* i18n: translate bookshelf management across all locales

* docs: document bookshelf behavior and review fixes

* docs: clarify missing values in bookshelf filters

* fix(bookshelves): address CI and sync review feedback
2026-09-21 08:47:42 +02:00
Tomi Hietala
05e8bd4523
docker: pull minio images from quay.io, Docker Hub removed them (#6196)
minio/minio and minio/mc 404 on Docker Hub now (MinIO discontinued free
Docker Hub distribution, pushing toward their paid AIStor product) -
docker pull fails with "repository does not exist or may require 'docker
login'", which reads like an auth problem but isn't (confirmed: neither a
fresh Docker Hub login nor a specific pinned version tag helps, since the
repo itself is gone). quay.io/minio/minio and quay.io/minio/mc still work,
no login needed.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-16 17:27:50 +02:00
Huang Xin
731b13ab6f
fix(docker): unbreak large uploads and self-hosted cloud sync (#6100)
* fix(web): stop truncating request bodies over 10MB (#6091)

`middleware.ts` matches /api/*, so Next buffers a clone of every non-GET
request body. Past `experimental.proxyClientMaxBodySize` (10MB by default)
`getCloneableBody` pushes null into both the middleware's stream and the one
`finalize()` splices back over the IncomingMessage, so the route handler sees a
short body ending cleanly: no error, no 413, just a stored file of exactly
10,485,760 bytes. `/api/send/inbox/file` accepts 40MB, so an inbox EPUB over
10MB was already being stored corrupt.

The clone is buffered in memory before any handler can reject it, which makes
the ceiling an unauthenticated memory budget on every /api/* route. Only the
self-hosted image, which may proxy whole book files through the Node server,
gets real headroom; `standaloneOutput` is the gate because BUILD_STANDALONE is
set by the Dockerfile alone and web.readest.com runs on Cloudflare/Vercel.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(settings): stop gating cloud sync as Premium when self-hosted (#6093)

Two causes of the same symptom on a self-hosted Docker deployment.

The badge keyed off sign-in, not entitlement:

  !user || (userProfilePlan !== undefined && !isCloudSyncPremium)

`!user` short-circuits, so a signed-out self-hoster — the normal state right
after `docker compose up` — got a Premium chip on WebDAV, Google Drive, S3 and
OneDrive. The rows opened fine and sync was never paused, but the chip reads as
"not available in this deployment". `shouldShowCloudProviderBadge` decides on
entitlement instead: self-hosting unlocks with or without a signed-in user.

`SELF_HOSTED` also only reached the container through `compose.yaml`
(`${SELF_HOSTED:-true}`), which landed in #5996. A compose file copied before
that survives every `docker compose pull`, so those deployments came up gated
with nothing on screen to explain why. The image now defaults it on: it is the
self-hosted artifact, web.readest.com never runs it, and an operator selling
plans still overrides with SELF_HOSTED=false.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(settings): clarify that the tier chip still gates signed-out visitors

The doc comment described what changed rather than what the predicate does, so
"entitlement is the deciding input, not sign-in state" read as if signed-out
users stopped being gated. They are not: a signed-out visitor to a hosted
deployment is not entitled, so the row is badged and stays behind
canToggleCloudProvider and the upgrade route, exactly as before. Only
entitlement — which self-hosting confers — removes the chip.

Assert the pairing in one test so a future refactor cannot decouple the badge
from the gate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 17:56:25 +02:00
Huang Xin
b80d83534e
feat(payments): separate storage and customization entitlements, unlock all when self-hosted (#5996)
* feat(payments): gate premium features on Full Customization

Premium access was any of plus, pro or purchase, and `getUserProfilePlan`
reports `purchase` for anyone holding ANY one-time purchase, which is how
a storage add-on presents. Buying space therefore unlocked cloud sync,
TTS download and Send to Readest as a side effect.

Route every premium gate through one predicate: a paid subscription, an
outright Full Customization unlock, or a self-hosted deployment.
`PREMIUM_PLANS` is plus and pro only; `purchase` is deliberately absent,
because that is exactly the value a storage-only buyer reports.

* isCloudSyncAllowed, isTTSCacheAllowed and isEmailInPlan now take the
  customization claim and delegate to isCustomizationAllowed. Both server
  routes under pages/api/send move with them, so the client and the
  server cannot disagree about who is entitled.
* Self-hosted deployments unlock everything, signed in or not. There is
  no store to buy from and the operator already runs the infrastructure
  the paywall funds. SELF_HOSTED is wired through runtimeConfig the same
  way STORAGE_FIXED_QUOTA is, and defaults to true in docker.
* STORAGE_GRANTS_CUSTOMIZATION keeps storage add-ons unlocking
  customization during the launch grace period. It drives a durable
  payment row rather than a derived rule, so switching it off cannot
  revoke anyone who bought while it was on: updateUserStorage is the only
  writer of customization_purchased and reruns on every later purchase.
  Recording the grant never fails the purchase it rides on.
* Google Play acknowledges a permanent unlock instead of consuming it.
  Consuming is what lets a SKU be rebought, which storage needs and an
  unlock must not have. isConsumablePurchase is an allowlist: an
  unrecognised product that cannot be repurchased is caught in testing,
  while wrongly consuming an unlock costs a user real money. It is still
  acknowledged, or Play auto-refunds after three days.
* The Lifetime card shows Full Customization as unlocked once owned,
  reusing the Current Plan chip so the card footers stay aligned.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(payments): clear the customization entitlement on sign-out

Three review findings.

The module-level entitlement cache survived a sign-out. `useQuotaStats`
returned early when there was no user or token, so nothing reset it, and
`resolveCloudSyncGate` reads it synchronously for non-React gates: a
signed-out session could still be treated as premium. Clear both caches
on that path, falling back to the restrictive side, which is how these
caches are already documented to behave before the first auth
resolution.

`customizationPurchased` is now derived from the token rather than held
in state. State lags a render behind a token change, which briefly
reported the previous account's entitlement after a switch.

`SELF_HOSTED` set to an empty string masked `NEXT_PUBLIC_SELF_HOSTED`,
because `??` only falls back on null or undefined, silently re-locking a
self-hosted deployment. Use `||` in both `isSelfHosted` and
`getServerRuntimeConfig`.

The Arabic and Turkish `Unlocked` strings inherited "open" from the
longer "Unlock All Customization Options" phrase, which reads as
"opened" when the word stands alone on a status chip. The remaining
locales keep their established verb deliberately.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(payments): cover the real sign-out path for the entitlement caches

The existing test called setCachedCustomizationPurchased directly, so it
pinned the wiring between the cache and the gate but never ran the
cleanup in useQuotaStats. Deleting that cleanup would have left it
green, which is exactly the regression it was meant to catch.

Drive the hook through renderHook instead: render with a session, then
rerender without one, and assert both caches are cleared and the derived
value flips in the same pass. Verified by removing the cleanup and
confirming the test fails, then restoring it.

The cache-to-gate wiring test stays; it covers a different link.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 07:37:42 +02:00
Huang Xin
80f196a9b8
fix(sync): resolve book groups and metadata on their own clock (#5911, #5912) (#5921)
* fix(sync): resolve book groups and metadata on their own clock (#5911, #5912)

Book groups (#5911) and book descriptions (#5912) are one defect: `groupId` /
`groupName` and the `metadata` blob were resolved on the whole-row `updatedAt`
clock with raw, clearing assignment, so a copy of a row that had neither could
overwrite a copy that had both.

`updatedAt` is stamped by operations that have nothing to do with either. The
important one is uploading: `cloudService.uploadBook` sets
`updatedAt = Date.now()` so the fresh `uploadedAt` reaches peers, and
`transferManager` runs uploads as a queue — which is exactly the reporter's
"19 records with sequential updatedAt within ~8 seconds". Those rows were never
re-grouped, they were re-uploaded, and that made them outrank every genuine
grouping edit that came before.

Two more things completed the chain. `isReadestCloudEnabled` falls back to
`enabled ?? !hasAnyThirdPartyEnabled`, so a WebDAV user's group edits never
reach Readest Cloud while a clean install (no backend configured yet) restores
those stale ungrouped rows on sign-in. And the pull side used a strict `>` while
the push side rebuilt library.json from the local rows unconditionally, so a TIE
did not mean "no opinion, keep both" — it meant "local wins, the peer's data is
destroyed", which is how the emptied rows propagated back to every device.

Group membership now merges on its own `groupUpdatedAt` / `group_updated_at`,
mirroring reading_status_updated_at (015, #4634), cover_updated_at (017, #4544)
and metadata_updated_at (018, #5438) across the schema, the server merge, the
Readest Cloud client merge and the third-party file-sync merge, and stamped at
every group mutation site.

One deliberate difference from those three: an unstamped TIE does NOT fall back
to the row winner — the side that actually has a group wins. Every existing row
is unstamped, so without this the fix would only prevent new damage and leave
already-broken libraries broken; instead the device that still has the groups
republishes them. "Never grouped" and "ungrouped by a client too old to stamp"
are indistinguishable on a tie, erasing a real group is unrecoverable, and
losing an un-group is not. A stamped removal still propagates, so the #4942
contract holds on the right clock (its merge.test case is restamped).

For #5912, an absent `metadata` blob now never wins on any clock. Nothing in the
app empties `book.metadata` — the editor edits fields inside it — so an absent
blob always means "this row never had one", never "the user cleared it".

The two clock-free repair clauses would otherwise fire for a whole library at
once on the first run after the fix, costing a cover GET and a config GET per
book and breaking the O(changed) contract of incremental sync. `engine.ts` gates
those pulls on `isRemoteBookClockNewer`; the repair path touches index fields
only, with regression tests asserting zero cover/config reads.

Shipping this needs a deploy, not just a client release: it adds migration 022
and changes the server-side books merge.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(sync): keep the group/metadata repair off the incremental path

Incremental sync is O(changed) by contract. The repair clauses added in
af4c3355 broke that: `isRemoteBookMissingLocally` is true for an ENTIRE library
at once on the first run after the fix, and each hit calls
`store.updateBookMetadata` -> `useLibraryStore.updateBook` ->
`saveLibraryBooks`, which serializes and rewrites the WHOLE library file plus
its `.bak`. A 181-book library whose rows all need a group back would do 181
full-library writes on an ordinary background sync — quadratic in bytes, for a
repair nobody asked for at that moment. Gating the cover and config GETs, as
that commit did, addressed the requests and missed the writes.

The repair moves to Full Sync, which is already where this engine reconciles
`uploadedHashes` / `emptyDirs` drift and row-vs-filesystem split-brain.

Stopping the DAMAGE does not need any of it, and is now free. The propagation in
#5911 / #5912 is entirely a PUSH-side effect: the index re-push rebuilds
library.json from the local rows, so a device whose row merely tied the row
clock republished its ungrouped, description-less copy over the peer's good one.
`resolvePublishedBook` resolves each row against the remote index entry as the
push walks the map it already walks — no request, no library write — and makes
the narrow claim that publishing must never DELETE what the remote already had.
This device's row still wins the row on its own clock.

So an incremental run now never repairs and never writes, yet can no longer
empty a peer's shelf; Full Sync is what puts a device's own groups and
descriptions back.

Both guards are mutation-checked: dropping `resolvePublishedBook` flips 2 tests
red, dropping the `fullSync` gate flips 1.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(sync): resolve the metadata group on its own clock when publishing

Review follow-up on #5921. `resolvePublishedBook` preferred any non-empty
`local.metadata`, so a device holding an older description could publish it over
a peer's newer one.

Not reachable under 'silent': the reconcile pass resolves the metadata clock
into the local row before the push, and a test now pins that. It is reachable
under 'send', which applies nothing from the remote and therefore skips the
reconcile block entirely — leaving `resolvePublishedBook` as the only thing
between a peer's newer description and a stale local blob. #5900 established
that a send run may publish its own rows but must not erase what peers
contributed to the index; this is the same invariant for a field rather than a
row.

Resolved as a GROUP (title / author / tags / blob / stamp move together), the
way `mergeBookMetadata` resolves it, so the published row cannot pair one
device's title with another's description. The never-delete fallback still
applies whichever side wins the clock.

Mutation-checked: pinning the winner back to `local` flips the send test red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 15:22:35 +02:00
Huang Xin
6834ee42ef
fix(stats): survive PostgREST's row cap when building archive segments (#5844)
* fix(stats): survive PostgREST's row cap when building archive segments

stat_archive_rows is called through PostgREST, which caps every response at
db-max-rows (1000 on Supabase). The LIMIT 10000 never survived the wire, so
segments silently held 1000 rows, and the truncation could cut inside a run of
rows sharing one updated_at (a push chunk shares one now()): the commit's
range delete then removed rows that were never archived, surfacing as
commit_mismatches during validation.

Migration 021 makes the pair loss-proof under any proxy truncation:
stat_archive_rows trims the trailing millisecond unless the page provably
holds every row of it (whole-millisecond extension only for the
single-millisecond page), so every result ends at a complete millisecond; and
stat_archive_commit refuses with P0001, rolling back the manifest insert and
the delete, when the range's delete count differs from the declared segment
row count.

The compact route now assembles each segment from sub-pages of at most 1000
rows, advancing p_from per sub-page until STATS_COMPACT_SEGMENT_ROWS or a
drained user (only an empty page means drained; a short page can just mean
the trailing millisecond was trimmed), writing one object and one commit per
assembled segment, and counting a refused commit as a mismatch plus an error.
The verification script applies 021 and asserts the trim, the equal-timestamp
run, the covered-millisecond keep, the single-millisecond extension and the
refusal rollback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(stats): keyset-paginate archive rows so no proxy row cap can wedge or lose data

Review found the remaining hole in the trim design: a millisecond holding more
rows than db-max-rows made the single-millisecond fallback return more than
p_limit, PostgREST truncated it to the same first 1000 rows every time, the
cursor stopped advancing and the sub-page loop repeated the identical page
forever (or, cut differently, produced a refused commit). A restore can create
such a millisecond: it re-inserts 500-row chunks, each stamping one now().

stat_archive_rows is now a plain keyset pager over (updated_at, book_hash,
page, start_time) with three tie-cursor parameters (the 020 signature is
dropped). Keyset pages are truncation-proof by construction: any cap only
shortens a page, the cursor comes from rows actually received, and the tie
columns paginate inside a millisecond of any size. The compaction route owns
the boundary policy: assemble pages until the segment target plus a complete
millisecond to cut at (or a drained user), trim the trailing millisecond
unless it is provably closed (drained and ended at least 60 s before the
window cutoff), defer a user whose only eligible rows sit in a still-fresh
millisecond, and hard-stop a pathological millisecond beyond 50k rows.

Regression tests: 1001 equal-timestamp rows in one millisecond become one
segment with no repeated page and no refused commit; a mid-millisecond target
cut trims and the next segment refetches the remainder; a still-fresh
millisecond defers the user. The SQL script asserts keyset tiling, the
tie-cursor resume inside an equal-timestamp run, and the refusal rollback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 15:07:01 +02:00
Huang Xin
9b33b52a40
feat(stats): tier stat_pages history into R2 segments behind a 7-day hot window (#5835)
* feat(stats): tier stat_pages history into R2 segments behind a 7-day hot window

stat_pages is an append-only per-user log of page events merged by longest
duration; the server never reads history for analytics and devices union-merge
everything locally, so keeping the whole history in Postgres is the most
expensive way to store it.

Migration 020 adds a second tier. Postgres keeps a hot window (updated_at
younger than 7 days by default); a cron job (POST /api/stats/compact, driven
by a scheduled() handler in a custom OpenNext worker entry) compacts older
rows per user into immutable JSON segments in R2, listed in the stat_archives
manifest. The commit RPC inserts the manifest row and deletes exactly the
archived (from, to] range in one transaction, compare-and-set on the user's
archived_to under a per-user advisory lock; segments never split a
millisecond, and objects are never deleted by the compaction path.

The stats pull composes pages server-side: hot rows are read before the
manifest (a concurrent commit can only duplicate, never lose), then the first
segment that still has rows past the cursor is served (paged, trailing
millisecond completed) or the hot rows; unpaginated pulls get every segment
then hot rows. The sync API, the app and the koplugin are unchanged.

Also: POST /api/stats/restore (rollback, re-inserts a user's segments through
upsert_stat_pages_as and drops the manifest rows; refuses while compaction is
enabled), account deletion removes the user's archive objects before the auth
user, a local PostgreSQL 15 verification script for the migration, and
docs/stats-archive.md. Ships disabled (STATS_COMPACT_ENABLED = "false").

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(stats): record one Analytics Engine point per archive-backed stats pull

Hot-only pulls write nothing; a pull that reads R2 segments writes one point
(indexes ['pull'], blobs ['paged'|'full'], doubles [segments_read, rows,
limit]) to STATS_COMPACT_AE. The share of pulls that reach the archive is the
number that should drive STATS_COMPACT_WINDOW_DAYS; we ship with 7 days.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(stats): targeted compaction run for one user, plus the deployment runbook

POST /api/stats/compact with a JSON body {"user_id"} compacts that user only:
no claiming, the enabled flag is ignored (operator action, usable while the
cron is off) and the batching thresholds are ignored (everything older than
the window is archived). Still token-guarded; malformed ids answer 400. This
is what lets the rollout validate on a known account in production before the
cron is enabled, and drain one heavy user by hand.

docs/stats-archive.md gains the step-by-step deployment guide: migration
check queries, bucket and secret creation, disabled deploy and its checks,
validation on one account (targeted run, manifest/object checks, fresh pull
on a device or through the API, optional restore), enabling the cron, the
Analytics Engine and Postgres checks to watch, the post-drain REINDEX, and
the window revisit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(stats): address review on the archive tier

- Account deletion: delete the identity first, then queue the user id in a
  new service-role-only stat_archive_orphans table and delete the R2 prefix
  best-effort; batch compaction runs sweep the queue (kill switch on or off)
  until each prefix lists empty. Deleting objects before a failed deleteUser
  would have left an active account with its history gone.
- stat_archive_state and stat_archive_orphans: RLS enabled and privileges
  revoked from PUBLIC/anon/authenticated so PostgREST does not expose them;
  the verify script asserts relrowsecurity on all three tables and that
  anon/authenticated cannot read the service-role-only ones.
- Compact route: only an empty body is the cron's batch request; every other
  body must be a valid {user_id} targeted request or it is a 400, so a typo
  never starts a batch run. Guard: 503 (no token/bucket), 401, then the
  kill switch, applied by the route after the orphan sweep.
- Paged stats pull fills a page across tiers: segments are read lazily until
  they fill the page, short archive pages are topped up with hot rows and
  the page is cut at limit with the trailing millisecond kept, so a client
  that stops on a short page (the koplugin) never stalls on a tier boundary.
- Restore reads the manifest page by page (PostgREST caps responses at 1000
  rows) until it is empty.
- Config knobs reject digit strings beyond the safe integer range.
- worker.ts logs a rejected cron fetch; the [limits] cpu_ms block is dropped
  (the job is I/O-bound and the ceiling would apply to every request).
- Tests: PostgREST mocks now apply eq/gt filters and honor range/delete so
  the query contract is exercised; rpcMock is cleared between tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(stats): refresh the compact route header comment for the reworked guard order

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(stats): address review round 2 on the archive tier

- The stats pull reads the stat_archives manifest in range pages (PostgREST
  caps a response at 1000 rows) and appends hot rows only once a short final
  page proves no archived rows remain past the cursor; a paged pull stops
  fetching manifest pages as soon as its response page is full. A truncated
  manifest list could otherwise let a client cursor skip segments. Regression
  test with 1001 single-row segments, unpaginated and paged.
- Account deletion writes the stat_archive_orphans tombstone BEFORE anything
  destructive and stops with 500 (retryable) if even that fails; a failed
  deleteUser compensates the tombstone; the orphan sweep additionally skips,
  keeping the row, any queued user that still exists, so a stale tombstone can
  never wipe a living account.
- The compaction loop asserts each segment boundary advances past the previous
  millisecond before writing the object. stat_archive_rows extends every
  segment to the end of its last millisecond, so consecutive segments cannot
  share an ms-keyed object name; the assertion turns a future SQL regression
  into a loud per-user error instead of a silent object overwrite.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 07:12:16 +02:00
Huang Xin
71b07b44ff
perf(sync): merge stat_pages pushes in one upsert_stat_pages RPC (#5832)
The stats push fetched the batch's existing rows (user_id = ?, book_hash IN,
start_time IN), decided longer-duration-wins in JS, then upserted in a second
round trip. That lookup ran about 9 req/s in production (17% of DB time) and
on PG 15 re-walks the whole (user_id, book_hash) primary-key range once per
start_time array element, because start_time sits after the unconstrained
page column of the PK.

Migration 019 adds public.upsert_stat_pages(jsonb): a single INSERT ... ON
CONFLICT DO UPDATE ... WHERE EXCLUDED.duration > stat_pages.duration that
probes the PK exactly, collapses duplicate keys inside a batch to the longest
duration, stamps user_id from auth.uid() and updated_at from now(), and runs
SECURITY INVOKER so the stat_pages RLS policies stay in force. The push
handler now calls the RPC per 500-row chunk; pickWinningPages is gone.

Deploy order: apply migration 019 before deploying this API change.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 06:48:45 +02:00
Huang Xin
73e933eb33
fix(docker): apply db migrations on first boot and let the font CDN be overridden (#5550) (#5551)
* fix(docker): apply db migrations on first boot and let the font CDN be overridden (#5550)

A fresh self-hosted stack only ran volumes/db/init/schema.sql, so the
incremental files under volumes/db/migrations never reached the database.
Deployments came up without files.replica_id, the replicas table and the
claim_inbox_item RPC, which broke uploads, replica sync and Send to Readest.

Mount the migrations directory into the db container together with an
apply-migrations.sh hook named so it sorts after the supabase image's own
migrate.sh. It globs the mounted directory, so a new migration file needs no
compose change, and it records what it applied in readest_meta.migrations so
it can be re-run by hand after an upgrade.

The reader also loaded its CJK webfont bundles from storage.readest.com, which
only sends CORS headers for readest.com origins, so they were blocked on a
custom domain. Read the base URL from runtime config via FONT_BASE_URL and keep
the CDN as the default.

Let SUPABASE_PUBLIC_URL and S3_PUBLIC_ENDPOINT be set directly instead of only
being derived from HOST_IP, so the stack can be served from one HTTPS origin.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(docker): add an example nginx config for a single HTTPS origin

Keeps the template out of the README as a copyable file next to .env.example.
Routes / to the client, /auth/v1 and /rest/v1 to kong, and the bucket prefix to
minio with the Host header preserved so presigned signatures still verify.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 10:19:44 +02:00
Huang Xin
165e3192ae
fix(sync): merge book metadata on its own clock so page turns cannot clobber edits (#5438) (#5442)
A metadata edit (title, author, tags, metadata incl. language) shares the
books row with page-turn progress, which dominates updated_at: any device
that reads the book after the edit pushes a stale-metadata row with a newer
updated_at and whole-row LWW reverts the edit server-side; on pull, the
locally-read book keeps its stale copy. RSS feed books are read daily on
every device, making the loss near-deterministic (issue #5438).

Give the metadata group its own field-level LWW timestamp, the same fix
reading_status (#4634) and the cover (#4544) received:

- migration 018 adds books.metadata_updated_at (nullable, additive)
- getBookWithUpdatedMetadata stamps it on every metadata edit; the ingest
  subject-tag append stamps it too since tags ride the metadata clock
- the server merge resolves the group by the stamp on both row outcomes,
  with a value-level no-op guard; an unstamped-vs-unstamped tie follows the
  row winner so legacy rows keep their historical behavior
- useBooksSync grafts the fresher group client-side and recomputes
  primaryLanguage (what TTS reads) from the adopted metadata, also when
  adopting a new cloud book
- the file-sync mergeBookMetadata mirrors the clock, and
  shouldApplyRemoteBookMetadata triggers on a metadata-only-newer remote
- the calibre plugin stamps metadataUpdatedAt when a push changes the
  group and carries the server stamp otherwise

The other half of the issue, feeds missing on Android entirely, is the
already-merged #5314 which is not in the shipped 0.11.20 builds.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-02 15:46:39 +02:00
Huang Xin
082edc204b
fix(sync): sync updated book covers across devices (#4544) (#4731)
* docs: design for syncing updated book data (cover + file) (#4544)

Cover-change sync via a content hash (coverHash = partial MD5 of cover.png)
plus a cover_updated_at field-level merge timestamp; file updates ride the
existing re-import / metaHash dedupe.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(sync): sync updated book covers across devices (#4544)

Editing a book's cover wrote cover.png locally but changed no hash (the
cover is keyed by the file hash), so peers had no signal to re-download it
and the change never propagated.

Give the cover its own content-addressed version:
- coverHash = partial MD5 of cover.png; a peer re-downloads the cover iff
  the synced hash differs from the local one (idempotent, no churn on
  identical/re-extracted covers — compatible with the metaHash dedupe).
- coverUpdatedAt = field-level LWW timestamp so a page-turn that wins
  whole-row LWW on updated_at can't clobber a cover edit (mirrors the
  reading_status_updated_at fix for #4634).

Editing a cover recomputes the hash, bumps coverUpdatedAt, and re-uploads
only the cover; the server merges cover fields independently; peers
re-download on a hash diff. File updates continue to ride the existing
re-import / metaHash dedupe (changed file -> changed hash -> re-key).

Migration 016 adds cover_hash / cover_updated_at to books.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:31:03 +02:00
Huang Xin
9155ae627c
feat(sync): decouple the incremental-pull cursor from updated_at via server synced_at (#4678) (#4712)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
PR checks / test_extensions (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(sync): decouple the incremental-pull cursor from updated_at (#4678)

`books.updated_at` was overloaded as both the incremental-pull cursor
(`GET /api/sync?since=…` filters `updated_at > since`, devices keep one
global `max(updated_at)` watermark) and the library "date read" sort key.
A server-resolved reading-status merge had to be written with a timestamp
greater than every peer's global cursor to propagate, which forced
`updated_at = now()` and reordered the date-read library by sync-processing
time (the #4677 symptom).

Introduce a server-assigned `synced_at` column on `books`, stamped by a
`BEFORE INSERT OR UPDATE` trigger on every write, used only as the pull
cursor. `updated_at` stays pure client event time used only for sorting.

- Migration 016 + baseline schema: add `synced_at` (NOT NULL DEFAULT now()),
  index `(user_id, synced_at)`, trigger `set_books_synced_at`. Backfill
  `synced_at = updated_at` before creating the trigger so existing devices'
  cursors hand over without a re-sync storm.
- GET: books filters/orders on `synced_at > since` (a delete bumps synced_at,
  so the deleted_at clause is dropped); configs/notes stay on updated_at.
- POST: extract `buildStatusPropagationRow` and drop the `updated_at = now()`
  bump — the trigger advances synced_at so peers re-pull the status change
  while updated_at (the sort key) stays put.
- Client `computeMaxTimestamp` keys on synced_at, falling back to
  updated_at/deleted_at for pre-migration servers and configs/notes.

Backward-compatible: `synced_at >= updated_at` always, so `synced_at > since`
is a strict superset of `updated_at > since` — old web clients and the
koplugin keep working with no data loss (at worst a redundant idempotent
re-pull of rare server-merged rows). The koplugin's shared pull/push cursor
is left untouched; a proper split is a follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(sync): make the books synced_at backfill safe for large live tables (#4678)

The single `UPDATE … WHERE synced_at IS NULL` deadlocked on a 3.8M-row
production `books` table: it rewrites every row in one transaction while the
live /api/sync push path upserts books rows, and the two lock rows in opposite
orders. `ALTER COLUMN … SET NOT NULL` (full-table ACCESS EXCLUSIVE scan) and a
plain CREATE INDEX (write-blocking SHARE lock) compounded it.

Rework migration 016 as an online migration (run via psql, not in a wrapping
transaction):
- backfill in small autocommitted batches via a procedure, using
  FOR UPDATE SKIP LOCKED so it never waits on an app-locked row;
- CREATE INDEX CONCURRENTLY instead of a blocking build;
- install the trigger last (so it can't clobber the updated_at backfill);
- drop the hard SET NOT NULL (the default + trigger + backfill keep the column
  populated and the client falls back to updated_at); a NOT VALID CHECK +
  VALIDATE alternative is included, commented, for operators who want it.

The baseline schema.sql (fresh, empty installs) keeps the simple inline
NOT NULL DEFAULT now() + trigger.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 21:24:01 +02:00
Huang Xin
72233e1c6a
feat: sync reading status across devices and with KOReader (#4634) (#4656)
* docs(sync): design spec for syncing reading status (#4634)

Field-level LWW for reading_status (dedicated reading_status_updated_at),
a new 'abandoned' status in the Readest UI, and a koplugin bridge to
KOReader's native summary.status (whole-library apply + capture).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(sync): implementation plan for syncing reading status (#4634)

Bite-sized TDD tasks across 3 parts: A) cloud field-level LWW
(reading_status_updated_at on server upsert + client pull-merge),
B) 'abandoned'/On-hold status in the Readest UI, C) koplugin bridge
to KOReader summary.status (mapping + reconcile + whole-library
apply/capture).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(sync): add reading_status_updated_at for field-level status LWW (#4634)

* feat(sync): stamp readingStatusUpdatedAt on status change in updateBookProgress

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(sync): stamp status timestamp on explicit library status edits

* feat(sync): resolve reading status by its own timestamp in client pull-merge

* feat(sync): resolve reading status by its own timestamp in server upsert (#4634)

* fix(sync): tighten reading-status merge typing + strengthen test (A5 review)

Replace as-unknown-as double-casts at read sites with typed locals
(clientBook/serverBook); retain a single as-unknown-as only at the
server-wins construction site where the static type is too narrow.
Strengthen test 3 to assert both fields with toEqual.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(library): render the 'On hold' (abandoned) status badge

* feat(library): add 'Mark as On hold' actions + i18n for abandoned status

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* i18n: translate 'On hold' and 'Mark as On hold' for the abandoned status (#4634)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(koplugin): add reading-status mapping + reconcile between Readest and KOReader

* feat(koplugin): persist + sync reading_status_updated_at in LibraryStore

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(koplugin): bridge reading status to KOReader summary.status on library sync (#4634)

* test(sync): cover koplugin v1->v2 migration + tighten status-sync tests (final review)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(sync): redesign KOReader first-sync (decisive-only + bootstrap) (#4634)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(koplugin): safe first-sync of reading status (decisive-only + bootstrap) (#4634)

KOReader auto-sets summary.status='reading' on first open, and legacy Readest
statuses have reading_status_updated_at=0, so pure timestamp LWW let opening a
finished book downgrade it. Restrict sync to deliberate statuses (finished/
complete, abandoned/on-hold, unread->clear); never capture KO 'reading'/'New'.
On the unsynced baseline (Readest ts=0) conflicts resolve Readest-authoritative,
then stamp now_ms to exit bootstrap into steady-state LWW. reconcile now returns
write_ko/write_store flags; statussync captures now_ms once and equalizes both
sides (convergent, idempotent, resumable).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(koplugin): cover remaining first-sync graph cells + document sort effect (review)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 05:00:40 +02:00
Huang Xin
35b02c4efc
feat(statistics): KOReader-compatible reading stats with cross-device sync (#4606)
Supersedes #3156. Adds a reading-statistics system whose canonical data model
is KOReader's own (book + page_stat_data), so stats round-trip losslessly
between Readest and KOReader.

- Storage: a cross-platform Turso statistics.db in KOReader's exact schema
  (web/Workers, desktop, iOS, Android) — replacing #3156's Node-only
  better-sqlite3 + statistics.json.
- Tracking: per-page reading events (time-on-page, idle-capped) flushed on
  page-change/idle/hide/close — the KOReader model — not session aggregates.
- Sync: legacy /api/sync extended with a stats type backed by self-contained
  Supabase tables (stat_books, stat_pages); union/longer-duration-wins merge
  keyed on book_hash. apps/readest.koplugin syncs through the same endpoint.
- Scale & robustness: per-tab singleton connection (avoids OPFS lock
  conflicts) + explicit WAL checkpoint; transactional bulk apply; chunked
  resumable push; client-driven paged pull with trailing-ms completion;
  paginated/scoped server merge.

Verified: 5668 unit tests, 155 koplugin busted tests, biome+tsgo + luacheck
all green; web OPFS DB verified live.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 10:42:39 +02:00
Amir Pourmand
b8d986cbd6
fix(docker): fix Docker image latest tag and production runtime errors; add dev compose file, Codespace support, and semver release tagging (#7) (#4277)
* fix: also tag Docker image as latest on main branch push

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/bbc0f66e-7488-4d9d-976b-434588b3faa8



* fix: production Dockerfile missing patches/.env.web; add compose.dev.yaml for dev hot-reload

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/e27bba4e-b8ea-4694-b44d-6308aa778d41



* fix: add devcontainer to init submodules; add clear Dockerfile error when submodules missing

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/16d24ae0-d2e8-4523-b47e-4969dd587c50



* simplify production-stage: COPY --from=build /app /app instead of selective copies

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/356fabe4-f944-48b6-a409-41640480d52f



* fix: add CI=true to dev compose to prevent pnpm no-TTY abort

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/ddc30fef-2c76-452d-aad6-d688ca912a1a



* fix: add semver Docker image version tags on release

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/18cbc3c6-ba92-4e63-bef9-93dcf6698c21



---------

Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
2026-05-23 10:39:15 +08:00
Amir Pourmand
9ad43aa8b2
feat(docker): add GHCR and Docker Hub image publishing (#4250)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / publish (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* Add GHCR and Docker Hub image publishing with fully runtime-configurable pull-first Docker setup (#1)

* feat: add container image publishing workflow and pull-based compose setup

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/23c31167-9e15-4d44-ab89-f267b8cd6304

* refine docker publishing workflow and pull-first compose docs

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/23c31167-9e15-4d44-ab89-f267b8cd6304

* chore: temporarily expose docker publish run results for pr branch

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/c946a2f2-2219-4dea-a829-61b287bc4859

* fix: update pinned SHAs for setup-qemu-action and setup-buildx-action to v3 heads

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/0db6957e-476b-48e0-acf3-bee6964c3b32

Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

* chore: switch all workflow action refs from SHA pins to stable version tags

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/19334b37-9b4c-45df-9c3c-81a497cef8e8

Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

* fix: restore missing `with:` blocks lost during SHA-to-tag substitution

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/f204f742-5b7d-4f05-9647-03b9db86ea3d

Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

* fix(ci): checkout submodules for docker image workflow

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/72309e8a-6c7c-4004-902a-565f67e5c15f

Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* feat(docker): support runtime client env for pulled web image

* refactor(web): serve runtime config via script endpoint

* fix(web): escape runtime config script payload

* fix: align docker runtime config with internal/public backend urls

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/3bbcb608-6202-4f9e-b288-5c95a259da93

Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

* chore: align published workflow tags with docs

* docs: clarify runtime config precedence and linux host mapping

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/3bbcb608-6202-4f9e-b288-5c95a259da93

* refactor: move storage/quota config from build args to runtime env

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/da9b749e-0b1c-47b9-b474-5009765b6ea6

Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

* fix: load runtime config in pages router app shell

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/b375132c-8317-4c98-b437-ae48c0153e3d

Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

* fix: apply biome formatting for runtime config quota helpers

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/778f5d75-884e-401b-b7cb-4ab40bc64a11

Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>
Co-authored-by: Amir Pourmand <pourmand1376@gmail.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* fix: S3_PUBLIC_ENDPOINT, _document.tsx for beforeInteractive, runtimeConfig fallbacks, README port (#2)

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/4f92f818-c008-4caa-9684-d530500b5fb2

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

* fix: reformat runtimeConfig.ts to satisfy biome formatter (#3)

Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/4eea77f4-67ab-4428-b59e-0b21be988037

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com>

---------

Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-21 19:57:35 +02:00
loveheaven
ae81cd0151
feat(annotator): support global highlights that fan out across all matching positions (#4257)
Introduces a 'global' annotation flag so a highlight/note created on one occurrence of a phrase is automatically applied to every matching occurrence in the book (and stays applied across reloads). Renders these expansions as transient overlays without creating duplicate persisted notes. This flag will not show when the book is fixed layout like PDF or CBZ.

- types: add 'global?: boolean' to BookNote and DBBookNote; transform layer round-trips the field, with regression coverage ensuring older clients do not clobber it on write-back.

- db: new migration 013_add_book_notes_global.sql adds nullable 'global' column to public.book_notes; init schema.sql updated to match.

- annotator: new utils/globalAnnotations.ts handles cfi expansion / text-match search across the spine and overlay synthesis. Annotator.tsx fans out global notes on load and on overlay creation; AnnotationPopup and HighlightOptions expose a toggle to mark a highlight as global.

- sync path is transparent: a global note created on another device is fanned out locally on next render with no extra UI required.
2026-05-21 18:59:07 +02:00
Huang Xin
0b18de0581
feat(send): Send to Readest — multi-channel capture into your library (#4230)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(send): Send to Readest — multi-channel capture into your library

A Send-to-Kindle equivalent: email, web-upload, share, or one-click
capture books and articles into the cloud library; they sync to every
device.

Architecture (client-side processing): out-of-app channels drop a raw
payload into a per-user send_inbox; Readest clients drain it through one
shared ingestService.ingestFile(). The server never parses or converts.

- ingestService.ingestFile() — channel-agnostic import orchestration
  extracted from library/page.tsx (DI-based, forceUpload support).
- send_addresses / send_allowed_senders / send_inbox tables + RLS + 4
  SECURITY DEFINER claim/lease RPCs (migration 012_send_to_readest.sql).
- Conversion subsystem (DOCX/RTF/HTML/article/TXT -> EPUB) in a Web Worker.
- send-email Cloudflare Email Worker; inbox-drainer controller +
  useInboxDrainer hook; /api/send/* routes.
- Send to Readest settings panel: inbound address, approved-sender
  allowlist, recent activity, per-device drain toggle.
- /send web page (file drop + article URL) + SSRF-guarded fetch-url proxy.
- OS-shared files routed through ingestFile; Manifest V3 browser extension.

Security: inbox state changes only via SECURITY DEFINER RPCs (clients get
SELECT-only on send_inbox); approved-sender allowlist gates email;
SSRF guard on the one server-side URL fetch; inbox payload signed URLs
authorize against send_inbox.user_id.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: run format:check in the pre-push hook

Biome format checking is fast (~0.4s), so gate pushes on it too — catches
mis-formatted files that bypassed the staged-only pre-commit hook before
they reach CI.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(send): address CodeQL security findings

- ReDoS (senders.ts): the email regex had ambiguous quantifiers around
  the literal dot. Rewrote it linear-time (domain labels exclude '.')
  and cap the input at 254 chars.
- XSS (convertToEpub.ts): run untrusted HTML through DOMPurify
  (sanitizeForParsing — keeps document structure) before DOMParser, so
  title extraction and Readability never parse executable markup.
- SSRF (fetch-url.ts): harden the host guard — block bare single-label
  hostnames, IPv4-mapped IPv6, CGNAT/benchmark/multicast ranges, and the
  unspecified address. DNS rebinding stays a documented residual risk.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:06:52 +02:00
Huang Xin
6e7c9d1395
feat(sync): bundled settings replica kind for cross-device prefs and credentials (#4094)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(sync): add bundled `settings` replica kind for cross-device prefs and credentials

Adds a single-row `settings` replica that syncs a whitelist of
`SystemSettings` fields across devices via per-field LWW (one entry
per dot-namespaced path). Plaintext for theme / highlight colour /
TTS configuration; encrypted (AES-GCM under the user's sync
passphrase) for kosync / Readwise / Hardcover credentials.

Highlights:
- Push-side diff against an in-memory snapshot for plaintext paths
  and a localStorage SHA-256 hash for encrypted paths, so a refresh
  doesn't re-publish or re-prompt for the passphrase.
- Pull-side cipher-fingerprint dedupe + per-row passphrase gate;
  decryption failures surface as toasts (wrong passphrase / orphan
  cipher) instead of silent drops.
- Auto-recovery for orphaned ciphers: when a row references a
  saltId no longer in `replica_keys`, clear the local hash and
  re-encrypt under the current salt on the next save.
- Single in-flight `/sync/replica-keys` fetch with a value cache
  to coalesce the boot-time burst of concurrent unlock callers.

* fix(sync): guard settings dot-path helpers against prototype-polluting keys

Reject `__proto__`, `constructor`, and `prototype` segments in the
settings adapter's `readPath` / `writePath`. Every caller currently
passes a constant from `SETTINGS_WHITELIST`, so the guard is purely
defensive — but it silences the CodeQL prototype-pollution warning
on PR #4094 and keeps the helpers safe if a future call site ever
forwards an untrusted path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 19:03:23 +02:00
Huang Xin
712d564e9d
feat(sync): encrypted OPDS credentials + Tauri keychain (PR 4c + 4d) (#4090)
* feat(sync): encrypt opds_catalog credentials end-to-end (TS path)

Wires encrypted-credential sync for opds_catalog via the CryptoSession
shipped in PR 4a (#4084) plus a new publish/pull crypto middleware.
TS-only — native still uses ephemeral storage (re-enter passphrase per
launch); PR 4d wires the OS keychain.

- ReplicaAdapter gains optional `encryptedFields: readonly string[]`.
  Adapters stay sync; the middleware handles the crypto round trip.
- replicaCryptoMiddleware.ts: encryptPackedFields drops the named
  fields from the push when the session is locked (no plaintext
  leak); decryptRowFields drops them on pull failure (local
  plaintext preserved by the store merge).
- replicaPublish / replicaPullAndApply invoke the middleware.
- OPDS adapter declares encryptedFields = [username, password] and
  now pack/unpack them as plaintext.
- passphraseGate.ts: ensurePassphraseUnlocked coalesces concurrent
  calls, prompts via the registered prompter with kind=setup|unlock,
  throws NO_PASSPHRASE on cancel.
- PassphrasePromptModal mounted at the Providers root; registers
  itself as the gate prompter.
- CryptoSession.forget() wipes server-side envelopes + salts.
- Migration 010 + replica_keys_forget RPC; DELETE
  /api/sync/replica-keys + client wrapper.
- SyncPassphraseSection on the user page: status / Set / Unlock /
  Lock / Forgot.
- CatalogManager pre-save: ensurePassphraseUnlocked when credentials
  are present; user cancel saves locally without sync.

Plan updated: PR 4 split documented as 4a/4b/4c/4d.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(sync): persist sync passphrase via OS keychain (Tauri)

Replaces the EphemeralPassphraseStore stub on native with real
OS-keychain storage so users don't re-enter their sync passphrase
every launch. Web stays on the in-memory ephemeral store by design.

Native bridge plugin gains 4 commands wired across all platforms:

- Rust desktop (`keyring` crate): macOS Keychain on apple-native,
  Windows Credential Manager on windows-native, Linux libsecret/
  Secret Service on sync-secret-service. Per-target features so each
  platform compiles only the backend it needs.
- iOS Swift: Security framework Keychain (kSecClassGenericPassword,
  SecItemAdd / Copy / Delete).
- Android Kotlin: androidx.security EncryptedSharedPreferences
  (AndroidKeystore-derived AES-GCM master key,
  AES256_SIV / AES256_GCM key/value encryption).

TS layer:

- TauriPassphraseStore wraps the bridge calls. set is fail-loud
  (surfaces keychain rejection); get is fail-soft (returns null on
  any error so the gate prompts).
- createPassphraseStore returns ephemeral synchronously;
  upgradeToKeychainIfAvailable swaps the singleton to
  TauriPassphraseStore on Tauri after probing the bridge. CryptoSession
  resolves the store via createPassphraseStore() each touch so the
  swap is transparent.
- CryptoSession.tryRestoreFromStore: silent unlock at boot. Stale-
  entry recovery clears the store when the account has no salt
  server-side. unlock/setup persist; forget also clears the store.
- Providers boot effect: upgrade keychain → silent restore.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sync): make encrypted-credential pull actually decrypt + UX polish

PR 4c shipped the encrypt path but the pull side silently dropped
ciphers when locked, the modal was busy with double-rings, and web
re-prompted on every page refresh. This rolls up the post-test
fixes + UX polish:

Pull-side decrypt:
- decryptRowFields takes an `onLocked` callback the orchestrator
  wires to the passphrase gate; encountering a cipher field with a
  locked session now triggers the lazy-prompt path instead of
  dropping the field.
- replicaPullAndApply re-applies the unpacked row for metadata-only
  kinds even when a local copy exists, so the now-decrypted creds
  reach the store (the binary-kind skip-if-local optimization
  doesn't apply).
- Cipher fingerprint comparison: capture the row's `cipher.c` for
  each encrypted field, compare against the local record's
  lastSeenCipher. Same → skip prompt + decrypt entirely. Different
  (rotation / value change on another device) → prompt to
  re-decrypt. Fingerprint persists via OPDSCatalog.lastSeenCipher.

Web persistence:
- SessionStoragePassphraseStore: passphrase survives page refresh
  within the same tab, dies on tab close. Replaces
  EphemeralPassphraseStore as the default on web. Avoids
  localStorage / IndexedDB to keep the tab-scoped trust boundary.

UI:
- Renamed PassphrasePromptModal → PassphrasePrompt; modernized: filled
  input style with single subtle focus border, btn-primary +
  btn-ghost replaced with leaner custom buttons. eink-bordered +
  btn-primary classes give the dialog correct e-paper rendering.
- globals.css: suppress redundant outline/box-shadow on focused text
  inputs / textareas (the element's own border is the focus
  indicator).
- AGENTS.md: documents the e-ink convention (`eink-bordered`,
  `btn-primary` for inverted CTAs, etc.) so future widgets ship with
  e-paper support.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 13:22:49 +02:00
Huang Xin
6bfeb295d2
feat(sync): add opds_catalog replica kind (plaintext fields) (#4087)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
Wires OPDS catalogs through replica sync as a metadata-only kind.
Plaintext fields only in this PR — encrypted credentials (username,
password) ship in the follow-up alongside the SyncPassphrasePanel UI
and Tauri keychain backend.

- Migration 009 extends the kind allowlist with 'opds_catalog'.
- replicaSchemas adds opdsCatalogFieldsSchema (name, url, description,
  icon, customHeaders, autoDownload, disabled, addedAt) with a 50-row
  per-user cap.
- New opdsCatalogAdapter is metadata-only (no `binary` capability).
  Stable cross-device id from md5("opds:" + url.lower()) so two
  devices that import the same URL converge to one row instead of
  duplicating.
- New customOPDSStore (zustand) hydrates from SystemSettings,
  publishes upserts/deletes through the replica pipeline, preserves
  local-only username/password when overlaying remote updates, and
  strips tombstones at the persistence boundary so existing
  useSettingsStore readers (useOPDSSubscriptions, pseStream,
  app/opds/page.tsx) need no migration.
- replicaPullAndApply branches on adapter.binary so metadata-only
  kinds skip the bundleDir requirement and the manifest/binary path.
- CatalogManager rewires Add / Edit / Remove / Toggle / Add-popular
  through the new store.

Plan update bundled in: tenet 8 (scalar settings sync via a bundled
row; collections sync per-record), per-kind allowlist now includes a
`settings` singleton that will collapse PRs 5 + 6+ into one bundled
adapter, and PR 4 is split into 4a (already merged) / 4b (this) / 4c
(encrypted credentials + UX).

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 05:33:18 +02:00
Huang Xin
35227ecd61
feat(sync): wire crypto session for encrypted-field sync (#4084)
Adds the per-account PBKDF2 salt endpoint and an in-memory CryptoSession
that derives keys lazily per saltId. Lets future kinds (OPDS catalogs in
PR 4b) encrypt/decrypt fields without re-deriving on every operation.

- Migration 008: replica_keys_{create,list} RPCs round-trip the bytea
  salt as base64; SECURITY INVOKER, RLS-gated by the existing replica_keys
  policies.
- /api/sync/replica-keys GET/POST endpoint matches the dual app/pages
  shape used by /api/sync/replicas.
- ReplicaSyncClient.{listReplicaKeys,createReplicaKey} wraps the endpoint.
- CryptoSession.{unlock,setup,encryptField,decryptField,lock} caches
  derived keys per saltId; foreign envelopes trigger a lazy re-list +
  derive. Iterations injectable so tests run with PBKDF2 ITER=1000.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 20:05:04 +02:00
Huang Xin
981579c255
feat(sync): cross-device custom font sync (#4077)
* refactor(sync): kind-agnostic replica primitives

Extract dict-only sync into shared primitives (registry, pull/apply
orchestrator, persist env, schema allowlist) so other kinds can plug
in. Companion changes: per-replica Storage Manager grouping,
useReplicaPull boot-race recovery, manifest=null reconciliation on
every boot pull, copyFile takes explicit srcBase + dstBase, settled-
event helpers, lenient webDownload Content-Length (R2/S3 signed URLs
commonly omit it), and generic "File" transfer toast copy any replica
kind can share.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(sync): cross-device custom font sync

Plug the font replica adapter into the kind-agnostic primitives:
font store gains replica wiring, custom font import publishes the
replica row + queues a binary upload, and bootstrap registers the
font adapter and download-complete handler.

Includes legacy flat-path migration so pre-existing fonts sync
without re-import, full @font-face activation on auto-download
(load + mount the rule, mirroring manual import), and a fix to
createCustomFont so contentId / bundleDir / byteSize survive the
trip through addFont — otherwise import-time publish silently
no-oped on missing contentId.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 08:28:44 +02:00
Huang Xin
cbdc3b8f52
feat(sync): wire dictionary store through replica sync (follow-up to #4075) (#4076)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(sync): cross-device dictionary sync

Custom MDict / StarDict / DICT / SLOB dictionaries now sync across
signed-in devices via the replica layer.

- Store mutations publish replica rows with field-level LWW + tombstones.
- Re-importing the same content (renamed or after delete) preserves the
  user's label and reincarnates the server row instead of duplicating.
- Manifest commits after binary upload so other devices never see a row
  whose binaries aren't on cloud storage yet.
- Pull-side orchestrator creates a placeholder dict, queues the binaries
  via TransferManager, and clears the unavailable flag on completion.
- Toast copy branches by transfer kind so dict uploads don't read
  "Book uploaded".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sync): boot pull and binary download path

- Defer the boot pull until TransferManager is initialized so download
  enqueues aren't dropped.
- Auto-persist the local dict store after applyRemoteDictionary; otherwise
  the next loadCustomDictionaries wipes the in-memory rows.
- Boot pull passes since=null so a device whose cursor advanced past
  unpersisted rows can still recover.
- Skip pulling when not authenticated instead of logging
  "SyncError: Not authenticated" on every boot of a signed-out device.
- downloadReplicaFile resolves the destination against the kind's base
  dir; binaries previously landed at the literal lfp and openFile then
  failed with "File not found".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(sync): per-page useReplicaPull hook

Lifts the boot-time pull out of EnvContext into a hook each page mounts
for the kinds it needs: useReplicaPull({ kinds: ['dictionary'] }).
Library page and the shared Reader component opt in. The hook fires 10s
after page load (so feature mounts hydrate first), dedups per-kind
across navigation, and releases the slot on failure so a later mount
can retry. Future kinds plug into the hook's per-kind switch.

Also closes two refresh-loop bugs:

- Hydrate the dict store from settings BEFORE the apply loop, so the
  auto-persist doesn't clobber persisted rows that the in-memory store
  hadn't yet read. Library-page refresh was the visible victim.
- Skip the download queue when every manifest file is already on disk
  under the resolved bundle dir. Refreshing is a no-op; partial-
  download recovery still queues because some files would be missing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 21:39:38 +02:00
Huang Xin
3b348c8f35
feat(sync): CRDT replica sync foundation (#4075)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(sync): foundation for CRDT-based cross-device replica sync (Phase 1+2)

Adds the primitives and orchestration layer for syncing user-imported
assets (dictionaries, fonts, textures, OPDS catalogs, dict settings)
across devices via a polymorphic `replicas` table with field-level LWW
under HLC ordering. Phase 1 ships the foundation (CRDT, crypto, server
schemas, SQL migrations, push/pull endpoint); Phase 2 adds the adapter
registry, HTTP client, and sync manager. No modifications to existing
book sync — additive only.

Phase 1:
- src/libs/crdt.ts — HlcGenerator (monotonic + remote-absorption +
  clock-regression-safe), per-field LWW with deviceId tiebreak,
  remove-wins tombstones, reincarnation token revival.
- src/libs/crypto/{derive,encrypt,envelope,passphrase}.ts —
  PBKDF2-600k key derivation (OWASP 2024), AES-GCM round-trip,
  envelope {c,i,s,alg,h} with SHA-256 sidecar integrity check,
  passphrase storage abstraction (web ephemeral; Tauri keychain stub).
- src/libs/replica-schemas.ts — Zod-backed allowlist (dictionary only
  in PR 1), 64KiB row cap, 64-field cap, schemaVersion bounds,
  filename validator.
- src/libs/replica-sync-server.ts — push batch validation
  (auth + allowlist + schema + HLC ±60s skew clamp).
- src/pages/api/sync/replicas.ts — POST/GET endpoint wrapping the
  Postgres crdt_merge_replica function via RPC.
- docker/volumes/db/migrations/003_add_replicas.sql — replicas table
  + replica_keys table + RLS.
- docker/volumes/db/migrations/004_crdt_merge_replica_fn.sql — atomic
  per-field LWW merge function (forwards-compat preserves unknown
  fields).

Phase 2:
- src/services/sync/replicaRegistry.ts — adapter contract
  (core + optional BinaryCapability + LifecycleHooks per eng review).
- src/libs/replica-sync-client.ts — HTTP wrapper mapping status codes
  to typed SyncError codes.
- src/services/sync/replicaSyncManager.ts — 5s debounced push,
  immediate flush on visibilitychange/online, per-kind pull cursor,
  remote HLC absorption.

Tests: 125 new (crdt 26, crypto 32, schemas 21, server 16, client 12,
registry 6, manager 12). Full suite 3656 passing, lint clean. Existing
book/config/note sync paths untouched.

Plan: ~/.claude/plans/vivid-orbiting-thimble.md
CEO plan: ~/.gstack/projects/readest-readest/ceo-plans/2026-05-06-replica-sync-cathedral.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(sync): add kind="replica" path through TransferManager (Phase 3)

Adds the replica branch to the existing book-shaped transfer
infrastructure so dictionary (and future kinds) bundles can flow through
the same queue, retry, and progress UI as book uploads.

Existing book transfer paths remain unchanged. The book-side regression
suite (37 tests in transfer-store.test.ts, 37 in transfer-manager.test.ts)
all stay green.

Store (src/store/transferStore.ts):
- TransferItem gains kind: 'book' | 'replica' (default 'book' on legacy
  persisted rows), replicaKind, replicaId, replicaFiles, replicaBase.
- New addReplicaTransfer(replicaKind, replicaId, displayTitle, type, opts)
  with files + base in opts; auto-computes totalBytes from file sizes.
- New getReplicaTransfer(replicaKind, replicaId, type) lookup.
- getTransferByBookHash filters to kind === 'book' (defensive against
  bookHash="" collisions on replica items).
- restoreTransfers fills kind: 'book' for legacy persisted rows.

Manager (src/services/transferManager.ts):
- queueReplicaUpload / queueReplicaDownload / queueReplicaDelete.
- executeTransfer dispatches by kind to the new executeReplicaTransfer
  (iterates files, calls appService.uploadReplicaFile per file with
  per-file progress aggregation) or the existing executeBookTransfer
  (refactored out, byte-identical behavior).
- Dispatches replica-transfer-complete event on success so stores can
  react (e.g., commit manifest_jsonb to the replica row).

Storage / cloud (src/libs/storage.ts, src/services/cloudService.ts):
- uploadReplicaFile bypasses the book-only File.name smuggling and
  takes an explicit cfp (cloud file path).
- uploadReplicaFileToCloud / downloadReplicaFileFromCloud /
  deleteReplicaBundleFromCloud orchestrate per-file operations under
  ${userId}/Readest/replicas/<kind>/<replicaId>/<filename>.
- replicaCloudKey() centralizes the path-construction rule.
- New CLOUD_REPLICAS_SUBDIR constant.

App service (src/services/appService.ts, src/types/system.ts):
- AppService gains uploadReplicaFile, downloadReplicaFile,
  deleteReplicaBundle (file-level operations; orchestration lives in
  TransferManager).

Tests: 18 new (12 in transfer-store.test.ts, 5 in transfer-manager.test.ts,
1 fixture). Full suite 3674 passing, lint clean. Existing book regression
clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(sync): dictionary replica adapter + bootstrap (Phase 4, partial)

Lands the safe-to-ship foundation of Phase 4 — adapter logic, registry
bootstrap, and SystemSettings hooks for replica sync. The on-disk
migration of legacy customDictionaries (bundleDir → content-hash id),
the live store wiring, and the Settings → Sync UI are deferred to a
follow-up PR so they can land with real-device QA.

Adapter (src/services/sync/adapters/dictionary.ts):
- dictionaryAdapter: kind='dictionary', schemaVersion=1.
- pack/unpack — only synced subset (name, kind, lang, addedAt,
  unsupported{,Reason}). bundleDir / files / unavailable / deletedAt
  stay per-device or are handled by the tombstone mechanism.
- BinaryCapability.enumerateFiles dispatches by bundle kind:
  - mdict:    mdx + mdd[] + css[]
  - stardict: ifo + idx + dict + syn (skips .idx.offsets / .syn.offsets
              sidecars — those are device-local indices)
  - dict:     dict + index
  - slob:     single .slob file
- primaryDictionaryFile() picks the anchor file per kind for
  partialMD5 hashing.
- computeDictionaryReplicaId(partialMd5, byteSize, sortedFilenames)
  produces a deterministic 32-hex content-hash id used at import time.
- 23 tests cover pack/unpack identity, kind dispatch, file enumeration,
  id determinism, and per-device-field exclusion.

Bootstrap (src/services/sync/replicaBootstrap.ts):
- bootstrapReplicaAdapters() registers all known adapters once at app
  start. Idempotent (safe to call multiple times). Wired into
  EnvContext.tsx so the registry populates on app mount.
- 3 tests cover registration, idempotency, and the PR-1 allowlist.

SystemSettings (src/types/settings.ts, src/services/constants.ts):
- +SyncCategory = 'book' | 'progress' | 'note' | 'dictionary' — typed
  union for the user-facing sync toggles. 'progress' gates the
  existing book-config sync (reading progress); 'note' gates
  annotations; 'book' gates book binaries + metadata; 'dictionary'
  gates the new replica sync. Future replica kinds extend the union.
- +SYNC_CATEGORIES readonly array for UI iteration.
- +syncCategories: Partial<Record<SyncCategory, boolean>> — per-
  category opt-in toggles in DEFAULT_SYSTEM_SETTINGS (default ON for
  all four). UI panel ships in the follow-up.
- +lastSyncedAtReplicas: Record<string, string> — per-kind HLC pull
  cursors (matches replicaSyncManager's CursorStore contract).

Registry type cleanup (src/services/sync/replicaRegistry.ts):
- BinaryCapability.enumerateFiles return shape: localRelPath → lfp
  to match the existing TransferStore.ReplicaTransferFile convention.

Tests: 28 new (23 dict + 3 bootstrap + 2 syncCategories defaults).
Full suite 3702 passing, lint clean. Existing book/config/note sync
paths untouched.

Deferred to PR 1 follow-up (with real-device QA):
- customDictionaryStore migration: rehash legacy uniqueId() bundleDir
  to content-hash id; preserve providerOrder mapping; staged
  .legacy/<old-id>/ backup.
- Wire customDictionaryStore mutations through replicaSyncManager
  (markDirty on add/rename/delete; pull on init).
- Settings → Sync panel: per-category toggles + last-sync timestamps.
- Sync passphrase modal: set / change / forgot flow (lazy first prompt
  on encrypted-field push/pull).
- <CloudReplicaRow> in CustomDictionaries.tsx for "Download from cloud
  (X MB)" affordance.
- Tauri keychain backend for sync passphrase storage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(sync): replicaSync singleton + content-hash id at dict import (Phase 4b)

Two foundation pieces that everything UI-side will sit on top of, both
purely additive — no live store wiring, no behavior change for existing
dictionary imports.

replicaSync singleton (src/services/sync/replicaSync.ts):
- initReplicaSync({deviceId, cursorStore, hlcStore?, client?}) builds
  one ReplicaSyncManager backed by an HlcGenerator with persistence
  wrapped around .next()/.observe(). Idempotent (second init returns
  the existing instance).
- LocalStorageHlcStore (src/libs/hlc-store.ts) snapshots the HLC
  counter under 'readest_replica_hlc' so it survives restart. Falls
  back silently when localStorage is unavailable (private mode, SSR);
  client re-derives via the existing remote max(updated_at_ts) repair
  path. InMemoryHlcStore is the test backend.
- 16 tests (9 hlc-store, 7 replicaSync) covering snapshot persistence,
  restore-on-init, and idempotency.
- Wiring into EnvContext for production deferred to the follow-up that
  also adds the cursor store backed by useSettingsStore.

Content-hash id at dictionary import
(src/services/dictionaries/contentId.ts):
- computeDictionaryContentId(primaryFile, filenames) wraps
  computeDictionaryReplicaId(partialMd5(primary), byteSize,
  sortedFilenames) — the cross-device id used as the replica_id when
  the dict actually pushes/pulls.
- Wired into all four import paths in dictionaryService.ts:
  - stardict primary = .ifo (small text, partialMD5 ≈ full hash)
  - mdict primary    = .mdx (body)
  - dict primary     = .dict.dz (gzipped body)
  - slob primary     = .slob (single-file bundle)
  ImportedDictionary gains contentId?: string. Optional for backwards
  compat; legacy bundles without contentId are flagged as
  "needs rehash before sync" by the upcoming store-wiring follow-up.
- 6 tests cover identity determinism, byteSize sensitivity, filename-
  set sensitivity, and order-independence.

Tests: 22 new (9 + 7 + 6). Full suite 3724 passing, lint clean.
Existing dictionary import flow unchanged for users — contentId is an
additional field, not a replacement for the bundleDir-based id.

Deferred to follow-up (with on-device QA):
- Production cursor store backed by useSettingsStore +
  appService.saveSettings.
- EnvContext call to initReplicaSync after appService boot.
- customDictionaryStore mutation hooks → replicaSyncManager.markDirty.
- Legacy bundleDir → contentId migration with .legacy/ backup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(sync): land replica-sync design plan in repo

Moves the plan document that drove this PR's foundation work
(`~/.claude/plans/vivid-orbiting-thimble.md`) into the project tree at
`apps/readest-app/.claude/plans/` so reviewers and future contributors
can read it alongside the code without leaving the repo.

The plan went through three review passes — Codex (19 findings, all
absorbed), CEO/scope review (mode SCOPE EXPANSION; encrypted secrets
pulled forward to v1, "private-only forever" posture lock), and eng
review (FULL_REVIEW mode, 16 findings absorbed). The full review trail
lives in the file's `## GSTACK REVIEW REPORT` section at the bottom.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(crdt): point README at in-repo plan path

Now that vivid-orbiting-thimble.md lives at
apps/readest-app/.claude/plans/, the README link should point there
rather than at the home-dir copy that no longer exists.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(sync): rename src/libs files to camelCase per project convention

Test files renamed in lockstep. Imports + comment references updated
across cloudService, storage, transferManager, replicaSync,
replicaSyncManager, /api/sync/replicas, and all four test files. No
behavior change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 15:50:15 +02:00
Huang Xin
e7564ffc27
fix(docker): correct Kong gateway port for client build arg (#4046)
The web client's NEXT_PUBLIC_SUPABASE_URL build arg pointed at port 7000,
but Kong is exposed on KONG_HTTP_PORT (8000 by default), so browser-side
Supabase calls failed in the self-hosted Docker setup.

Closes #4035

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 17:10:16 +02:00
Huang Xin
d1e7b4902c
feat(share): time-limited share links with cfi-aware imports (#4037)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
Add a Share Book feature that generates an expiring HTTPS share URL plus a
parallel readest://share/{token} deep link. Recipients land on /s/{token},
where logged-in users can one-tap "Add to my library" (R2 server-side
byte-copy) and anonymous users download the book or open it in the app.
Sharers manage active links from a dedicated "Manage Shared Links" panel
under user settings.

Highlights:
- 9 new App Router endpoints under /api/share (create, [token], cover,
  og.png, download, download/confirm, import, revoke, list).
- /s landing page with branded next/og chat unfurl image and SSR auth-cookie
  detection so logged-in recipients see "Add to my library" as the primary
  action without layout shift.
- Server-side R2 byte-copy for /import preserves the project's existing
  invariant that every files.file_key is prefixed with its row's user_id;
  stats / purge / delete / download routes work unchanged. URL-encodes the
  copy source so titles with spaces or '&' don't break the copy.
- Universal 7-day expiry cap, no tier differentiation, no "never". DMCA-risk
  reduction. Picker defaults to 3 days.
- Position-aware shares: "Share current page" toggle (off by default for
  privacy) attaches the sharer's CFI; recipient lands at the same paragraph.
- Per-user 50-share cap, rate limiting via Cache-Control: no-store on
  token-bearing responses, atomic SQL increment for download_count via a
  SECURITY DEFINER function so the public confirm beacon stays safe under
  concurrent fire.
- Soft revocation: presigned download URLs (5-min TTL) cannot be cancelled
  before TTL; documented as accepted v1 behavior.
- token + token_hash hybrid storage: public endpoints look up by hash and
  never select the raw token, so accidental SELECT-* leakage on a public
  route can't expose the bearer credential.
- Mobile / desktop Tauri share via tauri-plugin-sharekit; web falls back to
  navigator.share with a clipboard fallback when no native share method
  exists. Share-sheet dismissal no longer silently copies.

UI:
- New Dialog with a settings-card group: iOS-style segmented duration picker
  + toggle slider for "Share current page", on a single row each.
- Reader top-bar Share button, library context-menu Share entry, manage-
  shares list with cover thumbnails and overflow menu.
- New <SegmentedControl> primitive in src/components for reuse.

Coverage:
- Unit tests for token utils + URL parser (20 new tests, full suite at 3445).
- 31 locales translated for all new strings; en plurals hand-added per the
  project's hand-curated en convention.

DB migration in docker/volumes/db/migrations/002_add_book_shares.sql adds
the book_shares table, RLS policies, and the increment_book_share_download
RPC. Migration is idempotent.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 19:03:35 +02:00
Lex Moulton
baee85e7c8
feat(rsvp): sync reading position to cloud via book_configs (#3801) 2026-04-09 15:52:49 +02:00
Huang Xin
29df8522fa
chore(bump): bump Tauri to the latest version (#3716) 2026-04-01 10:06:23 +02:00
Huang Xin
76b239f382
feat(koplugin): add support for annotation sync (#3579)
Add bidirectional annotation/highlight sync between KOReader and Readest:

- Add xpointer0/xpointer1 fields to BookNote and DBBookNote types for
  KOReader XPointer positions alongside Readest's CFI format
- Extend transform layer to pass through xpointer fields to/from DB
- Convert CFI→XPointer on push and XPointer→CFI on pull in useNotesSync,
  discarding notes that fail conversion
- Support KOReader's text()[K].N indexed text node format in xcfi.ts for
  paragraphs with inline elements (e.g. <a> page anchors)
- Generate KOReader-compatible XPointers: text().N for single text nodes,
  text()[K].N only when multiple direct text nodes exist
- Skip cfi-inert elements (injected by Readest at runtime) in XPointer
  path building and resolution
- Map highlight colors between KOReader and Readest color systems
- Implement KOReader plugin annotation push/pull with deterministic IDs,
  auto-sync on document open/close, and UIManager refresh on pull
- Refactor koplugin into focused modules: syncauth, syncconfig,
  syncannotations, selfupdate

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 16:43:51 +01:00
Azeem Bande-Ali
34ad6e6749
fix(selfhost): update docker db schema to match FileRecords (#3527)
In #2636, FileRecord was defined to have updated_at  field
which is used when it is accessed from the database. But the
local dev setup is missing this field.

This diff adds an updated_at column to match the expectation
2026-03-13 05:15:55 +01:00
Huang Xin
c533da498d
feat(annotator): add page number for annotations, closes #3082 (#3405)
* feat(annotator): add page number in annotation

* feat: add page number for annotations, closes #3082
2026-02-28 08:08:56 +01:00
Aniket Kotal
eec2c39f19
feat(docker/podman): self-hosting with docker/podman compose (#3312)
Some checks failed
Deploy to vercel on merge / build_and_deploy (push) Has been cancelled
* initial files

* added testing files

* removed unused files

* cleaned additional mounts

* fixed sql init

* removed more unused files

* moved to docker folder

* revert package.json

* gitignore update

* env example comments and compose necessary healthcheck

* ghcr package impl

* updated dockerfile steps  for layer caching

* added development-stage to dockerfile to dev environment

* added documentation on how to use dockerfile and compose.yml

* fixed prettier issues

* fixed image tag

* removed workflow for later
2026-02-18 14:28:10 +01:00