fix(config): update corsResourcePolicy type to string, typecheck did not like previous method

This commit is contained in:
lzinga 2025-11-22 15:54:21 -08:00
parent 0bcc02dfab
commit 8cc4d08eae
2 changed files with 49 additions and 43 deletions

View File

@ -56,12 +56,18 @@ export default async function buildApp() {
app.use(compression()); // HTTP compression app.use(compression()); // HTTP compression
} }
let resourcePolicy = config["Network"]["corsResourcePolicy"] as 'same-origin' | 'same-site' | 'cross-origin' | undefined;
if(resourcePolicy !== 'same-origin' && resourcePolicy !== 'same-site' && resourcePolicy !== 'cross-origin') {
log.error(`Invalid CORS Resource Policy value: '${resourcePolicy}', defaulting to 'same-origin'`);
resourcePolicy = 'same-origin';
}
app.use( app.use(
helmet({ helmet({
hidePoweredBy: false, // errors out in electron hidePoweredBy: false, // errors out in electron
contentSecurityPolicy: false, contentSecurityPolicy: false,
crossOriginResourcePolicy: { crossOriginResourcePolicy: {
policy: config["Network"]["corsResourcePolicy"] || 'same-origin' policy: resourcePolicy
}, },
crossOriginEmbedderPolicy: false crossOriginEmbedderPolicy: false
}) })

View File

@ -98,7 +98,7 @@ export interface TriliumConfig {
/** CORS allowed headers (comma-separated header names) */ /** CORS allowed headers (comma-separated header names) */
corsAllowHeaders: string; corsAllowHeaders: string;
/** CORS Resource Policy ('same-origin', 'same-site', 'cross-origin') */ /** CORS Resource Policy ('same-origin', 'same-site', 'cross-origin') */
corsResourcePolicy: 'same-origin' | 'same-site' | 'cross-origin' | undefined; corsResourcePolicy: string;
}; };
/** Session management configuration */ /** Session management configuration */
Session: { Session: {
@ -150,27 +150,27 @@ export const LOGGING_DEFAULT_RETENTION_DAYS = 90;
* This interface defines how each configuration value is resolved from multiple sources. * This interface defines how each configuration value is resolved from multiple sources.
*/ */
interface ConfigValue<T> { interface ConfigValue<T> {
/** /**
* Standard environment variable name following TRILIUM_[SECTION]_[KEY] pattern. * Standard environment variable name following TRILIUM_[SECTION]_[KEY] pattern.
* This is the primary way to override configuration via environment. * This is the primary way to override configuration via environment.
*/ */
standardEnvVar?: string; standardEnvVar?: string;
/** /**
* Alternative environment variable names for additional flexibility. * Alternative environment variable names for additional flexibility.
* These provide shorter or more intuitive names for common settings. * These provide shorter or more intuitive names for common settings.
*/ */
aliasEnvVars?: string[]; aliasEnvVars?: string[];
/** /**
* Function to retrieve the value from the parsed INI configuration. * Function to retrieve the value from the parsed INI configuration.
* Returns undefined if the value is not set in config.ini. * Returns undefined if the value is not set in config.ini.
*/ */
iniGetter: () => IniConfigValue | IniConfigSection; iniGetter: () => IniConfigValue | IniConfigSection;
/** /**
* Default value used when no environment variable or INI value is found. * Default value used when no environment variable or INI value is found.
* This ensures every configuration has a sensible default. * This ensures every configuration has a sensible default.
*/ */
defaultValue: T; defaultValue: T;
/** /**
* Optional transformer function to convert string values to the correct type. * Optional transformer function to convert string values to the correct type.
* Common transformers handle boolean and integer conversions. * Common transformers handle boolean and integer conversions.
*/ */
@ -179,18 +179,18 @@ interface ConfigValue<T> {
/** /**
* Core configuration resolution function. * Core configuration resolution function.
* *
* Resolves configuration values using a clear precedence order: * Resolves configuration values using a clear precedence order:
* 1. Standard environment variable (highest priority) - Follows TRILIUM_[SECTION]_[KEY] pattern * 1. Standard environment variable (highest priority) - Follows TRILIUM_[SECTION]_[KEY] pattern
* 2. Alias environment variables - Alternative names for convenience and compatibility * 2. Alias environment variables - Alternative names for convenience and compatibility
* 3. INI config file value - User-defined settings in config.ini * 3. INI config file value - User-defined settings in config.ini
* 4. Default value (lowest priority) - Fallback to ensure valid configuration * 4. Default value (lowest priority) - Fallback to ensure valid configuration
* *
* This precedence allows for flexible configuration management: * This precedence allows for flexible configuration management:
* - Environment variables for container/cloud deployments * - Environment variables for container/cloud deployments
* - config.ini for traditional installations * - config.ini for traditional installations
* - Defaults ensure the application always has valid settings * - Defaults ensure the application always has valid settings
* *
* @param config - Configuration value definition with sources and transformers * @param config - Configuration value definition with sources and transformers
* @returns The resolved configuration value with appropriate type * @returns The resolved configuration value with appropriate type
*/ */
@ -225,7 +225,7 @@ function getConfigValue<T>(config: ConfigValue<T>): T {
* Helper function to safely access INI config sections. * Helper function to safely access INI config sections.
* The ini parser can return either a section object or a primitive value, * The ini parser can return either a section object or a primitive value,
* so we need to check the type before accessing nested properties. * so we need to check the type before accessing nested properties.
* *
* @param sectionName - The name of the INI section to access * @param sectionName - The name of the INI section to access
* @returns The section object or undefined if not found or not an object * @returns The section object or undefined if not found or not an object
*/ */
@ -239,15 +239,15 @@ function getIniSection(sectionName: string): IniConfigSection | undefined {
/** /**
* Transform a value to boolean, handling various input formats. * Transform a value to boolean, handling various input formats.
* *
* This function provides flexible boolean parsing to handle different * This function provides flexible boolean parsing to handle different
* configuration sources (environment variables, INI files, etc.): * configuration sources (environment variables, INI files, etc.):
* - String "true"/"false" (case-insensitive) * - String "true"/"false" (case-insensitive)
* - String "1"/"0" * - String "1"/"0"
* - Numeric 1/0 * - Numeric 1/0
* - Actual boolean values * - Actual boolean values
* - Any other value defaults to false * - Any other value defaults to false
* *
* @param value - The value to transform (string, number, boolean, etc.) * @param value - The value to transform (string, number, boolean, etc.)
* @returns The boolean value or false as default * @returns The boolean value or false as default
*/ */
@ -255,28 +255,28 @@ function transformBoolean(value: unknown): boolean {
// First try the standard envToBoolean function which handles "true"/"false" strings // First try the standard envToBoolean function which handles "true"/"false" strings
const result = envToBoolean(String(value)); const result = envToBoolean(String(value));
if (result !== undefined) return result; if (result !== undefined) return result;
// Handle numeric boolean values (both string and number types) // Handle numeric boolean values (both string and number types)
if (value === "1" || value === 1) return true; if (value === "1" || value === 1) return true;
if (value === "0" || value === 0) return false; if (value === "0" || value === 0) return false;
// Default to false for any other value // Default to false for any other value
return false; return false;
} }
/** /**
* Complete configuration mapping that defines how each setting is resolved. * Complete configuration mapping that defines how each setting is resolved.
* *
* This mapping structure: * This mapping structure:
* 1. Mirrors the INI file sections for consistency * 1. Mirrors the INI file sections for consistency
* 2. Defines multiple sources for each configuration value * 2. Defines multiple sources for each configuration value
* 3. Provides type transformers where needed * 3. Provides type transformers where needed
* 4. Maintains compatibility with various environment variable formats * 4. Maintains compatibility with various environment variable formats
* *
* Environment Variable Patterns: * Environment Variable Patterns:
* - Standard: TRILIUM_[SECTION]_[KEY] (e.g., TRILIUM_GENERAL_INSTANCENAME) * - Standard: TRILIUM_[SECTION]_[KEY] (e.g., TRILIUM_GENERAL_INSTANCENAME)
* - Aliases: Shorter alternatives (e.g., TRILIUM_OAUTH_BASE_URL) * - Aliases: Shorter alternatives (e.g., TRILIUM_OAUTH_BASE_URL)
* *
* Both patterns are equally valid and can be used based on preference. * Both patterns are equally valid and can be used based on preference.
* The standard pattern provides consistency, while aliases offer convenience. * The standard pattern provides consistency, while aliases offer convenience.
*/ */
@ -369,7 +369,7 @@ const configMapping = {
standardEnvVar: 'TRILIUM_NETWORK_CORSRESOURCEPOLICY', standardEnvVar: 'TRILIUM_NETWORK_CORSRESOURCEPOLICY',
aliasEnvVars: ['TRILIUM_NETWORK_CORS_RESOURCE_POLICY'], aliasEnvVars: ['TRILIUM_NETWORK_CORS_RESOURCE_POLICY'],
iniGetter: () => getIniSection("Network")?.corsResourcePolicy, iniGetter: () => getIniSection("Network")?.corsResourcePolicy,
defaultValue: 'same-origin' defaultValue: 'same-origin' as 'same-origin' | 'same-site' | 'cross-origin'
} }
}, },
Session: { Session: {
@ -463,13 +463,13 @@ const configMapping = {
/** /**
* Build the final configuration object by resolving all values through the mapping. * Build the final configuration object by resolving all values through the mapping.
* *
* This creates the runtime configuration used throughout the application by: * This creates the runtime configuration used throughout the application by:
* 1. Iterating through each section and key in the mapping * 1. Iterating through each section and key in the mapping
* 2. Calling getConfigValue() to resolve each setting with proper precedence * 2. Calling getConfigValue() to resolve each setting with proper precedence
* 3. Applying type transformers where needed (booleans, integers) * 3. Applying type transformers where needed (booleans, integers)
* 4. Returning a fully typed TriliumConfig object * 4. Returning a fully typed TriliumConfig object
* *
* The resulting config object is immutable at runtime and represents * The resulting config object is immutable at runtime and represents
* the complete application configuration. * the complete application configuration.
*/ */
@ -518,26 +518,26 @@ const config: TriliumConfig = {
* ===================================================================== * =====================================================================
* ENVIRONMENT VARIABLE REFERENCE * ENVIRONMENT VARIABLE REFERENCE
* ===================================================================== * =====================================================================
* *
* Trilium supports flexible environment variable configuration with multiple * Trilium supports flexible environment variable configuration with multiple
* naming patterns. Both formats below are equally valid and can be used * naming patterns. Both formats below are equally valid and can be used
* based on your preference. * based on your preference.
* *
* CONFIGURATION PRECEDENCE: * CONFIGURATION PRECEDENCE:
* 1. Environment variables (highest priority) * 1. Environment variables (highest priority)
* 2. config.ini file values * 2. config.ini file values
* 3. Default values (lowest priority) * 3. Default values (lowest priority)
* *
* FULL FORMAT VARIABLES (following TRILIUM_[SECTION]_[KEY] pattern): * FULL FORMAT VARIABLES (following TRILIUM_[SECTION]_[KEY] pattern):
* ==================================================================== * ====================================================================
* *
* General Section: * General Section:
* - TRILIUM_GENERAL_INSTANCENAME : Custom instance identifier * - TRILIUM_GENERAL_INSTANCENAME : Custom instance identifier
* - TRILIUM_GENERAL_NOAUTHENTICATION : Disable auth (true/false) * - TRILIUM_GENERAL_NOAUTHENTICATION : Disable auth (true/false)
* - TRILIUM_GENERAL_NOBACKUP : Disable backups (true/false) * - TRILIUM_GENERAL_NOBACKUP : Disable backups (true/false)
* - TRILIUM_GENERAL_NODESKTOPICON : No desktop icon (true/false) * - TRILIUM_GENERAL_NODESKTOPICON : No desktop icon (true/false)
* - TRILIUM_GENERAL_READONLY : Read-only mode (true/false) * - TRILIUM_GENERAL_READONLY : Read-only mode (true/false)
* *
* Network Section: * Network Section:
* - TRILIUM_NETWORK_HOST : Bind address (e.g., "0.0.0.0") * - TRILIUM_NETWORK_HOST : Bind address (e.g., "0.0.0.0")
* - TRILIUM_NETWORK_PORT : Server port (e.g., "8080") * - TRILIUM_NETWORK_PORT : Server port (e.g., "8080")
@ -549,15 +549,15 @@ const config: TriliumConfig = {
* - TRILIUM_NETWORK_CORSALLOWMETHODS : CORS allowed HTTP methods * - TRILIUM_NETWORK_CORSALLOWMETHODS : CORS allowed HTTP methods
* - TRILIUM_NETWORK_CORSALLOWHEADERS : CORS allowed headers * - TRILIUM_NETWORK_CORSALLOWHEADERS : CORS allowed headers
* - TRILIUM_NETWORK_CORSRESOURCEPOLICY : CORS Resource Policy * - TRILIUM_NETWORK_CORSRESOURCEPOLICY : CORS Resource Policy
* *
* Session Section: * Session Section:
* - TRILIUM_SESSION_COOKIEMAXAGE : Cookie lifetime in seconds * - TRILIUM_SESSION_COOKIEMAXAGE : Cookie lifetime in seconds
* *
* Sync Section: * Sync Section:
* - TRILIUM_SYNC_SYNCSERVERHOST : Sync server URL * - TRILIUM_SYNC_SYNCSERVERHOST : Sync server URL
* - TRILIUM_SYNC_SYNCSERVERTIMEOUT : Sync timeout in milliseconds * - TRILIUM_SYNC_SYNCSERVERTIMEOUT : Sync timeout in milliseconds
* - TRILIUM_SYNC_SYNCPROXY : Proxy URL for sync * - TRILIUM_SYNC_SYNCPROXY : Proxy URL for sync
* *
* Multi-Factor Authentication Section: * Multi-Factor Authentication Section:
* - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHBASEURL : OAuth base URL * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHBASEURL : OAuth base URL
* - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTID : OAuth client ID * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTID : OAuth client ID
@ -565,24 +565,24 @@ const config: TriliumConfig = {
* - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL : OAuth issuer URL * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL : OAuth issuer URL
* - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME : OAuth provider name * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME : OAuth provider name
* - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON : OAuth provider icon * - TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON : OAuth provider icon
* *
* Logging Section: * Logging Section:
* - TRILIUM_LOGGING_RETENTIONDAYS : Log retention period in days * - TRILIUM_LOGGING_RETENTIONDAYS : Log retention period in days
* *
* SHORTER ALTERNATIVE VARIABLES (equally valid, for convenience): * SHORTER ALTERNATIVE VARIABLES (equally valid, for convenience):
* ================================================================ * ================================================================
* *
* Network CORS (with underscores): * Network CORS (with underscores):
* - TRILIUM_NETWORK_CORS_ALLOW_ORIGIN : Same as TRILIUM_NETWORK_CORSALLOWORIGIN * - TRILIUM_NETWORK_CORS_ALLOW_ORIGIN : Same as TRILIUM_NETWORK_CORSALLOWORIGIN
* - TRILIUM_NETWORK_CORS_ALLOW_METHODS : Same as TRILIUM_NETWORK_CORSALLOWMETHODS * - TRILIUM_NETWORK_CORS_ALLOW_METHODS : Same as TRILIUM_NETWORK_CORSALLOWMETHODS
* - TRILIUM_NETWORK_CORS_ALLOW_HEADERS : Same as TRILIUM_NETWORK_CORSALLOWHEADERS * - TRILIUM_NETWORK_CORS_ALLOW_HEADERS : Same as TRILIUM_NETWORK_CORSALLOWHEADERS
* - TRILIUM_NETWORK_CORS_RESOURCE_POLICY : Same as TRILIUM_NETWORK_CORSRESOURCEPOLICY * - TRILIUM_NETWORK_CORS_RESOURCE_POLICY : Same as TRILIUM_NETWORK_CORSRESOURCEPOLICY
* *
* Sync (with SERVER prefix): * Sync (with SERVER prefix):
* - TRILIUM_SYNC_SERVER_HOST : Same as TRILIUM_SYNC_SYNCSERVERHOST * - TRILIUM_SYNC_SERVER_HOST : Same as TRILIUM_SYNC_SYNCSERVERHOST
* - TRILIUM_SYNC_SERVER_TIMEOUT : Same as TRILIUM_SYNC_SYNCSERVERTIMEOUT * - TRILIUM_SYNC_SERVER_TIMEOUT : Same as TRILIUM_SYNC_SYNCSERVERTIMEOUT
* - TRILIUM_SYNC_SERVER_PROXY : Same as TRILIUM_SYNC_SYNCPROXY * - TRILIUM_SYNC_SERVER_PROXY : Same as TRILIUM_SYNC_SYNCPROXY
* *
* OAuth (simplified without section name): * OAuth (simplified without section name):
* - TRILIUM_OAUTH_BASE_URL : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHBASEURL * - TRILIUM_OAUTH_BASE_URL : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHBASEURL
* - TRILIUM_OAUTH_CLIENT_ID : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTID * - TRILIUM_OAUTH_CLIENT_ID : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTID
@ -590,14 +590,14 @@ const config: TriliumConfig = {
* - TRILIUM_OAUTH_ISSUER_BASE_URL : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL * - TRILIUM_OAUTH_ISSUER_BASE_URL : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL
* - TRILIUM_OAUTH_ISSUER_NAME : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME * - TRILIUM_OAUTH_ISSUER_NAME : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME
* - TRILIUM_OAUTH_ISSUER_ICON : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON * - TRILIUM_OAUTH_ISSUER_ICON : Same as TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON
* *
* Logging (with underscore): * Logging (with underscore):
* - TRILIUM_LOGGING_RETENTION_DAYS : Same as TRILIUM_LOGGING_RETENTIONDAYS * - TRILIUM_LOGGING_RETENTION_DAYS : Same as TRILIUM_LOGGING_RETENTIONDAYS
* *
* BOOLEAN VALUES: * BOOLEAN VALUES:
* - Accept: "true", "false", "1", "0", 1, 0 * - Accept: "true", "false", "1", "0", 1, 0
* - Default to false for invalid values * - Default to false for invalid values
* *
* EXAMPLES: * EXAMPLES:
* export TRILIUM_NETWORK_PORT="8080" # Using full format * export TRILIUM_NETWORK_PORT="8080" # Using full format
* export TRILIUM_OAUTH_CLIENT_ID="my-client-id" # Using shorter alternative * export TRILIUM_OAUTH_CLIENT_ID="my-client-id" # Using shorter alternative
@ -608,23 +608,23 @@ const config: TriliumConfig = {
/** /**
* The exported configuration object used throughout the Trilium application. * The exported configuration object used throughout the Trilium application.
* This object is resolved once at startup and remains immutable during runtime. * This object is resolved once at startup and remains immutable during runtime.
* *
* To override any setting: * To override any setting:
* 1. Set an environment variable (see documentation above) * 1. Set an environment variable (see documentation above)
* 2. Edit config.ini in your data directory * 2. Edit config.ini in your data directory
* 3. Defaults will be used if neither is provided * 3. Defaults will be used if neither is provided
* *
* @example * @example
* // Accessing configuration in other modules: * // Accessing configuration in other modules:
* import config from './services/config.js'; * import config from './services/config.js';
* *
* if (config.General.noAuthentication) { * if (config.General.noAuthentication) {
* // Skip authentication checks * // Skip authentication checks
* } * }
* *
* const server = https.createServer({ * const server = https.createServer({
* cert: fs.readFileSync(config.Network.certPath), * cert: fs.readFileSync(config.Network.certPath),
* key: fs.readFileSync(config.Network.keyPath) * key: fs.readFileSync(config.Network.keyPath)
* }); * });
*/ */
export default config; export default config;