Skip to content

Claude/update prod runner script lq2g s - #55

Merged
gamblecodezcom merged 3 commits into
mainfrom
claude/update-prod-runner-script-Lq2gS
Feb 21, 2026
Merged

Claude/update prod runner script lq2g s#55
gamblecodezcom merged 3 commits into
mainfrom
claude/update-prod-runner-script-Lq2gS

Conversation

@gamblecodezcom

@gamblecodezcom gamblecodezcom commented Feb 21, 2026

Copy link
Copy Markdown
Owner

CodeAnt-AI Description

Improve deployment safety, health binding, and Telegram notification robustness

What Changed

  • Telegram notifications now use python3 JSON encoding and skip sending if python3 is absent to avoid malformed multi-line messages.
  • Health/metrics server now binds to localhost only, preventing external access to internal health endpoints.
  • Rollback now re-reads the restored release .env to recompute the service port and health probe URL before performing the post-rollback health check.
  • Smoke test better detects and reports whether logs/ is writable, and is run after installing npm dependencies on the server during deploy.
  • CI/deploy workflows run with minimal read-only repository permissions; deploy no longer accepts workflow_dispatch inputs and security audit step never blocks the deploy.
  • Admin-facing messages and exports for bonuses and giveaways consistently show readable Telegram usernames and clearer participant/wager displays.

Impact

✅ Fewer malformed Telegram notifications
✅ Correct health probes after rollback
✅ Safer internal metrics exposure

💡 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

  • Bug Fixes

    • Improved deployment reliability with enhanced error handling and validation
  • Chores

    • Strengthened CI/CD security with minimal read-only permissions
    • Enhanced infrastructure script robustness with environment checks and write-access validation
    • Optimized state handling and UI text consistency

**Infrastructure (GitHub Actions)**
- Add explicit `permissions: contents: read` to ci.yml and deploy.yml
- Remove workflow_dispatch inputs from deploy.yml (SLSA build-output integrity)
- Make npm audit always non-blocking (continue-on-error: true)
- Fix smoke test ordering: run AFTER npm ci so node_modules exist

**SAST**
- Bind health server to 127.0.0.1 instead of 0.0.0.0 (CWE-319)

**Antipatterns (index.js)**
- Use object/array destructuring (lines 447, 3034)
- Replace implicit boolean coercion !! with Boolean() (lines 2454, 3617)
- Replace ++ / -- with += 1 / -= 1 (lines 4091, 4584, 4656, 4768)
- Use const instead of let for non-reassigned report (line 4678)
- Add no-op comment in empty catch block (line 1736)
- Remove redundant trailing return statement (line 3912)
- Extract nested template literals to named variables (32 occurrences)
- Move user.pendingAction = null inside runUserMutation to fix race (line 3695)
- Inline gw.endTimer assignment with eslint-disable for lint false positive (4806)
- Add eslint-disable-next-line for intentional await-in-loop (line 1260)

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
notify-telegram.sh: require python3 before sending; removes the sed
fallback that produced invalid JSON for multi-line messages (newlines,
backslashes not escaped). Exits gracefully when python3 is absent.

rollback.sh: recompute PORT and HEALTH_URL from the restored release's
.env immediately after cp-a, so the post-rollback health check probes
the correct port even when the target release uses a different PORT.

smoke-test.sh: make the logs/ else-branch verify actual writability with
touch (mirrors the data/ check). Prevents a read-only filesystem from
silently passing the logs directory check.

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
@codeant-ai

codeant-ai Bot commented Feb 21, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Feb 21, 2026

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

The changes enhance CI/CD security and robustness across multiple components: adding read-only permissions to CI, restructuring the deploy workflow with hardcoded deployment mode and reorganized VPS steps, refactoring core application logic with standardized variable formatting and state migration, requiring Python 3 validation in notification scripts, improving rollback port detection, and validating log directory write permissions.

Changes

Cohort / File(s) Summary
CI/CD Workflows
.github/workflows/ci.yml, .github/workflows/deploy.yml
CI workflow adds minimal read-only permissions block. Deploy workflow removes workflow_dispatch inputs, hardcodes DEPLOY_MODE to normal, reorganizes VPS deployment to install dependencies before smoke testing, and updates security gate messaging to indicate non-blocking behavior.
Application Logic
index.js
Refactors data extraction with destructured variables, precomputes display values for consistent UI rendering (wagerDisplay, statusLabels, username formatting), normalizes legacy state migration paths, and binds health server to localhost for tighter exposure control.
Deployment Scripts
scripts/notify-telegram.sh, scripts/rollback.sh, scripts/smoke-test.sh
Notification script adds Python 3 requirement check, removing sed fallback. Rollback script adds port recalculation from restored release's .env. Smoke-test script enhances logs directory check with write permission validation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 Hoppy times ahead, I declare,
With permissions refined and deployed with care,
Variables dance in their standardized way,
Python checks thrice before scripts will play,
Port numbers found, and logs written true—
Burrow's deployments now safer, on queue! 🚀


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@gamblecodezcom
gamblecodezcom merged commit 409f0ab into main Feb 21, 2026
2 checks passed
@gamblecodezcom
gamblecodezcom deleted the claude/update-prod-runner-script-Lq2gS branch February 21, 2026 07:14
@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Feb 21, 2026
@codeant-ai

codeant-ai Bot commented Feb 21, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • .env PORT parsing fragility
    The new logic extracts PORT from .env using grep "^PORT=" + cut. This won't handle common variants such as export PORT=..., leading whitespace, inline comments, or different quoting styles. If the restored .env uses such formats the parsed port could be empty or wrong.

  • Payload construction / JSON safety
    The payload JSON is constructed by embedding a JSON-encoded text but the chat_id is inserted raw (unquoted). If chat_id contains unexpected characters the JSON may break. Also building only one field with Python leaves other fields vulnerable to subtle quoting bugs. Constructing the entire payload via Python or ensuring both fields are JSON-encoded would be more robust.

  • Portability / Missing fallback
    The script now aborts sending notifications if python3 is not available. This improves safety (avoids malformed JSON) but reduces portability on systems that lack python3. Consider whether skipping is the desired behavior across all deploy targets or if a safer fallback should be provided.

  • Predictable temp file / race
    The writability test uses a predictable temp filename with $$ which can collide across processes or be abused. Using mktemp (or creating an atomic temporary file) is safer and avoids race conditions.

  • Masked mkdir failures
    mkdir -p ... || true suppresses errors from directory creation (e.g. permission denied). While the subsequent touch will fail and report not writable, the real cause (mkdir failing) may be obscured. Consider surfacing mkdir failure separately.

Comment thread scripts/rollback.sh
# The restored release may use a different PORT than the one that was running,
# so we must re-read it now — before the health check — to probe the right port.
if [[ -f "${CURRENT_DIR}/.env" ]]; then
_RESTORED_PORT=$(grep "^PORT=" "${CURRENT_DIR}/.env" 2>/dev/null | cut -d= -f2 | tr -d ' "' || true)

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 restored release's PORT is parsed from .env using grep/cut/tr without stripping inline comments, so a line like PORT=3000 # app port will produce a malformed HEALTH_URL such as http://127.0.0.1:3000# app port/health, causing the health check to hit the wrong path or fail even when the service is healthy. [logic error]

