Skip to content

Admin VPS console, tips manager, secure health endpoint, and deployment hardening - #81

Merged
gamblecodezcom merged 2 commits into
mainfrom
codex/configure-git-and-update-project-files-gtxxel
Feb 25, 2026
Merged

Admin VPS console, tips manager, secure health endpoint, and deployment hardening#81
gamblecodezcom merged 2 commits into
mainfrom
codex/configure-git-and-update-project-files-gtxxel

Conversation

@gamblecodezcom

@gamblecodezcom gamblecodezcom commented Feb 25, 2026

Copy link
Copy Markdown
Owner

User description

Motivation

  • Improve operational tooling and admin UX by adding a lightweight VPS console, persistent admin menus, and safer admin modes.
  • Harden runtime security and file handling (safe path validation, stricter systemd/unit flags, .env protections) and support HTTPS health checks.
  • Make helpful messages/tips more robust with HTML support, import/export, persistence, and silent scheduled posting to the target group.
  • Improve deployment reliability by enhancing prod-run.sh with health probing, port conflict recovery, service user handling, and log/permission management.

Description

  • Index & runtime: added a permissioned lightweight SSHV admin console (/sshv) with per-admin sessions, editor mode, command execution with safety checks, session persistence to data/sshv-sessions.json, GC of expired sessions, and many helper functions (getSshvSession, executeSshvCommand, persistSshvSessions, etc.).
  • Health & TLS: health server now supports HTTPS when HTTPS_KEY_PATH/HTTPS_CERT_PATH are configured and validates allowed TLS paths via resolveTlsCertPathIfAllowed; requestHealthPayload centralizes health probes used by admin commands.
  • WebApp security: WebApp init-data verification now uses WEBAPP_HMAC_KEY (new env) instead of a constant string and returns false when not configured.
  • File I/O & path safety: introduced validateSafePath and updated loadJson/writeFileAtomic/saveJson to prevent path traversal and ensure writes use atomic temp files under data/.
  • Tips / helpful messages: changed tips to HTML-safe formatting (formatTipForHtml), added persistence to data/helpful_messages.json with import/overwrite support via /tipadd and /tipedit, added scheduler improvements to avoid duplicate sends (lastSentTipId) and permission checks before posting.
  • Admin UX & menus: persistent user/admin menus refined (admin view toggle via /on/off and UI toggle), ephemeral promo prompt that auto-removes, centralized replaceCallbackPanel, callback-audit added to testall, and a global fallback for stale callback_data.
  • Deployment & packaging: removed Dockerfile, added LICENSE and SECURITY.md, updated .env.example with WEBAPP_HMAC_KEY, cleaned up .gitignore entries, and major prod-run.sh enhancements including service user creation, log/data directory ownership/permissions, TLS-aware health checks, port conflict resolution, wait-for-health retries, more secure systemd unit flags, and logrotate updates.
  • Service file & scripts: updated runewager.service defaults to use runewager user and hardened unit options; improved scripts/self-diagnose.sh to produce a structured snapshot report.

Testing

  • Performed a runtime smoke-load with CI guard (CI=true node index.js) to ensure the updated module initializes without throwing; this succeeded.
  • Executed scripts/self-diagnose.sh locally to verify diagnostic output and presence of expected files and services; the script ran and produced a report.
  • Validated prod-run.sh logic in a non-production test environment by ensuring directories/files are created, the systemd unit template is written, and the health probe logic returns (health probe checks and port handling succeeded in the test run).

Codex Task


CodeAnt-AI Description

Improve admin menus, make group tips HTML-safe and testable, and harden production deploys

What Changed

  • Admin menus show a single, descriptive "Admin Mode" toggle; toggling updates the persistent admin menu in-place so admins see current mode immediately.
  • Group tips now preserve HTML markup (or escape plain text), are posted silently as HTML to the target group, and tip test/import actions post the selected tip to the target group (avoiding repeating the last-sent tip).
  • Tips dashboard updates in-place and adds a batch-import action; tests and scheduler avoid sending the same tip twice in a row.
  • Deployment scripts tightened: service runs under a dedicated service user, .env and data files get restricted permissions, systemd unit gains stricter sandboxing and controlled restart limits, and prod-run.sh probes the bot health (with HTTPS support) and auto-recovers from port conflicts.
  • Self-diagnose now captures a consistent read-only snapshot and prints a structured, actionable report (including menu/callback audit results that detect missing or duplicate keyboard callbacks).

