diff --git a/.env.example b/.env.example index 6d766e9..50e775e 100644 --- a/.env.example +++ b/.env.example @@ -15,7 +15,7 @@ POSTGRES_PASSWORD_ENCODED= NOSTR_PRIVATE_KEY= # DEFAULT_RELAYS: comma-separated list of wss:// relay URLs. This value is public: # it is sent to browsers and appears in generated RSS feeds. Never put credentials in it. -DEFAULT_RELAYS="wss://relay.damus.io,wss://nos.lol,wss://relay.nostr.band" +DEFAULT_RELAYS="wss://relay.damus.io,wss://nos.lol" # Optional: overrides the admin npub. Defaults to the bundled admin npub when unset. NEXT_PUBLIC_ADMIN_NPUB= diff --git a/.env.production.example b/.env.production.example index 4ad5a4c..b290228 100644 --- a/.env.production.example +++ b/.env.production.example @@ -10,7 +10,7 @@ NODE_ENV="production" # Nostr Configuration # DEFAULT_RELAYS: comma-separated list of wss:// relay URLs. This value is public: # it is sent to browsers and appears in generated RSS feeds. Never put credentials in it. -DEFAULT_RELAYS="wss://relay.damus.io,wss://nos.lol,wss://relay.nostr.band,wss://relay.snort.social" +DEFAULT_RELAYS="wss://relay.damus.io,wss://nos.lol,wss://relay.snort.social" NOSTR_BUNKER_URL="" # Optional: overrides the admin npub. Defaults to the bundled admin npub when unset. diff --git a/desktop/README.md b/desktop/README.md index a0594f6..58cec26 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -100,8 +100,9 @@ version replaces the older one in place, keeping its read and starred marks. Give Readstr your npub (or an nprofile, whose relay hints are asked too) with "Sync with Nostrโ€ฆ" in the `โ‹ฎ` menu or `readstr sync login npub1โ€ฆ`, and it pulls what the Readstr web app publishes for it: the subscription list -(kind 30404), the read articles (kind 30405, once the web app publishes it; -it does not yet), and the saved views (kind 30406). Only the public key is kept; nothing is ever signed or published, +(kind 30404), the read articles (kind 30405, which the web app publishes only +when its read-sync setting is on, and then only its most recent reads), and +the saved views (kind 30406). Only the public key is kept; nothing is ever signed or published, which is why no signer is needed: the web app publishes these events in cleartext, so anyone can read them. The window pulls right after you log in and after every refresh of all feeds, so read marks find the articles it diff --git a/desktop/src/relaypool.cpp b/desktop/src/relaypool.cpp index 1ea0f78..33263c9 100644 --- a/desktop/src/relaypool.cpp +++ b/desktop/src/relaypool.cpp @@ -349,9 +349,7 @@ RelayPool::~RelayPool() { } QStringList RelayPool::defaultRelays() { - // The web app's fallback relays, less relay.nostr.band and - // nostr-pub.wellorder.net, which no longer answer and would hold every - // refresh up until they time out. + // The web app's fallback relays. return {QStringLiteral("wss://relay.damus.io"), QStringLiteral("wss://relay.primal.net"), QStringLiteral("wss://nos.lol"), QStringLiteral("wss://relay.snort.social")}; } diff --git a/docker-compose.yml b/docker-compose.yml index 1e9d57c..4c7e0e1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -22,7 +22,7 @@ services: environment: - NODE_ENV=production - DATABASE_URL=postgresql://${POSTGRES_USER:-nostr_user}:${POSTGRES_PASSWORD_ENCODED:-${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}}@postgres:5432/${POSTGRES_DB:-readstr} - - DEFAULT_RELAYS=wss://relay.damus.io,wss://nos.lol,wss://relay.nostr.band + - DEFAULT_RELAYS=wss://relay.damus.io,wss://nos.lol depends_on: - postgres restart: unless-stopped diff --git a/docs/CLI_DEVELOPMENT_GUIDE.md b/docs/CLI_DEVELOPMENT_GUIDE.md index bd4b4aa..2b6a825 100644 --- a/docs/CLI_DEVELOPMENT_GUIDE.md +++ b/docs/CLI_DEVELOPMENT_GUIDE.md @@ -265,8 +265,6 @@ var DefaultRelays = []string{ "wss://relay.damus.io", "wss://nos.lol", "wss://relay.snort.social", - "wss://relay.nostr.band", - "wss://nostr-pub.wellorder.net", } ``` diff --git a/docs/SUBSCRIPTION_SYNC.md b/docs/SUBSCRIPTION_SYNC.md index e248684..c84b15b 100644 --- a/docs/SUBSCRIPTION_SYNC.md +++ b/docs/SUBSCRIPTION_SYNC.md @@ -23,6 +23,35 @@ Read status for feed items is synced using kind `30405`: - Syncs across all devices - Uses item GUIDs for identification +How the web app handles it: + +- **Opt-in.** It is off by default. The "Sync read articles across devices" + setting (localStorage `readstr_read_sync`) turns it on, and only signed-in + users who can sign take part. +- **Public.** The event is cleartext, so anyone can see which articles the + user read. Turning the setting off publishes an empty replacement list, best + effort; relays and other clients may keep older copies. +- **Capped.** Common strfry relays refuse events over 64 KiB, so the web app + publishes only the newest reads that fit about 60,000 bytes of event JSON + (`MAX_PUBLISHED_READ_CONTENT`): its own reads from feeds the user still + subscribes to, newest first, then the guids of the last list it pulled that + no feed of its own has. It accepts pulled lists of up to 8 MiB and 100,000 + guids of at most 256 UTF-16 units each, since other clients may publish + bigger ones. +- **Additive.** A pulled list only marks items read; a guid missing from it + never marks anything unread. The web app pulls once per session before it + publishes, and publishes only after a pull applied the newest list, found it + already applied, or found that no relay has one. "No relay has one" needs an + answer from every relay that connected, so a relay that connects and then + times out cannot lead to a replacement that drops another device's reads. + A relay that is down when this device pulls, and that alone holds another + device's newest list, can still be missed, so this is best effort. +- **Keys.** An item's key is its guid, trimmed, or its link when it has no + guid, as on the desktop. Stored guids are not trimmed, so a pulled key never + matches an item whose stored guid has leading or trailing whitespace. This + is a known, rare mismatch: trimming at ingest would change the identity of + existing items and create duplicates. + ### Event Structure - Subscription List ```json @@ -390,8 +419,6 @@ const SYNC_RELAYS = [ 'wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.snort.social', - 'wss://relay.nostr.band', - 'wss://nostr-pub.wellorder.net', ] ``` @@ -561,7 +588,7 @@ check(); ### Manual Event Inspection -Use [nostr.band](https://nostr.band) or [njump.me](https://njump.me) to search for kind 30404 events. +Use [njump.me](https://njump.me) to search for kind 30404 events. ## Security Considerations diff --git a/prisma/migrations/20261121000000_add_read_item_user_read_at_index/migration.sql b/prisma/migrations/20261121000000_add_read_item_user_read_at_index/migration.sql new file mode 100644 index 0000000..5ef2da7 --- /dev/null +++ b/prisma/migrations/20261121000000_add_read_item_user_read_at_index/migration.sql @@ -0,0 +1,2 @@ +-- CreateIndex +CREATE INDEX "ReadItem_userPubkey_readAt_idx" ON "ReadItem"("userPubkey", "readAt"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index b34ac3e..970b149 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -122,6 +122,7 @@ model ReadItem { @@unique([userPubkey, itemId]) @@index([userPubkey]) @@index([userPubkey, syncedAt]) + @@index([userPubkey, readAt]) } model Favorite { diff --git a/scripts/seed-guide.ts b/scripts/seed-guide.ts index 093bffb..a49bc92 100644 --- a/scripts/seed-guide.ts +++ b/scripts/seed-guide.ts @@ -12,8 +12,6 @@ const DEFAULT_RELAYS = [ 'wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.snort.social', - 'wss://relay.nostr.band', - 'wss://nostr-pub.wellorder.net' ] // Popular Nostr long-form content creators with relevant tags diff --git a/src/app/api/trpc/[trpc]/route.ts b/src/app/api/trpc/[trpc]/route.ts index 404039a..6b91494 100644 --- a/src/app/api/trpc/[trpc]/route.ts +++ b/src/app/api/trpc/[trpc]/route.ts @@ -5,21 +5,10 @@ import { buildRequestContext, type RequestLike } from '@/server/auth/request-con import { readBodyWithLimit, type ReadBodyResult } from '@/server/http/read-body' import { countTrpcCalls } from '@/server/http/trpc-batch' import { clientIpFromRequest, rateLimit } from '@/server/rate-limit' -import { MAX_TRPC_BATCH_SIZE } from '@/trpc/batch-limits' +import { MAX_TRPC_BATCH_SIZE, MAX_TRPC_BODY_BYTES } from '@/trpc/batch-limits' const TRPC_ENDPOINT = '/api/trpc' -/** - * Largest tRPC request body accepted. Only mutations send a body; queries such - * as getFeedItems carry their input in the GET URL. The biggest real body is a - * batch of markAsRead calls (~45 bytes each, so ~1,400 fit); most calls are - * well under 1 KB. The cap keeps zod v3's per-element parsing of hostile arrays - * (~150x heap amplification, GHSA-mrhx-c7xc-m3w5) to roughly 10 MB per - * request, and runs before NIP-98 auth and any procedure's rate limit, so it - * also protects public mutations. - */ -const MAX_TRPC_BODY_BYTES = 64_000 - /** * Per-IP budget of procedure calls per minute, charged one unit per call in a * batch so batching cannot dodge it. Normal use stays far below it: a page diff --git a/src/components/feed-reader.tsx b/src/components/feed-reader.tsx index e1d5269..540a807 100644 --- a/src/components/feed-reader.tsx +++ b/src/components/feed-reader.tsx @@ -40,7 +40,18 @@ import { fetchReadingPrefs, publishReadingPrefs, getPrefsSyncEnabled, + getSyncRelays, } from '@/lib/nostr-sync' +import { + newReadSyncSession, + nextReadSyncRetryDelay, + publishReadStatusIfChanged, + pullReadStatus, + readSyncAllowed, + READ_SYNC_PUBLISH_DELAY_MS, + READ_SYNC_RETRY_MIN_MS, + withdrawReadStatus, +} from '@/lib/read-sync' import type { UnsignedEvent } from 'nostr-tools' import { ArticlePane } from './reader/ArticlePane' import { ItemList } from './reader/ItemList' @@ -134,6 +145,18 @@ export function FeedReader() { const refreshIntervalRef = useRef | null>(null) const feedDataRefreshTimerRef = useRef | null>(null) const pendingMarksRef = useRef(0) + const readSyncSessionRef = useRef(newReadSyncSession()) + const readSyncUnmountedRef = useRef(false) + const readSyncPullingRef = useRef(false) + const hasPulledReadRef = useRef(false) + const readSyncReadyRef = useRef(false) + const readSyncPendingRef = useRef(false) + const readSyncPublishAfterPullRef = useRef(false) + const readSyncTimerRef = useRef | null>(null) + const readSyncRetryTimerRef = useRef | null>(null) + const readSyncRetryDelayRef = useRef(READ_SYNC_RETRY_MIN_MS) + const readSyncDepsRef = useRef({ canSign, npub: user?.npub, signEventOrThrow }) + const [readSyncTick, setReadSyncTick] = useState(0) // Mobile responsive state const [showSidebar, setShowSidebar] = useState(false) @@ -529,6 +552,97 @@ export function FeedReader() { if (feedDataRefreshTimerRef.current) clearTimeout(feedDataRefreshTimerRef.current) }, []) + // Read status sync (kind 30405): opt-in, signers only. Timers and the pull + // read auth from this ref, so a debounced publish sees the current signer. + useEffect(() => { + readSyncDepsRef.current = { canSign, npub: user?.npub, signEventOrThrow } + }, [canSign, user?.npub, signEventOrThrow]) + + const clearReadSyncRetry = () => { + if (readSyncRetryTimerRef.current) clearTimeout(readSyncRetryTimerRef.current) + readSyncRetryTimerRef.current = null + } + + // Sync state belongs to one account. On a switch, start over so the new + // account pulls before it publishes and never publishes the old one's list; + // work still queued for the old account sees the session's npub and stops. + useEffect(() => { + const npub = user?.npub ?? null + if (readSyncSessionRef.current.npub === npub) return + readSyncSessionRef.current = newReadSyncSession(npub) + hasPulledReadRef.current = false + readSyncPullingRef.current = false + readSyncReadyRef.current = false + readSyncPendingRef.current = false + readSyncPublishAfterPullRef.current = false + if (readSyncTimerRef.current) clearTimeout(readSyncTimerRef.current) + readSyncTimerRef.current = null + clearReadSyncRetry() + readSyncRetryDelayRef.current = READ_SYNC_RETRY_MIN_MS + }, [user?.npub]) + + const publishReadSyncNow = useCallback(() => { + if (readSyncTimerRef.current) clearTimeout(readSyncTimerRef.current) + readSyncTimerRef.current = null + return publishReadStatusIfChanged({ + canSign: () => readSyncDepsRef.current.canSign, + npub: () => readSyncDepsRef.current.npub, + session: readSyncSessionRef.current, + // cacheTime 0: the list can be megabytes and is only needed once. + fetchLocal: async () => (await utils.feed.getReadGuidsForSync.fetch(undefined, { cacheTime: 0 })).guids, + signEvent: (event) => readSyncDepsRef.current.signEventOrThrow(event), + }) + }, [utils]) + + // Pull again before publishing when the session's last pull failed, so a + // publish never replaces a list this device has not applied. The pull + // publishes when it is done. + const retryReadSyncPull = () => { + hasPulledReadRef.current = false + readSyncReadyRef.current = false + readSyncPendingRef.current = true + setReadSyncTick((t) => t + 1) + } + + // Called after every read change. Before the session's pull has finished, + // only note it, so the pull's publish carries it instead of racing it. + const scheduleReadSyncPublish = () => { + const { canSign: signer, npub } = readSyncDepsRef.current + if (!readSyncAllowed(signer, npub)) return + if (!readSyncReadyRef.current) { + readSyncPendingRef.current = true + return + } + if (readSyncTimerRef.current) clearTimeout(readSyncTimerRef.current) + readSyncTimerRef.current = setTimeout(() => { + if (readSyncSessionRef.current.pulled) void publishReadSyncNow() + else { + readSyncTimerRef.current = null + retryReadSyncPull() + } + }, READ_SYNC_PUBLISH_DELAY_MS) + } + + // Best effort: a page closing mid-debounce publishes now rather than never. + useEffect(() => { + const flush = () => { + if (readSyncTimerRef.current) void publishReadSyncNow() + } + window.addEventListener('pagehide', flush) + return () => window.removeEventListener('pagehide', flush) + }, [publishReadSyncNow]) + + // Set on mount too, since React's strict mode unmounts and remounts once. + useEffect(() => { + readSyncUnmountedRef.current = false + return () => { + readSyncUnmountedRef.current = true + if (readSyncTimerRef.current) clearTimeout(readSyncTimerRef.current) + if (readSyncRetryTimerRef.current) clearTimeout(readSyncRetryTimerRef.current) + readSyncRetryTimerRef.current = null + } + }, []) + // Auto-refresh all feeds function const handleRefreshAllFeeds = useCallback(() => { if (isRefreshingAll || !user?.npub) return @@ -621,6 +735,7 @@ export function FeedReader() { utils.feed.getFeeds.setData(undefined, context.previousFeeds) } }, + onSuccess: () => scheduleReadSyncPublish(), onSettled: () => { pendingMarksRef.current = Math.max(0, pendingMarksRef.current - 1) scheduleFeedDataRefresh() @@ -655,6 +770,7 @@ export function FeedReader() { utils.feed.getFeeds.setData(undefined, context.previousFeeds) } }, + onSuccess: () => scheduleReadSyncPublish(), onSettled: () => { pendingMarksRef.current = Math.max(0, pendingMarksRef.current - 1) scheduleFeedDataRefresh() @@ -664,8 +780,11 @@ export function FeedReader() { const markAllAsReadMutation = api.feed.markFeedAsRead.useMutation({ onSuccess: () => { invalidateFeedData() + scheduleReadSyncPublish() }, }) + + const markReadByGuidsMutation = api.feed.markReadByGuids.useMutation() const addFavoriteMutation = api.feed.addFavorite.useMutation({ onSuccess: invalidateFeedData, @@ -951,19 +1070,15 @@ export function FeedReader() { const signedEvent = await signEventOrThrow(unsignedEvent) - // Publish to relays + // Publish and wait for the first relay to accept. Promise.any, not + // race, so one relay refusing or being down does not fail the share. const pool = new SimplePool() - const relays = [ - 'wss://relay.damus.io', - 'wss://nos.lol', - 'wss://relay.nostr.band', - 'wss://relay.snort.social', - ] - - // Publish and wait for at least one relay to confirm - const publishPromises = pool.publish(relays, signedEvent) - await Promise.race(publishPromises) - pool.close(relays) + const relays = getSyncRelays() + try { + await Promise.any(pool.publish(relays, signedEvent)) + } finally { + pool.close(relays) + } setShareSuccess(true) setTimeout(() => setShareSuccess(false), 3000) @@ -1124,6 +1239,96 @@ export function FeedReader() { } }, []) + // Pull read status once per session after feeds load, and again when the + // setting is turned on (readSyncTick), which then publishes once. + useEffect(() => { + if (hasPulledReadRef.current) return + if (!feedsLoaded || !readSyncAllowed(canSign, user?.npub)) return + const session = readSyncSessionRef.current + if (session.npub !== (user?.npub ?? null)) return + hasPulledReadRef.current = true + readSyncPullingRef.current = true + clearReadSyncRetry() + const publishAfter = readSyncPublishAfterPullRef.current + readSyncPublishAfterPullRef.current = false + + void pullReadStatus({ + canSign: () => readSyncDepsRef.current.canSign, + npub: () => readSyncDepsRef.current.npub, + isCancelled: () => readSyncUnmountedRef.current || readSyncSessionRef.current !== session, + session, + markRead: (guids) => markReadByGuidsMutation.mutateAsync({ guids }), + onApplied: () => { + invalidateFeedData() + void utils.feed.getCategoriesWithUnread.invalidate() + }, + }).then((pulled) => { + if (readSyncSessionRef.current === session) readSyncPullingRef.current = false + // A pull for an account that is no longer signed in leaves the new + // session's state alone. + if (readSyncUnmountedRef.current || readSyncSessionRef.current !== session) return + if (!pulled) { + // Publishing now could replace reads this device has not seen, so the + // publish stays pending and the pull is retried with backoff. Read + // changes meanwhile only add to the pending publish. + if (publishAfter) readSyncPendingRef.current = true + const { canSign: signer, npub } = readSyncDepsRef.current + if (!readSyncAllowed(signer, npub)) { + // No retry is scheduled while sync is not allowed, so the effect + // must be free to pull again once signing or the account comes back. + // It re-runs only when its deps change, so this cannot loop. + hasPulledReadRef.current = false + return + } + const delay = readSyncRetryDelayRef.current + readSyncRetryDelayRef.current = nextReadSyncRetryDelay(delay) + readSyncRetryTimerRef.current = setTimeout(() => { + readSyncRetryTimerRef.current = null + if (readSyncUnmountedRef.current || readSyncSessionRef.current !== session) return + hasPulledReadRef.current = false + setReadSyncTick((t) => t + 1) + }, delay) + return + } + readSyncRetryDelayRef.current = READ_SYNC_RETRY_MIN_MS + readSyncReadyRef.current = true + if (publishAfter || readSyncPendingRef.current) { + readSyncPendingRef.current = false + void publishReadSyncNow() + } + }) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [user?.npub, canSign, feedsLoaded, readSyncTick]) + + const handleReadSyncChange = (enabled: boolean) => { + if (enabled) { + // A pull still applying (the setting turned off and on again) carries on + // and publishes when it ends; a second one alongside would share batched + // requests past the body cap and spend the rate limit twice. + if (readSyncPullingRef.current) { + readSyncPendingRef.current = true + return + } + readSyncSessionRef.current.pulled = false + hasPulledReadRef.current = false + readSyncReadyRef.current = false + readSyncPublishAfterPullRef.current = true + setReadSyncTick((t) => t + 1) + return + } + if (readSyncTimerRef.current) clearTimeout(readSyncTimerRef.current) + readSyncTimerRef.current = null + clearReadSyncRetry() + readSyncPendingRef.current = false + // Turning it off replaces the published list with an empty one. + void withdrawReadStatus({ + canSign: () => readSyncDepsRef.current.canSign, + npub: () => readSyncDepsRef.current.npub, + session: readSyncSessionRef.current, + signEvent: (event) => readSyncDepsRef.current.signEventOrThrow(event), + }) + } + // Handle importing feeds from Nostr sync const handleImportFeeds = async (feedsToImport: Array<{ type: 'RSS' | 'NOSTR'; url: string; tags?: string[]; category?: { name: string; color?: string; icon?: string } }>) => { // First, create a map of category names to IDs for existing categories @@ -1751,6 +1956,7 @@ export function FeedReader() { }))} userPubkey={user?.npub || user?.pubkey} onImportFeeds={handleImportFeeds} + onReadSyncChange={handleReadSyncChange} /> {/* Sync Prompt Dialog */} diff --git a/src/components/settings-dialog.tsx b/src/components/settings-dialog.tsx index 6a72392..58f803c 100644 --- a/src/components/settings-dialog.tsx +++ b/src/components/settings-dialog.tsx @@ -14,6 +14,8 @@ import { advanceSyncWatermarkIfFresh, getPrefsSyncEnabled, setPrefsSyncEnabled, + getReadSyncEnabled, + setReadSyncEnabled, type SubscriptionList, } from '@/lib/nostr-sync' import { parseOpml, buildOpml, planOpmlImport, MAX_CONTENT_BYTES } from '@/lib/opml' @@ -93,8 +95,6 @@ const POPULAR_RELAYS = [ { url: 'wss://relay.damus.io', name: 'Damus' }, { url: 'wss://nos.lol', name: 'nos.lol' }, { url: 'wss://relay.snort.social', name: 'Snort' }, - { url: 'wss://relay.nostr.band', name: 'Nostr Band' }, - { url: 'wss://nostr-pub.wellorder.net', name: 'Wellorder' }, { url: 'wss://relay.primal.net', name: 'Primal' }, { url: 'wss://relay.nostr.bg', name: 'Nostr BG' }, { url: 'wss://nostr.wine', name: 'Nostr Wine' }, @@ -223,6 +223,7 @@ interface SettingsDialogProps { onRenameView?: (id: string, name: string) => void onDeleteView?: (id: string) => void onMoveView?: (index: number, direction: -1 | 1) => void + onReadSyncChange?: (enabled: boolean) => void } // Default category colors/icons @@ -239,7 +240,7 @@ const CATEGORY_COLORS = [ const CATEGORY_ICONS = ['๐Ÿ“', '๐Ÿ“ฐ', '๐ŸŽฌ', '๐ŸŽต', '๐Ÿ’ผ', '๐ŸŽฎ', '๐Ÿ“š', '๐Ÿ”ฌ', '๐Ÿ’ก', '๐ŸŒ', 'โšก', '๐ŸŽฏ'] -export function SettingsDialog({ isOpen, onClose, markReadBehavior, onChangeMarkReadBehavior, layoutMode, onChangeLayoutMode, organizationMode, onChangeOrganizationMode, feeds = [], userPubkey, onImportFeeds, onFilterRulesChange, views = [], onRenameView, onDeleteView, onMoveView }: SettingsDialogProps) { +export function SettingsDialog({ isOpen, onClose, markReadBehavior, onChangeMarkReadBehavior, layoutMode, onChangeLayoutMode, organizationMode, onChangeOrganizationMode, feeds = [], userPubkey, onImportFeeds, onFilterRulesChange, views = [], onRenameView, onDeleteView, onMoveView, onReadSyncChange }: SettingsDialogProps) { const { user, canSign, signEventOrThrow } = useNostrAuth() const { readingPrefs, setReadingPref, resetReading } = useTheme() const { config: aiConfig, setConfig: setAiConfig } = useAiConfig() @@ -252,6 +253,7 @@ export function SettingsDialog({ isOpen, onClose, markReadBehavior, onChangeMark lastSync: null, }) const [prefsSyncEnabled, setPrefsSyncEnabledState] = useState(false) + const [readSyncEnabled, setReadSyncEnabledState] = useState(false) // Category management state const [newCategoryName, setNewCategoryName] = useState('') @@ -430,6 +432,7 @@ export function SettingsDialog({ isOpen, onClose, markReadBehavior, onChangeMark } setPrefsSyncEnabledState(getPrefsSyncEnabled()) + setReadSyncEnabledState(getReadSyncEnabled()) }, []) // Save relays to localStorage whenever they change @@ -1864,6 +1867,30 @@ export function SettingsDialog({ isOpen, onClose, markReadBehavior, onChangeMark Local-only when off.

+ +
+ +

+ When on, your most recently read articles are published publicly on + your Nostr relays (kind 30405), tied to your npub, so other apps such as + Readstr desktop can sync them. Anyone can see the list, and syncing only + marks articles read, never unread. Turning this off replaces the published + list with an empty one; relays and other apps may keep older copies. +

+
)} diff --git a/src/lib/nostr-sync-read-status.test.ts b/src/lib/nostr-sync-read-status.test.ts new file mode 100644 index 0000000..1f266d5 --- /dev/null +++ b/src/lib/nostr-sync-read-status.test.ts @@ -0,0 +1,147 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +type SubParams = { onevent: (event: unknown) => void; oneose: () => void; onclose: (reason: string) => void; eoseTimeout: number } +type Behaviour = 'eose' | 'silent' | 'down' | { events: unknown[] } + +const behaviours = new Map() +const closed: string[][] = [] +const published: { created_at: number }[] = [] + +vi.mock('nostr-tools', async (importOriginal) => { + const actual = await importOriginal() + class FakePool { + async ensureRelay(url: string) { + const behaviour = behaviours.get(url) + if (behaviour === 'down') throw new Error('connection failed') + return { + subscribe: (_filters: unknown[], params: SubParams) => { + if (typeof behaviour === 'object') { + setTimeout(() => { + for (const event of behaviour.events) params.onevent(event) + params.oneose() + }, 10) + } else if (behaviour === 'eose') { + setTimeout(() => params.oneose(), 10) + } + return { close: () => params.onclose('closed by caller') } + }, + } + } + publish(relays: string[], event: { created_at: number }) { + published.push(event) + return relays.map(async () => 'ok') + } + close(relays: string[]) { + closed.push(relays) + } + } + return { ...actual, SimplePool: FakePool } +}) + +const { fetchReadStatus, publishReadStatus, APPLIED_CREATEDAT_PREFIX, MAX_CONTENT_BYTES } = await import('./nostr-sync') + +const PUBKEY = '3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d' +const RELAYS = ['wss://a.invalid', 'wss://b.invalid'] + +function event(content: string, created_at = 100, pubkey = PUBKEY) { + return { kind: 30405, pubkey, created_at, tags: [['d', 'readstr-read-status']], content, id: 'x', sig: 'y' } +} + +beforeEach(() => { + vi.useFakeTimers() + behaviours.clear() + closed.length = 0 + published.length = 0 + const data = new Map([['nostr_relays', JSON.stringify(RELAYS)]]) + vi.stubGlobal('window', { localStorage: { getItem: (k: string) => data.get(k) ?? null } }) + vi.stubGlobal('localStorage', { getItem: (k: string) => data.get(k) ?? null, setItem: (k: string, v: string) => void data.set(k, v) }) + vi.spyOn(console, 'error').mockImplementation(() => {}) +}) + +afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +async function fetchWithTimers() { + const pending = fetchReadStatus(PUBKEY) + await vi.runAllTimersAsync() + return pending +} + +describe('fetchReadStatus', () => { + it('reports "no event" only when a relay sent EOSE', async () => { + behaviours.set(RELAYS[0]!, 'down') + behaviours.set(RELAYS[1]!, 'eose') + await expect(fetchWithTimers()).resolves.toEqual({ success: true, found: false }) + expect(closed).toEqual([RELAYS]) + }) + + it('fails when every relay times out or is down, rather than returning an empty list', async () => { + behaviours.set(RELAYS[0]!, 'down') + behaviours.set(RELAYS[1]!, 'silent') + await expect(fetchWithTimers()).resolves.toEqual({ success: false, error: 'Not every connected relay answered' }) + }) + + it('does not report "no event" when one relay answered empty and another connected but timed out', async () => { + // The timed-out relay may hold the only copy another device published. + behaviours.set(RELAYS[0]!, 'eose') + behaviours.set(RELAYS[1]!, 'silent') + await expect(fetchWithTimers()).resolves.toEqual({ success: false, error: 'Not every connected relay answered' }) + }) + + it('fails on a malformed payload', async () => { + behaviours.set(RELAYS[0]!, { events: [event('{"itemGuids":[1]}')] }) + await expect(fetchWithTimers()).resolves.toMatchObject({ success: false }) + behaviours.set(RELAYS[0]!, { events: [event('not json')] }) + await expect(fetchWithTimers()).resolves.toMatchObject({ success: false }) + }) + + it('returns the newest event and whether it is fresh', async () => { + behaviours.set(RELAYS[0]!, { events: [event('{"itemGuids":["old"]}', 50), event('{"itemGuids":["a"]}', 100)] }) + behaviours.set(RELAYS[1]!, 'silent') + await expect(fetchWithTimers()).resolves.toEqual({ + success: true, + found: true, + data: { itemGuids: ['a'] }, + createdAt: 100, + fresh: true, + complete: false, + }) + localStorage.setItem(APPLIED_CREATEDAT_PREFIX + 'readstr-read-status', '100') + await expect(fetchWithTimers()).resolves.toMatchObject({ found: true, fresh: false }) + }) + + it('marks a found event complete only when every connected relay answered', async () => { + behaviours.set(RELAYS[0]!, { events: [event('{"itemGuids":["a"]}')] }) + behaviours.set(RELAYS[1]!, 'eose') + await expect(fetchWithTimers()).resolves.toMatchObject({ found: true, complete: true }) + }) + + it('fails when the only matching event is too large, rather than reporting none', async () => { + const huge = 'x'.repeat(MAX_CONTENT_BYTES + 1) + behaviours.set(RELAYS[0]!, { events: [event(huge)] }) + behaviours.set(RELAYS[1]!, 'eose') + await expect(fetchWithTimers()).resolves.toEqual({ success: false, error: 'Read status event is too large' }) + }) + + it('ignores an oversized event from another author', async () => { + const other = 'a'.repeat(64) + behaviours.set(RELAYS[0]!, { events: [event('x'.repeat(MAX_CONTENT_BYTES + 1), 100, other)] }) + behaviours.set(RELAYS[1]!, 'eose') + await expect(fetchWithTimers()).resolves.toEqual({ success: true, found: false }) + }) +}) + +describe('publishReadStatus', () => { + const sign = async (e: unknown) => ({ ...(e as object), id: 'x', sig: 'y' }) as never + + it('uses the current second unless the caller asks for a later one', async () => { + vi.setSystemTime(1_000_000_000_000) + await expect(publishReadStatus(['a'], sign)).resolves.toMatchObject({ success: true, createdAt: 1_000_000_000 }) + await expect(publishReadStatus([], sign, 1_000_000_001)).resolves.toMatchObject({ createdAt: 1_000_000_001 }) + await expect(publishReadStatus([], sign, 5)).resolves.toMatchObject({ createdAt: 1_000_000_000 }) + expect(published.map((e) => e.created_at)).toEqual([1_000_000_000, 1_000_000_001, 1_000_000_000]) + }) +}) diff --git a/src/lib/nostr-sync.ts b/src/lib/nostr-sync.ts index 19f4a7b..7088876 100644 --- a/src/lib/nostr-sync.ts +++ b/src/lib/nostr-sync.ts @@ -1,5 +1,5 @@ import { SimplePool, Event, nip19 } from 'nostr-tools' -import type { UnsignedEvent } from 'nostr-tools' +import type { Filter, UnsignedEvent } from 'nostr-tools' import { z } from 'zod' import { normalizeViews, type SavedView } from './saved-views' import { getDefaultRelays, getUserOrDefaultRelays } from './relays' @@ -52,12 +52,12 @@ export interface ReadStatusList { // MAX_CONTENT_BYTES bounds event.content; getNewestReplaceableEvent skips frames // over the cap during selection so an oversized payload is never parsed. It // comfortably covers an honest max-size read-status list (~100k short guids). -const MAX_CONTENT_BYTES = 8 * 1024 * 1024 // max raw event.content length before parsing +export const MAX_CONTENT_BYTES = 8 * 1024 * 1024 // max raw event.content length before parsing const MAX_SYNC_FEEDS = 5000 // max rss/nostr/deleted entries, and tags/categories keys -const MAX_READ_ITEMS = 100000 // max read itemGuids +export const MAX_READ_ITEMS = 100000 // max read itemGuids const MAX_URL_LEN = 2048 // max length of a feed URL / npub const SYNC_QUERY_TIMEOUT_MS = 8000 // max time to wait for relays when fetching sync events -const MAX_GUID_LEN = 256 // max length of a read-status itemGuid +export const MAX_GUID_LEN = 256 // max length of a read-status itemGuid const MAX_TAGS_PER_FEED = 100 // max tags attached to a single feed const MAX_VIEWS_SYNC = 100 // max saved views accepted from a relay payload @@ -86,8 +86,15 @@ const subscriptionListSchema: z.ZodType = z.object({ lastUpdated: z.number().int().nonnegative().optional(), }) -const readStatusListSchema: z.ZodType = z.object({ - itemGuids: z.array(z.string().max(MAX_GUID_LEN)).max(MAX_READ_ITEMS), +// zod's string max counts code points, but both apps measure guids in UTF-16 +// units (string.length here, QString::size on the desktop), so the length is +// checked directly to keep the cap identical on both sides. +export const readGuidSchema = z.string().refine((s) => s.length <= MAX_GUID_LEN, { + message: `guid longer than ${MAX_GUID_LEN} UTF-16 units`, +}) + +export const readStatusListSchema: z.ZodType = z.object({ + itemGuids: z.array(readGuidSchema).max(MAX_READ_ITEMS), lastUpdated: z.number().int().nonnegative().optional(), }) @@ -207,7 +214,78 @@ async function getNewestReplaceableEvent( authors: [pubkeyHex], '#d': [dTag], }, { maxWait: SYNC_QUERY_TIMEOUT_MS }) + return selectNewestEvent(events, pubkeyHex, kind, dTag).newest +} + +/** + * Like pool.querySync, but also reports whether at least one relay sent EOSE. + * querySync resolves the same way when every relay times out or fails to + * connect as when they all answer with nothing, and a caller that publishes a + * replacement needs to tell "no event exists" from "no relay answered". Each + * subscription's own EOSE timeout is set past our deadline, so oneose fires + * only for a real EOSE. The caller closes the pool, which closes any + * subscription still open. + */ +async function queryTrackingEose( + pool: SimplePool, + relays: string[], + filter: Filter, + maxWait: number +): Promise<{ events: Event[]; complete: boolean }> { + const events: Event[] = [] + const subs: { close: () => void }[] = [] + // A publish may have reached a single relay, so "no relay has it" needs an + // EOSE from every relay that connected; one that connected and then timed + // out or closed may hold the only copy. Relays that never connect cannot + // answer either way and are left out, so one dead relay does not block sync. + let connected = 0 + let eosedCount = 0 + let finished = false + let timer: ReturnType | undefined + await new Promise((resolve) => { + let pending = relays.length + const settle = () => { + if (--pending <= 0) resolve() + } + timer = setTimeout(resolve, maxWait) + if (pending === 0) resolve() + for (const url of relays) { + pool.ensureRelay(url, { connectionTimeout: maxWait }).then((relay) => { + if (finished) return + connected++ + let done = false + const finish = () => { + if (done) return + done = true + settle() + } + subs.push(relay.subscribe([filter], { + onevent: (event) => events.push(event), + oneose: () => { + if (!done) eosedCount++ + finish() + }, + onclose: finish, + eoseTimeout: maxWait * 2, + })) + }, settle) + } + }) + finished = true + clearTimeout(timer) + for (const sub of subs) sub.close() + return { events, complete: eosedCount > 0 && eosedCount === connected } +} +// Also reports how many events from the expected author, kind and d-tag were +// skipped for size, so a caller can tell "nothing published" from "the only +// copy was too large to read". +function selectNewestEvent( + events: Event[], + pubkeyHex: string, + kind: number, + dTag: string +): { newest: Event | null; oversizedSkipped: number } { let newest: Event | null = null let oversizedSkipped = 0 for (const event of events) { @@ -223,7 +301,7 @@ async function getNewestReplaceableEvent( if (oversizedSkipped > 0) { console.error(`Skipped ${oversizedSkipped} oversized replaceable event payload(s)`) } - return newest + return { newest, oversizedSkipped } } /** @@ -659,6 +737,38 @@ export function setPrefsSyncEnabled(v: boolean): void { } } +export const READ_SYNC_KEY = 'readstr_read_sync' + +/** + * Whether read status is synced through Nostr (kind 30405). Opt-in, defaults to + * false: the event is cleartext, so it publishes the user's reading history. + */ +// Set when the setting could not be saved. Sync then reads as off for the +// rest of the page session, so turning it off takes effect even when storage +// still holds 'true'. +let readSyncOffOverride = false + +export function getReadSyncEnabled(): boolean { + if (typeof window === 'undefined' || readSyncOffOverride) return false + try { + return localStorage.getItem(READ_SYNC_KEY) === 'true' + } catch { + return false + } +} + +export function setReadSyncEnabled(v: boolean): void { + if (typeof window === 'undefined') return + try { + localStorage.setItem(READ_SYNC_KEY, v ? 'true' : 'false') + readSyncOffOverride = false + } catch (error) { + // Storage disabled: the setting stays off. + readSyncOffOverride = true + console.warn('Could not save the read status sync setting, so sync stays off:', error) + } +} + export const APPLIED_CREATEDAT_PREFIX = 'readstr_applied_createdat:' /** @@ -703,19 +813,23 @@ export function advanceSyncWatermarkIfFresh(dTag: string, createdAt?: number): v } /** - * Publish read status to Nostr relays using kind 30405 + * Publish read status to Nostr relays using kind 30405. The event's created_at + * is at least minCreatedAt, so a caller can keep its own events in order + * within one second: relays keep only the newest replaceable event, and of + * two with the same created_at they may keep either. */ export async function publishReadStatus( readItemGuids: string[], - signEvent: (event: UnsignedEvent) => Promise -): Promise<{ success: boolean; eventId?: string; error?: string }> { + signEvent: (event: UnsignedEvent) => Promise, + minCreatedAt = 0 +): Promise<{ success: boolean; eventId?: string; createdAt?: number; error?: string }> { const pool = new SimplePool() const relays = getSyncRelays() try { const unsignedEvent: UnsignedEvent = { kind: READ_STATUS_KIND, - created_at: Math.floor(Date.now() / 1000), + created_at: Math.max(Math.floor(Date.now() / 1000), minCreatedAt), tags: [ ['d', 'readstr-read-status'], ['client', 'readstr'], @@ -728,12 +842,13 @@ export async function publishReadStatus( } const signedEvent = await signEvent(unsignedEvent) - const publishPromises = pool.publish(relays, signedEvent) - await Promise.race(publishPromises) + // Promise.any, not race: the publish succeeds once any relay accepts it, + // so one relay refusing or being down does not fail it. + await Promise.any(pool.publish(relays, signedEvent)) debugLog('Published read status to Nostr:', signedEvent.id) - return { success: true, eventId: signedEvent.id } + return { success: true, eventId: signedEvent.id, createdAt: signedEvent.created_at } } catch (error) { console.error('Failed to publish read status:', error) return { @@ -745,56 +860,64 @@ export async function publishReadStatus( } } +/** + * Result of fetching the newest kind 30405 event. `found: false` means every + * relay that connected answered (EOSE) and none had an event, which is the + * only case where "nothing published" is known rather than guessed. A timeout, + * a malformed or oversized payload and other errors are `success: false`, so a + * caller never mistakes them for an empty list it may publish over. A found + * event has `complete: false` when some connected relay did not answer: a + * newer event may sit there, so the caller may apply this one but must not + * publish a replacement on the strength of it. + */ +export type ReadStatusFetchResult = + | { success: true; found: false } + | { success: true; found: true; data: ReadStatusList; createdAt: number; fresh: boolean; complete: boolean } + | { success: false; error: string } + /** * Fetch read status from Nostr relays */ -export async function fetchReadStatus( - userPubkey: string -): Promise<{ success: boolean; data?: ReadStatusList; createdAt?: number; error?: string }> { +export async function fetchReadStatus(userPubkey: string): Promise { const pool = new SimplePool() const relays = getSyncRelays() try { const pubkeyHex = getPubkeyHex(userPubkey) - - const event = await getNewestReplaceableEvent( + const { events, complete } = await queryTrackingEose( pool, relays, - pubkeyHex, - READ_STATUS_KIND, - 'readstr-read-status' + { kinds: [READ_STATUS_KIND], authors: [pubkeyHex], '#d': ['readstr-read-status'] }, + SYNC_QUERY_TIMEOUT_MS ) + const { newest: event, oversizedSkipped } = selectNewestEvent(events, pubkeyHex, READ_STATUS_KIND, 'readstr-read-status') if (!event) { - return { - success: true, - data: { itemGuids: [] }, - } + // An event exists but cannot be read, so publishing over it would drop + // whatever it holds. + if (oversizedSkipped > 0) return { success: false, error: 'Read status event is too large' } + return complete + ? { success: true, found: false } + : { success: false, error: 'Not every connected relay answered' } } const parsed = readStatusListSchema.safeParse(JSON.parse(event.content)) if (!parsed.success) { console.error('Rejected malformed read status payload:', parsed.error.message) - return { - success: true, - data: { itemGuids: [] }, - } - } - - // Defense-in-depth: drop stale/replayed events so a relay can't roll back - // read status. The caller advances the watermark on apply (mirrors the - // subscription path), so it isn't persisted here. - if (!isSyncEventFresh('readstr-read-status', event.created_at)) { - return { - success: true, - data: { itemGuids: [] }, - } + return { success: false, error: 'Malformed read status payload' } } + // Defense-in-depth: `fresh` is false for a stale or replayed event, which + // the caller must not apply, so a relay can't roll back read status. The + // caller advances the watermark on apply (mirrors the subscription path), + // so it isn't persisted here. return { success: true, + found: true, data: parsed.data, createdAt: event.created_at, + fresh: isSyncEventFresh('readstr-read-status', event.created_at), + complete, } } catch (error) { console.error('Failed to fetch read status:', error) diff --git a/src/lib/read-sync.test.ts b/src/lib/read-sync.test.ts new file mode 100644 index 0000000..3b85e2c --- /dev/null +++ b/src/lib/read-sync.test.ts @@ -0,0 +1,630 @@ +import type { Event, UnsignedEvent } from 'nostr-tools' +import superjson from 'superjson' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { MAX_TRPC_BODY_BYTES } from '@/trpc/batch-limits' +import { + APPLIED_CREATEDAT_PREFIX, + getReadSyncEnabled, + MAX_GUID_LEN, + MAX_READ_ITEMS, + READ_SYNC_KEY, + readStatusListSchema, + setReadSyncEnabled, + type ReadStatusFetchResult, +} from './nostr-sync' +import { + buildPublishedReadList, + chunkGuidsForRequest, + cleanPulledGuids, + MARK_READ_REQUEST_BYTES, + MAX_PUBLISHED_READ_CONTENT, + newReadSyncSession, + nextReadSyncRetryDelay, + publishReadStatusIfChanged, + pullReadStatus, + READ_STATUS_D_TAG, + READ_SYNC_RETRY_MAX_MS, + READ_SYNC_RETRY_MIN_MS, + readSyncAllowed, + withdrawReadStatus, +} from './read-sync' + +const NPUB = 'npub1test' +const WATERMARK = APPLIED_CREATEDAT_PREFIX + READ_STATUS_D_TAG + +function fakeStorage() { + const data = new Map() + return { + data, + getItem: (k: string) => data.get(k) ?? null, + setItem: (k: string, v: string) => void data.set(k, v), + removeItem: (k: string) => void data.delete(k), + } +} + +let storage: ReturnType + +beforeEach(() => { + storage = fakeStorage() + vi.stubGlobal('window', {}) + vi.stubGlobal('localStorage', storage) +}) + +afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('read sync setting', () => { + it('defaults to off and round-trips', () => { + expect(getReadSyncEnabled()).toBe(false) + setReadSyncEnabled(true) + expect(storage.data.get(READ_SYNC_KEY)).toBe('true') + expect(getReadSyncEnabled()).toBe(true) + setReadSyncEnabled(false) + expect(getReadSyncEnabled()).toBe(false) + }) + + it('is off on the server and when storage throws', () => { + vi.stubGlobal('localStorage', { + getItem: () => { + throw new Error('SecurityError') + }, + }) + expect(getReadSyncEnabled()).toBe(false) + vi.stubGlobal('window', undefined) + expect(getReadSyncEnabled()).toBe(false) + }) + + it('stays off for the page session when turning it off cannot be saved', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + setReadSyncEnabled(true) + storage.setItem = () => { + throw new Error('QuotaExceededError') + } + setReadSyncEnabled(false) + expect(storage.data.get(READ_SYNC_KEY)).toBe('true') + expect(getReadSyncEnabled()).toBe(false) + expect(warn).toHaveBeenCalled() + setReadSyncEnabled(true) + expect(getReadSyncEnabled()).toBe(false) + // Saving works again, so the stored setting counts once more. + storage.setItem = (k: string, v: string) => void storage.data.set(k, v) + setReadSyncEnabled(true) + expect(getReadSyncEnabled()).toBe(true) + }) +}) + +describe('nextReadSyncRetryDelay', () => { + it('doubles from 30 seconds up to 10 minutes', () => { + const delays = [READ_SYNC_RETRY_MIN_MS] + for (let i = 0; i < 6; i++) delays.push(nextReadSyncRetryDelay(delays.at(-1)!)) + expect(delays).toEqual([30_000, 60_000, 120_000, 240_000, 480_000, 600_000, 600_000]) + expect(READ_SYNC_RETRY_MAX_MS).toBe(600_000) + }) +}) + +describe('readSyncAllowed', () => { + it('needs the setting, a signer and an npub', () => { + expect(readSyncAllowed(true, NPUB)).toBe(false) + setReadSyncEnabled(true) + expect(readSyncAllowed(true, NPUB)).toBe(true) + expect(readSyncAllowed(false, NPUB)).toBe(false) + expect(readSyncAllowed(true, undefined)).toBe(false) + expect(readSyncAllowed(true, '')).toBe(false) + }) +}) + +describe('chunkGuidsForRequest', () => { + it('keeps every guid in order and each chunk within the byte budget', () => { + const guids = Array.from({ length: 5000 }, (_, i) => `https://example.com/post/${i}?รผ=${'x'.repeat(i % 200)}`) + const chunks = chunkGuidsForRequest(guids) + expect(chunks.flat()).toEqual(guids) + expect(chunks.length).toBeGreaterThan(1) + for (const part of chunks) { + expect(new TextEncoder().encode(JSON.stringify(part)).length).toBeLessThanOrEqual(MARK_READ_REQUEST_BYTES + 1) + } + }) + + it('returns no chunks for no guids', () => { + expect(chunkGuidsForRequest([])).toEqual([]) + }) + + it('keeps every markReadByGuids request body under the route cap, even with the worst guids', () => { + // JSON escapes a control character to six bytes, the most any one UTF-16 + // unit costs, so these are the largest guids the schema accepts. + const worst = Array.from({ length: 2000 }, (_, i) => `${i}`.padEnd(MAX_GUID_LEN, '\u0001')) + const mixed = Array.from({ length: 2000 }, (_, i) => `${i}`.padEnd(MAX_GUID_LEN / 2, '๐Ÿ˜€')) + for (const guids of [worst, mixed]) { + for (const part of chunkGuidsForRequest(guids)) { + // The httpBatchLink body: inputs keyed by their index in the batch. + // Room is left for ~200 markAsRead calls (~45 bytes each) batched alongside. + const body = JSON.stringify({ 0: superjson.serialize({ guids: part }) }) + expect(new TextEncoder().encode(body).length + 200 * 45).toBeLessThan(MAX_TRPC_BODY_BYTES) + } + } + }) +}) + +describe('readStatusListSchema caps', () => { + it('accepts the maximum and rejects past it', () => { + expect(readStatusListSchema.safeParse({ itemGuids: ['a'.repeat(MAX_GUID_LEN)] }).success).toBe(true) + expect(readStatusListSchema.safeParse({ itemGuids: ['a'.repeat(MAX_GUID_LEN + 1)] }).success).toBe(false) + expect(readStatusListSchema.safeParse({ itemGuids: Array(MAX_READ_ITEMS).fill('g') }).success).toBe(true) + expect(readStatusListSchema.safeParse({ itemGuids: Array(MAX_READ_ITEMS + 1).fill('g') }).success).toBe(false) + }) + + it('measures guids in UTF-16 units, as the desktop does, not code points', () => { + // 129 code points but 258 UTF-16 units. + expect(readStatusListSchema.safeParse({ itemGuids: ['๐Ÿ˜€'.repeat(129)] }).success).toBe(false) + expect(readStatusListSchema.safeParse({ itemGuids: ['๐Ÿ˜€'.repeat(MAX_GUID_LEN / 2)] }).success).toBe(true) + }) +}) + +describe('cleanPulledGuids', () => { + it('drops empty, whitespace-only and duplicate guids, keeping order', () => { + expect(cleanPulledGuids(['b', '', ' ', 'a', 'b', '\t', ' c '])).toEqual(['b', 'a', ' c ']) + }) +}) + +describe('buildPublishedReadList', () => { + it('puts local keys first, then the remote keys it lacks', () => { + expect(buildPublishedReadList(['c', 'a'], ['a', 'x', 'y'])).toEqual(['c', 'a', 'x', 'y']) + }) + + it('stays under the publish cap, keeping the newest local keys', () => { + const local = Array.from({ length: 5000 }, (_, i) => `local-${i}`) + const list = buildPublishedReadList(local, ['remote']) + expect(list).toEqual(local.slice(0, list.length)) + expect(JSON.stringify({ itemGuids: list, lastUpdated: 1_900_000_000 }).length).toBeLessThanOrEqual(MAX_PUBLISHED_READ_CONTENT) + }) +}) + +const ok = (createdAt = 200) => + vi.fn(async (_guids: string[], sign: (event: UnsignedEvent) => Promise, _minCreatedAt?: number) => { + await sign({} as UnsignedEvent) + return { success: true, createdAt } + }) +const signEvent = vi.fn(async (event: UnsignedEvent) => event as Event) + +function pulledSession(remote: string[] | null = null) { + return { ...newReadSyncSession(NPUB), pulled: true, remote } +} + +describe('pullReadStatus', () => { + const remote = (itemGuids: string[], createdAt = 100, fresh = true, complete = true) => + vi.fn(async (): Promise => ({ success: true, found: true, data: { itemGuids }, createdAt, fresh, complete })) + const base = (session = newReadSyncSession(NPUB)) => ({ + canSign: () => true, + npub: () => NPUB, + session, + onApplied: vi.fn(), + }) + + it('does nothing when the setting is off or the user cannot sign', async () => { + const fetchRemote = remote(['a']) + const markRead = vi.fn(async () => {}) + await pullReadStatus({ ...base(), markRead, fetchRemote }) + setReadSyncEnabled(true) + await pullReadStatus({ ...base(), canSign: () => false, markRead, fetchRemote }) + await pullReadStatus({ ...base(), npub: () => undefined, markRead, fetchRemote }) + expect(fetchRemote).not.toHaveBeenCalled() + expect(markRead).not.toHaveBeenCalled() + }) + + it('applies a fresh event, then advances the watermark and records what the relays hold', async () => { + setReadSyncEnabled(true) + const session = newReadSyncSession(NPUB) + const markRead = vi.fn(async () => {}) + const opts = { ...base(session), markRead, fetchRemote: remote(['b', '', 'a', 'b']) } + await expect(pullReadStatus(opts)).resolves.toBe(true) + expect(markRead).toHaveBeenCalledWith(['b', 'a']) + expect(opts.onApplied).toHaveBeenCalledOnce() + expect(storage.data.get(WATERMARK)).toBe('100') + expect(session).toMatchObject({ pulled: true, remote: ['b', 'a'] }) + }) + + it('skips stale events but still learns what the relays hold', async () => { + setReadSyncEnabled(true) + storage.data.set(WATERMARK, '100') + const markRead = vi.fn(async () => {}) + for (const fetchRemote of [remote(['a'], 100), remote(['a'], 50), remote(['a'], 150, false)]) { + const session = newReadSyncSession(NPUB) + await expect(pullReadStatus({ ...base(session), markRead, fetchRemote })).resolves.toBe(true) + expect(session).toMatchObject({ pulled: true, remote: ['a'] }) + } + expect(markRead).not.toHaveBeenCalled() + expect(storage.data.get(WATERMARK)).toBe('100') + }) + + it('applies an event found while a relay did not answer, but keeps publishing locked', async () => { + setReadSyncEnabled(true) + const markRead = vi.fn(async () => {}) + const session = newReadSyncSession(NPUB) + const opts = { ...base(session), markRead, fetchRemote: remote(['a'], 100, true, false) } + await expect(pullReadStatus(opts)).resolves.toBe(false) + expect(markRead).toHaveBeenCalledWith(['a']) + expect(session).toMatchObject({ pulled: false, remote: ['a'] }) + const publish = ok() + await publishReadStatusIfChanged({ ...base(session), fetchLocal: async () => ['a', 'b'], signEvent, publish }) + expect(publish).not.toHaveBeenCalled() + + // The same for an event already applied here. + const stale = newReadSyncSession(NPUB) + await expect(pullReadStatus({ ...base(stale), markRead, fetchRemote: remote(['c'], 100, true, false) })).resolves.toBe(false) + expect(stale).toMatchObject({ pulled: false, remote: ['c'] }) + }) + + it('unlocks publishing when no relay has an event', async () => { + setReadSyncEnabled(true) + const session = newReadSyncSession(NPUB) + const fetchRemote = vi.fn(async (): Promise => ({ success: true, found: false })) + await expect(pullReadStatus({ ...base(session), markRead: vi.fn(), fetchRemote })).resolves.toBe(true) + expect(session).toMatchObject({ pulled: true, remote: null }) + }) + + it('keeps publishing locked when no relay answered or the payload was malformed', async () => { + setReadSyncEnabled(true) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + for (const error of ['No relay answered', 'Malformed read status payload']) { + const session = newReadSyncSession(NPUB) + const fetchRemote = vi.fn(async (): Promise => ({ success: false, error })) + await expect(pullReadStatus({ ...base(session), markRead: vi.fn(), fetchRemote })).resolves.toBe(false) + expect(session.pulled).toBe(false) + const publish = ok() + await publishReadStatusIfChanged({ ...base(session), fetchLocal: async () => ['a'], signEvent, publish }) + expect(publish).not.toHaveBeenCalled() + } + }) + + it('keeps the watermark and the lock when applying fails, so the next pull retries', async () => { + setReadSyncEnabled(true) + vi.spyOn(console, 'error').mockImplementation(() => {}) + const session = newReadSyncSession(NPUB) + const markRead = vi.fn(async () => { + throw new Error('429') + }) + const opts = { ...base(session), markRead, fetchRemote: remote(['a']) } + await expect(pullReadStatus(opts)).resolves.toBe(false) + expect(opts.onApplied).not.toHaveBeenCalled() + expect(storage.data.has(WATERMARK)).toBe(false) + expect(session).toMatchObject({ pulled: false, remote: null }) + }) + + it('stops between chunks when the account changes, the setting turns off or it is cancelled', async () => { + setReadSyncEnabled(true) + const guids = Array.from({ length: 3000 }, (_, i) => `https://example.com/${'p'.repeat(40)}/${i}`) + expect(chunkGuidsForRequest(guids).length).toBeGreaterThan(2) + const stops: Array<(state: { npub: string; cancelled: boolean }) => void> = [ + (state) => void (state.npub = 'npub1other'), + () => setReadSyncEnabled(false), + (state) => void (state.cancelled = true), + ] + for (const stop of stops) { + setReadSyncEnabled(true) + const state = { npub: NPUB, cancelled: false } + const session = newReadSyncSession(NPUB) + const markRead = vi.fn(async () => stop(state)) + const opts = { + ...base(session), + npub: () => state.npub, + isCancelled: () => state.cancelled, + markRead, + fetchRemote: remote(guids), + } + await expect(pullReadStatus(opts)).resolves.toBe(false) + expect(markRead).toHaveBeenCalledOnce() + expect(opts.onApplied).not.toHaveBeenCalled() + expect(storage.data.has(WATERMARK)).toBe(false) + expect(session.pulled).toBe(false) + } + }) + + it('drops a result that arrives after the account changed', async () => { + setReadSyncEnabled(true) + let npub = NPUB + const markRead = vi.fn() + const fetchRemote = vi.fn(async (): Promise => { + npub = 'npub1other' + return { success: true, found: true, data: { itemGuids: ['a'] }, createdAt: 100, fresh: true, complete: true } + }) + await expect(pullReadStatus({ ...base(), npub: () => npub, markRead, fetchRemote })).resolves.toBe(false) + expect(markRead).not.toHaveBeenCalled() + }) + + // Sync turned off and on again while the pull is in flight: the withdrawal + // records [], and the older pulled list must not replace it. + async function withdrawMidPull(session: ReturnType) { + setReadSyncEnabled(false) + await withdrawReadStatus({ canSign: () => true, npub: () => NPUB, session, signEvent, publish: ok(300) }) + setReadSyncEnabled(true) + } + + it('keeps a withdrawal made while a fresh event was being applied', async () => { + setReadSyncEnabled(true) + const session = newReadSyncSession(NPUB) + const markRead = vi.fn(async () => withdrawMidPull(session)) + const opts = { ...base(session), markRead, fetchRemote: remote(['old'], 100, true, false) } + await expect(pullReadStatus(opts)).resolves.toBe(true) + expect(markRead).toHaveBeenCalledWith(['old']) + expect(session).toMatchObject({ pulled: true, remote: [] }) + }) + + it('keeps a withdrawal made while fetching an event already applied here', async () => { + setReadSyncEnabled(true) + const session = newReadSyncSession(NPUB) + const fetchRemote = vi.fn(async (): Promise => { + await withdrawMidPull(session) + return { success: true, found: true, data: { itemGuids: ['old'] }, createdAt: 100, fresh: false, complete: true } + }) + await expect(pullReadStatus({ ...base(session), markRead: vi.fn(), fetchRemote })).resolves.toBe(true) + expect(session).toMatchObject({ pulled: true, remote: [] }) + }) + + it('makes the next publish and withdrawal go after the newest pulled event', async () => { + setReadSyncEnabled(true) + storage.data.set(WATERMARK, '2000') + const markRead = vi.fn(async () => {}) + // A stale event from a pull a relay did not fully answer counts as much as a complete one. + for (const fetchRemote of [remote(['a'], 1000, false, false), remote(['a'], 1000, true, true)]) { + const session = newReadSyncSession(NPUB) + await pullReadStatus({ ...base(session), markRead, fetchRemote }) + expect(session.latestSeenAt).toBe(1000) + session.pulled = true + const publish = ok(1001) + await publishReadStatusIfChanged({ ...base(session), signEvent, publish, fetchLocal: async () => ['b'] }) + expect(publish).toHaveBeenLastCalledWith(['b', 'a'], expect.any(Function), 1001) + setReadSyncEnabled(false) + await withdrawReadStatus({ ...base(session), signEvent, publish }) + expect(publish).toHaveBeenLastCalledWith([], signEvent, 1002) + setReadSyncEnabled(true) + } + }) + + it('never lowers the publish floor when a pull finds an older event', async () => { + setReadSyncEnabled(true) + const session = pulledSession() + await publishReadStatusIfChanged({ ...base(session), signEvent, publish: ok(500), fetchLocal: async () => ['a'] }) + await pullReadStatus({ ...base(session), markRead: vi.fn(async () => {}), fetchRemote: remote(['x'], 100, false) }) + expect(session.latestSeenAt).toBe(500) + expect(newReadSyncSession(NPUB).latestSeenAt).toBeNull() + }) + + it('raises the publish floor from an event found just before the pull stopped', async () => { + setReadSyncEnabled(true) + const session = newReadSyncSession(NPUB) + const fetchRemote = vi.fn(async (): Promise => { + setReadSyncEnabled(false) + return { success: true, found: true, data: { itemGuids: ['a'] }, createdAt: 900, fresh: true, complete: true } + }) + await expect(pullReadStatus({ ...base(session), markRead: vi.fn(), fetchRemote })).resolves.toBe(false) + const publish = ok(901) + await withdrawReadStatus({ ...base(session), signEvent, publish }) + expect(publish).toHaveBeenCalledWith([], signEvent, 901) + }) +}) + +describe('publishReadStatusIfChanged', () => { + const opts = (session = pulledSession()) => ({ canSign: () => true, npub: () => NPUB, session, signEvent }) + + it('does nothing when the setting is off, the user cannot sign or the account changed', async () => { + const fetchLocal = vi.fn(async () => ['a']) + const publish = ok() + await publishReadStatusIfChanged({ ...opts(), fetchLocal, publish }) + setReadSyncEnabled(true) + await publishReadStatusIfChanged({ ...opts(), canSign: () => false, fetchLocal, publish }) + await publishReadStatusIfChanged({ ...opts(), npub: () => 'npub1other', fetchLocal, publish }) + expect(fetchLocal).not.toHaveBeenCalled() + expect(publish).not.toHaveBeenCalled() + }) + + it('waits for a successful pull', async () => { + setReadSyncEnabled(true) + const fetchLocal = vi.fn(async () => ['a']) + const publish = ok() + await publishReadStatusIfChanged({ ...opts(newReadSyncSession(NPUB)), fetchLocal, publish }) + expect(fetchLocal).not.toHaveBeenCalled() + expect(publish).not.toHaveBeenCalled() + }) + + it('publishes a changed list once and skips one the relays already hold', async () => { + setReadSyncEnabled(true) + const session = pulledSession() + const publish = ok() + await publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['a', 'b'] }) + await publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['b', 'a'] }) + expect(publish).toHaveBeenCalledOnce() + expect(publish).toHaveBeenCalledWith(['a', 'b'], expect.any(Function), 0) + + // Echo guard: right after a pull applied the list, the server's list adds nothing. + const pulled = pulledSession(['c', 'd']) + await publishReadStatusIfChanged({ ...opts(pulled), publish, fetchLocal: async () => ['d', 'c'] }) + await publishReadStatusIfChanged({ ...opts(pulled), publish, fetchLocal: async () => [] }) + expect(publish).toHaveBeenCalledOnce() + }) + + it('publishes local keys first, then the pulled keys this server lacks', async () => { + setReadSyncEnabled(true) + const session = pulledSession(['old', 'elsewhere']) + const publish = ok() + await publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['new', 'old'] }) + expect(publish).toHaveBeenCalledWith(['new', 'old', 'elsewhere'], expect.any(Function), 0) + expect(session.remote).toEqual(['new', 'old', 'elsewhere']) + }) + + it('does not republish a capped subset of a bigger pulled list', async () => { + setReadSyncEnabled(true) + const big = Array.from({ length: 5000 }, (_, i) => `remote-${i}`) + const session = pulledSession(big) + const publish = ok() + await publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => big.slice(0, 10) }) + expect(publish).not.toHaveBeenCalled() + }) + + it('advances the watermark to its own event, so the next pull skips it', async () => { + setReadSyncEnabled(true) + storage.data.set(WATERMARK, '100') + await publishReadStatusIfChanged({ ...opts(), publish: ok(250), fetchLocal: async () => ['a'] }) + expect(storage.data.get(WATERMARK)).toBe('250') + }) + + it('does not advance the shared watermark once the account changed during the publish', async () => { + setReadSyncEnabled(true) + storage.data.set(WATERMARK, '100') + let npub = NPUB + const session = pulledSession() + const publish = vi.fn(async () => { + npub = 'npub1other' + return { success: true, createdAt: 250 } + }) + await publishReadStatusIfChanged({ ...opts(session), npub: () => npub, publish, fetchLocal: async () => ['a'] }) + expect(storage.data.get(WATERMARK)).toBe('100') + expect(session.remote).toEqual(['a']) + }) + + it('gives each publish a created_at after the last one this session published', async () => { + setReadSyncEnabled(true) + const session = pulledSession() + const publish = ok(500) + await publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['a'] }) + await publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['a', 'b'] }) + expect(publish.mock.calls.map((call) => call[2])).toEqual([0, 501]) + expect(session.latestSeenAt).toBe(500) + }) + + it('re-checks the setting before signing a publish already past its gate', async () => { + setReadSyncEnabled(true) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const sign = vi.fn(async (event: UnsignedEvent) => event as Event) + const publish = vi.fn(async (_guids: string[], s: (event: UnsignedEvent) => Promise) => { + try { + await s({} as UnsignedEvent) + return { success: true, createdAt: 200 } + } catch (error) { + return { success: false, error: String(error) } + } + }) + const session = pulledSession() + await publishReadStatusIfChanged({ + ...opts(session), + signEvent: sign, + publish, + fetchLocal: async () => { + setReadSyncEnabled(false) + return ['a'] + }, + }) + expect(sign).not.toHaveBeenCalled() + expect(session.remote).toBeNull() + expect(storage.data.has(WATERMARK)).toBe(false) + }) + + it('retries a list whose publish failed and never throws', async () => { + setReadSyncEnabled(true) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + const session = pulledSession() + const publish = vi.fn(async () => ({ success: false, error: 'no relay' })) + const o = { ...opts(session), publish, fetchLocal: async () => ['a'] } + await publishReadStatusIfChanged(o) + await publishReadStatusIfChanged(o) + expect(publish).toHaveBeenCalledTimes(2) + await expect( + publishReadStatusIfChanged({ ...o, fetchLocal: async () => Promise.reject(new Error('down')) }) + ).resolves.toBeUndefined() + }) + + it('keeps running queued publishes after a rejected one', async () => { + setReadSyncEnabled(true) + const session = pulledSession() + session.queue = Promise.reject(new Error('earlier failure')) + const publish = ok() + await publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['a'] }) + expect(publish).toHaveBeenCalledOnce() + }) + + it('runs queued publishes one at a time', async () => { + setReadSyncEnabled(true) + const session = pulledSession() + let active = 0 + let maxActive = 0 + const publish = vi.fn(async () => { + active++ + maxActive = Math.max(maxActive, active) + await new Promise((r) => setTimeout(r, 5)) + active-- + return { success: true } + }) + await Promise.all([ + publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['a'] }), + publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['a', 'b'] }), + ]) + expect(publish).toHaveBeenCalledTimes(2) + expect(maxActive).toBe(1) + }) +}) + +describe('withdrawReadStatus', () => { + const opts = (session = pulledSession(['a'])) => ({ canSign: () => true, npub: () => NPUB, session, signEvent }) + + it('publishes an empty list once the setting is off', async () => { + const session = pulledSession(['a']) + const publish = ok(300) + await withdrawReadStatus({ ...opts(session), publish }) + expect(publish).toHaveBeenCalledWith([], signEvent, 0) + expect(session.remote).toEqual([]) + expect(storage.data.get(WATERMARK)).toBe('300') + }) + + it('does not advance the shared watermark once the account changed during the withdrawal', async () => { + storage.data.set(WATERMARK, '100') + let npub = NPUB + const session = pulledSession(['a']) + const publish = vi.fn(async () => { + npub = 'npub1other' + return { success: true, createdAt: 300 } + }) + await withdrawReadStatus({ ...opts(session), npub: () => npub, publish }) + expect(publish).toHaveBeenCalledOnce() + expect(storage.data.get(WATERMARK)).toBe('100') + }) + + it('skips when the setting is back on, the user cannot sign or the account changed', async () => { + const publish = ok() + await withdrawReadStatus({ ...opts(), canSign: () => false, publish }) + await withdrawReadStatus({ ...opts(), npub: () => 'npub1other', publish }) + setReadSyncEnabled(true) + await withdrawReadStatus({ ...opts(), publish }) + expect(publish).not.toHaveBeenCalled() + }) + + it('runs after a publish already queued, which then stops before signing', async () => { + setReadSyncEnabled(true) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const session = pulledSession() + const calls: string[][] = [] + const publish = vi.fn(async (guids: string[], s: (event: UnsignedEvent) => Promise) => { + try { + await s({} as UnsignedEvent) + } catch (error) { + return { success: false, error: String(error) } + } + calls.push(guids) + return { success: true, createdAt: 400 } + }) + const queued = publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['a'] }) + setReadSyncEnabled(false) + await Promise.all([queued, withdrawReadStatus({ ...opts(session), publish })]) + expect(calls).toEqual([[]]) + }) + + it('goes after a list this session published in the same second', async () => { + setReadSyncEnabled(true) + const session = pulledSession() + const publish = ok(400) + await publishReadStatusIfChanged({ ...opts(session), publish, fetchLocal: async () => ['a'] }) + setReadSyncEnabled(false) + await withdrawReadStatus({ ...opts(session), publish }) + expect(publish).toHaveBeenLastCalledWith([], signEvent, 401) + }) +}) diff --git a/src/lib/read-sync.ts b/src/lib/read-sync.ts new file mode 100644 index 0000000..b8dad30 --- /dev/null +++ b/src/lib/read-sync.ts @@ -0,0 +1,351 @@ +import type { Event, UnsignedEvent } from 'nostr-tools' +import { + advanceSyncWatermarkIfFresh, + fetchReadStatus, + getReadSyncEnabled, + isSyncEventFresh, + MAX_GUID_LEN, + MAX_READ_ITEMS, + publishReadStatus, +} from './nostr-sync' + +export const READ_STATUS_D_TAG = 'readstr-read-status' + +// Read changes come in bursts (auto-mark), and each publish re-sends the whole +// list, so wait for a quiet spell. +export const READ_SYNC_PUBLISH_DELAY_MS = 30_000 + +// The /api/trpc route refuses bodies over 64,000 bytes. Applying a pulled list +// is split into calls whose guids take at most this many UTF-8 bytes, which +// leaves room for the tRPC envelope and small mutations batched alongside. +export const MARK_READ_REQUEST_BYTES = 48_000 + +// Common strfry relays (damus, nos.lol) refuse events over 64 KiB of JSON, so a +// bigger list would fail to publish without any error. The web publishes only +// the newest reads that fit this budget. Pulls still accept lists up to +// MAX_CONTENT_BYTES, since other clients may publish bigger ones. +export const MAX_PUBLISHED_READ_CONTENT = 60_000 + +// Room for the {"itemGuids":[],"lastUpdated":...} wrapper and the event's own +// fields (id, pubkey, sig, tags, created_at), so the whole event stays under +// the relays' limit. +const CONTENT_ENVELOPE_RESERVE = 1024 + +const utf8 = new TextEncoder() + +// What one key adds to the published event: its JSON string and a comma in +// content, escaped a second time when content is embedded in the event JSON, +// in UTF-8 bytes. Relays limit the event's JSON in bytes, and this is never +// less than the key's UTF-16 length in content, so the content cap holds too. +function publishedKeyCost(key: string): number { + return utf8.encode(JSON.stringify(JSON.stringify(key))).length - 1 +} + +/** + * Collects read-status keys in the order given (newest read first), skipping + * duplicates and keys over MAX_GUID_LEN UTF-16 units, until the list would + * break readStatusListSchema or the published event would pass + * MAX_PUBLISHED_READ_CONTENT. It stops at the first key that does not fit, so + * the result is always a prefix of the newest reads. + */ +export class ReadSyncGuidCollector { + readonly guids: string[] = [] + private readonly seen = new Set() + private size = CONTENT_ENVELOPE_RESERVE + private done = false + + constructor( + private readonly maxItems = MAX_READ_ITEMS, + private readonly maxSize = MAX_PUBLISHED_READ_CONTENT + ) {} + + get full(): boolean { + return this.done || this.guids.length >= this.maxItems + } + + add(key: string | null): void { + if (this.full || !key || key.length > MAX_GUID_LEN || this.seen.has(key)) return + const cost = publishedKeyCost(key) + if (this.size + cost > this.maxSize) { + this.done = true + return + } + this.size += cost + this.seen.add(key) + this.guids.push(key) + } +} + +/** + * The list to publish: this server's keys first (newest read first), then the + * keys of the last list seen on the relays that this server lacks, so a key + * another device published is not dropped just because no feed here has it. + * Everything is under the publish cap. + */ +export function buildPublishedReadList(local: string[], remote: string[]): string[] { + const collector = new ReadSyncGuidCollector() + for (const key of local) collector.add(key) + for (const key of remote) collector.add(key) + return collector.guids +} + +export function readSyncAllowed(canSign: boolean, npub: string | null | undefined): boolean { + return canSign && !!npub && getReadSyncEnabled() +} + +export function chunkGuidsForRequest(guids: string[], maxBytes = MARK_READ_REQUEST_BYTES): string[][] { + const chunks: string[][] = [] + let current: string[] = [] + let bytes = 0 + for (const guid of guids) { + const cost = utf8.encode(JSON.stringify(guid)).length + 1 + if (current.length > 0 && bytes + cost > maxBytes) { + chunks.push(current) + current = [] + bytes = 0 + } + current.push(guid) + bytes += cost + } + if (current.length > 0) chunks.push(current) + return chunks +} + +/** Pulled guids without empty or whitespace-only entries and duplicates, in order. */ +export function cleanPulledGuids(guids: string[]): string[] { + const seen = new Set() + const out: string[] = [] + for (const guid of guids) { + if (!guid.trim() || seen.has(guid)) continue + seen.add(guid) + out.push(guid) + } + return out +} + +/** Per-account session state for read-status sync. */ +export interface ReadSyncSession { + // The account this state belongs to. Work queued for another account stops. + npub: string | null + // True once a pull that every connected relay answered applied the newest + // event, or found that it was already applied here, or that none exists. + // Publishing waits for it: a publish replaces the event, so one made after a + // failed or partial pull could drop reads another device published. + pulled: boolean + // The guids of the newest event known to be on the relays (pulled or + // published here), or null when unknown. Publishes add to it rather than + // drop its keys, and a list it already covers is not published again. + remote: string[] | null + // Bumped each time a publish or withdrawal records what the relays hold. A + // pull compares it with the value it saw at the start, so a result fetched + // before that publish does not overwrite the newer `remote`. + remoteVersion: number + // The greatest created_at this session has published or seen in a pulled + // event, or null. The next publish goes strictly after it, so it replaces + // that event even when made within the same second or under a clock that + // runs behind another device's. + latestSeenAt: number | null + queue: Promise +} + +export function newReadSyncSession(npub: string | null = null): ReadSyncSession { + return { npub, pulled: false, remote: null, remoteVersion: 0, latestSeenAt: null, queue: Promise.resolve() } +} + +// Retry delays for a pull that failed or that not every relay answered. +export const READ_SYNC_RETRY_MIN_MS = 30_000 +export const READ_SYNC_RETRY_MAX_MS = 10 * 60_000 + +/** The delay after `delay` when a retried pull fails again: doubled, capped. */ +export function nextReadSyncRetryDelay(delay: number): number { + return Math.min(delay * 2, READ_SYNC_RETRY_MAX_MS) +} + +type SignEvent = (event: UnsignedEvent) => Promise + +// Sync is allowed and the signed-in account is still the session's, so work +// queued for an earlier account stops. +function sessionAllowed(opts: { + canSign: () => boolean + npub: () => string | null | undefined + session: ReadSyncSession +}): boolean { + const npub = opts.npub() + return readSyncAllowed(opts.canSign(), npub) && npub === opts.session.npub +} + +/** + * Pull the newest kind 30405 event and mark its guids read on the server. + * Additive only. The pull stops between chunks once it is cancelled, the + * setting is turned off or the account changes. The watermark advances only + * once every chunk is applied, so a failed or stopped apply is retried on the + * next pull. A pull that not every connected relay answered still applies + * what it found, but leaves publishing locked. Returns whether publishing is + * now safe (see ReadSyncSession.pulled), so false means "retry the pull". + * Never throws. + */ +export async function pullReadStatus(opts: { + canSign: () => boolean + npub: () => string | null | undefined + isCancelled?: () => boolean + session: ReadSyncSession + markRead: (guids: string[]) => Promise + onApplied: () => void + fetchRemote?: typeof fetchReadStatus +}): Promise { + const { session } = opts + const live = () => !opts.isCancelled?.() && sessionAllowed(opts) + if (!live()) return false + const remoteVersion = session.remoteVersion + // A publish or withdrawal that finished during the pull already set what the + // relays hold, after the pulled event, so the pulled list must not replace + // it. Publishing is then safe too, since that publish set the relay state. + const settle = (guids: string[], complete: boolean): boolean => { + if (session.remoteVersion !== remoteVersion) { + session.pulled = true + return true + } + session.remote = guids + session.pulled = complete + return complete + } + try { + const result = await (opts.fetchRemote ?? fetchReadStatus)(session.npub!) + // Raised even when the pull then stops, so a withdrawal made right after + // still goes after the event the relays hold. + if (result.success && result.found) raiseLatestSeenAt(session, result.createdAt) + if (!live()) return false + if (!result.success) { + console.warn('Read status sync fetch failed:', result.error) + return false + } + if (!result.found) { + session.pulled = true + return true + } + const guids = cleanPulledGuids(result.data.itemGuids) + if (!result.fresh || !isSyncEventFresh(READ_STATUS_D_TAG, result.createdAt)) { + // Applied before, or published by this device: nothing to apply, but it + // is what the relays hold, so publishes build on it. + return settle(guids, result.complete) + } + for (const part of chunkGuidsForRequest(guids)) { + if (!live()) return false + await opts.markRead(part) + } + if (!live()) return false + opts.onApplied() + advanceSyncWatermarkIfFresh(READ_STATUS_D_TAG, result.createdAt) + return settle(guids, result.complete) + } catch (error) { + console.error('Read status sync pull failed:', error) + return false + } +} + +const turnedOff = () => new Error('Read status sync was turned off') + +function raiseLatestSeenAt(session: ReadSyncSession, createdAt: number): void { + if (session.latestSeenAt == null || createdAt > session.latestSeenAt) session.latestSeenAt = createdAt +} + +// The lowest created_at the session's next event may have. +function nextCreatedAt(session: ReadSyncSession): number { + return session.latestSeenAt == null ? 0 : session.latestSeenAt + 1 +} + +// The watermark is shared by every account on this device, so it only moves +// while the session's account is still the signed-in one; otherwise one +// account's publish could make the next account skip its own newer event. +function recordPublished( + session: ReadSyncSession, + guids: string[], + createdAt: number | undefined, + npub: string | null | undefined +): void { + session.remote = guids + session.remoteVersion++ + if (createdAt != null) raiseLatestSeenAt(session, createdAt) + if (npub === session.npub) advanceSyncWatermarkIfFresh(READ_STATUS_D_TAG, createdAt) +} + +/** + * Publish the union of the server's read guids and the last list seen on the + * relays, unless the relays already hold every guid in it. Waits for a + * successful pull. Publishes are queued so two never race, and a failed one + * does not block the next. Never throws. + */ +export function publishReadStatusIfChanged(opts: { + canSign: () => boolean + npub: () => string | null | undefined + session: ReadSyncSession + fetchLocal: () => Promise + signEvent: SignEvent + publish?: typeof publishReadStatus +}): Promise { + const { session } = opts + const allowed = () => sessionAllowed(opts) + const run = async () => { + try { + // Re-checked when the queued run starts: the setting or signer may have + // changed during the debounce. + if (!allowed() || !session.pulled) return + const local = await opts.fetchLocal() + const guids = buildPublishedReadList(local, session.remote ?? []) + const remote = new Set(session.remote ?? []) + if (guids.every((guid) => remote.has(guid))) return + // Checked again around signing, so turning the setting off while this + // run waits on the server or the signer stops it before it publishes. + const result = await (opts.publish ?? publishReadStatus)( + guids, + async (event) => { + if (!allowed()) throw turnedOff() + const signed = await opts.signEvent(event) + if (!allowed()) throw turnedOff() + return signed + }, + nextCreatedAt(session) + ) + if (result.success) recordPublished(session, guids, result.createdAt, opts.npub()) + else { + console.warn('Read status auto-export failed:', result.error) + } + } catch (error) { + console.error('Read status auto-export failed:', error) + } + } + session.queue = session.queue.then(run, run) + return session.queue +} + +/** + * After the setting is turned off, replace the published list with an empty + * one, best effort. Relays and other clients may keep older copies. Queued + * behind any publish in flight, and skipped if the setting was turned back on + * or the account changed by the time it runs. Never throws. + */ +export function withdrawReadStatus(opts: { + canSign: () => boolean + npub: () => string | null | undefined + session: ReadSyncSession + signEvent: SignEvent + publish?: typeof publishReadStatus +}): Promise { + const { session } = opts + const run = async () => { + try { + const npub = opts.npub() + if (getReadSyncEnabled() || !opts.canSign() || !npub || npub !== session.npub) return + const result = await (opts.publish ?? publishReadStatus)([], opts.signEvent, nextCreatedAt(session)) + // npub is read again: the account may have changed while signing. + if (result.success) recordPublished(session, [], result.createdAt, opts.npub()) + else { + console.warn('Read status withdraw failed:', result.error) + } + } catch (error) { + console.error('Read status withdraw failed:', error) + } + } + session.queue = session.queue.then(run, run) + return session.queue +} diff --git a/src/lib/relays.test.ts b/src/lib/relays.test.ts index 160afd5..eb6f44d 100644 --- a/src/lib/relays.test.ts +++ b/src/lib/relays.test.ts @@ -1,3 +1,5 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' import { afterEach, describe, expect, it, vi } from 'vitest' import { @@ -106,6 +108,32 @@ describe('resolveDefaultRelays', () => { }) }) +describe('dead relays', () => { + const DEAD = ['wss://relay.nostr.band', 'wss://nostr-pub.wellorder.net'] + + it('are not in the fallback list', () => { + expect(FALLBACK_RELAYS).toEqual([ + 'wss://relay.damus.io', + 'wss://relay.primal.net', + 'wss://nos.lol', + 'wss://relay.snort.social', + ]) + }) + + it('are dropped from a list saved before they were removed', () => { + const saved = JSON.stringify(['wss://relay.nostr.band', 'wss://ok.example', 'WSS://nostr-pub.wellorder.net/']) + expect(pickRelays(saved, ['wss://default.example'])).toEqual(['wss://ok.example']) + expect(pickRelays(JSON.stringify(DEAD), ['wss://default.example'])).toEqual(['wss://default.example']) + }) + + it('are not suggested in settings or used for sharing', () => { + for (const file of ['../components/settings-dialog.tsx', '../components/feed-reader.tsx']) { + const source = readFileSync(fileURLToPath(new URL(file, import.meta.url)), 'utf8') + for (const relay of DEAD) expect(source, file).not.toContain(relay) + } + }) +}) + describe('getDefaultRelays', () => { afterEach(() => { vi.unstubAllEnvs() diff --git a/src/lib/relays.ts b/src/lib/relays.ts index be5f13f..aa2f827 100644 --- a/src/lib/relays.ts +++ b/src/lib/relays.ts @@ -5,8 +5,6 @@ export const FALLBACK_RELAYS: readonly string[] = [ 'wss://relay.primal.net', 'wss://nos.lol', 'wss://relay.snort.social', - 'wss://relay.nostr.band', - 'wss://nostr-pub.wellorder.net', ] export const CONTROL_OR_SPACE = /[\u0000-\u0020\u007f-\u009f\s]/ @@ -46,12 +44,23 @@ export function getDefaultRelays(): string[] { return runtimeDefaultRelays ? [...runtimeDefaultRelays] : [...FALLBACK_RELAYS] } +// Relays that no longer answer. Lists saved before they were dropped from the +// defaults can still name them, and each one holds a query up until it times +// out, so they are removed whenever a saved list is read. +export const DEAD_RELAYS: readonly string[] = ['wss://relay.nostr.band', 'wss://nostr-pub.wellorder.net'] + +export function isDeadRelay(url: string): boolean { + const normalized = url.trim().toLowerCase().replace(/\/+$/, '') + return DEAD_RELAYS.includes(normalized) +} + export function pickRelays(saved: string | null, defaults: string[]): string[] { if (!saved) return [...defaults] try { const parsed: unknown = JSON.parse(saved) if (Array.isArray(parsed) && parsed.length > 0 && parsed.every((r) => typeof r === 'string')) { - return parsed as string[] + const live = (parsed as string[]).filter((r) => !isDeadRelay(r)) + if (live.length > 0) return live } } catch { // fall through to defaults diff --git a/src/lib/sign-out.test.ts b/src/lib/sign-out.test.ts index 6ef82a4..c723f24 100644 --- a/src/lib/sign-out.test.ts +++ b/src/lib/sign-out.test.ts @@ -42,6 +42,9 @@ describe('clearUserClientState', () => { readstr_filters: '[]', readstr_profiles: '{}', readstr_last_sync: '1', + readstr_prefs_sync: 'true', + readstr_read_sync: 'true', + 'readstr_applied_createdat:readstr-read-status': '1700000000', 'readstr_applied_createdat:readstr-views': '1700000000', 'readstr_applied_createdat:readstr-prefs': '1700000000', [OWNER_PUBKEY_KEY]: 'alice', diff --git a/src/lib/sign-out.ts b/src/lib/sign-out.ts index d6ddc47..40cc2bd 100644 --- a/src/lib/sign-out.ts +++ b/src/lib/sign-out.ts @@ -1,7 +1,7 @@ import { AI_CONFIG_KEY } from './ai/config' import { clearSummaryCache } from './ai/summary-cache' import { clearProfileCache } from './nostr-profile' -import { APPLIED_CREATEDAT_PREFIX } from './nostr-sync' +import { APPLIED_CREATEDAT_PREFIX, READ_SYNC_KEY } from './nostr-sync' import { clearHistory } from './reading-history' import { USER_STATE_CLEARED_EVENT } from './user-state-events' @@ -31,6 +31,7 @@ export const USER_STORAGE_KEYS = [ 'readstr_profiles', 'readstr_last_sync', 'readstr_prefs_sync', + READ_SYNC_KEY, // read status sync publishes reading history; the next user opts in themselves 'last_feed_refresh', RELAYS_KEY, ] as const diff --git a/src/server/api/routers/feed.ts b/src/server/api/routers/feed.ts index f620b94..7ed93dc 100644 --- a/src/server/api/routers/feed.ts +++ b/src/server/api/routers/feed.ts @@ -7,6 +7,13 @@ import { withRequestFetcher } from '@/lib/safe-relays' import { rateLimit } from '@/server/rate-limit' import { MAX_RELAY_URL_LENGTH, MAX_CLIENT_RELAYS } from '@/lib/relays' import { discoverFeed } from '@/lib/feed-discovery' +import { + chunk, + GUID_QUERY_CHUNK, + readGuidsInputSchema, + readSyncKey, + ReadSyncGuidCollector, +} from '@/server/read-sync' import { FeedType, type Prisma } from '@prisma/client' import { nip19 } from 'nostr-tools' import { @@ -16,10 +23,8 @@ import { normalizeNpub } from '@/lib/nostr-sync' -// Profile discovery opens up to MAX_REQUEST_RELAYS sockets and lookups per -// call, so it gets its own per-user budget. -function limitProfileDiscovery(name: string, pubkey: string) { - const limit = rateLimit(name, pubkey, 30, 60 * 1000) +function limitPerUser(name: string, pubkey: string, max: number, windowMs: number) { + const limit = rateLimit(name, pubkey, max, windowMs) if (!limit.allowed) { throw new TRPCError({ code: 'TOO_MANY_REQUESTS', @@ -28,6 +33,19 @@ function limitProfileDiscovery(name: string, pubkey: string) { } } +// Profile discovery opens up to MAX_REQUEST_RELAYS sockets and lookups per +// call, so it gets its own per-user budget. +function limitProfileDiscovery(name: string, pubkey: string) { + limitPerUser(name, pubkey, 30, 60 * 1000) +} + +// Read-status sync budgets. A publish fetches the list at most once per +// 30-second debounce, plus a page close or a settings toggle, so a few a +// minute is plenty. Applying an 8 MiB pulled list takes about 175 calls of +// 48 KB each, so 250 per 10 minutes lets one full pull through. +const READ_GUIDS_FOR_SYNC_PER_MINUTE = 6 +const MARK_READ_BY_GUIDS_PER_10_MIN = 250 + // Type for subscription with feed include type SubscriptionWithFeed = Prisma.SubscriptionGetPayload<{ include: { feed: true } }> @@ -2021,4 +2039,71 @@ export const feedRouter = createTRPCRouter({ readAt: item.readAt, })) }), + // Read-status keys for the kind 30405 event, newest read first, from feeds + // the user still subscribes to, capped to what the web publishes (see + // ReadSyncGuidCollector). The cap also bounds the response and the pages read. + getReadGuidsForSync: subscribedProcedure + .query(async ({ ctx }) => { + limitPerUser('feed.getReadGuidsForSync', ctx.nostrPubkey, READ_GUIDS_FOR_SYNC_PER_MINUTE, 60 * 1000) + const subscriptions = await ctx.db.subscription.findMany({ + where: { userPubkey: ctx.nostrPubkey, deletedAt: null }, + select: { feedId: true }, + }) + const feedIds = subscriptions.map((sub: { feedId: string }) => sub.feedId) + if (feedIds.length === 0) return { guids: [] as string[] } + + const PAGE_SIZE = 1000 + const collector = new ReadSyncGuidCollector() + let cursor: string | undefined + while (!collector.full) { + const page = await ctx.db.readItem.findMany({ + where: { userPubkey: ctx.nostrPubkey, feedItem: { feedId: { in: feedIds } } }, + orderBy: [{ readAt: 'desc' }, { id: 'desc' }], + select: { id: true, feedItem: { select: { guid: true, url: true } } }, + take: PAGE_SIZE, + ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), + }) + for (const row of page) collector.add(readSyncKey(row.feedItem)) + if (page.length < PAGE_SIZE) break + cursor = page[page.length - 1]!.id + } + return { guids: collector.guids } + }), + + // Apply a pulled kind 30405 event: mark read the user's subscribed items whose + // key matches. Additive only, as on the desktop: a key missing from the list + // never marks anything unread. + markReadByGuids: subscribedProcedure + .input(readGuidsInputSchema) + .mutation(async ({ ctx, input }) => { + limitPerUser('feed.markReadByGuids', ctx.nostrPubkey, MARK_READ_BY_GUIDS_PER_10_MIN, 10 * 60 * 1000) + const guids = [...new Set(input.guids)].filter(g => g.length > 0) + if (guids.length === 0) return { marked: 0 } + + const subscriptions = await ctx.db.subscription.findMany({ + where: { userPubkey: ctx.nostrPubkey, deletedAt: null }, + select: { feedId: true }, + }) + const feedIds = subscriptions.map((sub: { feedId: string }) => sub.feedId) + if (feedIds.length === 0) return { marked: 0 } + + let marked = 0 + for (const part of chunk(guids, GUID_QUERY_CHUNK)) { + const items = await ctx.db.feedItem.findMany({ + where: { + feedId: { in: feedIds }, + OR: [{ guid: { in: part } }, { guid: null, url: { in: part } }], + readItems: { none: { userPubkey: ctx.nostrPubkey } }, + }, + select: { id: true }, + }) + if (items.length === 0) continue + const result = await ctx.db.readItem.createMany({ + data: items.map((item: { id: string }) => ({ userPubkey: ctx.nostrPubkey, itemId: item.id })), + skipDuplicates: true, + }) + marked += result.count + } + return { marked } + }), }) \ No newline at end of file diff --git a/src/server/read-sync.test.ts b/src/server/read-sync.test.ts new file mode 100644 index 0000000..9340ba9 --- /dev/null +++ b/src/server/read-sync.test.ts @@ -0,0 +1,246 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { MAX_GUID_LEN, MAX_READ_ITEMS, readStatusListSchema } from '@/lib/nostr-sync' +import { MAX_PUBLISHED_READ_CONTENT } from '@/lib/read-sync' +import { feedRouter } from '@/server/api/routers/feed' +import { __resetRateLimitForTests } from '@/server/rate-limit' +import type { SubscriptionLookups } from '@/server/paywall' +import { chunk, GUID_QUERY_CHUNK, readGuidsInputSchema, readSyncKey, ReadSyncGuidCollector } from './read-sync' + +const PUBKEY = '3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d' + +function ctx(db: unknown) { + return { db: db as never, nostrPubkey: PUBKEY, clientIp: '127.0.0.1', subscriptionLookups: new Map() as SubscriptionLookups } +} + +beforeEach(() => { + __resetRateLimitForTests() +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('readSyncKey', () => { + it('uses the trimmed guid, else the link, as the desktop does', () => { + expect(readSyncKey({ guid: ' tag:a ', url: 'https://a.example/1' })).toBe('tag:a') + expect(readSyncKey({ guid: null, url: 'https://a.example/1' })).toBe('https://a.example/1') + expect(readSyncKey({ guid: ' ', url: 'https://a.example/1' })).toBe('https://a.example/1') + expect(readSyncKey({ guid: null, url: null })).toBeNull() + }) +}) + +describe('ReadSyncGuidCollector', () => { + it('keeps order, drops duplicates and over-long keys', () => { + const c = new ReadSyncGuidCollector() + for (const key of ['b', 'a', 'b', null, 'x'.repeat(MAX_GUID_LEN + 1), 'x'.repeat(MAX_GUID_LEN)]) c.add(key) + expect(c.guids).toEqual(['b', 'a', 'x'.repeat(MAX_GUID_LEN)]) + }) + + it('stops at the item cap', () => { + const c = new ReadSyncGuidCollector(3) + for (const key of ['a', 'b', 'c', 'd']) c.add(key) + expect(c.guids).toEqual(['a', 'b', 'c']) + expect(c.full).toBe(true) + }) + + it('keeps the published event under the publish cap and the relays\' 64 KiB limit', () => { + // Short keys carry the most quoting overhead, escaped and non-ASCII keys + // the most bytes per UTF-16 unit. + const shapes = [ + (i: number) => `${i}`, + (i: number) => `${i}`.padStart(MAX_GUID_LEN, 'g'), + (i: number) => `${i}"\\`.padEnd(40, '"'), + (i: number) => `${i}`.padEnd(60, 'รผโ‚ฌ'), + ] + for (const shape of shapes) { + const c = new ReadSyncGuidCollector() + for (let i = 0; !c.full; i++) c.add(shape(i)) + const content = JSON.stringify({ itemGuids: c.guids, lastUpdated: 1_900_000_000 }) + const event = JSON.stringify({ + id: 'f'.repeat(64), + pubkey: 'f'.repeat(64), + created_at: 1_900_000_000, + kind: 30405, + tags: [['d', 'readstr-read-status'], ['client', 'readstr']], + content, + sig: 'f'.repeat(128), + }) + expect(content.length).toBeLessThanOrEqual(MAX_PUBLISHED_READ_CONTENT) + expect(new TextEncoder().encode(event).length).toBeLessThanOrEqual(MAX_PUBLISHED_READ_CONTENT) + expect(c.guids.length).toBeGreaterThan(100) + expect(readStatusListSchema.safeParse(JSON.parse(content)).success).toBe(true) + } + }) +}) + +describe('chunk', () => { + it('splits into fixed-size parts', () => { + expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]) + expect(chunk([], 2)).toEqual([]) + }) + + it('refuses a size below one instead of looping forever', () => { + for (const size of [0, -1, 0.5, Number.NaN]) expect(() => chunk([1], size)).toThrow(RangeError) + }) +}) + +describe('readGuidsInputSchema', () => { + it('enforces the read-status caps', () => { + expect(readGuidsInputSchema.safeParse({ guids: Array(MAX_READ_ITEMS).fill('g') }).success).toBe(true) + expect(readGuidsInputSchema.safeParse({ guids: Array(MAX_READ_ITEMS + 1).fill('g') }).success).toBe(false) + expect(readGuidsInputSchema.safeParse({ guids: ['g'.repeat(MAX_GUID_LEN + 1)] }).success).toBe(false) + }) + + it('measures guids in UTF-16 units, not code points', () => { + expect(readGuidsInputSchema.safeParse({ guids: ['๐Ÿ˜€'.repeat(129)] }).success).toBe(false) + expect(readGuidsInputSchema.safeParse({ guids: ['๐Ÿ˜€'.repeat(MAX_GUID_LEN / 2)] }).success).toBe(true) + }) +}) + +describe('feed.getReadGuidsForSync', () => { + type Row = { id: string; feedItem: { guid: string | null; url: string | null } } + type FindArgs = { take: number; cursor?: { id: string }; skip?: number; where: unknown } + + // Serves rows newest first in pages, as Prisma's cursor pagination does. + function fakeDb(rows: Row[], feedIds = ['feed-1']) { + return { + subscription: { findMany: vi.fn(async () => feedIds.map((feedId) => ({ feedId }))) }, + readItem: { + findMany: vi.fn(async (args: FindArgs) => { + const start = args.cursor ? rows.findIndex((r) => r.id === args.cursor!.id) + (args.skip ?? 0) : 0 + return rows.slice(start, start + args.take) + }), + }, + } + } + + it('returns the user\'s read keys newest first, only from active subscriptions', async () => { + const db = fakeDb([ + { id: 'r2', feedItem: { guid: 'nostr-event-id', url: null } }, + { id: 'r1', feedItem: { guid: null, url: 'https://a.example/1' } }, + { id: 'r0', feedItem: { guid: null, url: null } }, + ]) + const result = await feedRouter.createCaller(ctx(db)).getReadGuidsForSync() + expect(result).toEqual({ guids: ['nostr-event-id', 'https://a.example/1'] }) + expect(db.subscription.findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { userPubkey: PUBKEY, deletedAt: null } }) + ) + expect(db.readItem.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userPubkey: PUBKEY, feedItem: { feedId: { in: ['feed-1'] } } }, + orderBy: [{ readAt: 'desc' }, { id: 'desc' }], + }) + ) + }) + + it('skips the read lookup without active subscriptions', async () => { + const db = fakeDb([{ id: 'r0', feedItem: { guid: 'g', url: null } }], []) + await expect(feedRouter.createCaller(ctx(db)).getReadGuidsForSync()).resolves.toEqual({ guids: [] }) + expect(db.readItem.findMany).not.toHaveBeenCalled() + }) + + it('pages through reads with a cursor', async () => { + const rows = Array.from({ length: 1500 }, (_, i) => ({ id: `r${i}`, feedItem: { guid: `${i}`, url: null } })) + const db = fakeDb(rows) + const { guids } = await feedRouter.createCaller(ctx(db)).getReadGuidsForSync() + expect(guids).toEqual(rows.map((r) => r.feedItem.guid)) + expect(db.readItem.findMany).toHaveBeenCalledTimes(2) + expect(db.readItem.findMany.mock.calls[1]![0]).toMatchObject({ cursor: { id: 'r999' }, skip: 1 }) + }) + + it('stops reading once the publish cap fills mid-page', async () => { + const rows = Array.from({ length: 5000 }, (_, i) => ({ + id: `r${i}`, + feedItem: { guid: `${i}`.padStart(MAX_GUID_LEN, 'g'), url: null }, + })) + const db = fakeDb(rows) + const { guids } = await feedRouter.createCaller(ctx(db)).getReadGuidsForSync() + expect(guids.length).toBeGreaterThan(0) + expect(guids.length).toBeLessThan(1000) + expect(guids).toEqual(rows.slice(0, guids.length).map((r) => r.feedItem.guid)) + expect(db.readItem.findMany).toHaveBeenCalledOnce() + }) + + it('is rate limited per user', async () => { + const db = fakeDb([]) + const caller = feedRouter.createCaller(ctx(db)) + for (let i = 0; i < 6; i++) await caller.getReadGuidsForSync() + await expect(caller.getReadGuidsForSync()).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' }) + }) +}) + +describe('feed.markReadByGuids', () => { + type ItemArgs = { where: { feedId: { in: string[] }; OR: [{ guid: { in: string[] } }, unknown] } } + + // Every guid exists in feed-1 and feed-2; the lookup honours the feedId filter. + function fakeDb(feedIds: string[], itemFeeds = ['feed-1', 'feed-2']) { + return { + subscription: { findMany: vi.fn(async () => feedIds.map((feedId) => ({ feedId }))) }, + feedItem: { + findMany: vi.fn(async (args: ItemArgs) => + itemFeeds + .filter((feedId) => args.where.feedId.in.includes(feedId)) + .flatMap((feedId) => args.where.OR[0].guid.in.map((guid) => ({ id: `${feedId}-${guid}` }))) + ), + }, + readItem: { + createMany: vi.fn(async (args: { data: unknown[] }) => ({ count: args.data.length })), + deleteMany: vi.fn(), + delete: vi.fn(), + }, + } + } + + it('marks matching subscribed items read in chunks, never unread', async () => { + const db = fakeDb(['feed-1']) + const guids = Array.from({ length: GUID_QUERY_CHUNK * 2 + 5 }, (_, i) => `g${i}`) + const result = await feedRouter.createCaller(ctx(db)).markReadByGuids({ guids: [...guids, 'g0', ''] }) + expect(result).toEqual({ marked: guids.length }) + expect(db.feedItem.findMany).toHaveBeenCalledTimes(3) + const where = (db.feedItem.findMany.mock.calls[0]![0] as { where: Record }).where + expect(where).toEqual({ + feedId: { in: ['feed-1'] }, + OR: [{ guid: { in: guids.slice(0, GUID_QUERY_CHUNK) } }, { guid: null, url: { in: guids.slice(0, GUID_QUERY_CHUNK) } }], + readItems: { none: { userPubkey: PUBKEY } }, + }) + expect(db.readItem.createMany).toHaveBeenCalledWith( + expect.objectContaining({ data: expect.arrayContaining([{ userPubkey: PUBKEY, itemId: 'feed-1-g0' }]), skipDuplicates: true }) + ) + expect(db.readItem.delete).not.toHaveBeenCalled() + expect(db.readItem.deleteMany).not.toHaveBeenCalled() + }) + + it('marks only items in the user\'s subscribed feeds', async () => { + const db = fakeDb(['feed-2']) + await expect(feedRouter.createCaller(ctx(db)).markReadByGuids({ guids: ['a', 'b'] })).resolves.toEqual({ marked: 2 }) + expect(db.readItem.createMany).toHaveBeenCalledWith({ + data: [ + { userPubkey: PUBKEY, itemId: 'feed-2-a' }, + { userPubkey: PUBKEY, itemId: 'feed-2-b' }, + ], + skipDuplicates: true, + }) + }) + + it('is rate limited per user, with room for a full pull', async () => { + const caller = feedRouter.createCaller(ctx(fakeDb(['feed-1']))) + for (let i = 0; i < 250; i++) await caller.markReadByGuids({ guids: ['a'] }) + await expect(caller.markReadByGuids({ guids: ['a'] })).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' }) + }) + + it('skips the item lookup without subscriptions or guids', async () => { + for (const [feeds, guids] of [[[], ['a']], [['feed-1'], []]] as [string[], string[]][]) { + const db = fakeDb(feeds) + await expect(feedRouter.createCaller(ctx(db)).markReadByGuids({ guids })).resolves.toEqual({ marked: 0 }) + expect(db.feedItem.findMany).not.toHaveBeenCalled() + } + }) + + it('rejects input past the caps', async () => { + const db = fakeDb(['feed-1']) + const caller = feedRouter.createCaller(ctx(db)) + await expect(caller.markReadByGuids({ guids: ['g'.repeat(MAX_GUID_LEN + 1)] })).rejects.toMatchObject({ code: 'BAD_REQUEST' }) + await expect(caller.markReadByGuids({ guids: Array(MAX_READ_ITEMS + 1).fill('g') })).rejects.toMatchObject({ code: 'BAD_REQUEST' }) + expect(db.subscription.findMany).not.toHaveBeenCalled() + }) +}) diff --git a/src/server/read-sync.ts b/src/server/read-sync.ts new file mode 100644 index 0000000..ad80043 --- /dev/null +++ b/src/server/read-sync.ts @@ -0,0 +1,33 @@ +import { z } from 'zod' +import { MAX_READ_ITEMS, readGuidSchema } from '@/lib/nostr-sync' + +export { ReadSyncGuidCollector } from '@/lib/read-sync' + +// Rows per `in` query, so a 100k-guid import never builds one giant statement. +export const GUID_QUERY_CHUNK = 1000 + +export const readGuidsInputSchema = z.object({ + guids: z.array(readGuidSchema).max(MAX_READ_ITEMS), +}) + +/** + * The key an item has in a kind 30405 event: its guid, or its link when it has + * none. The desktop keys items the same way (feedparser.cpp finishItem, with the + * guid trimmed) and uses the Nostr event id for Nostr items, which the web + * stores as the guid. + */ +export function readSyncKey(item: { guid: string | null; url: string | null }): string | null { + const guid = item.guid?.trim() + if (guid) return guid + const url = item.url?.trim() + return url || null +} + +export function chunk(items: T[], size: number): T[][] { + // A size below one would loop forever; that is a caller bug, not a request. + if (!(size >= 1)) throw new RangeError(`chunk size must be at least 1, got ${size}`) + const step = Math.floor(size) + const chunks: T[][] = [] + for (let i = 0; i < items.length; i += step) chunks.push(items.slice(i, i + step)) + return chunks +} diff --git a/src/trpc/batch-limits.ts b/src/trpc/batch-limits.ts index e6266f8..0c4a836 100644 --- a/src/trpc/batch-limits.ts +++ b/src/trpc/batch-limits.ts @@ -21,3 +21,18 @@ export const TRPC_MAX_URL_LENGTH = 2_000 * headroom while stopping a single 16 KB URL from fanning out to ~900 calls. */ export const MAX_TRPC_BATCH_SIZE = 200 + +/** + * Largest tRPC request body the /api/trpc route accepts. Only mutations send + * a body; queries such as getFeedItems carry their input in the GET URL. The + * biggest real body is a markReadByGuids call applying a pulled read-status + * list, which the client splits into calls of at most MARK_READ_REQUEST_BYTES + * (48 KB) of guids, leaving room for the envelope and a batch of markAsRead + * calls (~45 bytes each); most calls are well under 1 KB. The cap keeps zod v3's + * per-element parsing of hostile arrays (~150x heap amplification, + * GHSA-mrhx-c7xc-m3w5) to roughly 10 MB per request, and runs before NIP-98 + * auth and any procedure's rate limit, so it also protects public mutations. + * It lives here, not in the route, because a Next.js route file may only + * export its handlers and config. + */ +export const MAX_TRPC_BODY_BYTES = 64_000 diff --git a/tsconfig.json b/tsconfig.json index 836738c..26fd28f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,7 +3,8 @@ "lib": [ "dom", "dom.iterable", - "es6" + "es6", + "es2021.promise" ], "allowJs": true, "skipLibCheck": true,