Skip to content

Extract bounded feature modules - #72

Merged
gitcommit90 merged 1 commit into
mainfrom
refactor/bounded-modules-phase6
Aug 4, 2026
Merged

Extract bounded feature modules#72
gitcommit90 merged 1 commit into
mainfrom
refactor/bounded-modules-phase6

Conversation

@gitcommit90

@gitcommit90 gitcommit90 commented Aug 4, 2026

Copy link
Copy Markdown
Owner

Outcome

Phase 6 reduces future change risk through three bounded, behavior-preserving extractions:

  • client thread formatting from app.ts;
  • HTTP boundary utilities from server/index.ts;
  • bot completion/output formatting from server/bots.ts.

It also adds a concise module map and nonblocking architecture-size/cycle report for future agents. No framework, schema, API, UX, installer, or runtime behavior changes.

Verification

  • Phase 6 characterization/integration: 22/22 passed
  • typecheck passed
  • full local CI previously passed on the exact Phase 6 tree: 127 native checks; 174 repository tests + 2 environment skips; 0 failures
  • private preview smoke passed
  • architecture report shows no new cycles or regressed budgets
  • Stable, website, releases, data and infrastructure untouched

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added clearer tool completion messages, action summaries, and status indicators.
    • Improved thread progress, usage, token, and countdown formatting.
    • Added shared HTTP handling with request limits, security headers, mobile access support, and rate limiting.
  • Documentation

    • Added module ownership guidance and architecture budgets.
  • Tests

    • Added module architecture validation and expanded coverage for HTTP, bot output, and thread formatting.

Move cohesive HTTP, bot-output, and thread-formatting behavior behind narrow interfaces and add advisory architecture budgets without changing runtime contracts.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Joseph Yaksich <gitcommit90@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds module architecture guidance, budgets, and reporting. It extracts client thread formatters, server HTTP utilities, and bot output helpers into separate modules. New phase-6 tests validate the extracted modules and architecture report.

Changes

Modular architecture boundaries