Severity Level: Major ⚠️
- ❌ Rollback health check can fail on healthy deployments.
- ❌ Telegram alert incorrectly reports rollback health failure.
- ⚠️ Operators may perform unnecessary manual interventions.
- ⚠️ Future automated rollback logic could misinterpret failures.
Suggested change
_RESTORED_PORT=$(grep "^PORT=" "${CURRENT_DIR}/.env" 2>/dev/null | cut -d= -f2 | tr -d ' "' || true)
_RESTORED_PORT=$(
grep -m1 "^PORT=" "${CURRENT_DIR}/.env" 2>/dev/null \
| cut -d= -f2- \
| sed 's/[[:space:]]*#.*$//' \
| tr -d ' "'
|| true)
Steps of Reproduction ✅
1. Confirm rollback entry point: in `package.json:19-20` the npm scripts `"rollback":
"./scripts/rollback.sh"` and `"rollback:list": "./scripts/rollback.sh --list"` show that
operators will trigger `/workspace/Runewager/scripts/rollback.sh` directly in production.

2. Note paths used by rollback: in `scripts/rollback.sh:21-26` the script defines
`BASE_DIR="/var/www/html/Runewager"`, `RELEASES_DIR="${BASE_DIR}/releases"`,
`CURRENT_DIR="${BASE_DIR}/current"`, and initial
`HEALTH_URL="http://127.0.0.1:${PORT}/health"`, so any rollback operates on
`${RELEASES_DIR}/release_*` directories and checks health via this URL.

3. Create or edit a release `.env` with an inline comment on PORT in a release directory,
e.g. `/var/www/html/Runewager/releases/release_123/.env` containing a line `PORT=3000 #
app port`. This is a realistic pattern: `README.md:129-131` instructs operators `cp -n
.env.example .env` then `nano .env`, and `.env.example:11` defines `PORT=3000` without
comments, so admins commonly add comments when customizing.

4. Ensure there are at least two releases so that `scripts/rollback.sh` will copy a
previous release into `CURRENT_DIR` (`scripts/rollback.sh:90-93`), then run a rollback
pointing at the commented-port release: `npm run rollback -- releases/release_123` (which
invokes `./scripts/rollback.sh <release_dir>` as documented at `scripts/rollback.sh:7-8`).

5. During rollback, after copying the target release into `CURRENT_DIR`, the block at
`scripts/rollback.sh:99-109` executes: it reads `${CURRENT_DIR}/.env`, runs `grep "^PORT="
... | cut -d= -f2 | tr -d ' "'`. For the line `PORT=3000 # app port`, `cut` yields `3000 #
app port`, and `tr -d ' "'` strips spaces/quotes but leaves `#` and letters, producing
`_RESTORED_PORT="3000#apput"` (similar malformed value).

6. With `_RESTORED_PORT` non-empty, the script sets `PORT="$_RESTORED_PORT"` and
recomputes `HEALTH_URL="http://127.0.0.1:${PORT}/health"` at
`scripts/rollback.sh:105-106`, resulting in a malformed URL like
`http://127.0.0.1:3000#apput/health` that includes a fragment/garbage in place of a clean
port.

7. The health check loop at `scripts/rollback.sh:123-135` then calls `curl ...
"$HEALTH_URL"`; because the URL is malformed (fragment and junk after the port), curl
either fails to connect properly or hits the wrong effective path, so `HTTP_CODE` remains
non-200 for all attempts even though the bot process (Node health endpoint in
`index.js:1910` and `index.js:4923` which listen on `process.env.PORT || 3000`) is
correctly serving `/health` on port 3000.

8. As a result, the script sets `HEALTH_OK=false` and the block at
`scripts/rollback.sh:137-140` fires, logging `Health check FAILED after rollback. The bot
may be down.` and sending a Telegram notification via `notify()` indicating rollback
health check failure, even though the service is actually healthy and running on the
intended port.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** scripts/rollback.sh
**Line:** 103:103
**Comment:**
	*Logic Error: The restored release's `PORT` is parsed from `.env` using `grep`/`cut`/`tr` without stripping inline comments, so a line like `PORT=3000 # app port` will produce a malformed `HEALTH_URL` such as `http://127.0.0.1:3000# app port/health`, causing the health check to hit the wrong path or fail even when the service is healthy.

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 21, 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

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants