
Welcome to the comprehensive technical specification for StoriesHut—India's premier digital reading and publishing platform engineered to deliver feature parity with Amazon Kindle and Kindle Direct Publishing (KDP) whilst maintaining strict compliance with Indian regulatory frameworks, GST mandates, and payment processing standards.
This document serves as the authoritative, end-to-end developer specification for engineering teams, product managers, and technical architects responsible for building and maintaining the StoriesHut ecosystem. It encompasses the complete technical stack required to deliver a world-class digital reading experience comparable to Amazon's Kindle platform whilst addressing the unique requirements of the Indian market.
The specification explicitly covers reader experience engineering (Kindle-class rendering and offline capabilities), writer monetization systems (KDP-style page-read royalty calculations), comprehensive administrative controls, financial compliance mechanisms, fraud detection frameworks, security protocols including digital rights management (DRM), and abuse prevention systems designed to protect both content creators and the platform's revenue integrity.
Every component detailed within this documentation has been architected with scalability, security, and regulatory compliance as foundational principles, ensuring that StoriesHut can compete effectively in the global digital publishing marketplace whilst respecting local regulatory boundaries.
Flutter-based native applications for Android and iOS platforms, delivering consistent cross-platform experiences with offline-first architecture and sophisticated rendering engines.
Dedicated portals for writers (KDP equivalent) and administrative teams, enabling content management, royalty tracking, and platform oversight capabilities.
Supabase-powered infrastructure providing authentication, PostgreSQL databases with Row Level Security, content access APIs with signed URLs, and sophisticated analytics engines.
IDFC Razorpay integration managing subscriptions, refunds, writer payouts via Route/NEFT/UPI, ensuring compliance with Indian payment regulations and tax frameworks.
The StoriesHut platform architecture borrows proven principles from Amazon Kindle's two-decade evolution whilst adapting them for Indian regulatory requirements and market conditions. These foundational principles guide every technical decision across the platform stack.
All reader applications must function seamlessly without internet connectivity, with intelligent synchronization occurring transparently when network access becomes available, mirroring Kindle's renowned offline capabilities.
Every page read generates immutable events validated against fraud detection rules before inclusion in royalty calculations, ensuring writers receive accurate compensation for legitimate readership.
Reading positions, highlights, notes, and preferences synchronize automatically across all authorized devices, implementing a "Whispersync-like" experience that maintains reading continuity regardless of device switching.
Content delivery employs time-limited signed URLs, device binding, and encrypted storage, ensuring that unauthorized access becomes computationally infeasible even if storage infrastructure is compromised.
Multi-layered fraud detection systems analyze reading patterns, device fingerprints, and behavioral signals to exclude fraudulent activity from royalty pools, protecting writer earnings and platform integrity.
The Flutter-based reader application represents the primary interface through which users consume content on StoriesHut. Engineering this component requires careful attention to rendering accuracy, performance optimization, offline functionality, and security implementation. The application must deliver an experience indistinguishable from Amazon's Kindle applications whilst incorporating robust telemetry for royalty calculation and fraud detection.
The rendering engine serves as the critical foundation, supporting ePub 3.x as the primary format with PDF fallback capabilities. True page-based pagination with accurate boundary detection enables precise royalty calculations, whilst dynamic reflow responds intelligently to user preference changes including font selection, sizing adjustments, theme modifications, and device orientation shifts. Every rendered page generates immutable tracking events capturing book ID, chapter ID, page index, timestamp ranges, device fingerprints, user identifiers, geographic location data, device manufacturer and model information, demographic attributes including age and gender—all essential for both royalty calculation and fraud pattern detection.
Google AdMob integration and equivalent advertising platforms must be incorporated strategically to generate supplementary revenue streams without compromising reading experience quality. Advertisement placements should respect chapter boundaries and user engagement patterns, avoiding intrusive interruptions during active reading sessions.
Readers control font family selection from curated typeface collections optimized for extended reading sessions, with dynamic size adjustment spanning eight distinct levels, line spacing configuration, margin width preferences, and text alignment options including left-aligned and fully justified modes.
Four carefully designed reading themes accommodate diverse lighting conditions and user preferences: Light mode for daytime reading, Sepia for reduced eye strain, Dark mode for low-light environments, and AMOLED-optimized black for maximum battery conservation on modern displays.
Orientation lock functionality enables users to prevent accidental rotation during reading sessions, particularly valuable during one-handed operation scenarios. All preferences persist locally with encrypted storage and synchronize across authorized devices per user account.
Preference management implements a hybrid storage strategy: local encryption ensures immediate availability and offline functionality, whilst cloud synchronization maintains consistency across the user's device ecosystem. Basic subscription tiers restrict active reading to one device simultaneously, whereas premium subscriptions enable concurrent multi-device access, balancing accessibility with abuse prevention requirements.

The cloud-based bookshelf system maintains a comprehensive record of all books a user has purchased, subscribed to, or added to their library. Visual indicators clearly distinguish between downloaded content available for offline reading and cloud-only titles requiring network connectivity for access. Users maintain full control over local storage management through manual re-download capabilities and selective content removal.
Sophisticated sorting algorithms organize libraries according to multiple criteria: recently read titles surface books where users have active reading sessions, alphabetical sorting by title or author name enables rapid location of specific works, and chronological organization by acquisition date helps users rediscover forgotten purchases. Custom collections function as user-created folders enabling thematic or project-based organization, with individual books capable of appearing in multiple collections simultaneously without duplication.
The library interface implements infinite scroll with virtualized rendering to maintain performance even with libraries containing thousands of titles, whilst integrated search capabilities enable full-text queries across titles, author names, and metadata tags.
Full-text indexing enables readers to locate specific passages, quotes, or references within the current book. Search results display contextual snippets with highlighted query terms, enabling rapid navigation to relevant sections whilst maintaining reading flow.
Platform-wide search queries scan the entire StoriesHut catalog, matching against book titles, author names, genre classifications, publisher information, and keyword metadata. Advanced filtering options refine results by publication date, language, rating thresholds, and pricing tiers.
Machine learning algorithms analyze reading history, genre preferences, completion rates, and time-spent patterns to generate personalized book recommendations. Collaborative filtering identifies books enjoyed by readers with similar tastes, whilst content-based filtering suggests titles sharing thematic or stylistic characteristics.
The annotation system replicates and extends Kindle's renowned highlighting and note-taking capabilities, enabling readers to mark significant passages, add contextual commentary, and build personal reference libraries. Multi-color highlighting supports organizational schemes where different colors represent distinct categories—readers might use yellow for important concepts, blue for beautiful prose, and pink for passages requiring further research.
Inline notes attach directly to highlighted text, creating contextual annotations visible during subsequent reading sessions. The highlight index provides book-level navigation, displaying all marked passages with their associated notes in a scrollable interface sorted chronologically or by location within the text. Cloud synchronization ensures annotations persist across device changes and operating system migrations.
Advanced export functionality generates formatted documents containing all highlights and notes from a single book or across the entire library. Export formats include PDF with preserved formatting and highlighting colors, plain text for import into note-taking applications like Notion or Obsidian, and structured data formats enabling integration with research management tools. These exports transform casual reading into productive knowledge management workflows, particularly valuable for students, researchers, and professional readers.
Tap-to-define functionality integrates offline dictionary databases supporting English, Hindi, and major Indian regional languages. Long-pressing any word displays definition overlays without interrupting reading flow, with pronunciation guides and usage examples enhancing vocabulary acquisition. Phase 2 development will introduce inline translation capabilities, enabling readers to instantly translate selected passages between supported language pairs—particularly valuable for multilingual readers and language learners exploring content in non-native languages.
Etymology information and word frequency data provide additional context for advanced readers interested in linguistic nuances, whilst simplified definitions accommodate younger readers and English language learners.
Comprehensive accessibility support ensures StoriesHut serves readers with visual impairments and other disabilities. Screen reader integration provides full text-to-speech narration with intelligent handling of navigation elements, chapter headings, and metadata. Adjustable contrast ratios exceed WCAG 2.1 Level AAA standards, whilst dynamic font scaling extends beyond standard reader controls to accommodate severe vision impairment.
Keyboard navigation enables complete application control without touch interaction, whilst alternative input methods including voice commands and switch controls support users with motor impairments. Semantic HTML structure and ARIA labels ensure compatibility with assistive technologies across Android and iOS platforms.
When users request offline access, the backend generates time-limited signed URLs granting download authorization. These URLs embed cryptographic signatures verifying request authenticity and embed expiration timestamps typically ranging from 5-15 minutes, sufficient for download completion but minimizing exposure window if URLs are intercepted.
Upon successful download, the Flutter application immediately encrypts the entire book file using AES-256 encryption with keys derived from combined user credentials and device-specific hardware identifiers. This binding ensures encrypted files cannot be decrypted on unauthorized devices even if copied from device storage.
Encryption keys never persist in plain text—instead, they derive from cryptographic key derivation functions (PBKDF2 or Argon2) combining user authentication tokens with hardware-backed keystores available on modern Android and iOS devices. This architecture ensures that even full device compromise requires sophisticated attacks to extract usable encryption keys.
Multiple events trigger automatic invalidation of offline access permissions: subscription expiration dates, explicit account logout actions, administrative content takedown orders, and device authorization revocation. Upon invalidation, local decryption keys are destroyed, rendering downloaded content permanently inaccessible without re-authorization and fresh download.
StoriesHut's security architecture implements defense-in-depth strategies borrowed from banking and enterprise content management systems, recognizing that digital content protection requires multiple overlapping security layers rather than reliance on any single mechanism. The platform must balance user experience convenience against robust protection of intellectual property rights for authors and publishers.
Digital Rights Management (DRM) extends beyond simple encryption to encompass device binding, access control policies, watermarking technologies, and behavioral monitoring systems. Unlike physical books that naturally restrict simultaneous access, digital content faces inherent challenges around unauthorized duplication and distribution. StoriesHut's DRM implementation addresses these challenges through cryptographic access controls, behavioral fraud detection, and legal deterrence mechanisms.
The security model assumes adversarial users with technical sophistication attempting to circumvent protection measures for unauthorized content distribution. Therefore, every security control includes monitoring and alerting capabilities enabling rapid detection and response to circumvention attempts, protecting both platform revenue integrity and author intellectual property rights.
Android applications enable FLAG_SECURE at the window level, instructing the operating system to exclude application content from screenshots, screen recordings, and screen sharing sessions. This system-level flag prevents both built-in screenshot mechanisms and third-party screen capture applications from accessing rendered book content.
iOS implementations utilize secure rendering surfaces that automatically blank during screenshot attempts or screen recording sessions. While iOS provides less granular FLAG_SECURE equivalent functionality, secure rendering APIs prevent screenshot content capture, generating blank images even when users successfully trigger screenshot mechanisms.
Both platforms implement OS-level hooks detecting screenshot and screen recording attempts regardless of whether content actually appears in captured media. Detection occurs via platform-specific notification APIs: userDidTakeScreenshot on iOS and ContentResolver observation on Android. Even "failed" capture attempts where resulting images are blank trigger security events.
Screenshot and screen recording protection extends beyond mere blocking—every capture attempt, successful or not, generates immutable security event records transmitted immediately to backend infrastructure. This reporting requirement is mandatory and non-negotiable for platform operation.
Each security event contains comprehensive contextual information: complete user account identifier, registered email address or phone number, device ID and OS version details, book ID and chapter ID identifying protected content, precise page index within the chapter, ISO 8601 formatted timestamp, capture type classification (screenshot vs. screen recording), and capture result status (blocked, blank, or successful).
The platform explicitly treats blank screenshots—where FLAG_SECURE or iOS protection mechanisms successfully prevent content capture but users complete screenshot gestures—as violation signals requiring identical logging and response protocols. Users demonstrating repeated blank screenshot behavior exhibit concerning patterns suggesting persistent circumvention attempts warranting increased scrutiny.
Security events flow through a dedicated processing pipeline: immediate persistence into the immutable security_events table with cryptographic hash verification, real-time admin notification via dashboard alerts and email distribution to security personnel, automatic risk score increment in the user_risk_scores table, and trigger evaluation for automated response actions including reading suspension or royalty exclusion.
Administrative interfaces provide comprehensive security event analytics: per-user violation histories with timeline visualizations, book-specific vulnerability analysis identifying frequently targeted content, geographic clustering analysis revealing potential organized piracy operations, and author notification workflows alerting writers when their content faces elevated security threats enabling collaboration on protection strategies.
Beyond security event reporting, StoriesHut implements platform-wide audit logging capturing all user actions, system events, and administrative operations for compliance, debugging, and forensic analysis.
Repeated security violations trigger graduated response protocols designed to deter unauthorized content capture whilst avoiding false positives that might penalize legitimate users experiencing accidental screenshot triggers. First violations generate log entries and increment user risk scores but take no user-facing actions, recognizing that single incidents often represent accidental behavior.
Second and third violations trigger automated warning notifications educating users about Terms of Service provisions prohibiting screenshot capture and explaining potential account consequences. Fourth violations initiate temporary reading suspensions lasting 24-72 hours, during which users cannot access any content whilst maintaining account access for support inquiries. Fifth violations mandate admin review before account restoration, whilst seventh violations result in permanent account termination with forfeiture of subscription fees and library access.
Affected reading sessions face immediate royalty exclusion—pages read during sessions where security violations occurred do not contribute to writer earnings calculations, protecting author revenue from abuse-related artificial inflation whilst maintaining zero-tolerance enforcement.
Dynamic watermarking embeds user-identifiable information directly into rendered content at the pixel level, creating forensic evidence trails enabling source attribution if unauthorized screenshots or screen captures circumvent protection mechanisms and subsequently appear on piracy forums or social media platforms. Unlike static watermarks visible to readers, dynamic watermarks operate steganographically—invisible during normal reading but extractable through forensic analysis.
Each rendered page incorporates a unique watermark containing masked user identifier strings (non-reversible hashes preventing privacy violations), precise timestamp information recording rendering moment down to millisecond resolution, and randomized positioning patterns preventing watermark location prediction. Randomization occurs per-page rather than per-book, forcing hypothetical attackers to analyze every page individually rather than applying batch processing automation.
Backend infrastructure generates cryptographically signed URLs embedding HMAC-SHA256 signatures verifying request authenticity, time-to-live parameters (typically 300-900 seconds balancing security with download completion reliability), and device fingerprint hashes. This ensures URLs function exclusively on the *currently registered active device*, preventing unauthorized access or content transfer to other devices.
Upon first login per device, a mandatory registration flow captures hardware identifiers (Android ID, iOS UDID), operating system, and application details. The backend strictly maintains *only one active device_id and session token per user account*. Subsequent logins from new devices will trigger re-registration, invalidating any previous device record.
Users are limited to a single active login session across all subscription tiers. If a user logs in on a new device, all previous active sessions are immediately invalidated. A push notification is sent to the automatically logged-out device, informing the user of the concurrent access restriction and the need to manually log out or accept the automatic logout when switching devices.
Active reading sessions send heartbeats to backend servers every 60-120 seconds, explicitly checking the active `device_id` against the registered record, validating subscription status, and confirming no security flags are present. Heartbeat failures or a mismatch in `device_id` trigger graceful session termination, with local content access revoked after a brief grace period to accommodate temporary connectivity loss.
Future platform iterations will incorporate industry-standard DRM systems providing enhanced protection for premium publisher content and commercially sensitive materials requiring maximum security assurance. Two primary integration candidates offer distinct advantages suitable for different content categories and publisher relationships.
Readium LCP represents the open-source DRM standard developed by the Readium Foundation, offering royalty-free implementation whilst providing robust content protection comparable to proprietary alternatives. LCP architecture separates content encryption from license management, enabling flexible business models including subscription access, rental periods, and loan systems. Native EPUB 3 compatibility ensures seamless integration with StoriesHut's existing rendering engine without requiring format conversion or compatibility layers.
LCP's user-centric design philosophy aligns with StoriesHut's reader-first approach—licenses transfer between authorized devices without artificial restrictions, offline reading requires no "phone home" validation after initial license acquisition, and the absence of vendor lock-in protects platform independence. Open specifications enable in-house development and customization without dependency on external vendors or licensing negotiations.
Adobe Content Server dominates enterprise digital publishing with near-universal support across e-reader hardware, library systems, and retail platforms. Integration with Adobe's DRM infrastructure enables seamless content distribution through established publishing channels, facilitating partnerships with major publishers already utilizing Adobe's ecosystem. Publisher confidence in Adobe's proven protection mechanisms may accelerate premium content acquisition negotiations.
However, Adobe DRM implementation requires ongoing licensing fees, vendor dependency for critical security infrastructure, and potential user experience friction from Adobe Digital Editions ecosystem requirements. These tradeoffs warrant careful evaluation against specific publisher partnership requirements and premium content acquisition strategies rather than platform-wide default deployment.
Sophisticated fraud detection algorithms analyze reading behavior patterns in real-time, identifying anomalous activity indicating bot-driven page-read farming, coordinated abuse schemes artificially inflating writer royalties, or automated systems attempting to game recommendation algorithms. Detection rules employ statistical analysis, machine learning models, and heuristic pattern matching to distinguish legitimate reading behavior from fraudulent activity.
Rapid page flipping detection identifies sessions where page advancement rates exceed humanly plausible reading speeds—legitimate readers average 1-3 minutes per page depending on complexity and reading proficiency, whilst automated scripts often flip pages every few seconds to maximize apparent reading volume. Zero-time page reads where users advance immediately upon page load without plausible content consumption similarly indicate automation or fraud attempts.
Bot-like reading patterns exhibit tell-tale characteristics: perfectly consistent page timing suggesting scripted automation, absence of natural reading variation including page reversals or extended pauses, reading sessions occurring during sleep hours relative to user timezone, and geometric reading position advancement lacking organic navigation patterns including highlights, notes, or dictionary lookups that characterize human reading.
Multi-device farming schemes coordinate across numerous accounts and devices to artificially inflate individual book readership metrics or royalty generation. Detection algorithms identify shared IP addresses, device fingerprint similarities, synchronized reading patterns across supposedly independent accounts, and unusual geographic clustering suggesting coordinated operations rather than organic geographic readership concentration.
Reading events flagged as potentially fraudulent face immediate exclusion from active royalty calculations whilst undergoing secondary validation. Events remain in quarantine status pending manual review or automated re-evaluation through enhanced detection algorithms with higher confidence thresholds, preventing fraudulent reads from distorting writer earnings even temporarily.
User accounts exhibiting fraud indicators transition to "under review" status triggering enhanced monitoring, reduced trust scores affecting recommendation algorithm weighting, and potential temporary restrictions on new content access whilst maintaining access to previously read materials during investigation periods. False positive mitigation ensures legitimate users facing erroneous flagging can rapidly appeal through support channels with admin override capabilities.
Writer accounts receiving unusually high page-read volumes from flagged reader accounts face temporary payout holds whilst fraud investigation teams examine traffic sources, reading pattern distributions, and potential coordination between writer and reader accounts. Legitimate writers impacted by organized fraud targeting their content receive protection through these holds preventing royalty clawbacks after payment distribution.
Confirmed fraud results in permanent account termination, forfeiture of remaining subscription periods without refund, and addition to platform-wide ban lists preventing re-registration. Device fingerprints and payment method identifiers associated with banned accounts face blacklisting preventing simple re-registration with new email addresses, forcing sophisticated attackers to acquire new devices and payment methods substantially raising fraud cost thresholds.

StoriesHut implements flexible authentication supporting diverse user preferences and security requirements. Email-based authentication with one-time password (OTP) delivery provides passwordless authentication reducing credential theft risks whilst maintaining accessibility for users preferring email-based workflows. Six-digit OTPs expire after 10 minutes with rate limiting preventing brute-force enumeration attacks.
Optional password authentication accommodates users preferring traditional credential-based login, with enforcement of minimum password complexity requirements: 12-character minimum length, mandatory inclusion of uppercase letters, lowercase letters, numbers, and special characters, and prohibition of common passwords through validation against Have I Been Pwned breach databases. Password reset flows utilize the same OTP mechanism ensuring account recovery security matches initial authentication security.
Multi-factor authentication (MFA) support enables security-conscious users to require time-based one-time passwords (TOTP) via authenticator applications, SMS-based verification codes as secondary factors, or biometric authentication on supporting devices. MFA requirement remains optional for basic accounts but becomes mandatory for writer accounts upon first royalty payout eligibility, protecting revenue-generating accounts against credential compromise.
All users across all roles (Reader, Writer, Admin, Finance) must enable 2FA during account registration or first login. The platform supports three 2FA methods:
Default role assigned to all registered users, granting access to book catalog browsing, subscription management, library organization, reading functionality across all supported formats, and community participation including reviews and discussions. Readers cannot access writer portal features or administrative interfaces.
Granted through writer program application and approval process, enabling access to manuscript editor, publishing workflow, royalty dashboard, and book performance analytics. Writers retain full reader privileges, allowing consumption of other authors' content whilst managing their own publications. Enhanced identity verification requirements ensure payout authenticity.
Platform administrators access user management tools, content moderation interfaces, security event monitoring dashboards, and system configuration controls. Admins cannot directly access financial payout processing or GST compliance functions, maintaining separation of duties between operational administration and financial operations.
Finance team members access royalty calculation verification tools, payout approval workflows, tax compliance reporting interfaces, and financial reconciliation systems. Finance roles cannot modify content, user accounts, or security configurations, limiting potential damage from compromised finance accounts to financial data rather than operational platform infrastructure.
Highest privilege level granting unrestricted platform access including database direct access, system configuration modification, role assignment authority, and override capabilities for all automated systems. Super admin access restricted to technical infrastructure team leads with comprehensive audit logging of all actions for security accountability.
Row Level Security (RLS) enforcement occurs at the PostgreSQL database layer rather than application logic, ensuring that even direct database queries respect role-based access restrictions. RLS policies evaluate user JWT tokens on every query, preventing privilege escalation through API bypasses or SQL injection vulnerabilities. All role transitions generate immutable audit trail entries capturing actor, timestamp, justification, and approval chain for compliance documentation.
StoriesHut implements a comprehensive four-tier role hierarchy with granular permission controls enforced at the API level. This matrix defines exact capabilities for each role across all platform operations, ensuring security boundaries and operational clarity.
Note: Two-Factor Authentication (2FA) is mandatory for all roles during account registration and must remain enabled for continued platform access.
Super Admin (Level 4)
└── Admin (Level 3)
└── Writer (Level 2)
└── Reader (Level 1)
The Writer Portal serves as StoriesHut's equivalent to Amazon's Kindle Direct Publishing (KDP) platform, providing comprehensive content creation, publishing, and earnings management tools. This web-based console enables writers to transform raw manuscripts into published books, monitor readership engagement, and track royalty earnings—all without requiring technical expertise or external service dependencies.
Portal architecture prioritizes writer productivity through intuitive interfaces, comprehensive documentation, and intelligent automation reducing repetitive tasks. Writers should focus creative energy on content quality rather than navigating complex publishing workflows or troubleshooting technical issues. Every interface element serves a specific writer need identified through user research and competitive analysis of existing self-publishing platforms.
Unlike traditional publishing workflows requiring intermediaries, agents, or specialized knowledge, the Writer Portal democratizes publishing by providing professional-grade tools directly to creators. A novelist in Mumbai can publish content reaching readers nationwide within hours rather than months, whilst retaining full creative control and receiving transparent, data-driven insights into reader engagement and revenue generation.
Built on TipTap or ProseMirror frameworks, the manuscript editor provides familiar word-processor functionality: text formatting (bold, italic, underline), paragraph styling, heading hierarchies, and list creation. Writers compose directly in browser without external tool dependencies or complex import procedures.
Manuscripts organize into discrete chapters with drag-and-drop reordering, nested sub-chapter support, and automatic table of contents generation. Writers navigate large manuscripts efficiently through chapter sidebar navigation whilst readers benefit from EPUB 3 structural metadata enabling precise chapter navigation.
Content saves automatically every 30 seconds without writer intervention, preventing work loss from browser crashes or accidental tab closures. Complete version history enables rollback to any previous save point, providing confidence to experiment with structural revisions knowing original versions remain recoverable.
Editor generates structurally valid EPUB 3 output incorporating proper semantic HTML, navigation documents, and metadata packaging. Writers need no technical knowledge of EPUB specification—editor automation handles format compliance whilst preserving creative formatting choices like poetry line breaks or dramatic spacing.
Initial manuscript state where writers compose, revise, and refine content without visibility to readers or platform review queues. Drafts support unlimited revisions with no review overhead, encouraging iterative refinement before submission.
Writers mark drafts complete and submit for administrative review, entering moderation queue. Submissions lock content preventing further edits during review—writers wanting to modify content must withdraw submission, returning books to draft status.
Admin team evaluates content for policy compliance, quality standards, and appropriate categorization. Review criteria include: absence of prohibited content, proper metadata accuracy, cover image appropriateness, and basic formatting quality. Typical review completes within 24-48 hours.
Approved books become immediately available in catalog with full reader visibility. Writers can unpublish books temporarily (removing from catalog whilst preserving data) but cannot delete books—deletion requires admin or super admin authorization maintaining audit trail integrity.
Books failing review return to writer control with detailed rejection reasons explaining specific policy violations or quality issues requiring remediation. Writers address concerns, revise content, and resubmit—resubmissions receive priority review scheduling.

Cover image generation integrates multiple AI image generation models—DALL-E 3, Midjourney API, Stable Diffusion XL—enabling writers to produce professional-quality cover artwork without graphic design expertise or external designer costs. Writers provide text excerpts from their manuscript, select artistic styles matching genre conventions, and receive generated cover options within minutes.
The generation workflow begins with writers selecting representative passages—typically 500-1000 words from opening chapters—which natural language processing algorithms analyze to extract thematic elements, mood descriptors, setting details, and character archetypes. These extracted elements combine with genre-specific prompt templates optimized for each model's strengths: DALL-E 3 excels at conceptual illustration, Midjourney produces painterly aesthetics popular in literary fiction, whilst Stable Diffusion XL offers photorealistic rendering for contemporary fiction and non-fiction.
Generated images populate a selection interface displaying 6-12 variations with ability to regenerate alternatives, adjust aspect ratios for print-on-demand compatibility, and apply text overlays with title and author name using professionally designed typography templates. Writers lacking design skills receive publication-ready covers, whilst sophisticated users can export base images for further customization in external tools.
Credit-based pricing enables flexible usage: new writers receive 10 free generation credits upon account creation, with additional credit purchases through micro-transaction bundles (50 credits for ₹99, 200 credits for ₹299). Each generation consumes 1-3 credits depending on selected model and image complexity, with transparent pricing displayed before confirmation.
StoriesHut's royalty system directly implements Kindle Unlimited's proven model where writers earn compensation based on pages read rather than book sales, incentivizing content quality and reader engagement over traditional units-sold metrics. This approach democratizes earning potential—an unknown debut novelist producing compelling content can earn substantially more than established authors with weak reader engagement, fundamentally rewarding writing quality.
Royalty calculations employ normalized page length definitions accounting for font sizes, formatting variations, and content density. The platform establishes a "Kindle Edition Normalized Page Count" (KENPC) equivalent where one normalized page represents approximately 187 words of standard prose at median font sizing. This normalization ensures that writers cannot artificially inflate earnings through extreme formatting—massive fonts or excessive whitespace don't increase page counts.
The global royalty pool distributes monthly subscriber revenue minus platform operational costs (typically 30-40%) proportionally among writers based on their share of total pages read. If subscribers generate ₹10,000,000 in monthly revenue with 60% allocated to royalties (₹6,000,000), and a specific book accounts for 2% of total platform pages read, that book's writer receives ₹120,000 before tax deductions. This creates direct economic alignment between platform success and writer earnings—as StoriesHut grows, individual writer income scales proportionally.
Critical fraud protection excludes illegitimate reads from calculations: pages skipped by readers, zero-time page reads indicating automation, fraudulent reads from flagged accounts, pages read during security violation-flagged sessions, and reads from accounts subsequently banned for abuse all face retroactive exclusion protecting royalty pool integrity.
Real-time counter updating every 15 minutes showing daily reading activity across all published books
Projected earnings based on current month's reading activity, updated daily as new reads accumulate
Confirmed earnings for completed settlement period, scheduled for payout after 90-day holding period
Unique readers accessing content within past 30 days, indicating sustained audience engagement
Detailed analytics drill down into book-specific performance enabling strategic content decisions. Writers identify which books attract the most readers, which chapters see highest completion rates, and which promotional efforts correlate with traffic spikes. Geographic breakdowns reveal unexpected international audiences, suggesting translation opportunities or targeted marketing in specific regions.
Time-series graphs display reading trends over weeks and months, helping writers understand seasonal patterns or content lifecycle trajectories. A thriller novelist might notice increased readership during winter months suggesting optimal release timing for future works, whilst educational content sees spikes during academic terms indicating student reader demographics.
Comparative analytics benchmark individual books against genre averages and top performers, providing context for evaluating success. A writer whose fantasy novel achieves 80th percentile completion rates within the fantasy category understands they've produced above-average engaging content even if absolute numbers seem modest during early promotion phases.
Writers download comprehensive royalty data in CSV format compatible with spreadsheet applications, accounting software, and data analysis tools. Export files include daily granular data: date, book title, pages read, estimated earnings per book, cumulative monthly totals, and metadata enabling pivot table analysis or chart generation in Excel or Google Sheets.
Filtered exports enable custom date range selection—writers preparing tax documentation extract specific fiscal year data without manually parsing broader datasets. Book-specific exports isolate individual title performance for detailed analysis, whilst aggregate exports provide portfolio-level overviews across all published works.
Formalized monthly statements generate automatically upon settlement period completion, providing official documentation suitable for tax filing, income verification, and financial planning purposes. Statements include: writer identification details, book inventory with ISBNs where applicable, itemized page-read counts per title, gross royalty calculation breakdowns, platform fee deductions, applicable tax withholdings, and net payout amounts.
PDF format statements include official StoriesHut letterhead and digital signatures verifying authenticity for submission to banks, tax authorities, or other institutions requiring income documentation. Writers access complete historical statement archives extending indefinitely, ensuring permanent record availability for audit compliance or financial planning.
Administrative infrastructure provides platform operators with comprehensive oversight, control, and response capabilities across user management, content moderation, financial operations, and security monitoring. The console architecture separates concerns through role-specific interfaces: operational admins focus on user issues and content quality, finance teams manage payment operations and compliance, whilst security personnel monitor threat detection and respond to abuse patterns.
The dashboard aggregates critical platform health metrics: active user counts, new registration velocity, subscription conversion rates, content catalog growth, reading activity levels, security event frequency, and financial transaction volumes. Real-time alerting highlights anomalies requiring immediate attention—sudden traffic spikes suggesting viral content or DDoS attacks, payment processing failures indicating gateway issues, or concentrated security violations suggesting organized fraud attempts.
Administrative actions generate comprehensive audit logs capturing actor identity, timestamp, affected resources, actions taken, and justifications provided through required comment fields. These logs satisfy regulatory requirements for financial services, provide forensic evidence for security investigations, and enable accountability when admin decisions face dispute. Logs are immutable—even super admins cannot modify or delete historical records, preventing evidence tampering.
Admins temporarily or permanently restrict user accounts in response to Terms of Service violations, payment disputes, security concerns, or legal requirements. Suspension actions specify duration for temporary restrictions, affected services (reading access vs. full account), and user-visible explanation messages. Suspended users retain support channel access enabling appeal processes and dispute resolution.
Copyright claims, legal notices, or policy violations trigger content removal workflows where admins hide books from catalog, revoke reader access, and notify affected writers with detailed justification. Takedown actions preserve content data enabling restoration if disputes resolve favorably, whilst immediately protecting platform from legal liability. DMCA-compliant counter-notification processes allow writers to dispute illegitimate takedown requests.
Territorial licensing requirements or regional legal restrictions necessitate geo-blocking capabilities where specific books become unavailable in particular countries or states. Geo-restriction rules operate at IP geolocation and billing address levels, preventing access from restricted regions whilst maintaining availability elsewhere. Writers configure restrictions during publishing workflows or subsequently modify through support requests.
Extraordinary circumstances require admin override of automated systems: fraud detection false positives blocking legitimate users, billing system errors preventing subscription access, or technical glitches corrupting user data. Override actions require mandatory justification documentation and automatically escalate to senior admin review preventing abuse of override authority for unauthorized access or favoritism.
Financial operations implement rigorous controls balancing timely writer compensation against fraud prevention and regulatory compliance. The royalty processing pipeline progresses through multiple validation stages before releasing funds, protecting platform finances from abuse whilst maintaining writer trust through transparent, predictable payout schedules.
At month end (00:00 UTC on first day of new month), automated systems finalize previous month's royalty calculations. All page-read events from the completed month undergo final fraud validation, exclusion rules application, and normalized page count calculation. Writers receive preliminary statements within 24 hours showing finalized earnings pending payout processing.
Following Kindle's precedent, earnings enter mandatory 90-day holding periods before payout eligibility. January earnings become payable on April 1st, February earnings on May 1st, etc. This holding period accommodates payment reversals, fraud investigation completion, and dispute resolution without clawing back already-distributed funds. Writers plan finances accordingly, treating StoriesHut income as delayed rather than instantaneous.
Payout eligibility requires minimum accumulated balance (typically ₹1,000) reducing transaction costs for micro-earnings. Earnings below threshold accumulate across months until reaching payout minimum. Finance team reviews all pending payouts above ₹50,000 for additional validation before approval, whilst smaller amounts process automatically. Manual review identifies potential fraud, validates writer identity documentation, and confirms tax compliance.
Approved payouts transmit to Razorpay Route for distribution via writer-specified methods: bank account NEFT transfers (2-3 business day settlement), UPI instant payments (minutes to hours), or international wire transfers for non-Indian writers. Failed payments retry automatically with exponential backoff, whilst persistent failures trigger email notifications requesting updated payment details.
All subscription revenues and book purchase transactions include appropriate GST calculations at rates mandated by Indian tax law (typically 18% for digital content services). Platform automatically generates GST invoices for B2C transactions and compliance-ready data for quarterly/annual GST return filing. Integration with GST Network (GSTN) APIs enables electronic filing where applicable, reducing manual data entry and transcription errors.
Input tax credit calculations offset GST paid on business expenses (hosting costs, payment gateway fees, third-party services) against GST collected from subscribers, accurately determining net GST liability. Automated reconciliation identifies discrepancies between calculated liability and payment gateway reported amounts, flagging investigation requirements before filing deadlines.
Tax Deducted at Source (TDS) requirements apply to writer payouts above statutory thresholds. Platform automatically calculates applicable TDS rates based on payment amounts and writer PAN availability, deducts TDS before net payout release, and remits deducted amounts to tax authorities through designated channels. Writers receive TDS certificates (Form 16A equivalents) documenting deductions for income tax return filing purposes.
Non-resident writers face different TDS rate structures requiring tax residency certificate verification and double taxation treaty applicability assessment. International payout processing includes automated FEMA compliance checks ensuring cross-border payments adhere to foreign exchange regulations and reporting requirements.
Financial data exports in formats compatible with Zoho Books, QuickBooks, Tally, and other popular accounting platforms enable seamless integration with existing business accounting workflows. Export schemas include chart of accounts mappings, journal entry formats, and reconciliation keys enabling automated import without manual data transformation. This compatibility reduces accounting overhead for finance teams whilst ensuring audit trail continuity between StoriesHut systems and official financial records.
IDFC Razorpay subscription management handles recurring billing with configurable cycles (monthly, quarterly, annual), automatic payment method charging on renewal dates, retry logic for failed payments with exponential backoff, and grace period provisions maintaining access during payment resolution. Subscription management APIs enable programmatic upgrades, downgrades, and cancellations with prorated refund calculations.
Refund policies balance customer satisfaction against abuse prevention: 7-day full refund windows for new subscriptions, prorated refunds for mid-cycle cancellations where applicable, and discretionary refunds for technical issues preventing service access. Automated refund processing through Razorpay APIs releases funds to original payment methods within 5-7 business days, with notification emails confirming processing status.
Razorpay Route facilitates writer compensation distribution with support for multiple payout methods addressing diverse writer preferences and banking access. NEFT transfers accommodate traditional banking relationships, UPI enables instant payments to mobile-first writers, whilst international wire transfers serve non-resident writers. Payout status tracking provides real-time visibility into processing stages from initiation through settlement.
International writer payouts comply with FEMA regulations through proper documentation, purpose code assignment, and reporting to authorized dealer banks. Currency conversion occurs at competitive exchange rates with transparent fee disclosure, whilst alternative options like PayPal or Payoneer integration provide familiar interfaces for writers accustomed to freelance platform payment methods.
Comprehensive event tracking captures granular user behavior across the platform, generating data streams feeding both operational dashboards and machine learning models powering personalized recommendations. Every significant user action—app launches, book selections, page reads, time-spent measurements, downloads, highlights, notes, searches—generates structured events with standardized schemas enabling consistent analysis across diverse interaction types.
Event payloads include contextual metadata: user identifiers, session IDs, device characteristics, timestamp precision to millisecond resolution, geographic data when available, and activity-specific attributes like page numbers, chapter IDs, or search queries. These rich events enable sophisticated analysis distinguishing casual browsers from engaged readers, identifying content discovery patterns, and measuring feature adoption rates for product development prioritization.
Page-read events receive special handling given their royalty calculation criticality. Each page read records exact in/out timestamps enabling accurate duration calculation, device fingerprints for fraud detection, sequential page ordering for skip detection, and immutable storage in append-only logs preventing retroactive manipulation. Reading session events aggregate page reads into coherent reading blocks, tracking session start times, cumulative duration, interruption patterns, and completion status.
Fraud signal tracking captures security events, rapid navigation patterns, suspicious timing anomalies, and abuse indicator metrics. Security violation events from screenshot attempts integrate with the same analytics pipeline, enabling unified fraud analysis correlating multiple signal types. Device fingerprinting combines hardware identifiers, browser characteristics, network details, and behavioral biometrics creating unique device signatures enabling multi-account detection and device farm identification.
Recommendation algorithms identify readers with similar taste profiles based on shared reading history, comparable ratings, and aligned genre preferences. Books enjoyed by similar readers surface in personalized recommendation feeds, implementing the "readers who enjoyed X also enjoyed Y" pattern proven effective across e-commerce platforms. Collaborative filtering excels at discovering unexpected connections—a reader primarily consuming historical fiction might receive excellent science fiction recommendations if taste-similar readers bridge both genres.
Natural language processing analyzes book content extracting themes, writing styles, pacing characteristics, and subject matter profiles. Readers enjoying fast-paced thrillers with female protagonists receive recommendations for stylistically similar works regardless of exact genre classifications. Content-based methods excel during cold-start scenarios where new books lack sufficient reader interaction history for collaborative filtering effectiveness, using textual similarity as proxy for reading appeal.
Real-time popularity signals identify emerging hits before they achieve widespread recognition. Velocity-based trending algorithms detect books with accelerating read rates, distinguishing genuine viral growth from steady-state popularity. Readers interested in cultural moments discover trending books organically through prominent homepage placement and category-specific trending sections. Popularity metrics account for catalog tenure—new releases achieving strong initial reception score differently than established classics maintaining sustained readership.
StoriesHut implements a hierarchical category system mirroring Kindle's proven organizational structure, enabling readers to discover content through genre browsing whilst providing writers with targeting mechanisms for audience reach. The taxonomy balances breadth for content diversity against depth for precise categorization, with admin-controlled master categories preventing tag spam whilst allowing sufficient specificity for niche genre identification.
Writers select up to three sub-categories per book during publishing workflow, with mandatory designation of one primary category determining default catalog placement and recommendation algorithm weighting. Multiple category selection enables books spanning genre boundaries—a romantic thriller occupies both Romance (Romantic Suspense) and Mystery (Thriller) categories reaching broader audiences.
Category assignments face admin review during book approval workflow, correcting miscategorizations that degrade recommendation quality or frustrate reader discovery expectations. Admin override authority exists for blatant miscategorization—self-help books incorrectly filed as fiction, or adult content misrepresented as young adult—maintaining category browsing utility.
Category pages generate automatically displaying filtered book lists with configurable sort orders: trending books show velocity-ranked recent gainers, new releases sort by publication date, top-rated display highest-reviewed titles, whilst most-read ranks by cumulative page-read volume. This multi-dimensional presentation surfaces different discovery pathways acknowledging that readers value diverse quality signals—some prioritize critical acclaim (ratings), others prefer popular validation (read counts), whilst trend-followers want emerging hits.
Leaderboards gamify the platform experience creating competitive motivation for writers whilst providing readers with curated discovery mechanisms highlighting exceptional content and prolific creators. Automated leaderboard generation refreshes daily incorporating previous 24-hour activity, with separate weekly and monthly leaderboards providing different temporal perspectives on platform dynamics.
Book rankings aggregate across multiple dimensions: Most Read ranks by cumulative pages read over specified time periods, Trending identifies books with highest growth velocity relative to baseline, Top Rated displays highest average star ratings among books exceeding minimum review thresholds, whilst New & Rising highlights recently published books achieving strong early traction. Each leaderboard type emphasizes different success patterns—viral hits dominate trending whilst literary masterpieces lead top-rated categories.
Writer rankings provide portfolio-level visibility recognizing prolific creators with multiple successful books. Metrics include cumulative pages read across entire author catalog, total earnings acknowledging commercial success, and active reader counts measuring sustained audience engagement. Category-specific author leaderboards highlight genre specialists—a romance author dominating Romance rankings might not appear on global leaderboards dominated by thriller writers with broader mass appeal.
Gamified reader rankings encourage platform engagement through competitive reading volume tracking. Metrics include total pages read, reading streak durations (consecutive days with reading activity), and time-spent measurements. Badge systems award milestone achievements—100-book completion, million-page lifetime reading, or year-long daily reading streaks. Opt-in visibility protects privacy-concerned users whilst allowing competitive readers to share achievements socially. Virtual rewards like exclusive badges, profile flair, or early access to new releases incentivize engagement without monetary cost.
Reddit-style discussion threads create community spaces around individual books, enabling readers to discuss plot developments, share theories, debate character motivations, and connect with fellow fans. Threaded conversation structures with nested reply support facilitate organized discussions even in high-traffic threads, whilst voting mechanisms (upvote/downvote) surface community-endorsed comments and bury low-quality contributions.
Each book maintains a dedicated discussion space accessible through book detail pages, with comments organized by multiple sort orders: Top displays highest-voted comments, New shows chronologically recent contributions, Controversial highlights divisive comments with balanced vote counts, and Hot combines recency with engagement velocity identifying active conversation topics. Sort flexibility accommodates different reader priorities—some want community consensus (Top), others prefer fresh perspectives (New), whilst controversy-seekers find Hot debates.
Emoji reactions provide lightweight engagement options supplementing voting: readers express agreement, surprise, laughter, or appreciation without composing replies. Reaction aggregation surfaces emotional valence—comments receiving primarily laugh reactions might be humorous observations, whilst comments with surprised reactions might reference plot twists. These reaction patterns inform content moderation highlighting potentially problematic comments generating angry or shocked reactions disproportionately.

StoriesHut implements comprehensive group functionality enabling users to create themed communities around genres, books, authors, or shared interests. Groups serve as dedicated spaces for focused discussions, media sharing, and collaborative discovery beyond individual book comment threads.
Any registered user can create unlimited groups with customizable settings:
Chronological feed displaying member posts, shared content, and group announcements:
StoriesHut implements a zero-upload media sharing model where all images and videos are linked via external URLs rather than uploaded to platform storage. This architecture reduces infrastructure costs, eliminates content hosting liability, and leverages existing CDN infrastructure from established platforms.
Users share images by providing publicly accessible URLs from external sources:
Initial video support exclusively through YouTube embeds using YouTube's official embed API:
The URL-based media architecture enables seamless integration of additional video platforms without fundamental system redesign:
Backend implements intelligent URL parsing detecting video platform from URL structure:
URL Pattern Matching:
- youtube.com|youtu.be → YouTube handler
- vimeo.com → Vimeo handler
- dailymotion.com → Dailymotion handler
- instagram.com/reel → Instagram handler
- tiktok.com → TikTok handler
- twitter.com|x.com/*/video → Twitter handler
Each platform handler:
group_videos table:
- video_id (UUID primary key)
- group_post_id (foreign key)
- platform (enum: youtube, vimeo, dailymotion, instagram, tiktok, twitter)
- platform_video_id (platform-specific identifier)
- original_url (user-provided URL)
- title, description, thumbnail_url
- duration_seconds, view_count
- channel_name, channel_url
- created_at, last_validated_at
- is_accessible (boolean, updated by validation jobs)
Since media content resides on external platforms, moderation focuses on link appropriateness rather than content hosting:
Real-time communication infrastructure keeps group members engaged and informed about new activity, replies, and mentions.
Groups support threaded discussions with real-time message delivery:
Granular notification controls prevent notification fatigue:
Admins and moderators maintain healthy group environments:
Comprehensive data model supporting group functionality, media sharing, and moderation workflows.
groups table:
- group_id (UUID primary key)
- name (VARCHAR 100, unique within platform)
- description (TEXT, max 1000 characters)
- cover_image_url (TEXT, nullable - external URL)
- group_type (ENUM: public, private, restricted)
- category (VARCHAR 50, for discovery/filtering)
- creator_user_id (UUID foreign key → users)
- created_at, updated_at (TIMESTAMP)
- member_count (INTEGER, denormalized for performance)
- is_active (BOOLEAN, soft delete flag)
group_members table:
- membership_id (UUID primary key)
- group_id (UUID foreign key → groups)
- user_id (UUID foreign key → users)
- role (ENUM: admin, moderator, member)
- joined_at (TIMESTAMP)
- last_active_at (TIMESTAMP, updated on any group interaction)
- notification_preference (ENUM: all, mentions, important, muted)
- is_banned (BOOLEAN, prevents rejoin if removed)
- UNIQUE constraint on (group_id, user_id)
group_posts table:
- post_id (UUID primary key)
- group_id (UUID foreign key → groups)
- author_user_id (UUID foreign key → users)
- content_type (ENUM: text, image, video, book_reference)
- text_content (TEXT, max 2000 characters)
- media_url (TEXT, nullable - external image/video URL)
- media_platform (ENUM: youtube, vimeo, google_images, imgur, etc.)
- media_metadata (JSONB - stores title, thumbnail, duration, etc.)
- book_id (UUID foreign key → books, nullable - for book recommendations)
- parent_post_id (UUID foreign key → group_posts, nullable - for threaded replies)
- is_pinned (BOOLEAN, max 3 per group enforced at application level)
- is_locked (BOOLEAN, prevents new replies)
- is_hidden (BOOLEAN, moderator action)
- like_count, reply_count (INTEGER, denormalized)
- created_at, updated_at, edited_at (TIMESTAMP)
- reported_count (INTEGER, auto-hide threshold = 5)
group_post_likes table:
- like_id (UUID primary key)
- post_id (UUID foreign key → group_posts)
- user_id (UUID foreign key → users)
- created_at (TIMESTAMP)
- UNIQUE constraint on (post_id, user_id)
group_invitations table:
- invitation_id (UUID primary key)
- group_id (UUID foreign key → groups)
- inviter_user_id (UUID foreign key → users)
- invitee_user_id (UUID foreign key → users, nullable for link invites)
- invitation_code (VARCHAR 32, unique, for shareable links)
- status (ENUM: pending, accepted, declined, expired)
- created_at, expires_at (TIMESTAMP, 7-day expiration)
media_url_cache table:
- cache_id (UUID primary key)
- original_url (TEXT, indexed)
- url_hash (VARCHAR 64, SHA-256 hash for deduplication)
- media_type (ENUM: image, video)
- platform (VARCHAR 50)
- thumbnail_url (TEXT, Cloudflare proxy URL)
- metadata (JSONB - dimensions, duration, title, etc.)
- is_accessible (BOOLEAN, updated by validation jobs)
- last_validated_at (TIMESTAMP)
- access_count (INTEGER, for popularity tracking)
- created_at (TIMESTAMP)
- UNIQUE constraint on url_hash
Comprehensive screen specifications for group functionality within the Flutter mobile application.
StoriesHut incorporates social media functionality enabling readers and writers to share thoughts, updates, reading experiences, and creative content through profile-based posts visible to followers and the broader community.
- post_id (UUID, primary key)
- user_id (foreign key to users)
- post_type (text, image, video, book_share, poll)
- content (text, max 5000 chars)
- media_urls (JSON array)
- visibility (public, followers, private, unlisted)
- hashtags (array)
- mentioned_users (array of user_ids)
- book_id (foreign key, nullable)
- created_at, updated_at
- deleted_at (soft delete)- interaction_id (UUID)
- post_id (foreign key)
- user_id (foreign key)
- interaction_type (like, comment, repost, bookmark, report)
- comment_text (nullable)
- parent_comment_id (for nested replies)
- created_at- follower_id (foreign key to users)
- following_id (foreign key to users)
- created_at
- muted (boolean)
- notifications_enabled (boolean)StoriesHut implements a comprehensive direct messaging system enabling private conversations between readers, writers, and community members. The chat architecture supports one-on-one conversations, group chats, and writer-reader engagement channels.
code blocks)





- conversation_id (UUID, primary key)
- conversation_type (direct, group, broadcast)
- created_at, updated_at
- last_message_at (for sorting)
- group_name (nullable, for groups)
- group_description (nullable)
- group_photo_url (nullable)- participant_id (UUID)
- conversation_id (foreign key)
- user_id (foreign key)
- role (member, admin, owner)
- joined_at
- left_at (nullable)
- muted (boolean)
- archived (boolean)
- last_read_message_id (for unread count)- message_id (UUID, primary key)
- conversation_id (foreign key)
- sender_id (foreign key to users)
- message_type (text, image, file, voice, book_share, system)
- content (text, nullable)
- media_urls (JSON array, nullable)
- reply_to_message_id (nullable, for threaded replies)
- created_at, updated_at
- edited_at (nullable)
- deleted_at (soft delete)
- deleted_for_everyone (boolean)- receipt_id (UUID)
- message_id (foreign key)
- user_id (foreign key)
- status (delivered, read)
- timestamp- reaction_id (UUID)
- message_id (foreign key)
- user_id (foreign key)
- emoji (text)
- created_at


StoriesHut transforms private bookmarks into shareable social objects, enabling readers to curate and share their favorite passages, create thematic collections, and discover content through community curation.








- bookmark_id (UUID, primary key)
- user_id (foreign key)
- book_id (foreign key)
- chapter_id (foreign key, nullable)
- bookmark_type (highlight, page, chapter, quote_card)
- content (text of highlighted passage)
- start_position, end_position (character offsets)
- color (yellow, blue, pink, green, nullable)
- note (user annotation, nullable)
- visibility (public, followers, private)
- created_at, updated_at- collection_id (UUID, primary key)
- user_id (foreign key)
- name (text)
- description (text, nullable)
- visibility (public, private)
- created_at, updated_at- item_id (UUID)
- collection_id (foreign key)
- bookmark_id (foreign key)
- position (integer, for ordering)
- added_at- list_id (UUID, primary key)
- creator_id (foreign key to users)
- title (text)
- description (text, nullable)
- cover_image_url (text, nullable)
- visibility (public, unlisted, private, collaborative)
- list_type (curated, challenge, book_club, recommendation)
- created_at, updated_at- item_id (UUID)
- list_id (foreign key)
- book_id (foreign key)
- position (integer, for ordering)
- added_by_user_id (foreign key, for collaborative lists)
- notes (text, nullable)
- added_at- follower_id (UUID)
- list_id (foreign key)
- user_id (foreign key)
- followed_at
- notifications_enabled (boolean)- interaction_id (UUID)
- bookmark_id (foreign key)
- user_id (foreign key)
- interaction_type (like, save, comment, report)
- comment_text (nullable)
- created_at

When composing comments, readers specify which chapter their discussion references, with optional spoiler flags marking content revealing plot developments. Tags display prominently alongside comments: "Chapter 12 - Spoiler" warnings alert readers to hidden content requiring explicit opt-in reveal actions. This system respects reader agency—those caught up to Chapter 12 can safely engage with tagged discussions whilst earlier readers avoid unwanted revelations.
Comment threads automatically hide spoiler-tagged comments by default, displaying collapsed placeholders indicating hidden content availability. Readers explicitly choose to reveal spoilers through interaction with placeholder elements, acknowledging awareness of potential plot revelations. This friction reduces accidental spoiler exposure from casual scrolling whilst permitting intentional engagement when readers desire deeper discussion.
Comments can include specific passage quotes with chapter/page attribution, enabling precise reference without requiring readers to recall exact wording from memory. Quote attribution provides context for discussion whilst enabling spoiler-sensitive readers to assess whether quoted passages precede or follow their current reading position. Rich quote formatting differentiates quoted book content from commenter commentary preventing confusion about authorship.
Discussion interfaces optionally integrate with reader progress tracking, automatically filtering comments to display only those referencing chapters the reader has completed. This personalized filtering prevents accidental spoiler exposure even when readers forget to check chapter tags before engaging. Advanced readers can disable filtering when seeking future-chapter discussions or participating in full-book retrospectives after completion.
Discussion health requires proactive moderation preventing harassment, hate speech, spam, and other harmful behaviors that degrade community quality and discourage participation. Multi-layered moderation combines automated filtering, community reporting, and human review creating scalable safety systems addressing harmful content quickly whilst minimizing false positives that might silence legitimate discourse.
Natural language processing models scan comments for prohibited content patterns: profanity, slurs, personal attacks, spam signatures, and malicious link patterns. High-confidence detections face automatic removal with notification to commenters explaining policy violations, whilst ambiguous cases enter human review queues for contextual evaluation. Machine learning models improve continuously through feedback loops incorporating moderator decisions and user report patterns.
Rate limiting prevents spam and harassment through velocity restrictions: new accounts face stricter comment frequency limits until establishing trust scores through positive community engagement, whilst established users enjoy relaxed limits reflecting earned reputation. Sudden velocity spikes—users posting dozens of comments within minutes—trigger automatic throttling and moderator alerts suggesting potential compromise or coordinated brigading attempts.
Report buttons accompany every comment enabling community members to flag concerning content for moderator review. Report categories include: harassment/bullying, hate speech, spam/commercial promotion, spoilers without proper tagging, and off-topic content. Report aggregation identifies problematic comments receiving multiple independent reports, prioritizing these for rapid review.
Reporter abuse prevention systems track reporting patterns identifying users who frivolously report benign content or weaponize reporting to silence disagreement. Accounts exhibiting abuse patterns face reduced report weight or reporting privilege suspension, preventing mob censorship or bad-faith reporting campaigns whilst maintaining legitimate safety reporting effectiveness.
Book authors automatically receive moderation rights for their book discussion threads, enabling comment removal, user bans from specific discussions, and thread locking during particularly heated controversies. Admin moderators provide platform-wide oversight addressing cross-book patterns and adjudicating author moderation disputes. Moderation actions generate transparent mod logs visible to other moderators documenting removal reasons and maintaining accountability against arbitrary censorship or personal biases influencing moderation decisions.
The discussion system now extends to support both book-specific discussion threads AND group-based community discussions with media sharing capabilities.
Row Level Security policies enforce: users can only vote once per comment, users can delete their own comments within edit windows (typically 5-15 minutes post-publication), moderators can remove any comments within their jurisdiction, and deleted comments retain data for audit purposes displaying "[deleted]" placeholders to readers whilst preserving moderator visibility for pattern analysis.
Comments become immutable after edit window expiration preventing post-publication content modification that might misrepresent replied-to content or enable manipulation. Edit history tracking records all modifications during edit windows maintaining transparency about comment evolution. Deletion operations soft-delete records updating status flags rather than removing rows, ensuring complete audit trails persist indefinitely for legal compliance and abuse investigation.
group_id (PK), name, description, created_by_user_id (FK), created_at, visibilitygroup_member_id (PK), group_id (FK), user_id (FK), role, joined_atpost_id (PK), group_id (FK), user_id (FK), content, media_url (nullable), created_atlike_id (PK), post_id (FK), user_id (FK), created_atinvitation_id (PK), group_id (FK), invited_by_user_id (FK), invited_user_id (FK), status, created_atmedia_url_id (PK), original_url, cached_path, content_type, size, created_atComprehensive quality assurance processes validate platform functionality, security, and regulatory compliance before production deployment. Multi-layered testing strategies combine automated unit testing, integration testing, end-to-end scenario validation, penetration testing, and compliance auditing ensuring robust software quality meeting professional standards and user expectations.
Automated test suites execute on every code commit validating individual function correctness and component integration behavior. Unit tests verify business logic correctness in isolation—royalty calculation functions receive mock input data and assert expected output accuracy. Integration tests validate API contracts, database schema compatibility, and external service integration functionality ensuring system components interoperate correctly. Code coverage targets exceed 80% for critical paths including authentication, payment processing, and royalty calculation.
Security professionals conduct adversarial testing attempting to compromise platform security through SQL injection, cross-site scripting, authentication bypass, privilege escalation, and other attack vectors. Quarterly penetration tests identify vulnerabilities before malicious actors discover them, with immediate remediation of critical findings preceding next release. Third-party security firms provide independent validation ensuring internal security reviews don't suffer from blind spots or conflicts of interest.
Security architecture explicitly addresses OWASP Top 10 vulnerabilities: injection protection through parameterized queries and input validation, broken authentication mitigation through secure session management and MFA support, sensitive data exposure prevention through encryption and access controls, XML external entity attack prevention, broken access control protection through RLS enforcement, security misconfiguration auditing, cross-site scripting prevention through content security policies and output encoding, insecure deserialization protection, component vulnerability monitoring, and insufficient logging/monitoring remediation through comprehensive audit systems.
Mobile applications comply with Google Play Store and Apple App Store content policies, privacy requirements, and technical guidelines. Compliance reviews address: content rating accuracy for mature themes, privacy policy completeness and data handling transparency, payment processing guideline adherence, and prohibited functionality avoidance. Pre-submission compliance validation reduces rejection risks accelerating release velocity.
Comprehensive penetration testing validates platform security posture before production launch and periodically thereafter. Testing scope encompasses all attack surfaces including mobile applications, web portals, APIs, and backend infrastructure.

Comprehensive Testing Framework
Multi-layered testing strategy ensures platform reliability, performance, and user experience quality across all components. Testing pyramid balances automated unit tests, integration tests, and manual exploratory testing.

Continuous integration and deployment automation streamlines release processes: Git commits trigger automated builds, test suite execution blocks merge on failures, staging environment deployments enable QA validation, and production deployments execute through controlled promotion workflows with rollback capabilities. Deployment automation reduces human error whilst accelerating release cycles from weeks to days or hours.
Feature flag systems enable deploying code to production with inactive features, separating deployment from release decisions. Complex features develop behind flags enabling incremental production testing without exposing incomplete functionality to users. Flags enable gradual rollouts—activating features for 1% of users initially, monitoring metrics, and expanding percentages progressively. Emergency kill switches disable problematic features instantly without requiring code deployments.
Mobile application releases employ staged rollout—Google Play's release channels distribute new versions to progressively larger user cohorts (5% → 25% → 50% → 100%) over several days. Early adopter feedback identifies critical bugs before mass exposure, whilst rollback capabilities revert problematic releases instantly. Web application deployments follow similar patterns using load balancer traffic shifting.
Automated crash reporting tools capture application failures across diverse devices and conditions. Crash reports include stack traces, device characteristics, OS versions, and reproduction steps when available. Analytics dashboards aggregate crashes identifying common patterns requiring prioritization, whilst alerting notifies engineering teams when crash rates exceed thresholds suggesting critical regressions.
Comprehensive backup architecture ensuring data durability and disaster recovery:
Backup Schedule:
Global content delivery network for performance and security:
Multi-tier load balancing for high availability:
StoriesHut's architectural foundation supports extensive future enhancements expanding platform capabilities, revenue streams, and user value propositions. The following initiatives represent strategic priorities informed by user research, competitive analysis, and market opportunity assessment. While not committing to specific delivery timelines, these enhancements guide architectural decisions ensuring current systems remain extensible without requiring fundamental redesigns.
Enhanced cross-device sync improves upon basic Whispersync-like functionality introducing real-time position synchronization enabling seamless device switching mid-paragraph, synchronized highlight and note editing across devices with conflict resolution for simultaneous edits, and reading position sharing enabling social reading experiences where friends read together asynchronously whilst seeing each other's progress and annotations.
Multi-device reading modes allow reading different books simultaneously across devices—novel on tablet whilst reading reference book on phone—with intelligent context switching recognizing which book to surface based on device type and usage patterns. Family account sharing extends device limits enabling household members to share single subscription whilst maintaining separate reading histories and recommendations.
Advanced ML models incorporating deep learning architectures, transformer-based natural language understanding, and hybrid collaborative-content filtering provide substantially improved recommendation accuracy. Models analyze reading velocity patterns identifying when readers accelerate through exciting passages or slow during complex sections, using these signals to recommend pacing-appropriate content.
Sentiment analysis of highlights and notes reveals reader emotional responses—repeatedly highlighting inspirational quotes suggests preference for uplifting content, whilst notes expressing confusion indicate complexity tolerance. These implicit signals supplement explicit ratings providing richer taste profiling than ratings alone. Graph neural networks model complex relationships between books, authors, themes, and stylistic elements discovering non-obvious similarity patterns invisible to simpler algorithms.
Initial audiobook capabilities leverage advanced neural text-to-speech (TTS) synthesis generating high-quality narration from written content. Modern TTS engines produce natural-sounding speech with proper prosody, emotion, and pronunciation accuracy suitable for long-form content consumption. Writer-opt-in programs allow authors to enable automatic TTS audiobook generation for their catalog, expanding accessibility whilst generating supplementary revenue from audio-preferring readers.
Premium audiobook tier connects writers with professional narrators through marketplace-style matching. Writers post narration projects with compensation offers, narrators audition with sample recordings, and writers select preferred narrators. Platform facilitates contract management, payment escrow, recording workflow coordination, and final production quality assurance creating end-to-end audiobook production pipeline without external service dependencies.
Whispersync-style immersion reading synchronizes audiobook playback with text highlighting enabling simultaneous audio listening and text following. This multimodal experience benefits language learners, readers with visual impairments, and anyone preferring hybrid reading modes. Position synchronization ensures seamless switching between pure text reading, pure audio listening, and immersion mode based on context—commuting via audio, reading text during focused sessions.
Variable playback speeds accommodate different consumption preferences—some listeners prefer accelerated 1.5x or 2x speeds whilst others want slower speeds for complex content. Chapter navigation, bookmarking, and sleep timers provide audiobook-specific controls missing from pure text interfaces. Offline download with encrypted storage mirrors e-book offline functionality ensuring audiobook access during connectivity absence.
Enterprise publisher partnerships expand catalog beyond self-published content incorporating traditional publishing house backlists and frontlist titles. Partnership programs address publisher concerns around revenue models, content protection, distribution control, and market analytics whilst providing StoriesHut with premium content attracting broader readership and validating platform legitimacy.
Revenue sharing models accommodate publisher preferences: wholesale pricing where StoriesHut purchases books at discount retaining retail margin flexibility, agency pricing where publishers set retail prices and StoriesHut receives commission, or hybrid page-read royalty models mirroring Kindle Unlimited where publishers participate in global fund distribution based on read activity. Flexibility demonstrates willingness to adapt business models attracting risk-averse publishers hesitant about non-traditional digital models.
Enhanced DRM integration through Readium LCP or Adobe Content Server addresses publisher security requirements for premium content. Geographic rights management respects territorial licensing agreements preventing books from appearing in markets where publishers lack distribution rights. Analytics sharing provides publishers with aggregated reader engagement data—completion rates, reading velocity, popular sections—enabling data-driven editorial decisions and marketing optimization whilst protecting individual reader privacy.
The security_events table serves as the immutable audit log for all security-sensitive client actions, providing forensic evidence for investigations, supporting automated fraud detection, and enabling compliance reporting for regulatory requirements. Table design prioritizes append-only immutability preventing tampering whilst optimizing query performance for admin dashboard analytics and real-time alerting systems.
CREATE TABLE security_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id),
username TEXT NOT NULL, -- denormalized for audit
device_id TEXT NOT NULL,
os_type TEXT NOT NULL CHECK (os_type IN ('android', 'ios', 'web')),
book_id UUID NOT NULL REFERENCES books(id),
chapter_id UUID REFERENCES chapters(id),
page_index INTEGER NOT NULL,
event_type TEXT NOT NULL CHECK (event_type IN
('screenshot', 'screen_record', 'drm_violation')),
capture_result TEXT CHECK (capture_result IN
('blocked', 'blank', 'successful')),
timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ip_address INET,
user_agent TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Indexes for query performance
CREATE INDEX idx_security_events_user_id ON security_events(user_id);
CREATE INDEX idx_security_events_timestamp ON security_events(timestamp DESC);
CREATE INDEX idx_security_events_book_id ON security_events(book_id);
CREATE INDEX idx_security_events_event_type ON security_events(event_type);
-- RLS policies (insert-only for application role)
ALTER TABLE security_events ENABLE ROW LEVEL SECURITY;
CREATE POLICY security_events_insert ON security_events
FOR INSERT WITH CHECK (auth.role() = 'service_role');
CREATE POLICY security_events_select ON security_events
FOR SELECT USING (auth.role() IN ('admin', 'super_admin'));
Retention policies mandate minimum 5-year data retention meeting legal discovery requirements and enabling long-term fraud pattern analysis. Archive strategies migrate aged records to cold storage reducing active database size whilst maintaining query access through federated query capabilities when historical analysis requires deep time-range investigation.
Users with 0-2 security events and no other fraud indicators maintain low risk classification receiving no reading restrictions or increased monitoring
Users with 3-4 events or suspicious reading patterns face enhanced monitoring and potential temporary reading restrictions pending investigation
Users with 5-6 events and confirmed fraud indicators receive mandatory admin review before account restoration and permanent monitoring flags
Users with 7+ events or severe violations face permanent suspension with potential legal action for intellectual property theft or ToS violations
Risk scores aggregate security events, fraud detection signals, payment dispute history, community moderation violations, and support ticket sentiment creating holistic user trustworthiness assessments. Scores increment automatically on new violations but decrease slowly over time rewarding sustained compliant behavior—users demonstrating 6 months of clean activity after moderate violations see risk scores gradually reset enabling redemption pathways.
The user_risk_scores table maintains current risk assessment with efficient update patterns supporting real-time admin dashboard queries whilst avoiding expensive full-table scans during security event processing.
Security events generate immediate alerts delivered through multiple channels ensuring admin awareness regardless of current workflow context. Dashboard notifications appear prominently in admin console interfaces with unread counts and priority classifications, email notifications deliver to designated security team distribution lists with event details and direct links to investigation interfaces, whilst SMS notifications escalate critical events to on-call personnel ensuring 24/7 incident response capability.
Alert aggregation prevents notification fatigue—rapid bursts of events from single users trigger consolidated notifications rather than individual alerts for each event, whilst pattern detection surfaces coordinated attacks spanning multiple accounts differently from isolated incidents. Alert prioritization ranks events by severity: first-time violations generate low-priority informational notifications, whilst repeat violations from high-risk users escalate to critical priority demanding immediate response.
Service level agreements define mandatory response timeframes ensuring consistent incident handling: first violations require acknowledgment within 24 hours but no immediate action, second-third violations need review within 12 hours with risk score updates, fourth violations mandate 4-hour response and temporary suspension execution, whilst fifth+ violations demand immediate (<1 hour) senior admin review and permanent action decisions.
Missed SLA tracking identifies resource capacity issues when admin teams cannot meet response requirements consistently, triggering hiring needs or workflow optimization to maintain service quality. SLA reporting provides executive visibility into security operations efficiency whilst automated escalation ensures critical incidents never languish unaddressed when primary responders are unavailable.
Protecting royalty pool integrity requires stringent exclusion rules preventing fraudulent or abusive reading activity from inflating writer earnings at expense of legitimate traffic. Invalidation logic executes during monthly settlement calculations reviewing all page-read events against multiple fraud detection criteria before including reads in royalty distributions.
Reading sessions where screenshot attempts occurred face complete exclusion—all pages read during violation-flagged sessions become non-billable regardless of whether specific violated pages differ from broader session content. This strict policy disincentivizes circumvention attempts by eliminating any earnings potential from violation-containing sessions.
Page reads with less than 3-second durations indicate automated page flipping rather than genuine content consumption. These events exclude from royalty calculations whilst generating fraud signals for account risk scoring. Legitimate readers occasionally advance pages quickly when scanning content, but sustained patterns of rapid page flipping conclusively indicate automation.
All page reads from accounts flagged for fraud and subsequently banned face retroactive exclusion from royalty calculations even if reads occurred before ban enforcement. This retroactive exclusion prevents fraudsters from "banking" earnings through brief legitimate-appearing activity before ban execution, protecting writer earnings from deliberate gaming.
Basic subscription tiers restricting single-device concurrent access invalidate reads when users violate limits through simultaneous multi-device reading. While premium subscribers legitimately read across multiple devices, basic tier violations suggest account sharing abuse requiring royalty exclusion to enforce subscription tier value propositions.
Legal defensibility of security measures requires explicit user consent to monitoring, enforcement actions, and data collection practices. Terms of Service documentation and consent flows must clearly communicate platform security policies, user obligations, and consequence frameworks ensuring users cannot claim ignorance when facing enforcement actions resulting from ToS violations.
First-time login triggers mandatory Terms of Service acceptance requiring affirmative opt-in through checkbox confirmation and "I Agree" button activation—passive acceptance through continued usage provides insufficient legal standing for enforcement defense. Consent screens present key terms in plain language avoiding legalistic jargon that might obscure actual user obligations, particularly around screenshot restrictions, security monitoring, and violation consequences.
Major platform updates modifying security policies or adding new enforcement mechanisms trigger re-consent requirements where users must acknowledge updated terms before regaining platform access. Re-consent prevents situations where users accepted terms years ago but face enforcement under substantially modified policies they never explicitly agreed to. Consent records persist indefinitely recording acceptance timestamps, software versions, and specific terms versions users accepted providing audit trail for legal proceedings.
The following represents legally defensible Terms of Service language addressing security enforcement mechanisms. Legal counsel should review and adapt to specific jurisdictional requirements and risk tolerance preferences.
Section 7: Content Protection and Security Monitoring
7.1 Screenshot and Recording Restrictions: You explicitly agree that all content accessed through StoriesHut applications and services is protected by technical security measures including but not limited to screenshot prevention, screen recording detection, and watermarking technologies. You acknowledge that attempting to capture, record, or circumvent these protection mechanisms violates this Agreement and applicable intellectual property laws.
7.2 Security Event Monitoring: You consent to comprehensive monitoring of your device interactions with StoriesHut applications for security and fraud prevention purposes. This monitoring includes but is not limited to: detection of screenshot attempts regardless of success, screen recording detection, reading pattern analysis, device fingerprinting, and behavioral anomaly detection. All security events generate immutable logs accessible to StoriesHut security personnel and potentially shared with law enforcement or rights holders.
7.3 Blank Screenshot Treatment: You acknowledge that screenshot attempts resulting in blank captured images due to security protection mechanisms constitute violations of this Agreement identical to successful content captures. The attempt itself, rather than success, triggers violation recording and consequence enforcement.
7.4 Consequences and Enforcement: Security violations trigger graduated enforcement responses including but not limited to: risk score increases, reading session invalidation for royalty purposes, temporary account suspension, permanent account termination, legal action for intellectual property theft, and referral to law enforcement. You acknowledge these consequences and agree that suspension or termination for security violations does not entitle you to subscription refunds.
PostgreSQL vertical scaling accommodates early growth phases through incremental compute and memory increases, whilst horizontal scaling via read replicas distributes query load across multiple database instances. Partitioning strategies segregate high-volume tables like security_events and page_reads by time ranges enabling efficient archival and query optimization. Supabase managed infrastructure simplifies scaling operations providing automatic failover and backup systems.
CDN integration caches static assets (book covers, UI resources) at edge locations globally reducing latency and origin server load. Encrypted book content requires origin server processing for signed URL generation and access validation but benefits from regional caching after initial authorization reducing repeated origin requests for popular titles. Adaptive bitrate streaming for future audiobook features requires CDN sophistication supporting chunked delivery and quality switching.
Monolithic backend services transition to microservices architecture as complexity grows: authentication service, content delivery service, royalty calculation service, payment processing service, and analytics service operate independently with defined API contracts. Service isolation enables independent scaling—high read traffic scales content delivery without overprovisioning payment processing capacity. Event-driven architectures using message queues decouple services reducing synchronous dependency chains.
Comprehensive monitoring across application metrics (request latency, error rates, throughput), infrastructure metrics (CPU, memory, disk I/O), and business metrics (active users, reading volume, revenue) enables proactive capacity planning and rapid incident response. Distributed tracing correlates requests across microservices debugging complex failure scenarios spanning multiple system components. Log aggregation centralizes diagnostic information from distributed service fleet enabling efficient troubleshooting.
Cloudflare CDN automatically scales to handle traffic spikes without configuration changes. ALB scales horizontally by adding target instances based on auto-scaling policies. Database read replicas can be added for read-heavy workloads (analytics, reporting).
S3 storage scales infinitely without capacity planning. Glacier archival costs decrease with volume, making long-term retention economically viable. Cross-region replication bandwidth scales with data volume.
Partition audit log tables by month for query performance. Archive older logs to S3 for cost-effective long-term storage. Consider dedicated analytics database (AWS Redshift) if audit log queries impact production performance.
Primary navigation hub displaying platform health metrics: active user count, daily/weekly/monthly signups, revenue trends, content growth (books published), security event frequency, support ticket volume. Alert feed shows critical notifications requiring immediate attention. Quick access buttons link to major functional areas: User Management, Content Moderation, Security Monitoring, Financial Operations.

Searchable user directory with filters (role, status, risk score, registration date). User detail views show: account info, subscription status, payment history, content access history, security events, support interactions. Action buttons enable: temporary suspension, permanent ban, password reset, role modification, manual verification. Links to: Security Events Details, Transaction History, Communication Log.

Prioritized list of books awaiting review with filters (submission date, category, flagged items). Book review interface displays: full manuscript preview, metadata verification form, cover image assessment, category appropriateness check, policy compliance checklist. Actions: approve publication, reject with reason, request revisions, escalate for senior review. Links to: Writer Profile, Related Content, Policy Guidelines.

Real-time security event stream with filtering (event type, severity, user). Aggregated threat analysis shows trending patterns, high-risk users, affected books. Investigation tools enable: user behavior timeline, correlated event analysis, IP address tracking, device fingerprint clustering. Response actions: flag for investigation, initiate suspension, invalidate sessions, escalate to legal. Links to: User Risk Scores, Affected Books, Incident Reports.

Home Screen: Featured books carousel, personalized recommendations, category shortcuts, reading progress widgets, continue reading section. Links to: Category Browser, Search, Library, Profile.
Book Detail Screen: Cover image, title/author, description, rating summary, sample chapter link, purchase/subscribe button, "Add to Library" action, reader reviews section, discussion forum link. Links to: Reading Interface, Author Profile, Similar Books.
Reading Interface: Full-screen book content, top toolbar (back, bookmark, settings), bottom navigation (chapter, page position), tap zones (page forward/back), long-press menu (highlight, note, define, share). Links to: Chapter Navigation, Settings Overlay, Bookmark List.
Library Screen: Downloaded books grid/list, cloud books section, collections folders, sort/filter controls, storage management. Links to: Book Detail, Collections Manager, Download Management.
Dashboard Home: Earnings summary cards, recent activity feed, quick actions (new book, view analytics), notification center, help resources. Links to: Book Manager, Analytics, Earnings Details, Account Settings.
Manuscript Editor: Chapter navigation sidebar, rich text editing canvas, formatting toolbar, autosave indicator, version history access, preview mode. Links to: Chapter Manager, Publishing Workflow, Cover Generator.
Publishing Workflow: Submission status tracker, metadata editor (title, description, categories), cover image uploader, pricing configuration, rights/availability settings, submit/publish buttons. Links to: Dashboard, Book Preview, Cover Generator.
Analytics Dashboard: Key metrics overview, time-series charts (reads, earnings), book comparison tables, geographic distribution maps, reader demographic breakdowns, export data controls. Links to: Detailed Reports, Dashboard Home.
StoriesHut logo with animated loading indicator
Brand colors and tagline
Version number footer
Auto-transitions after 2 seconds

3-4 slides showcasing key features:
Skip button (top right)
Next/Previous indicators (dots)
"Get Started" CTA on final slide

Phone number input field (+91 prefix)
"Continue with Phone" primary button
Divider with "OR"
"Continue with Google" button (Google icon)
"Continue with Apple" button (Apple icon, iOS only)
Terms & Privacy policy links (small text)
"Already have an account? Log In" link

"Enter verification code" heading
"Code sent to +91-XXXXXXXXXX" subtext with Edit link
6-digit OTP input boxes (auto-focus, auto-submit)
Countdown timer "Resend code in 0:45"
"Resend Code" button (enabled after timer)
"Verify" primary button

"Complete Your Profile" heading
Profile photo upload (circular, camera icon, optional)
Full Name input field (required)
Email input field (optional)
Date of Birth picker (optional)
Gender selection (Male/Female/Other/Prefer not to say)
"Finish Setup" primary button
"Skip for Now" text link
There was an error generating this image




























Below are the proposed table schemas for managing friendships and related data.
- friendship_id (UUID, primary key)
- user_id_1 (foreign key to users)
- user_id_2 (foreign key to users)
- status (pending, accepted, declined, blocked)
- requested_by (user_id_1 or user_id_2)
- requested_at (timestamp)
- accepted_at (timestamp, nullable)
- created_at, updated_at- request_id (UUID, primary key)
- sender_id (foreign key to users)
- receiver_id (foreign key to users)
- status (pending, accepted, declined, cancelled)
- message (optional text, nullable)
- created_at, updated_at- suggestion_id (UUID, primary key)
- user_id (foreign key to users)
- suggested_user_id (foreign key to users)
- reason (mutual_friends, similar_interests, location, contacts)
- score (relevance score, float)
- dismissed (boolean)
- created_at- close_friend_id (UUID)
- user_id (foreign key)
- friend_id (foreign key)
- added_at (timestamp)

















Monthly settlement dashboard displays: total pages read platform-wide, global royalty pool amount, per-writer allocation preview, fraud exclusion summary, validation status indicator. Drill-down enables book-level and writer-level detail inspection. Approval workflow requires finance manager sign-off before proceeding to payout preparation. Linked reports show exclusion details and anomaly flags requiring investigation before finalization.
Writer payout list showing: writer name, total amount, payout method, bank details verification status, tax compliance indicators, approval status. Batch actions enable: bulk approval for amounts below threshold, individual review for high-value payouts, payment hold flagging, bank detail update requests. Generates payout files formatted for Razorpay Route batch processing with reconciliation references.
Real-time payment processing status across: subscriber payments (success rate, failure reasons), writer payouts (processing status, settlement times), refund operations. Filter and search capabilities enable rapid transaction lookup by user, amount, date range, status. Failed transaction investigation tools show detailed error messages, retry attempts, manual intervention options.
Automated GST return preparation interface aggregating transaction data, calculating tax liability, generating electronic filing formats. TDS certificate generation queue for writer payouts with bulk processing and individual PDF downloads. Export capabilities for Zoho/QuickBooks integration with configurable chart of accounts mapping. Audit trail documentation for compliance verification.
The StoriesHut platform implementation follows a structured progression from foundational infrastructure through feature development, testing, and production deployment. This phased approach ensures stable foundations before adding complexity, enables parallel workstreams where dependencies allow, and maintains continuous integration throughout development.
StoriesHut's implementation follows a strategic two-phase approach balancing rapid market entry with competitive differentiation. Phase 1 establishes feature parity with Amazon Kindle, delivering a proven, production-ready reading platform. Phase 2 introduces innovative social, community, and collaboration features that differentiate StoriesHut in the Indian market.
Phased approach reduces multiple risk vectors:
Phase 1 features have proven implementations and established best practices
Launch with familiar feature set reduces user learning curve and adoption friction
Smaller initial scope enables faster time-to-market with limited team
Phase 1 validates core reading experience before investing in social features
Phase 2 development begins when Phase 1 achieves:
Phase 1 delivers a complete, production-ready reading and publishing platform replicating Amazon Kindle's proven feature set. This foundation establishes StoriesHut as a credible Kindle alternative for Indian readers and writers.
Complete web-based publishing infrastructure enabling writers to create, publish, and monetize content through the KDP-equivalent Writer Portal.
Core platform infrastructure, security systems, and administrative tools required for production operations.
Infrastructure, quality assurance, and operational readiness requirements for Phase 1 production launch.

GitHub Actions or GitLab CI for automated build and deployment
Automated testing execution on every commit (unit, integration, E2E)
Staging environment mirroring production configuration
Blue-green deployment strategy for zero-downtime releases
Automated rollback on deployment failure detection
Multi-AZ deployment for high availability
Application Load Balancer distributing traffic across EC2/ECS instances
Auto-scaling groups responding to CPU and request metrics
RDS PostgreSQL with automated backups and point-in-time recovery
S3 with versioning and cross-region replication for disaster recovery
CloudFront CDN for static asset delivery (book covers, app assets)
Prometheus + Grafana for metrics visualization
ELK Stack (Elasticsearch, Logstash, Kibana) for log aggregation
AWS CloudWatch for infrastructure monitoring
PagerDuty integration for critical incident alerting
Uptime monitoring with external service (Pingdom, UptimeRobot)
3-2-1 backup strategy (3 copies, 2 media types, 1 off-site)
Database snapshots every 6 hours with 30-day retention
Transaction log archival for point-in-time recovery
Weekly full backups to S3 Glacier for long-term retention
Quarterly disaster recovery drills validating restore procedures
Cloudflare for DDoS protection and WAF (Web Application Firewall)
SSL/TLS certificates with automatic renewal (Let's Encrypt or AWS ACM)
Secrets management using AWS Secrets Manager or HashiCorp Vault
Network segmentation with VPC and security groups
Intrusion detection system (AWS GuardDuty)

Penetration testing by external security firm
Legal review of Terms of Service, Privacy Policy, and EULA
GST registration and tax compliance verification
Payment gateway production approval (Razorpay KYC completion)
App Store and Google Play Store listing approval
Customer support infrastructure (email, chat, knowledge base)

Production database seeded with initial content (minimum 100 books)
Writer onboarding documentation and video tutorials
Reader onboarding flow with sample books for trial
Marketing website with feature descriptions and pricing
Social media presence (Twitter, Instagram, LinkedIn)
Press kit and media outreach materials
Analytics tracking (Google Analytics, Mixpanel, or Amplitude)
Error tracking and crash reporting (Sentry, Bugsnag)
Phase 2 transforms StoriesHut from a Kindle alternative into a unique social reading platform, introducing features that create competitive differentiation and viral growth mechanisms unavailable on traditional e-reading platforms.

User profiles with customizable bio, profile picture, and reading interests
Personal activity feed showing reading progress, book completions, and reviews
Follow/follower system enabling users to track friends' reading activity
Public reading lists and "Currently Reading" shelf visibility
Book reviews and ratings with social sharing
Reading streaks and achievement badges (gamification)
Friend request system with accept/decline workflows
Friend discovery through mutual connections and reading interests
Friends' reading activity feed showing what connections are reading
Private reading lists shareable only with friends
Friend recommendations based on similar reading tastes
One-on-one private messaging between users
Real-time chat with typing indicators and read receipts
Message threads organized by conversation
Book recommendations sent via DM with deep links
Group chat support for small discussion groups (max 10 members)
Message notifications with customizable preferences
Public bookmark collections with favorite passages
Curated reading lists by theme, genre, or mood
Collaborative reading lists (multiple users can contribute)
Bookmark comments and discussions on specific passages
Social sharing of bookmarks to activity feed
Discovery feed showing popular bookmarks and reading lists

Book-specific discussion boards with threaded comments
Upvote/downvote system for comment ranking
Sorting options (hot, new, top, controversial)
Spoiler tags and chapter-specific discussion threads
Moderator tools for community management
Report system for inappropriate content
Chapter-aware comment tagging preventing spoilers
Spoiler blur requiring click-to-reveal
User-configurable spoiler sensitivity (hide all vs. show with warning)
Automatic spoiler detection using NLP algorithms
Chapter progress-based content filtering (hide discussions beyond current chapter)
Advanced community features enabling users to create themed groups, share multimedia content, and build engaged reading communities around shared interests.

User-created groups around genres, books, authors, or reading interests
Group types: Public (open to all), Private (invite-only), Restricted (join approval required)
Group admin and moderator roles with permission hierarchies
Customizable group settings: name, description, cover image (URL-linked), category tags
Member management tools: invite, remove, ban, promote to moderator
Group discovery through search, categories, and recommendations
Chronological group feed with posts, media, and discussions
Post types: text, image links, video embeds, book recommendations
Threaded comments with nested replies (max 3 levels)
Like/react system for posts and comments
Pinned posts for important announcements (max 3 per group)
@mentions notifying tagged members
Real-time typing indicators and online member status
Granular notification preferences per group (All Activity, Mentions Only, Important Only, Muted)
Smart notification batching (multiple notifications within 5 minutes batched into one)
Push notifications, in-app notifications, and optional email digests
Unread post count badges on group icons
"New since last visit" markers on posts

External image URL linking (no uploads to platform)
Supported sources: Google Images, Imgur, Flickr, social media platforms
Backend URL validation and accessibility checking
Cloudflare thumbnail proxy for consistent loading
Inline image rendering with lazy loading
Click-to-expand full-resolution view
Broken link detection with periodic validation jobs
YouTube video URL parsing and validation
YouTube Data API v3 integration for metadata retrieval
In-app video playback using YouTube IFrame Player API
Video thumbnail previews with play button overlay
Metadata display: title, channel, duration, view count
Respects YouTube ToS (no downloads, maintains branding)
Vimeo integration with oEmbed API
Dailymotion support with Player API
Instagram Reels and TikTok embeds (vertical video format)
Twitter/X video embeds with tweet context
Unified video data model supporting multiple platforms
Platform detection and routing based on URL patterns

Automated profanity filtering with customizable word lists
Spam detection and rate limiting (max 10 posts per hour)
New member restrictions (no external links for first 7 days)
Community reporting system (auto-hide posts with 5+ reports)
Admin/moderator tools: delete posts, hide content, lock threads, mute members
URL blacklisting for known malicious domains
Optional NSFW detection using image recognition APIs (Google Cloud Vision, AWS Rekognition)
Backend infrastructure extensions, database schema additions, and API endpoints required to support Phase 2 social and community features.

user_profiles (extended):
- bio (TEXT, max 500 characters)
- reading_interests (TEXT[], array of genre tags)
- profile_visibility (ENUM: public, friends_only, private)
- follower_count, following_count (INTEGER, denormalized)
user_follows:
- follow_id (UUID primary key)
- follower_user_id (UUID foreign key → users)
- following_user_id (UUID foreign key → users)
- created_at (TIMESTAMP)
- UNIQUE constraint on (follower_user_id, following_user_id)
activity_feed:
- activity_id (UUID primary key)
- user_id (UUID foreign key → users)
- activity_type (ENUM: book_started, book_finished, review_posted, bookmark_shared, list_created)
- book_id (UUID foreign key → books, nullable)
- content (JSONB, activity-specific data)
- visibility (ENUM: public, friends_only, private)
- created_at (TIMESTAMP)
friend_requests:
- request_id (UUID primary key)
- sender_user_id (UUID foreign key → users)
- receiver_user_id (UUID foreign key → users)
- status (ENUM: pending, accepted, declined)
- created_at, responded_at (TIMESTAMP)
direct_messages:
- message_id (UUID primary key)
- conversation_id (UUID, groups messages between same users)
- sender_user_id (UUID foreign key → users)
- receiver_user_id (UUID foreign key → users)
- message_text (TEXT, max 2000 characters)
- is_read (BOOLEAN)
- created_at, read_at (TIMESTAMP)
reading_lists:
- list_id (UUID primary key)
- creator_user_id (UUID foreign key → users)
- title (VARCHAR 100)
- description (TEXT, max 500 characters)
- is_public (BOOLEAN)
- is_collaborative (BOOLEAN, allows multiple contributors)
- created_at, updated_at (TIMESTAMP)
reading_list_books:
- list_book_id (UUID primary key)
- list_id (UUID foreign key → reading_lists)
- book_id (UUID foreign key → books)
- added_by_user_id (UUID foreign key → users)
- added_at (TIMESTAMP)
groups, group_members, group_posts, group_post_likes, group_invitations
media_url_cache (for external image/video URL validation and caching)
New mobile app screens and UI components required for Phase 2 social and community features, extending the Phase 1 reader application.

Profile header with cover photo and profile picture
Bio section (editable by profile owner)
Reading interests tags (genre preferences)
Follower/following counts with tap-to-view lists
"Currently Reading" shelf (3-5 books displayed)
Recent activity feed (last 10 activities)
Public reading lists section
Follow/Unfollow button (for other users' profiles)
Message button (opens DM conversation)
Settings icon (profile owner only)
Tab navigation: "Following" | "Discover" | "My Activity"
Following tab: Activity from followed users and friends
Discover tab: Popular activity from all users (trending books, popular reviews)
My Activity tab: User's own reading activity history
Activity cards showing: user avatar, name, activity type, book cover, timestamp
Like and comment buttons on activity posts
Infinite scroll pagination
Friends List Screen: Grid/list view of friends with profile pics and names
Followers Screen: List of users following you
Following Screen: List of users you follow
Search bar for filtering friends/followers
Quick actions: Message, View Profile, Unfollow/Remove Friend
Pending incoming requests with Accept/Decline buttons
Sent requests with "Pending" status indicator
Request timestamp and mutual friends count
Tap on user to view full profile before accepting
Conversation list sorted by most recent message
Each conversation shows: other user's avatar, name, last message preview, timestamp
Unread message count badges
Swipe actions: Archive, Delete, Mute
Search conversations by user name
New message floating action button
Chat interface with message bubbles (sent messages right-aligned, received left-aligned)
Typing indicator when other user is typing
Message timestamps (grouped by day)
Text input field with send button
Book recommendation button (opens book search, sends book link in message)
Long-press message for copy/delete options
Read receipts (checkmarks indicating message read status)
Grid view of user's created reading lists with cover images (first 4 book covers in grid)
List metadata: title, book count, privacy indicator (public/private)
Create New List button
Tap list to view details
List title and description at top
Book grid with covers
Add Books button (opens book search)
Remove book option (long-press on book)
Share list button (generates shareable link)
Collaborative list: Shows contributors' avatars
Edit list settings (owner only)
User's public bookmark collections
Each bookmark shows: book title, passage text, highlight color, timestamp
Filter by book or highlight color
Share bookmark button (posts to activity feed or shares externally)
Comment section for each bookmark (if public)
Trending bookmarks from all users
Filter by genre or book
Like and comment on bookmarks
Follow users who share interesting bookmarks
Quality assurance, deployment strategy, and key performance indicators for Phase 2 social features rollout.
Social Features: Follow/unfollow workflows, activity feed generation, friend request flows
Messaging: Real-time message delivery, typing indicators, read receipts, notification delivery
Groups: Group creation, membership management, post creation, media embedding, moderation tools
Reading Lists: List creation, book addition/removal, collaborative editing, sharing
Media Sharing: URL validation, image/video embedding, broken link handling, platform detection
Social features integration with existing Phase 1 reading experience
Notification system integration across all social features
WebSocket connection stability and reconnection handling
Database performance with increased query complexity (joins across social tables)
API rate limiting and abuse prevention
Activity feed generation performance with 10,000+ followed users
Group feed loading with 1,000+ posts
Real-time messaging latency (target: <500ms message delivery)
Media URL validation and caching performance
Database query optimization for social graph queries
Beta testing with 500-1,000 Phase 1 users
Focus groups testing social features usability
A/B testing notification frequency and content
Feedback collection on group discovery and recommendation algorithms
Monitor: Follow graph growth, activity feed engagement
Monitor: Message volume, response rates, spam reports
Monitor: List creation rate, bookmark shares, discovery engagement
Monitor: Group creation rate, member engagement, moderation needs
Monitor: Media post volume, broken link rates, moderation flags
Full social feature set available to all users
Social Graph Growth: 30%+ of active users follow at least 5 other users within 30 days
Activity Feed Engagement: 50%+ of users check activity feed at least weekly
Messaging Adoption: 20%+ of users send at least one message per week
Group Participation: 40%+ of users join at least one group within 60 days
Content Creation: 15%+ of users create at least one post, bookmark share, or reading list
7-day retention improves from Phase 1 baseline by 10+ percentage points
30-day retention improves by 15+ percentage points
Daily active users (DAU) increases by 25%+
Average session duration increases by 20%+
Invitation rate: 10%+ of users invite at least one friend
Viral coefficient: Each new user brings 0.3+ additional users (through invites/shares)
Social sharing: 5%+ of users share content externally (Twitter, WhatsApp, etc.)
Moderation action rate: <2% of posts require moderation intervention
User report rate: <1% of posts receive user reports
Spam detection accuracy: 95%+ precision and recall
Average group size: 20+ active members per group
API response times: p95 <500ms for social endpoints
WebSocket connection stability: 99%+ uptime
Message delivery latency: p95 <1 second
Database query performance: No queries exceeding 2 seconds
50,000+ active users with social features enabled
5,000+ active groups with regular posting activity
100,000+ messages sent per week
Positive user sentiment (NPS score 40+)
Stable platform performance (no degradation from Phase 1 metrics)
Moderation workload manageable with existing team