Layer / File(s) Summary
Architecture reporting and governance
AGENTS.md, config/module-budgets.json, docs/module-map.md, scripts/module-architecture-report.mjs, package.json, scripts/run-test-suite.mjs, test/phase6-modules.mjs
Adds module ownership guidance, architecture budgets, dependency analysis, cycle detection, reporting commands, and architecture validation.
Client thread formatting extraction
src/client/thread-formatters.ts, src/client/app.ts, test/phase6-modules.mjs
Moves thread progress, working-state, usage, and countdown formatting into shared pure helpers used by app.ts.
Server HTTP utility extraction
src/server/http.ts, src/server/index.ts, test/phase6-modules.mjs, test/workspace-interactions.mjs
Centralizes HTTP limits, headers, CORS, body parsing, address resolution, JSON responses, and rate limiting.
Server bot output extraction
src/server/bot-output.ts, src/server/bots.ts, test/phase6-modules.mjs
Centralizes tool completion messages, action summaries, and tool-result status classification.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the outcome and verification, but it omits the required change type, release notes, acceptance ledger, and checklist sections. Add the missing template sections, select the change type, provide release notes or N/A, complete the numbered acceptance ledger, and record all verification checks.
Docstring Coverage ⚠️ Warning Docstring coverage is 14.63% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: extracting cohesive feature modules.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/bounded-modules-phase6

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/server/http.ts`:
- Around line 44-68: Update body to reject immediately when received exceeds
limit, while ensuring the promise rejects only once and the request stream
continues draining so the connection is handled cleanly. For declared content
lengths over the limit, reject immediately and keep consuming the request rather
than returning without attaching stream handlers; preserve PayloadTooLargeError
details for both declared and streamed oversized bodies.
- Around line 72-75: Update the jbody function to validate that the parsed JSON
result is an object before returning it. After JSON.parse succeeds, check
whether the result is actually a Record (object type), and return an empty
record instead if the parsed value is null, an array, or a scalar type. This
ensures the function always returns a valid record matching its declared return
type, preventing downstream property access errors like b.username from throwing
on non-object JSON inputs.
- Around line 78-80: Update requestAddress to trust CF-Connecting-IP only when
req.socket.remoteAddress belongs to the configured trusted proxy addresses;
otherwise use the socket’s remote address. Add or reuse the trusted-proxy
configuration for this validation, preserving the existing format check for
accepted forwarded values.
- Around line 26-28: Update the headers in the json() helper’s res.writeHead()
call to include cache-control: no-store alongside the existing content type and
security headers, ensuring authenticated JSON responses are not cached.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d8484b97-5144-4727-acda-b43249104f9a

📥 Commits

Reviewing files that changed from the base of the PR and between 1e3ccf1 and 3e15d56.

📒 Files selected for processing (14)
  • AGENTS.md
  • config/module-budgets.json
  • docs/module-map.md
  • package.json
  • scripts/module-architecture-report.mjs
  • scripts/run-test-suite.mjs
  • src/client/app.ts
  • src/client/thread-formatters.ts
  • src/server/bot-output.ts
  • src/server/bots.ts
  • src/server/http.ts
  • src/server/index.ts
  • test/phase6-modules.mjs
  • test/workspace-interactions.mjs

Comment thread src/server/http.ts
Comment on lines +26 to +28
export function json(res: ServerResponse, code: number, responseBody: unknown): void {
res.writeHead(code, { "content-type": "application/json", ...SECURITY_HEADERS });
res.end(JSON.stringify(responseBody));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

# First, inspect the HTTP module to see what SECURITY_HEADERS contains
cat -n src/server/http.ts

Repository: gitcommit90/1Helm

Length of output: 5600


🏁 Script executed:

# Search for SECURITY_HEADERS definition and any cache-control headers
rg "SECURITY_HEADERS|cache-control|Cache-Control" -i src/server/

Repository: gitcommit90/1Helm

Length of output: 1916


🏁 Script executed:

# Check if there's any middleware or other code that adds cache headers
rg "cache-control|Cache-Control|writeHead" -i src/server/ -A 2 -B 2

Repository: gitcommit90/1Helm

Length of output: 6947


🏁 Script executed:

# Verify the /api/me endpoint and confirm it uses json()
rg "/api/me|api/me" src/server/index.ts -A 5 -B 5

Repository: gitcommit90/1Helm

Length of output: 4120


Sensitive Data Exposure (CWE-525): Use of Web Browser Cache Containing Sensitive Information

Reachability: External

Reachability path
● Entry
  src/server/index.ts:466
  applyMobileCors
│
▼
● Sink
  src/server/http.ts

Add cache-control: no-store to the json() helper.

The json() function serves authenticated endpoints such as /api/me that return user-specific data. Without cache-control: no-store, browsers cache these responses at the profile level. When the same browser profile authenticates as a different account, the cached data can be reused, exposing the previous user's identity.

Add cache-control: no-store to the header object passed to res.writeHead().

Proposed fix
 export function json(res: ServerResponse, code: number, responseBody: unknown): void {
-  res.writeHead(code, { "content-type": "application/json", ...SECURITY_HEADERS });
+  res.writeHead(code, {
+    "content-type": "application/json",
+    "cache-control": "no-store",
+    ...SECURITY_HEADERS,
+  });
   res.end(JSON.stringify(responseBody));
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function json(res: ServerResponse, code: number, responseBody: unknown): void {
res.writeHead(code, { "content-type": "application/json", ...SECURITY_HEADERS });
res.end(JSON.stringify(responseBody));
export function json(res: ServerResponse, code: number, responseBody: unknown): void {
res.writeHead(code, {
"content-type": "application/json",
"cache-control": "no-store",
...SECURITY_HEADERS,
});
res.end(JSON.stringify(responseBody));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server/http.ts` around lines 26 - 28, Update the headers in the json()
helper’s res.writeHead() call to include cache-control: no-store alongside the
existing content type and security headers, ensuring authenticated JSON
responses are not cached.

Comment thread src/server/http.ts
Comment on lines +44 to +68
export function body(req: IncomingMessage, limit = JSON_BODY_LIMIT): Promise<Buffer> {
return new Promise((resolve, reject) => {
const declared = Number(req.headers["content-length"] || 0);
if (declared > limit) {
const error = new Error(`Request exceeds the ${Math.floor(limit / 1024 / 1024)} MB limit.`);
error.name = "PayloadTooLargeError";
reject(error);
return;
}
const chunks: Buffer[] = [];
let received = 0;
let oversized = false;
req.on("data", (chunk: Buffer) => {
received += chunk.length;
if (received > limit) { oversized = true; chunks.length = 0; }
else if (!oversized) chunks.push(chunk);
});
req.on("end", () => {
if (oversized) {
const error = new Error(`Request exceeds the ${Math.floor(limit / 1024 / 1024)} MB limit.`);
error.name = "PayloadTooLargeError";
reject(error);
} else resolve(Buffer.concat(chunks));
});
req.on("error", reject);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Reject an oversized streamed body when the limit is exceeded.

Line 58 marks the request as oversized, but Lines 61-66 wait for end before rejecting. A client can exceed the limit with chunked input and keep the request open. The route then cannot return its 413 response.

Reject once at the threshold. Drain declared-oversized requests after rejection.

Proposed fix
 export function body(req: IncomingMessage, limit = JSON_BODY_LIMIT): Promise<Buffer> {
   return new Promise((resolve, reject) => {
+    const payloadTooLarge = () => {
+      const error = new Error(`Request exceeds the ${Math.floor(limit / 1024 / 1024)} MB limit.`);
+      error.name = "PayloadTooLargeError";
+      return error;
+    };
     const declared = Number(req.headers["content-length"] || 0);
     if (declared > limit) {
-      const error = new Error(`Request exceeds the ${Math.floor(limit / 1024 / 1024)} MB limit.`);
-      error.name = "PayloadTooLargeError";
-      reject(error);
+      req.resume();
+      reject(payloadTooLarge());
       return;
     }
@@
     req.on("data", (chunk: Buffer) => {
       received += chunk.length;
-      if (received > limit) { oversized = true; chunks.length = 0; }
+      if (received > limit && !oversized) {
+        oversized = true;
+        chunks.length = 0;
+        reject(payloadTooLarge());
+      }
       else if (!oversized) chunks.push(chunk);
     });
     req.on("end", () => {
-      if (oversized) {
-        const error = new Error(`Request exceeds the ${Math.floor(limit / 1024 / 1024)} MB limit.`);
-        error.name = "PayloadTooLargeError";
-        reject(error);
-      } else resolve(Buffer.concat(chunks));
+      if (!oversized) resolve(Buffer.concat(chunks));
     });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function body(req: IncomingMessage, limit = JSON_BODY_LIMIT): Promise<Buffer> {
return new Promise((resolve, reject) => {
const declared = Number(req.headers["content-length"] || 0);
if (declared > limit) {
const error = new Error(`Request exceeds the ${Math.floor(limit / 1024 / 1024)} MB limit.`);
error.name = "PayloadTooLargeError";
reject(error);
return;
}
const chunks: Buffer[] = [];
let received = 0;
let oversized = false;
req.on("data", (chunk: Buffer) => {
received += chunk.length;
if (received > limit) { oversized = true; chunks.length = 0; }
else if (!oversized) chunks.push(chunk);
});
req.on("end", () => {
if (oversized) {
const error = new Error(`Request exceeds the ${Math.floor(limit / 1024 / 1024)} MB limit.`);
error.name = "PayloadTooLargeError";
reject(error);
} else resolve(Buffer.concat(chunks));
});
req.on("error", reject);
export function body(req: IncomingMessage, limit = JSON_BODY_LIMIT): Promise<Buffer> {
return new Promise((resolve, reject) => {
const payloadTooLarge = () => {
const error = new Error(`Request exceeds the ${Math.floor(limit / 1024 / 1024)} MB limit.`);
error.name = "PayloadTooLargeError";
return error;
};
const declared = Number(req.headers["content-length"] || 0);
if (declared > limit) {
req.resume();
reject(payloadTooLarge());
return;
}
const chunks: Buffer[] = [];
let received = 0;
let oversized = false;
req.on("data", (chunk: Buffer) => {
received += chunk.length;
if (received > limit && !oversized) {
oversized = true;
chunks.length = 0;
reject(payloadTooLarge());
}
else if (!oversized) chunks.push(chunk);
});
req.on("end", () => {
if (!oversized) resolve(Buffer.concat(chunks));
});
req.on("error", reject);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server/http.ts` around lines 44 - 68, Update body to reject immediately
when received exceeds limit, while ensuring the promise rejects only once and
the request stream continues draining so the connection is handled cleanly. For
declared content lengths over the limit, reject immediately and keep consuming
the request rather than returning without attaching stream handlers; preserve
PayloadTooLargeError details for both declared and streamed oversized bodies.

Comment thread src/server/http.ts
Comment on lines +72 to +75
export async function jbody(req: IncomingMessage): Promise<Record<string, unknown>> {
const raw = await body(req);
try { return JSON.parse(raw.toString() || "{}"); }
catch { return {}; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Normalize valid non-object JSON input.

JSON.parse can return null or a scalar. The declared return type hides this condition. Routes then access fields such as b.username, which throws for null and returns a 500 response.

Return an empty record for non-object JSON roots.

Proposed fix
 export async function jbody(req: IncomingMessage): Promise<Record<string, unknown>> {
   const raw = await body(req);
-  try { return JSON.parse(raw.toString() || "{}"); }
+  try {
+    const parsed: unknown = JSON.parse(raw.toString() || "{}");
+    return parsed && typeof parsed === "object" && !Array.isArray(parsed)
+      ? parsed as Record<string, unknown>
+      : {};
+  }
   catch { return {}; }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export async function jbody(req: IncomingMessage): Promise<Record<string, unknown>> {
const raw = await body(req);
try { return JSON.parse(raw.toString() || "{}"); }
catch { return {}; }
export async function jbody(req: IncomingMessage): Promise<Record<string, unknown>> {
const raw = await body(req);
try {
const parsed: unknown = JSON.parse(raw.toString() || "{}");
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
? parsed as Record<string, unknown>
: {};
}
catch { return {}; }
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server/http.ts` around lines 72 - 75, Update the jbody function to
validate that the parsed JSON result is an object before returning it. After
JSON.parse succeeds, check whether the result is actually a Record (object
type), and return an empty record instead if the parsed value is null, an array,
or a scalar type. This ensures the function always returns a valid record
matching its declared return type, preventing downstream property access errors
like b.username from throwing on non-object JSON inputs.

Comment thread src/server/http.ts
Comment on lines +78 to +80
export function requestAddress(req: IncomingMessage): string {
const forwarded = String(req.headers["cf-connecting-ip"] || "").trim();
return /^[a-f0-9:.]{3,64}$/i.test(forwarded) ? forwarded : String(req.socket.remoteAddress || "unknown");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 3 --glob '*.{ts,js,mjs,json,yml,yaml}' \
  'cf-connecting-ip|requestAddress\(|createServer\(|\.listen\(|reverse proxy|cloudflare' .

Repository: gitcommit90/1Helm

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- src/server/http.ts ---'
sed -n '1,110p' src/server/http.ts

printf '%s\n' '--- src/server/index.ts server startup and imports ---'
sed -n '1,90p' src/server/index.ts
sed -n '450,575p' src/server/index.ts
sed -n '2185,2210p' src/server/index.ts

printf '%s\n' '--- address and rate-limit references ---'
rg -n -C 4 'requestAddress|rateLimited|HOST|PORT|server\.listen' src/server/index.ts src/server/http.ts

printf '%s\n' '--- deployment files mentioning the application port or proxy ---'
fd -t f . deploy config | sort | while read -r file; do
  if rg -qi '8130|1helm|proxy|cloudflared|listen|localhost|127\.0\.0\.1|0\.0\.0\.0' "$file"; then
    printf '\n### %s\n' "$file"
    rg -n -C 3 -i '8130|1helm|proxy|cloudflared|listen|localhost|127\.0\.0\.1|0\.0\.0\.0' "$file"
  fi
done

Repository: gitcommit90/1Helm

Length of output: 30229


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- runtime and service configuration ---'
rg -n -C 4 --glob '!node_modules/**' --glob '!dist/**' \
  'HELM_HOST|Environment=PORT|Environment=HELM|ExecStart=.*server|src/server/index|8123|reverse proxy|proxy_pass|cloudflared.*8123|127\.0\.0\.1:8123|0\.0\.0\.0' \
  .github deploy scripts site package.json README.md docs container 2>/dev/null || true

printf '%s\n' '--- relevant deployment and installer files ---'
fd -t f . deploy scripts site docs container | sort | while read -r file; do
  if rg -q 'HELM_HOST|8123|reverse proxy|proxy_pass|cloudflared|server/index|node .*server|PORT=' "$file"; then
    printf '\n### %s\n' "$file"
    rg -n -C 5 'HELM_HOST|8123|reverse proxy|proxy_pass|cloudflared|server/index|node .*server|PORT=' "$file"
  fi
done

printf '%s\n' '--- Cloudflare connector target ---'
rg -n -C 6 'startTunnelConnector|localhost|127\.0\.0\.1|PORT|service|ingress|tunnel' \
  src/server/cloudflare.ts src/server/connectors.ts cloudflare deploy 2>/dev/null || true

Repository: gitcommit90/1Helm

Length of output: 50376


🏁 Script executed:

#!/bin/bash
set -euo pipefail

node - <<'JS'
function requestAddress(req) {
  const forwarded = String(req.headers["cf-connecting-ip"] || "").trim();
  return /^[a-f0-9:.]{3,64}$/i.test(forwarded)
    ? forwarded
    : String(req.socket.remoteAddress || "unknown");
}

const socket = { remoteAddress: "10.0.0.5" };
const headers = ["192.0.2.1", "198.51.100.7", "2001:db8::1", "not-an-ip"];
for (const value of headers) {
  console.log(JSON.stringify({ header: value, key: requestAddress({ headers: { "cf-connecting-ip": value }, socket }) }));
}
console.log(JSON.stringify({
  directListener: "0.0.0.0",
  forwardedHeaderTrustedByCode: true,
  attackerCanChooseDistinctRateLimitKeys: requestAddress({
    headers: { "cf-connecting-ip": "192.0.2.1" }, socket
  }) !== requestAddress({
    headers: { "cf-connecting-ip": "198.51.100.7" }, socket
  })
}));
JS

printf '%s\n' '--- production unit binding ---'
sed -n '68,88p' site/public/install-linux-units.sh

printf '%s\n' '--- Cloudflare tunnel target configuration ---'
sed -n '1,18p' deploy/config-1helm-site.yml.example

Repository: gitcommit90/1Helm

Length of output: 1662


Spoofed Client Identity Used For Rate Limiting (CWE-345)

Reachability: External · Exploitability: Moderate

Reachability path
● Entry
  src/server/index.ts:466
  applyMobileCors
│
▼
● Sink
  src/server/http.ts

Trust CF-Connecting-IP only from a trusted proxy.

The production service binds to 0.0.0.0, so a directly reachable client can submit different valid CF-Connecting-IP values and bypass access and login rate limits. Restrict port 8123 to the proxy, or accept this header only from trusted proxy addresses.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server/http.ts` around lines 78 - 80, Update requestAddress to trust
CF-Connecting-IP only when req.socket.remoteAddress belongs to the configured
trusted proxy addresses; otherwise use the socket’s remote address. Add or reuse
the trusted-proxy configuration for this validation, preserving the existing
format check for accepted forwarded values.

@gitcommit90
gitcommit90 merged commit e9f028e into main Aug 4, 2026
6 of 7 checks passed
@gitcommit90
gitcommit90 deleted the refactor/bounded-modules-phase6 branch August 4, 2026 14:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant