Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🔨 Refactoring load-config.js #4440

Open
wants to merge 12 commits into
base: master
Choose a base branch
from

Conversation

lelemm
Copy link
Contributor

@lelemm lelemm commented Feb 24, 2025

Refactoring load-config.js

Copy link

netlify bot commented Feb 24, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit cdc2627
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67c1ed120fc33d000894d4f6
😎 Deploy Preview https://deploy-preview-4440.demo.actualbudget.org
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@lelemm lelemm marked this pull request as ready for review February 27, 2025 23:00
Copy link
Contributor

coderabbitai bot commented Feb 27, 2025

Walkthrough

The changes update the configuration management throughout the repository by replacing direct property accesses with calls to the config.get() method. This shift is applied in several files, ensuring that values such as serverFiles, userFiles, token_expiration, and various other configuration parameters are retrieved consistently. In addition, the configuration loading mechanism has been revamped in favor of a declarative schema using the convict library, with new dependencies added to the package.json for both convict and its type definitions. Some functions have also seen parameter renaming and minor logic adjustments to better align with the new configuration approach. Additionally, the multiuser property has been removed from the configuration type definitions.

Suggested labels

":sparkles: Merged"

Suggested reviewers

  • MikesGlitch
✨ Finishing Touches
  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
packages/sync-server/src/scripts/enable-openid.js (1)

24-24: Use config alias to avoid parameter naming conflicts.

The change to use config.getProperties() is good, but based on the project's conventions, when config is used as a function parameter, the imported configuration should use the alias finalConfig to avoid naming conflicts.

- import { config } from '../load-config.js';
+ import { config as finalConfig } from '../load-config.js';

  // Then update line 24 to use finalConfig
- const { error } = (await enableOpenID(config.getProperties())) || {};
+ const { error } = (await enableOpenID(finalConfig.getProperties())) || {};
packages/sync-server/src/scripts/health-check.js (1)

5-8: Improved protocol handling with explicit key and cert checks

The protocol determination logic has been updated to specifically check for both https.key and https.cert rather than a simple boolean flag. This provides more explicit validation that all requirements for HTTPS are present before using it.

packages/sync-server/src/app.js (1)

108-117: Mixed usage of config.https and config.get('https.key') / config.get('https.cert').
While calling config.get('https.key') and config.get('https.cert') is correct, consider also replacing ...config.https with an object destructured from config.get('https') for full consistency.

packages/sync-server/src/load-config.js (1)

189-211: Validation and sensitive output masking.
Good job validating with { allowed: 'strict' } and obscuring HTTPS secrets in debug logs. For further security, consider secrets management to avoid storing them on-disk in plain text.

packages/sync-server/src/accounts/openid.js (1)

5-5: Consider renaming the imported config to avoid naming conflicts.

Based on project conventions, the imported config should be renamed to finalConfig when config is used as a function parameter to avoid naming conflicts. This practice is established elsewhere in the codebase.

-import { config } from '../load-config.js';
+import { config as finalConfig } from '../load-config.js';
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c931cf and df6f6cc.

⛔ Files ignored due to path filters (2)
  • upcoming-release-notes/4440.md is excluded by !**/*.md
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (13)
  • packages/sync-server/migrations/1694360000000-create-folders.js (1 hunks)
  • packages/sync-server/package.json (2 hunks)
  • packages/sync-server/src/account-db.js (3 hunks)
  • packages/sync-server/src/accounts/openid.js (6 hunks)
  • packages/sync-server/src/accounts/password.js (1 hunks)
  • packages/sync-server/src/app.js (5 hunks)
  • packages/sync-server/src/config-types.ts (0 hunks)
  • packages/sync-server/src/load-config.js (1 hunks)
  • packages/sync-server/src/migrations.js (1 hunks)
  • packages/sync-server/src/scripts/enable-openid.js (1 hunks)
  • packages/sync-server/src/scripts/health-check.js (1 hunks)
  • packages/sync-server/src/util/paths.js (1 hunks)
  • packages/sync-server/src/util/validate-user.js (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/sync-server/src/config-types.ts
🧰 Additional context used
🧠 Learnings (2)
packages/sync-server/src/scripts/enable-openid.js (1)
Learnt from: matt-fidd
PR: actualbudget/actual#4363
File: packages/sync-server/src/scripts/enable-openid.js:6-6
Timestamp: 2025-02-11T23:39:06.219Z
Learning: In the Actual codebase, when `config` is used as a function parameter, the imported configuration should use the alias `finalConfig` to avoid naming conflicts. Example: `import { config as finalConfig } from '../load-config.js'`.
packages/sync-server/src/accounts/openid.js (1)
Learnt from: matt-fidd
PR: actualbudget/actual#4363
File: packages/sync-server/src/scripts/enable-openid.js:6-6
Timestamp: 2025-02-11T23:39:06.219Z
Learning: In the Actual codebase, when `config` is used as a function parameter, the imported configuration should use the alias `finalConfig` to avoid naming conflicts. Example: `import { config as finalConfig } from '../load-config.js'`.
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Visual regression
  • GitHub Check: Functional
  • GitHub Check: build (windows-latest)
  • GitHub Check: Build Docker image (alpine)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Build Docker image (ubuntu)
🔇 Additional comments (27)
packages/sync-server/package.json (1)

50-50: Added dependencies for configuration management with convict.

The addition of convict and its TypeScript type definitions supports the refactoring of configuration management throughout the codebase, moving from direct property access to a schema-based approach.

Also applies to: 60-60

packages/sync-server/src/util/validate-user.js (1)

49-50: Configuration access standardized with config.get().

Good change to maintain consistency with the rest of the codebase by replacing direct property access with the config.get() method while preserving the fallback logic.

packages/sync-server/src/migrations.js (1)

15-18: Standardized configuration access using config.get().

Good implementation of the refactoring strategy, consistently using config.get() for all configuration values rather than direct property access.

packages/sync-server/src/accounts/password.js (1)

88-94: Standardized configuration access with config.get()

The change from direct property access to the config.get() method aligns with the PR's refactoring goal of standardizing configuration access throughout the codebase.

packages/sync-server/src/util/paths.js (2)

7-7: Standardized configuration access in getPathForUserFile

Using config.get('userFiles') instead of direct property access aligns with the PR's refactoring goal.


12-12: Standardized configuration access in getPathForGroupFile

Using config.get('userFiles') instead of direct property access aligns with the PR's refactoring goal.

packages/sync-server/migrations/1694360000000-create-folders.js (2)

18-19: Standardized configuration access in migration up function

The change to use config.get() instead of direct property access for both serverFiles and userFiles is consistent with the PR's refactoring goal.


23-24: Standardized configuration access in migration down function

The change to use config.get() instead of direct property access for both serverFiles and userFiles is consistent with the PR's refactoring goal.

packages/sync-server/src/app.js (7)

26-26: Consistent use of config.get('trustedProxies').
This change aligns with the new schema-based configuration approach, ensuring all config values are retrieved uniformly.


38-40: Switched to config.get('upload.fileSizeLimitMB').
The new usage simplifies retrieval of this limit. Confirm that fileSizeLimitMB is suitably validated in the schema.


44-45: Use of config.get('upload.fileSizeSyncLimitMB').
The transition away from direct property access is consistent with the rest of the refactor.


50-51: Adoption of config.get('upload.syncEncryptedFileSizeLimitMB').
Good job maintaining consistency. Ensure this limit adequately protects against large uploads.


64-64: Replaced direct property access with config.get('mode').
This is consistent with the new schema pattern. No issues are apparent here.


94-97: Switched to serving static files from config.get('webRoot').
This maintains uniform usage of config values. Confirm that the configured path is correct in production.


119-124: Adoption of config.get('port') and config.get('hostname').
These changes unify server listening configuration with the updated schema approach.

packages/sync-server/src/account-db.js (4)

14-14: Use of config.get('serverFiles').
Efficiently retrieves the path for the account database. This helps maintain a single source of truth from the convict schema.


32-34: Incorporation of config.get('enforceOpenId').
Ensures that OpenID enforcement is taken from the schema. The conditional logic is correct given the new config approach.


60-61: Use of config.get('allowedLoginMethods').
Good shift to the standardized get method. Confirm edge cases where allowedLoginMethods might be empty or missing are handled gracefully in the schema.


65-66: Fallback to config.get('loginMethod').
Using the convict-based approach for login method retrieval improves consistency and maintainability.

packages/sync-server/src/load-config.js (4)

6-6: Introduction of convict.
Adopting convict is a solid move for declaring and validating configuration in a structured manner.


24-32: Implementation of custom tokenExpiration format.
This is a valid custom convict format. It handles both numeric and explicit string values (like 'never'). No issues found.


34-185: Schema definitions partially omit 'production' from mode.
Your schema allows env: ['production', 'development', 'test'] but mode only includes ['test', 'development']. Verify that excluding 'production' from mode is intentional.


187-188: configSchema.loadFile('config.json') usage.
This is the standard convict pattern. Ensure that a missing or invalid config.json is handled gracefully.

packages/sync-server/src/accounts/openid.js (4)

12-15: Parameter renaming improves clarity, but check validation logic.

The parameter rename from config to configParameter is good for clarity. The added check for discoveryURL improves validation, but consider how this relates to line 52 where it appears only one of issuer or discoveryURL is required.


141-149: Good variable rename for clarity.

Renaming config to configFromDb clearly indicates this is configuration data retrieved from the database, reducing confusion with the imported config module.


266-273: Consistent use of config.get() improves configuration management.

The change to use config.get('token_expiration') instead of direct property access aligns with the refactoring objective of standardizing configuration access across the codebase.

However, there might be confusion about why direct property access is used for configFromDb while config.get() is used for token expiration. Consider adding a comment explaining the different sources of configuration.


51-59:

✅ Verification successful

Verify that the issuer determination logic is consistent with previous behavior.

The changes to the issuer discovery process now allow for either discoveryURL or an explicit issuer configuration. Ensure this maintains backward compatibility with existing configurations.


🏁 Script executed:

#!/bin/bash
# Check other places in the codebase where OpenID clients are created to ensure consistent behavior
rg -A 3 "new Issuer" --glob "*.js"

Length of output: 418


Issuer determination logic verified: No issues found.

The updated code correctly maintains the prior behavior by choosing between issuer discovery via discoveryURL and using an explicit issuer configuration. Our search confirmed that the explicit issuer instantiation remains consistent with earlier implementations, with no further instances or conflicts detected.

@lelemm lelemm changed the title 🔨 Refactoring load-config.js [WIP] 🔨 Refactoring load-config.js Feb 28, 2025
@lelemm lelemm changed the title [WIP] 🔨 Refactoring load-config.js 🔨 Refactoring load-config.js Feb 28, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/sync-server/src/load-config.js (1)

269-269: Consider providing a helper method for accessing nested configuration.

The export renames configSchema to config, which is good for backward compatibility. For improved developer experience when accessing deeply nested properties, consider adding utility methods to make access more concise.

- export { configSchema as config };
+ const config = configSchema;
+ 
+ // Helper for cleaner nested property access
+ config.getPath = function(path) {
+   return this.get(path);
+ };
+ 
+ export { config };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df6f6cc and 98b1e88.

📒 Files selected for processing (1)
  • packages/sync-server/src/load-config.js (1 hunks)
🔇 Additional comments (6)
packages/sync-server/src/load-config.js (6)

6-6: Good choice of configuration library.

Using convict is a solid approach for configuration management as it provides schema validation, format checking, and centralized configuration management.


24-32: Well-implemented custom format validation.

The custom format for token expiration is thorough, handling multiple valid use cases ('never', 'openid-provider', or a non-negative number) and providing clear error messages.


35-239: Well-structured configuration schema with comprehensive documentation.

The schema is well-organized with appropriate documentation, default values, environment variable mappings, and format validations for each property. The nested objects for complex configurations like HTTPS and OpenID follow good practices.


241-243: Good defensive programming with config file loading.

The code checks for the existence of the config file before attempting to load it, preventing potential errors when the file doesn't exist.


245-245: Strict validation ensures configuration integrity.

Using { allowed: 'strict' } for validation prevents unknown properties in the configuration, which helps catch typos and configuration errors early.


257-267: Good security practice for sensitive information logging.

The code properly masks sensitive information in regular debug logs while still providing access to the full values in sensitive debug logs for troubleshooting when needed.

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

Successfully merging this pull request may close these issues.

2 participants