Impact

✅ Clearer group tips
✅ Fewer duplicate tip posts
✅ Shorter recovery from port conflicts

💡 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

Release Notes

  • New Features

    • Enhanced production monitoring with automated health checks and recovery mechanisms.
  • Documentation

    • Added MIT License file.
    • Added Security Policy document detailing vulnerability reporting process.
    • Updated deployment documentation to reflect systemd-based deployment (Docker support removed).
  • Improvements

    • Strengthened service security by running under non-root user with hardened permission controls.
    • Improved deployment script with better directory and file permission management.
  • Chores

    • Added WEBAPP_HMAC_KEY environment variable configuration.
    • Reorganized .gitignore for clearer artifact management.

@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 13 minutes and 7 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 8151137 and 21f650f.

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

Walkthrough

Deployment infrastructure overhaul: Docker removed in favor of systemd-only deployment; added WEBAPP_HMAC_KEY environment variable; enhanced deploy.sh and prod-run.sh with directory creation, ownership management, health checks, and port conflict resolution; secured runewager.service with non-root user and hardening directives; refactored diagnostic tool for structured snapshot-based reporting.

Changes

Cohort / File(s) Summary
Environment & Configuration
.env.example, .gitignore
Added WEBAPP_HMAC_KEY environment variable with documentation; consolidated .gitignore patterns for env files, logs, build artifacts (dist/, build/), and data files (data/admin-events.log, data/*.json, backups).
Documentation
LICENSE, SECURITY.md, README.md
Introduced MIT LICENSE (2026 Runewager), SECURITY.md with vulnerability reporting policy and 72-hour acknowledgment commitment; updated README to remove Docker references and describe systemd-based deployment with HTTPS/HTTP health checks.
Deployment Removal
Dockerfile
Completely removed Dockerfile; Docker-based deployment path no longer supported.
Service & Deployment Scripts
deploy.sh, prod-run.sh, runewager.service
deploy.sh now creates data/backups and logs directories, sshv-sessions.json and admin-events.log files with ownership/permission enforcement (0750 for dirs, 0640 for files, 0600 for .env). prod-run.sh adds 8 helper functions (ensure_service_user, read_env_value, resolve_health_url, check_health_endpoint, wait_for_health, is_port_listening, port_listener_pids, free_port_if_conflicted) for user management, health probing with TLS-insecure mode, and dynamic port conflict resolution; integrates preflight health checks with auto-recovery and fallback restart logic. runewager.service changed to non-root user (runewager), added security hardening (ReadWritePaths, ProtectSystem=strict, ProtectHome, PrivateTmp, NoNewPrivileges, UMask=0077).
Diagnostics
scripts/self-diagnose.sh
Refactored from simple counter-based checks to structured snapshot-based diagnostics with per-section rendering; added PID/restart detection, bot state snapshots, unified status formatting, 5-line log capture, and consolidated "SELF-DIAGNOSE REPORT" output; adjusted exit behavior to exit 0 unless failures detected.

Sequence Diagram(s)

sequenceDiagram
    participant startup as Startup Script<br/>(prod-run.sh)
    participant user as Service User<br/>Manager
    participant port as Port Listener<br/>Manager
    participant health as Health Endpoint<br/>Checker
    participant systemd as Systemd<br/>Service
    participant fallback as Fallback<br/>Recovery

    startup->>user: ensure_service_user()
    user-->>startup: User created/confirmed
    
    startup->>startup: Create data/, logs/,<br/>data/backups/ dirs
    startup->>startup: Set permissions<br/>(0750, 0640, 0600)
    
    startup->>port: is_port_listening()
    port-->>startup: Port status
    
    alt Port conflict detected
        startup->>port: free_port_if_conflicted()
        port->>port: Kill conflicting<br/>processes
        port-->>startup: Port freed
    end
    
    startup->>systemd: Start/restart service
    systemd-->>startup: Service started
    
    startup->>health: resolve_health_url()<br/>(TLS-aware)
    health-->>startup: Health URL
    
    startup->>health: wait_for_health()<br/>(with probe/retry)
    
    alt Health check passes
        health-->>startup: ✓ Healthy
        startup-->>startup: Success, exit 0
    else Health check fails
        health-->>startup: ✗ Unhealthy
        startup->>fallback: Attempt recovery
        fallback->>port: free_port_if_conflicted()
        fallback->>systemd: Conditional restart
        fallback->>health: Retry health check
        fallback-->>startup: Recovery attempt logged
        startup-->>startup: Dump logs, may exit non-zero
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Runewager#8: Introduces the runtime/systemd scaffolding foundation that this PR extends with health checks, port conflict resolution, and security hardening.
  • Runewager#71: Modifies .gitignore with identical consolidation of env-file and log patterns.
  • Runewager#33: Overlaps on Dockerfile removal, prod-run.sh enhancements, and WEBAPP_HMAC_KEY environment variable handling.

Suggested labels

size:XL

Poem

🐰 Hops with joy at deployment's song,
Systemd reigns where Docker once belonged,
Health checks bounce like rabbits in spring,
Security hardened—no root-user fling!
Permissions tight, diagnostics pristine, 🔒✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% 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 mentions 'Admin VPS console', 'tips manager', 'secure health endpoint', and 'deployment hardening', which are all present in the changeset. However, the PR includes many other significant changes (SSHV admin console, WebApp HMAC verification, file I/O safety, health server TLS, service hardening, LICENSE/SECURITY files) that are not captured. The title partially represents the main changes but is somewhat incomplete.

✏️ 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-gtxxel

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:XL This PR changes 500-999 lines, ignoring generated files label Feb 25, 2026
@gamblecodezcom
gamblecodezcom merged commit 952db28 into main Feb 25, 2026
1 check passed
@gamblecodezcom
gamblecodezcom deleted the codex/configure-git-and-update-project-files-gtxxel branch February 25, 2026 04:58
@codeant-ai

codeant-ai Bot commented Feb 25, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Secrets exposure
    The diagnostic script sources the repository .env into the shell environment (via set -o allexport && source .env) which exports secrets into the process environment while the script runs. That can expose secrets to other local processes or to logs if later printed; review whether sourcing is required or if selective reading of only needed variables is safer.

  • Kill semantics
    The function that force-kills processes listening on a port (free_port_if_conflicted) returns the numeric killed value via return $killed. In shell, a non-zero return code is treated as failure; callers may misuse this or inadvertently interpret success/failure incorrectly. Also the function kills ANY PID returned by port listeners without additional validation (risk of killing unrelated system processes). Consider changing the return convention and adding stricter checks before killing.

  • TLS & health probes
    Health probing supports HTTPS and an opt-in insecure mode (HEALTH_TLS_INSECURE=1) that disables cert verification using curl -k. This is useful for self-signed certs but is a security risk if accidentally enabled on production. Validate env handling and ensure maintainers are aware when this mode is used. Also resolve_health_url trusts .env paths; ensure these values are validated and protected.

  • File ownership & permissions
    The deploy script now creates data/ and logs/, touches session/log files and then chowns/chmods them. Verify that chown -R and chmod operations run under expected privileges and that the logic correctly handles the case when the runewager user doesn't exist or when the script runs under different uid/gid (fallbacks exist but should be audited). Creating files with 0640/0600 is good but ensure other processes (logrotate, backup scripts) still have needed access.

  • Copyright accuracy
    Verify the copyright year and legal entity ("Runewager") are correct and cover the intended range (single year vs. year range). Incorrect or imprecise attribution can complicate license compliance.

@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:XL This PR changes 500-999 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant