diff --git a/README.md b/README.md index dbe1224..db1836e 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,158 @@ # CyberChat -CyberChat is a framework-free PHP, SQLite, JavaScript, and HTML5 chat application with configurable paid tiers, Stripe subscriptions, Mailgun email verification, voice messages, personal archives, an administrator dashboard, and an optional MySQL/MariaDB mirror. +CyberChat is a framework-free PHP, SQLite, JavaScript, and HTML5 chat application. It includes text and voice messaging, configurable service tiers, Stripe subscriptions, Mailgun email verification, private archives, resilient queued polling, an administrator dashboard, and optional FFmpeg and MySQL/MariaDB integrations. -## Included Features +## Current Capabilities -- Registration without an email address -- Verified email required before premium checkout -- Mailgun email verification and email two-factor login codes -- Stripe Checkout, Billing Portal, webhook synchronization, and cancellation -- Configurable plans, prices, Stripe Price IDs, limits, and feature assignments -- Subscription display switch that hides new sales while preserving billing management for existing customers -- Premium-configurable recording presence for both sending and viewing -- Premium-configurable automatic voice sending -- Tier-configurable automatic playback of newly received voice clips -- Optional FFmpeg voice transcoding to iPhone-compatible AAC/M4A or H.264/AAC MP4 -- Administrator tier overrides that grant plan features without payment -- Single-worker queued polling with cursor catch-up, request timeouts, deduplication, bounded retry backoff, and a capped browser message buffer -- Plan-based custom username colors -- Personal text archives retained for at least 30 days -- Plan-based voice archive access and JSON/CSV exports -- Visitor and feature usage statistics -- SQLite by default, with optional automatic MySQL/MariaDB mirroring -- Dark neon interface with a saved light-mode toggle +### Chat and Interface + +- Authenticated public chat with text and voice messages +- Chronological message reconciliation with the newest message at the bottom +- Single-worker cursor polling with catch-up batches, deduplication, request timeouts, retry backoff, and immediate wake-up after sending +- Poll recovery when the browser returns online or the tab becomes visible +- Configurable poll interval, timeout, maximum retry delay, batch size, and browser message limit +- Online-user count and connection-status indicator +- Configurable message and username length limits +- Automatic link detection for HTTP and HTTPS URLs +- Dark cyberpunk interface with neon green, blue, purple, pink, red, and orange accents +- Saved light-mode toggle +- Configurable application title, subtitle, and username color palette +- Embeddable frontend through `CyberChat.init()` + +### Voice and Audio + +- Browser microphone recording with a configurable duration and upload-size limit +- WebM/Opus recording by default on supported browsers +- MP4/AAC and AAC recording fallback for Safari and iPhone +- Upload validation for WebM, WAV, MP4/M4A, and AAC +- Recording preview with explicit send and discard controls +- Configurable automatic voice sending by tier +- Configurable recording-status indication by tier; entitled users can both send and see the `is recording...` status +- Configurable sequential playback of newly received voice clips by tier +- Saved per-browser automatic-play preference +- Automatic-play queue recovery and a user notice when browser autoplay policy blocks playback +- Custom cyberpunk audio player for chat and archives +- Audio play/pause, seek bar, elapsed and total time, mute control, playback animation, and single-active-player behavior +- MIME-aware `` elements and inline mobile playback +- Voice duration, MIME type, source filename, and storage path tracking +- Administrator playback, filtering, manual archiving, deletion, file-size display, and missing-file indication +- Optional FFmpeg transcoding with a configurable executable, bitrate, timeout, output profile, and source fallback +- Recommended AAC-LC audio in an M4A container for iPhone, Safari, Android, and desktop playback +- Optional MP4 profile with a small H.264 baseline video track and AAC-LC audio +- Original browser recording retained when transcoding is disabled +- Existing voice files remain unchanged when transcoding settings are enabled or modified + +### Accounts and Security + +- Registration with username and password; email is not required +- Case-insensitive unique usernames using letters, numbers, underscores, and hyphens +- Bcrypt password hashing with a configurable cost +- Optional IP conflict restriction when an account already has an active session +- Configurable session lifetime with HTTP-only, strict SameSite cookies and the secure flag under HTTPS +- Email verification by six-digit code or verification link +- Verified email required only before premium checkout +- Unique verified email addresses +- Mailgun-based email delivery through a reusable cURL mailer +- Tier-configurable email two-factor authentication +- Six-digit login challenges with expiration and attempt limits +- Account view for email verification, 2FA, plan details, billing, and current feature entitlements +- Tier-configurable custom username colors +- Administrator user creation, username/color/password editing, session termination, and deletion +- CSRF protection on administrator actions + +### Plans and Subscriptions + +- Fully configurable plans, prices, currencies, billing intervals, descriptions, ordering, and active status +- Dashboard creation of additional tiers +- Per-tier feature toggles and archive retention +- Current configurable entitlements: + - Voice messages + - Recording-status sending and viewing + - Automatic voice send + - Automatic voice play + - Custom username color + - Text archive retention + - Text export + - Voice archive access + - Voice export + - Email 2FA +- Stripe Price ID assignment per paid tier +- Stripe Checkout with promotion-code support +- Stripe Billing Portal for payment details and plan management +- Subscription cancellation at the end of the billing period +- Signed webhook verification and duplicate event protection +- Stripe customer, subscription, status, plan, billing-period end, and cancellation-state synchronization +- Paid statuses include active, trialing, and past due +- Global subscription visibility switch +- New plans and checkout are hidden when subscriptions are disabled +- Existing Stripe customers retain billing-management and cancellation access while new subscriptions are hidden +- Administrator tier overrides that grant features without payment and take precedence over Stripe +- Subscriber table showing email verification, effective plan, status, period end, cancellation state, and Stripe customer ID + +### Archives and Exports + +- Automatic prior-day SQLite archival during chat activity +- Configurable archive path using year, month, and day placeholders +- Authenticated personal archive; users can access only their own messages +- Minimum text retention of 30 days, configurable upward by tier +- Search across live and archived personal messages +- Voice history included only when the tier has voice archive access +- JSON and CSV exports when the tier has text export access +- Voice URLs included in exports only when the tier has voice export access +- Administrator archive-day browser with user and message filters +- Administrator editing and deletion of archived messages +- Manual movement of live voice clips into the appropriate daily archive +- Whole-day archive deletion with associated voice-file cleanup +- Legacy public archive browser redirects to the authenticated personal archive + +### Administrator Dashboard + +- Password-protected dashboard with configurable administrator password +- Overview totals for users, live messages, voice clips, daily messages, sessions, and active users +- Recent-message and recent-user panels +- Searchable live-message management by user, text, day, and message type +- Edit displayed sender and message text +- Individual, bulk, day-level, and full live-message deletion +- Dedicated voice library covering live and archived clips +- Voice filters by user, date, and source +- Voice playback, format, duration, file-size, archive, deletion, and missing-file status +- Archive list with message totals and database file sizes +- User creation and account editing +- Manual tier assignment without Stripe payment +- User kicking and deletion +- Active and expired session inspection +- Individual, expired, and all-session termination +- Plans, pricing, Stripe, Mailgun, FFmpeg, subscription visibility, and MySQL configuration +- Subscriber tracking and 30-day event totals +- Live `config.json` editor with JSON validation and formatting +- Manual MySQL mirror action + +### Storage, Statistics, and Integration + +- SQLite is the required primary database +- Automatic schema creation and additive migrations +- SQLite WAL mode and foreign-key enforcement +- Dynamic/searchable records stored in SQLite +- Runtime/service settings stored in dashboard-editable JSON +- Optional MySQL/MariaDB mirror of the main and archive SQLite databases +- Configurable automatic mirror interval and manual mirror execution +- Visitor and feature event tracking with salted IP hashes and truncated user agents +- Statistics can be disabled globally +- Apache and Nginx examples include protected internal paths and audio MIME mappings +- Diagnostic endpoint for PHP, SQLite, JSON configuration, storage permissions, and session support + +Groups and group navigation have been removed from the application and plan system. ## Requirements - PHP 8.1 or newer - PHP extensions: `pdo_sqlite`, `curl`, and `fileinfo` +- PHP functions `proc_open` and `proc_terminate` when FFmpeg transcoding is enabled - A web server with HTTPS for production - Write access to `db/`, `archive/`, `uploads/voice/`, and `config.json` - A modern browser with `MediaRecorder` for voice recording -- Optional: FFmpeg with AAC support; `libx264` is also required for the H.264 profile +- Optional: FFmpeg with AAC support +- Optional: FFmpeg compiled with `libx264` for the H.264 profile - Optional: PDO MySQL for the MySQL/MariaDB mirror ## Installation @@ -38,13 +160,14 @@ CyberChat is a framework-free PHP, SQLite, JavaScript, and HTML5 chat applicatio 1. Place the application in the web root. 2. Make the runtime directories and configuration writable by the web-server user. 3. Configure Apache with the included `.htaccess`, or adapt `nginx-example.conf`. -4. Open `admin.php` and sign in with the initial password `changeme123`. -5. Immediately change `admin.password` in the Configuration tab. -6. Open **Plans & Platform** to configure tiers, Mailgun, Stripe, optional voice transcoding, and MySQL mirroring. +4. Visit `api/ping.php` and resolve any failed permission or PHP checks. +5. Open `admin.php` and sign in with the initial password `changeme123`. +6. Immediately change `admin.password` in the Configuration tab. +7. Open **Plans & Platform** to configure tiers, Mailgun, Stripe, optional voice transcoding, and MySQL mirroring. The SQLite schema and default Free, Plus, and Pro tiers are created automatically on first use. -For a simple shared-hosting deployment: +For simple shared hosting: ```bash chmod 0777 db archive uploads/voice @@ -57,24 +180,66 @@ chown -R www-data:www-data db archive uploads/voice chmod -R 0770 db archive uploads/voice ``` -Replace `www-data` with the PHP-FPM or web-server account. SQLite must be able to create the database plus `-wal` and `-shm` sidecar files. When the application directory itself is restricted, `database.main_db` may be an absolute path to a writable persistent directory. +Replace `www-data` with the PHP-FPM or web-server account. SQLite must be able to create the database plus its `-wal` and `-shm` sidecar files. When the application directory is restricted, `database.main_db` may use an absolute path to a writable persistent directory. ## Default Tiers -The defaults are starting points and are fully editable in the dashboard. +The defaults are starting points. Plans, prices, and every listed entitlement can be changed in the dashboard. | Feature | Free | Plus | Pro | |---|---:|---:|---:| +| Voice messages | Yes | Yes | Yes | | Recording status send/view | No | Yes | Yes | | Automatic voice send | No | Yes | Yes | | Automatic voice play | No | Yes | Yes | | Custom username color | No | Yes | Yes | | Text archive | 30 days | 90 days | 365 days | | Text export | Yes | Yes | Yes | -| Voice archive/export | No | Yes | Yes | +| Voice archive | No | Yes | Yes | +| Voice export | No | Yes | Yes | | Email 2FA | No | Yes | Yes | -Administrators can assign a tier directly from **Admin > Users > Edit > Tier Override**. The override grants that tier's features without changing Stripe billing data and remains in effect until it is changed back to **Follow Stripe / billing status**. +Administrators can assign a tier directly from **Admin > Users > Edit > Tier Override**. The override does not alter Stripe billing and remains effective until changed back to **Follow Stripe / billing status**. + +## Audio Configuration + +Global audio settings are under **Admin > Config** and **Admin > Plans & Platform > Voice Transcoding / FFmpeg**. + +Important settings: + +| Setting | Purpose | +|---|---| +| `voice.enabled` | Globally show or hide voice recording controls | +| `voice.max_duration_seconds` | Maximum accepted recording duration | +| `voice.max_upload_bytes` | Maximum uploaded voice-file size | +| `voice.auto_play_default` | Initial automatic-play preference for entitled users | +| `voice.upload_dir` | Voice-file storage path | +| `voice.transcoding.enabled` | Enable server-side FFmpeg conversion | +| `voice.transcoding.ffmpeg_path` | FFmpeg executable name or absolute path | +| `voice.transcoding.profile` | `m4a_aac` or `mp4_h264_aac` | +| `voice.transcoding.audio_bitrate_kbps` | AAC bitrate from 48 to 320 kbps | +| `voice.transcoding.timeout_seconds` | Conversion timeout from 5 to 300 seconds | +| `voice.transcoding.fallback_to_source` | Keep the source file if conversion fails | + +Recording selection is browser-driven: + +1. WebM with Opus +2. WebM +3. MP4 with AAC-LC +4. MP4 +5. AAC +6. Browser default MediaRecorder format + +When FFmpeg is disabled, the accepted browser recording is stored unchanged. WebM remains the preferred default when the browser supports it. Safari and iPhone can upload MP4/AAC directly. + +When FFmpeg is enabled: + +- `m4a_aac` produces audio-only AAC-LC in an M4A container and is the recommended compatibility profile. +- `mp4_h264_aac` adds a 16-by-16 black H.264 baseline video track with AAC-LC audio for systems requiring conventional MP4. +- New uploads are converted; existing files are not rewritten. +- The original file can be retained automatically if FFmpeg fails. + +The web server must serve `.webm`, `.wav`, `.aac`, `.m4a`, and `.mp4` with the MIME mappings shown in `.htaccess` and `nginx-example.conf`. ## Mailgun @@ -84,22 +249,28 @@ Configure these fields under **Admin > Plans & Platform**: - Sending domain - From address - API base, normally `https://api.mailgun.net/v3` -- EU API base, when applicable: `https://api.eu.mailgun.net/v3` +- EU API base when applicable: `https://api.eu.mailgun.net/v3` -The reusable mailer is in `lib/mailer.php`. It sends verification links and codes, limits verification attempts, and sends 2FA codes with a direct link to the authentication screen. +The reusable mailer in `lib/mailer.php` sends: + +- Email verification codes and links that expire after 30 minutes +- Login 2FA codes and authentication links that expire after 10 minutes + +Verification and login challenges are attempt-limited. When a verified account already has a Stripe customer, changing the verified email also updates that Stripe customer. Mailgun API reference: ## Stripe -1. Create recurring Stripe Prices for the paid tiers. +1. Create recurring Stripe Prices for paid tiers. 2. Enter each `price_...` ID in the matching dashboard plan. 3. Enter the Stripe secret key and webhook signing secret. -4. Add this webhook endpoint: +4. Optionally set success, cancel, and Billing Portal return URLs. +5. Add this webhook endpoint: `https://YOUR-DOMAIN/YOUR-PATH/api/stripe-webhook.php` -5. Subscribe the endpoint to: +6. Subscribe the endpoint to: - `checkout.session.completed` - `customer.subscription.created` @@ -110,47 +281,113 @@ Mailgun API reference: