Skip to content

Add SSHV (VPS console), tips persistence & scheduler improvements, HTTPS health server, admin-mode UX and deployment updates - #75

Merged
gamblecodezcom merged 3 commits into
mainfrom
codex/configure-git-and-update-project-files-7yx6nr
Feb 25, 2026
Merged

Add SSHV (VPS console), tips persistence & scheduler improvements, HTTPS health server, admin-mode UX and deployment updates#75
gamblecodezcom merged 3 commits into
mainfrom
codex/configure-git-and-update-project-files-7yx6nr

Conversation

@gamblecodezcom

@gamblecodezcom gamblecodezcom commented Feb 25, 2026

Copy link
Copy Markdown
Owner

User description

Motivation

  • Provide safer file/path handling, persistent admin tools, and an interactive lightweight VPS console for admins to run quick commands from Telegram.
  • Harden runtime and deployment: support HTTPS health endpoint, make prod-run/service installation idempotent, and include license/security docs.
  • Improve tips/helpful messages management with import/export, persistence, and smarter scheduling to avoid repeat posts.

Description

  • Added files: LICENSE (MIT) and SECURITY.md; removed Dockerfile and updated README.md to reflect systemd deployment.
  • .env and .env.example: added WEBAPP_HMAC_KEY guidance; .gitignore updated to include *.env, data and logs layout changes.
  • Major index.js changes: replaced internal http usage with HTTPS-aware health checks, added TLS cert path validation, implemented validateSafePath for safe data I/O, and switched WebApp init-data verification to use WEBAPP_HMAC_KEY instead of a constant.
  • New admin VPS console feature (/sshv): session store, editor mode, command execution with safety checks (blocked patterns, dangerous command confirmation), session persistence to data/sshv-sessions.json, lifecycle/GC, buttons and callbacks for run/lock/refresh/exit, and UI rendering in chat.
  • Admin UX & mode changes: introduced explicit admin view toggles (persisted per-admin) that show/hide admin UI rather than global auth bypass, consolidated admin menus, persistent user/admin menus, ephemeral promo prompt for onboarding, and many callback/command renames/adjustments to align with admin view behavior.
  • Tips/helpful messages: tipsStore persistence to data/helpful_messages.json, import/overwrite via JSON payloads in /tipadd and /tipedit, prevented consecutive duplicate posts using lastSentTipId, permission check before posting, and save/load helpers (saveHelpfulMessages/loadHelpfulMessages).
  • Health server now supports HTTPS when HTTPS_KEY_PATH/HTTPS_CERT_PATH are provided and valid; startHealthServer will fall back to HTTP and exposes /health and /metrics on loopback only.
  • Persistence & safety: loadJson, writeFileAtomic, and related persistence now leverage safe path validation; admin events are appended to data/admin-events.log.
  • Deployment (prod-run.sh) and runewager.service updates: ensure runtime directories/files exist (data/*, admin-events, sshv sessions), health URL resolver and checks (HTTP/HTTPS), improved logrotate config includes admin events file, creation of systemd service with secure user/group and tightened service sandbox options, health wait-and-report logic, and enhanced final status output.

Testing

  • Executed CI-mode module load using CI=true to ensure the bot runtime file loads safely without starting services; this succeeded (no runtime throw).
  • Ran prod-run.sh in a non-production/dry environment to validate directory creation, env handling and health URL resolution; automated health probe logic (HTTP/HTTPS) was exercised and returned expected status in the test environment.
  • No unit tests were added; all runtime behavior changes were validated via the above automated smoke/load checks.

Codex Task


CodeAnt-AI Description

Add admin VPS console, persistent helpful messages, HTTPS health server, and refined admin UI

What Changed

  • Admins can open a lightweight VPS console (/sshv) in DM: run shell commands, edit files in an editor mode, lock/refresh/exit sessions, confirm dangerous commands, and have sessions persisted across restarts.
  • Helpful messages (tips) are persisted to disk, can be imported/overwritten via JSON in /tipadd and /tipedit, and the scheduler avoids posting the same tip twice in a row and checks bot permissions before posting.
  • Local health server now uses HTTPS when TLS cert/key are configured and falls back to HTTP otherwise; health checks from the prod-run wrapper respect that and wait for a healthy response.
  • Admin UI is now a visibility toggle ("admin view") that shows/hides admin controls without changing identity permissions; persistent admin/user menus are managed to avoid duplicate lingering messages and a short-lived promo prompt auto-deletes after 15s.
  • File and path operations guard against path traversal and restrict reads/writes to allowed data directories; deploy/prod-run scripts ensure runtime data files exist and report health/port status more accurately.

Impact

✅ Shorter admin debugging time
✅ Fewer duplicate tips
✅ More accurate health checks

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • New Features

    • Added SSHV console subsystem for admin operations
    • Admin view toggle functionality with persistent state
    • Configurable helpful messages/tips system
    • HTTPS support for health endpoints with TLS configuration
  • Improvements

    • Enhanced path validation for file operations
    • Systemd is now the only supported production deployment method
  • Documentation

    • Added MIT License and security policy documentation

@codeant-ai

codeant-ai Bot commented Feb 25, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.


Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@coderabbitai

coderabbitai Bot commented Feb 25, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@gamblecodezcom has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between adc4ed8 and 3204285.

📒 Files selected for processing (2)
  • index.js
  • prod-run.sh
📝 Walkthrough

Walkthrough

This pull request introduces infrastructure modernization and security hardening: removing Docker support, adding TLS-based health checks, implementing a new SSHV console subsystem for admin operations, enhancing admin UI with view toggles, consolidating git ignore patterns, hardening systemd service configuration with sandboxing, and establishing security policies alongside MIT licensing.

Changes

Cohort / File(s) Summary
Configuration & Environment
.env.example, .gitignore
Added WEBAPP_HMAC_KEY environment variable; consolidated wildcard patterns for environment files, logs, and build artifacts; broadened data ignores with per-directory targeting.
Deployment Infrastructure
Dockerfile, deploy.sh, prod-run.sh, runewager.service
Removed Dockerfile; added directory/file initialization in deploy.sh; extended prod-run.sh with health utilities, TLS-aware URL resolution, and diagnostics; hardened systemd service with non-root user execution and security sandboxing (ProtectSystem, ProtectHome, PrivateTmp, NoNewPrivileges).
Documentation & Licensing
README.md, SECURITY.md, LICENSE
Updated README to document systemd-only deployment (replacing Docker instructions); added SECURITY.md with vulnerability reporting policy and timelines; added MIT LICENSE file.
Core Application Logic
index.js
Introduced HTTPS/TLS support for health endpoints with fallback to HTTP; implemented SSHV console subsystem with session persistence, command execution, and editor mode; added admin view toggles (adminModeOn/Off) affecting menu visibility; introduced persistent helpful messages (tips) with disk I/O; added validateSafePath for path traversal protection; enhanced health checks with TLS awareness; expanded admin UX and menu controls; added global callback fallback handler.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Telegram Client
    participant Server as index.js
    participant SessionStore as SSHV Session Store
    participant ChildProcess as child_process
    participant Disk as File System

    Client->>Server: Open SSHV console (open_sshv)
    Server->>SessionStore: Create new session with TTL
    SessionStore->>Disk: Persist session to sshv-sessions.json
    Client->>Server: Send command (run_sshv_cmd)
    Server->>SessionStore: Load session, validate TTL
    alt Command is 'cd'
        Server->>SessionStore: Update session cwd
    else Command is editor mode
        Server->>Client: Render editor keyboard
        Client->>Server: Editor input (edit_save/edit_cancel)
        Server->>Disk: Write/discard changes
    else Regular command
        Server->>ChildProcess: Execute via spawn
        ChildProcess->>ChildProcess: Run with cwd
        ChildProcess-->>Server: Return stdout/stderr
    end
    Server->>SessionStore: Update session state
    SessionStore->>Disk: Persist session to sshv-sessions.json
    Server->>Client: Render console output
    Client->>Server: Exit console (exit_sshv)
    Server->>SessionStore: Destroy session
    SessionStore->>Disk: Remove session data
Loading
sequenceDiagram
    participant HealthCheck as Health Check Process
    participant ConfigReader as Config Reader
    participant TLS as TLS System
    participant Server as HTTP/HTTPS Server
    participant Endpoint as /health Endpoint

    HealthCheck->>ConfigReader: Read PORT, HTTPS_KEY_PATH, HTTPS_CERT_PATH
    ConfigReader-->>HealthCheck: Environment values
    HealthCheck->>TLS: Check if TLS certs/key available
    alt TLS certs valid
        TLS-->>HealthCheck: Use HTTPS
        HealthCheck->>Server: Connect to https://localhost:PORT/health
    else TLS certs invalid/missing
        TLS-->>HealthCheck: Fall back to HTTP
        HealthCheck->>Server: Connect to http://localhost:PORT/health
    end
    Server->>Endpoint: Route request
    Endpoint-->>Server: Return health status
    Server-->>HealthCheck: Health response
    HealthCheck->>HealthCheck: Determine overall health
Loading

Estimated Code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

size:XXL

Poem

🐰 A hop through the changes, so grand and so neat,
No Docker, just systemd—the deployment's complete!
SSHV consoles spawning, with sessions that stay,
TLS guards the health checks—secure every way,
Admin views toggle, and paths are made safe,
Our burrow's now fortified, locked up with grace! 🔐

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.19% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main additions: SSHV console, tips persistence, HTTPS health server, admin-mode UX, and deployment updates. It directly reflects the scope of changes across multiple files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/configure-git-and-update-project-files-7yx6nr

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codeant-ai codeant-ai Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files label Feb 25, 2026
@codeant-ai

codeant-ai Bot commented Feb 25, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • File ownership
    The deploy step creates data/logs and touches session/log files but does not set ownership or restrictive permissions. If the deploy is run as root or another user, created files may be owned by that user and be world-readable, causing permission mismatches with the service user or leaking sensitive admin/session data.

  • SPDX Identifier
    The LICENSE file does not include an SPDX short identifier. Adding an SPDX identifier enables automated license scanners and tooling to unambiguously detect the license.

  • File access restrictions
    New hardening flags (ReadWritePaths, ProtectSystem, ProtectHome, PrivateTmp, NoNewPrivileges) restrict filesystem access. Verify the app does not need additional write/read access outside the explicitly allowed paths (including any runtime temp, sockets, or PID/state paths). Ensure Node binary and any required runtime resources remain accessible under these sandboxing settings.

  • Service User
    The service now runs as runewager (non-root). Confirm that the runewager user/group exist on target systems and that ownership/permissions for WorkingDirectory, log and data directories allow this user to read/write. Also validate the deployment script creates/chowns these directories before service start to avoid permission failures.

  • Logging path ownership
    StandardOutput/StandardError append to files under the repository. Running as runewager requires those files and parent dirs exist and be writable by that user. If these files are not created before start, the service may fail to write logs; consider journald or ensure deploy creates and chowns log files.

@gamblecodezcom
gamblecodezcom merged commit d69da45 into main Feb 25, 2026
1 check passed
@gamblecodezcom
gamblecodezcom deleted the codex/configure-git-and-update-project-files-7yx6nr branch February 25, 2026 03:57
Comment thread prod-run.sh
mkdir -p "$PROJECT_DIR/data"
mkdir -p "$PROJECT_DIR/data/backups"
touch "$MAIN_LOG" "$ERROR_LOG" "$ADMIN_EVENTS_LOG" "$SSHV_SESSIONS_FILE" # create if missing; safe on existing files

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The data directory and JSON/log files are created as root-owned by this script, but the systemd unit is configured to run the Node process as an unprivileged user; this will cause permission denied errors when the app tries to write admin events and SSHV session state. Ensuring the data directory is owned by the service user when it exists fixes this mismatch. [logic error]

Severity Level: Major ⚠️
- ❌ SSHV sessions cannot persist to data/sshv-sessions.json.
- ❌ Admin events log file not writable; audit trail lost.
- ⚠️ Data directory permissions may block other JSON persist helpers.
Suggested change
# Ensure data directory and its files are writable by the service user when it exists
if id -u "$APP_NAME" >/dev/null 2>&1; then
chown -R "$APP_NAME":"$APP_NAME" "$PROJECT_DIR/data"
fi
Steps of Reproduction ✅
1. Create a dedicated system user for the service so `id -u runewager` succeeds; this
causes `ensure_systemd_service()` in `prod-run.sh` (lines 187–201) to generate a unit with
`User=runewager`/`Group=runewager`.

2. As root, run `/workspace/Runewager/prod-run.sh`. It creates `$PROJECT_DIR/data` and
`$PROJECT_DIR/data/backups`, then touches `$PROJECT_DIR/data/admin-events.log` and
`$PROJECT_DIR/data/sshv-sessions.json` as root at `prod-run.sh:113–116`, leaving the
directory and files owned by root with default 0755/0644-style permissions.

3. The same script restarts the service via systemd at `prod-run.sh:385–412`, so
`index.js` now runs as the unprivileged `runewager` user while the `data/` directory and
its files remain root-owned and not writable by `runewager`.

4. Trigger an admin feature that persists state: (a) use the `/sshv` admin console so its
session code calls `saveJson(sshvSessionsFile, entries)` at `index.js:969` with
`sshvSessionsFile` defined at `index.js:206`, which goes through `writeFileAtomic()` at
`index.js:2264–10`, or (b) execute any admin action that calls `adminLog()` at
`index.js:2141–24` to append to `admin-events.log`. In both cases the Node process,
running as `runewager`, attempts to write under `$PROJECT_DIR/data` but lacks write
permission due to root ownership, causing `fs.writeFileSync`/`fs.appendFileSync` to
receive EACCES and preventing SSHV session and admin event data from being persisted.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** prod-run.sh
**Line:** 117:117
**Comment:**
	*Logic Error: The data directory and JSON/log files are created as root-owned by this script, but the systemd unit is configured to run the Node process as an unprivileged user; this will cause permission denied errors when the app tries to write admin events and SSHV session state. Ensuring the data directory is owned by the service user when it exists fixes this mismatch.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
👍 | 👎

@codeant-ai

codeant-ai Bot commented Feb 25, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex size:XXL This PR changes 1000+ lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant