Skip to content

feat: add COOKIE_SECURE and COOKIE_SAMESITE environment variables (v2.0.1)#156

Merged
Yeraze merged 3 commits into
mainfrom
fix/cookie-secure-env-var
Oct 10, 2025
Merged

feat: add COOKIE_SECURE and COOKIE_SAMESITE environment variables (v2.0.1)#156
Yeraze merged 3 commits into
mainfrom
fix/cookie-secure-env-var

Conversation

@Yeraze

@Yeraze Yeraze commented Oct 10, 2025

Copy link
Copy Markdown
Owner

Summary

  • Add COOKIE_SECURE and COOKIE_SAMESITE environment variables for configurable cookie security
  • Fix login issues when accessing MeshMonitor over HTTP in production
  • Bump version to 2.0.1

Problem

Users reported login failures in production when accessing over HTTP (Issue #153). The session cookie was configured with secure: true based on NODE_ENV=production, which causes browsers to reject cookies over insecure HTTP connections. This resulted in successful authentication on the backend, but no persistent session in the browser.

Solution

Added two new environment variables:

  • COOKIE_SECURE: Override the secure cookie requirement (default: true in production, false in development)
  • COOKIE_SAMESITE: Customize SameSite policy (default: strict in production, lax in development)

Changes

  1. Session Configuration (src/server/auth/sessionConfig.ts)

    • Parse COOKIE_SECURE and COOKIE_SAMESITE environment variables
    • Add warning when COOKIE_SECURE=false in production
    • Validate COOKIE_SAMESITE values
  2. Documentation (README.md)

  3. Configuration Examples

    • Update .env.example with session configuration section
    • Update docker-compose.yml with commented COOKIE_SECURE=false example
  4. Version Bump

    • package.json: 2.0.0 → 2.0.1
    • helm/meshmonitor/Chart.yaml: 2.0.0 → 2.0.1
    • Regenerate package-lock.json

Backward Compatibility

Fully backward compatible - existing deployments continue to work without changes. New variables are optional and default to previous behavior.

Security Considerations

  • Secure by default: Production still requires HTTPS unless explicitly overridden
  • Warning logged when COOKIE_SECURE=false in production
  • Recommendation in documentation to use HTTPS

Test Plan

Usage Example

For users accessing over HTTP (not recommended for production):

environment:
  - NODE_ENV=production
  - SESSION_SECRET=your-secret-here
  - COOKIE_SECURE=false  # Allow HTTP access

Fixes #153

🤖 Generated with Claude Code

Add configurable cookie security settings to fix login issues when
accessing MeshMonitor over HTTP in production environments.

Changes:
- Add COOKIE_SECURE env var to override secure cookie requirement
- Add COOKIE_SAMESITE env var to customize SameSite policy
- Add warning log when COOKIE_SECURE=false in production
- Update README with session and cookie configuration docs
- Add examples to .env.example and docker-compose.yml
- Bump version to 2.0.1

Previously, session cookies required HTTPS in production (NODE_ENV=production)
with no way to override. This caused login failures when users accessed the
app over HTTP, as browsers reject secure cookies over insecure connections.

Users can now set COOKIE_SECURE=false to allow HTTP access, though HTTPS
is still recommended for production deployments.

Fixes #153

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@Yeraze Yeraze force-pushed the fix/cookie-secure-env-var branch from da41e43 to 40f432c Compare October 10, 2025 19:48
@claude

claude Bot commented Oct 10, 2025

Copy link
Copy Markdown
Contributor

Claude finished @Yeraze's task —— View job


PR Review: Cookie Security Environment Variables

Comprehensive code review completed for PR #156

Review Summary

This is an excellent implementation that addresses the HTTP access issue while maintaining strong security practices. The code quality is high, documentation is thorough, and the approach is well-architected.

✅ Strengths

Code Quality & Architecture:

  • Clean, well-commented implementation with proper separation of concerns
  • Type-safe with explicit TypeScript types for cookieSameSite values
  • Excellent error handling and validation logic
  • Follows existing codebase patterns and conventions

Security Best Practices:

  • Secure by default: Production remains secure unless explicitly overridden
  • Clear warnings: Logs security warnings when COOKIE_SECURE=false in production
  • Input validation: Properly validates COOKIE_SAMESITE values with fallback
  • No security regression: Maintains existing security posture

Documentation Excellence:

  • Complete README: Well-formatted environment variables table
  • Clear examples: Both .env.example and docker-compose.yml updated
  • Security guidance: Includes recommendations to use HTTPS

Backward Compatibility:

  • No breaking changes: Existing deployments continue working unchanged
  • Optional configuration: New variables are optional with sensible defaults
  • Version consistency: All files properly updated to 2.0.1

🔍 Technical Analysis

Environment Variable Handling:

  • COOKIE_SECURE: Properly handles string→boolean conversion with undefined check
  • COOKIE_SAMESITE: Case-insensitive validation with type safety
  • Default behavior preserved when environment variables not set

Edge Cases Covered:

  • Invalid COOKIE_SAMESITE values → logs warning, uses default
  • COOKIE_SECURE=false in production → logs security warning
  • Empty/undefined environment variables → proper fallback behavior

Performance & Memory:

  • No performance impact - configuration parsed once at startup
  • Minimal memory footprint - only adds two conditional checks

🛡️ Security Assessment

Risk Level: Low

  • Feature is opt-in and secure by default
  • Explicit user action required to reduce security
  • Clear warnings prevent accidental misconfigurations

Appropriate for Use Case:
This solution correctly addresses Issue #153 where users need HTTP access in production environments while maintaining security as the default behavior.

📋 Test Coverage

Existing Tests: Claims 513 tests pass ✅
Areas that could benefit from tests:

  • Unit tests for sessionConfig.ts environment variable parsing
  • Integration tests for cookie behavior with different environment variable combinations
  • Tests for warning log messages

🏆 Final Recommendation

✅ APPROVE - This is a well-implemented, secure, and thoroughly documented solution.

Notable Quality Indicators:

  • Addresses the exact issue described in [BUG] Unable to login on 2.0.0 #153
  • Maintains security best practices
  • Excellent documentation and examples
  • Clean, readable, maintainable code
  • Proper version management

Minor Enhancement Opportunities:

  • Consider adding unit tests for the new environment variable parsing logic
  • Could add TypeScript const assertions for environment variable names to prevent typos

This PR demonstrates excellent software engineering practices and can be merged with confidence.


Add automatic trust proxy configuration to properly handle HTTPS
reverse proxy deployments where the proxy terminates SSL/TLS.

Changes:
- Add TRUST_PROXY environment variable support
- Default to trusting 1 proxy hop in production
- Support custom trust configurations (true, false, number, IP/CIDR)
- Add comprehensive reverse proxy documentation in README
- Update .env.example with trust proxy configuration
- Add debug logging for trust proxy configuration

This fixes login issues for users behind HTTPS reverse proxies. When
a reverse proxy terminates HTTPS, MeshMonitor needs to trust the
X-Forwarded-Proto header to correctly set secure cookies.

Without this, users experience:
- Successful backend authentication
- No persistent session (cookies rejected)
- Login appears to work but immediately logs out

With TRUST_PROXY enabled, Express reads X-Forwarded-* headers and
correctly identifies the connection as HTTPS, allowing secure cookies
to work properly.

Related to #153

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude

claude Bot commented Oct 10, 2025

Copy link
Copy Markdown
Contributor

Claude finished @Yeraze's task —— View job


PR Review: Cookie Security Environment Variables

Comprehensive code review completed for PR #156

Review Summary

This is an excellent implementation that addresses the HTTP access issue while maintaining strong security practices. The code quality is high, documentation is thorough, and the approach is well-architected.

Todo List:

  • Read and analyze core session configuration changes
  • Review environment variable handling implementation
  • Check documentation updates (README.md, .env.example)
  • Verify version consistency across all files
  • Assess security implications and best practices
  • Evaluate backward compatibility
  • Check for potential bugs or edge cases
  • Assess performance considerations
  • Evaluate test coverage needs
  • Provide comprehensive review feedback

✅ Strengths

Code Quality & Architecture:

  • Clean, well-commented implementation with proper separation of concerns
  • Type-safe with explicit TypeScript types for cookieSameSite values
  • Excellent error handling and validation logic
  • Follows existing codebase patterns and conventions

Security Best Practices:

  • Secure by default: Production remains secure unless explicitly overridden
  • Clear warnings: Logs security warnings when COOKIE_SECURE=false in production
  • Input validation: Properly validates COOKIE_SAMESITE values with fallback
  • No security regression: Maintains existing security posture

Documentation Excellence:

  • Complete README: Well-formatted environment variables table
  • Clear examples: Both .env.example and docker-compose.yml updated
  • Security guidance: Includes recommendations to use HTTPS

Backward Compatibility:

  • No breaking changes: Existing deployments continue working unchanged
  • Optional configuration: New variables are optional with sensible defaults
  • Version consistency: All files properly updated to 2.0.1

🔍 Technical Analysis

Environment Variable Handling:

  • COOKIE_SECURE: Properly handles string→boolean conversion with undefined check
  • COOKIE_SAMESITE: Case-insensitive validation with type safety
  • Default behavior preserved when environment variables not set

Edge Cases Covered:

  • Invalid COOKIE_SAMESITE values → logs warning, uses default
  • COOKIE_SECURE=false in production → logs security warning
  • Empty/undefined environment variables → proper fallback behavior

Performance & Memory:

  • No performance impact - configuration parsed once at startup
  • Minimal memory footprint - only adds two conditional checks

🛡️ Security Assessment

Risk Level: Low

  • Feature is opt-in and secure by default
  • Explicit user action required to reduce security
  • Clear warnings prevent accidental misconfigurations

Appropriate for Use Case:
This solution correctly addresses Issue #153 where users need HTTP access in production environments while maintaining security as the default behavior.

📋 Test Coverage

Existing Tests: Claims 513 tests pass ✅
Areas that could benefit from tests:

  • Unit tests for sessionConfig.ts environment variable parsing
  • Integration tests for cookie behavior with different environment variable combinations
  • Tests for warning log messages

🏆 Final Recommendation

✅ APPROVE - This is a well-implemented, secure, and thoroughly documented solution.

Notable Quality Indicators:

  • Addresses the exact issue described in [BUG] Unable to login on 2.0.0 #153
  • Maintains security best practices
  • Excellent documentation and examples
  • Clean, readable, maintainable code
  • Proper version management

Minor Enhancement Opportunities:

  • Consider adding unit tests for the new environment variable parsing logic
  • Could add TypeScript const assertions for environment variable names to prevent typos

This PR demonstrates excellent software engineering practices and can be merged with confidence.


Add extensive documentation for reverse proxy deployments and login
troubleshooting to help users quickly identify and fix cookie issues.

Changes:
- Add detailed troubleshooting section for login/session issues
- Document three deployment scenarios with clear guidance:
  * Scenario A: HTTPS reverse proxy (use TRUST_PROXY)
  * Scenario B: Direct HTTP access (use COOKIE_SECURE=false)
  * Scenario C: Direct HTTPS access (no config needed)
- Add comprehensive reverse proxy examples:
  * nginx (root path and subfolder)
  * Traefik (with Docker labels)
  * Caddy (simplest setup)
- Include MeshMonitor configuration for each proxy example
- Update docker-compose.yml with TRUST_PROXY example comment
- Add diagnostic steps for cookie issues

This documentation helps users:
1. Quickly identify which scenario matches their deployment
2. Apply the correct configuration without trial and error
3. Understand why each setting is needed
4. Diagnose cookie issues using browser DevTools

Related to #153

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude

claude Bot commented Oct 10, 2025

Copy link
Copy Markdown
Contributor

Claude finished @Yeraze's task —— View job


PR Review: Cookie Security Environment Variables

Comprehensive code review completed for PR #156

Todo List:

  • Read and analyze core session configuration changes
  • Review environment variable handling implementation
  • Check documentation updates (README.md, .env.example)
  • Verify version consistency across all files
  • Assess security implications and best practices
  • Evaluate backward compatibility
  • Check for potential bugs or edge cases
  • Assess performance considerations
  • Evaluate test coverage needs
  • Provide comprehensive review feedback

Review Summary

This is an excellent implementation that addresses the HTTP access issue while maintaining strong security practices. The code quality is high, documentation is thorough, and the approach is well-architected.

✅ Strengths

Code Quality & Architecture:

  • Clean, well-commented implementation with proper separation of concerns
  • Type-safe with explicit TypeScript types for cookieSameSite values
  • Excellent error handling and validation logic
  • Follows existing codebase patterns and conventions

Security Best Practices:

  • Secure by default: Production remains secure unless explicitly overridden
  • Clear warnings: Logs security warnings when COOKIE_SECURE=false in production
  • Input validation: Properly validates COOKIE_SAMESITE values with fallback
  • No security regression: Maintains existing security posture

Documentation Excellence:

  • Complete README: Well-formatted environment variables table
  • Clear examples: Both .env.example and docker-compose.yml updated
  • Security guidance: Includes recommendations to use HTTPS

Backward Compatibility:

  • No breaking changes: Existing deployments continue working unchanged
  • Optional configuration: New variables are optional with sensible defaults
  • Version consistency: All files properly updated to 2.0.1

🔍 Technical Analysis

Environment Variable Handling:

  • COOKIE_SECURE: Properly handles string→boolean conversion with undefined check
  • COOKIE_SAMESITE: Case-insensitive validation with type safety
  • Default behavior preserved when environment variables not set

Edge Cases Covered:

  • Invalid COOKIE_SAMESITE values → logs warning, uses default
  • COOKIE_SECURE=false in production → logs security warning
  • Empty/undefined environment variables → proper fallback behavior

Performance & Memory:

  • No performance impact - configuration parsed once at startup
  • Minimal memory footprint - only adds two conditional checks

🛡️ Security Assessment

Risk Level: Low

  • Feature is opt-in and secure by default
  • Explicit user action required to reduce security
  • Clear warnings prevent accidental misconfigurations

Appropriate for Use Case:
This solution correctly addresses Issue #153 where users need HTTP access in production environments while maintaining security as the default behavior.

📋 Test Coverage

Existing Tests: Claims 513 tests pass ✅
Areas that could benefit from tests:

  • Unit tests for sessionConfig.ts environment variable parsing
  • Integration tests for cookie behavior with different environment variable combinations
  • Tests for warning log messages

🏆 Final Recommendation

✅ APPROVE - This is a well-implemented, secure, and thoroughly documented solution.

Notable Quality Indicators:

  • Addresses the exact issue described in [BUG] Unable to login on 2.0.0 #153
  • Maintains security best practices
  • Excellent documentation and examples
  • Clean, readable, maintainable code
  • Proper version management

Minor Enhancement Opportunities:

  • Consider adding unit tests for the new environment variable parsing logic
  • Could add TypeScript const assertions for environment variable names to prevent typos

This PR demonstrates excellent software engineering practices and can be merged with confidence.


@Yeraze Yeraze merged commit 52b737a into main Oct 10, 2025
12 checks passed
Yeraze added a commit that referenced this pull request Oct 12, 2025
….0.1) (#156)

Co-authored-by: Claude <noreply@anthropic.com>
Yeraze added a commit that referenced this pull request Oct 29, 2025
….0.1) (#156)

Co-authored-by: Claude <noreply@anthropic.com>
@Yeraze Yeraze deleted the fix/cookie-secure-env-var branch March 13, 2026 21:01
Yeraze added a commit that referenced this pull request Jun 18, 2026
…#152/153/155/156) (#3544)

* fix(security): use RE2 for user-supplied regexes to eliminate ReDoS (#3543)

Resolves the two high-severity CodeQL js/regex-injection alerts (#153, #155) by
compiling all user/admin-supplied regular expressions with RE2, a linear-time
engine immune to catastrophic backtracking. The previous heuristic guards
(length caps + nested-quantifier checks) reduced but could not eliminate the
risk, and CodeQL (correctly) kept flagging the user→RegExp dataflow.

- New src/utils/safeRegex.ts: compileUserRegex(pattern, flags) wraps RE2 and
  returns a RegExp-compatible matcher (test/exec/match/replace). RE2 rejects
  backreferences and lookaround — the intended trade-off — so callers keep their
  existing try/catch to treat unsupported patterns as "invalid regex".
- Convert every user-supplied regex site, validation AND execution:
  - server.ts: remote(-localstats) name-filter validation (2 sites).
  - services/database.ts: the name-filter execution sites that actually match
    node names (traceroute + localstats union filters) — the real ReDoS surface
    CodeQL didn't reach through the settings store.
  - routes/scriptRoutes.ts + meshtasticManager.ts: auto-responder trigger and
    auto-acknowledge pattern matching.
- Dockerfile: add build-base + python3 to the builder stage so re2 (native) can
  compile from source where no prebuilt exists (Alpine/musl arm). Builder stage
  only — not in the runtime image.

Tests: new safeRegex suite asserts linear-time behaviour on the classic (a+)+$
ReDoS pattern and rejection of backreference/lookaround. Full suite green.

The two non-regex alerts are handled separately: #152 (frontend routing, not a
security gate) dismissed as false-positive; #156 (authenticated admin script
import, path-sanitized) dismissed as by-design.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* address review: convert remaining regex sites to RE2; harden tests/docs (#3544)

Claude review feedback on the RE2 security PR:

1. autoAckRegex.ts:69 — convert the MeshCore auto-ack pattern compile to
   compileUserRegex (the charset allowlist/length/shape guards stay as a fast
   pre-rejection). Residual ReDoS surface CodeQL may not flag through the
   barrier, now closed for consistency.
2. settingsRoutes.ts:215 — convert the regex-validation compile to
   compileUserRegex so stored patterns are guaranteed RE2-compatible.
3. safeRegex.ts — document that the result is not `instanceof RegExp` and that
   length bounding stays the caller's responsibility; add a test asserting
   `.source`/`.flags` behave.
4. safeRegex.test.ts — raise the ReDoS timing threshold to 1000ms and use a
   larger input, so the assertion can't flake on loaded CI runners.
5. Dockerfile — clarify the builder comment (build-base is the new compiler;
   python3 is node-gyp's other requirement).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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.

[BUG] Unable to login on 2.0.0

1 participant