env variables handling

This commit is contained in:
cpu
2025-03-31 01:26:50 +02:00
parent c2e7bd5f1e
commit 51a1be22d2
15 changed files with 209 additions and 106 deletions

View File

@@ -49,9 +49,11 @@ build/
# We need .env for our application
#.env
.env.*
# Don't ignore config.env.js
!config.env.js
# Project specific files
dev-start.sh
labels.example
virt-game-timer.service
package.json

1
.gitignore vendored
View File

@@ -19,6 +19,7 @@ yarn-error.log*
.env.development.local
.env.test.local
.env.production.local
config.env.js
# Editor directories and files
.idea/

View File

@@ -1,14 +1,35 @@
# Use a lightweight server
FROM nginx:alpine
# Install bash for the script execution
RUN apk add --no-cache bash
# Set working directory
WORKDIR /usr/share/nginx/html
# Copy all the application files
COPY . .
# Copy the .env file
COPY .env .
# Create a simple script to generate config.env.js
RUN echo '#!/bin/sh' > /usr/share/nginx/html/docker-generate-config.sh && \
echo 'echo "// config.env.js - Generated from .env" > config.env.js' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo 'echo "// This file contains environment variables for the PWA" >> config.env.js' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo 'echo "// Generated on $(date)" >> config.env.js' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo 'echo "" >> config.env.js' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo 'echo "window.ENV_CONFIG = {" >> config.env.js' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo 'grep -v "^#" .env | grep "=" | while read line; do' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo ' key=$(echo $line | cut -d= -f1)' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo ' value=$(echo $line | cut -d= -f2-)' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo ' echo " $key: \"$value\"," >> config.env.js' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo 'done' >> /usr/share/nginx/html/docker-generate-config.sh && \
echo 'echo "};" >> config.env.js' >> /usr/share/nginx/html/docker-generate-config.sh && \
chmod +x /usr/share/nginx/html/docker-generate-config.sh
# Generate config.env.js from .env
RUN /usr/share/nginx/html/docker-generate-config.sh
# Remove the .env file and the generation script for security
RUN rm .env docker-generate-config.sh
# Expose port 80
EXPOSE 80

View File

@@ -27,7 +27,7 @@ game-timer/
## Environment Variables
The application uses environment variables for configuration. These are loaded from a `.env` file at runtime.
The application uses environment variables for configuration. These are loaded from a `.env` file and converted to a `config.env.js` file that is served by the web server.
### Setting Up Environment Variables
@@ -45,7 +45,12 @@ The application uses environment variables for configuration. These are loaded f
BACKEND_URL=https://your-push-server.example.com
```
3. For security, never commit your `.env` file to version control. It's already included in `.gitignore`.
3. Generate the `config.env.js` file using the provided script:
```bash
./generate-config.sh
```
4. For security, never commit your `.env` file to version control. It's already included in `.gitignore`.
### Generating VAPID Keys

30
dev-start.sh Executable file
View File

@@ -0,0 +1,30 @@
#!/bin/bash
# Script to start a local development server with environment variables
# Check if .env file exists
if [ ! -f .env ]; then
echo "Error: .env file not found!"
echo "Please create a .env file based on .env.example"
exit 1
fi
# Generate config.env.js from .env
echo "Generating config.env.js from .env..."
./generate-config.sh
# Start a local development server
echo "Starting development server..."
if command -v python3 &> /dev/null; then
echo "Using Python3 HTTP server on port 8000..."
python3 -m http.server 8000
elif command -v python &> /dev/null; then
echo "Using Python HTTP server on port 8000..."
python -m SimpleHTTPServer 8000
elif command -v npx &> /dev/null; then
echo "Using npx serve on port 8000..."
npx serve -l 8000
else
echo "Error: Could not find a suitable static file server."
echo "Please install Python or Node.js, or manually start a server."
exit 1
fi

39
generate-config.sh Executable file
View File

@@ -0,0 +1,39 @@
#!/bin/bash
# Script to generate config.env.js from .env file
# Usage: ./generate-config.sh
# Check if .env file exists
if [ ! -f .env ]; then
echo "Error: .env file not found!"
echo "Please create a .env file based on .env.example"
exit 1
fi
echo "Generating config.env.js from .env..."
# Create config.env.js file
echo "// config.env.js - Generated from .env" > config.env.js
echo "// This file contains environment variables for the PWA" >> config.env.js
echo "// Generated on $(date)" >> config.env.js
echo "" >> config.env.js
echo "window.ENV_CONFIG = {" >> config.env.js
# Read .env file line by line
while IFS="=" read -r key value || [ -n "$key" ]; do
# Skip comments and empty lines
[[ $key =~ ^#.*$ ]] && continue
[[ -z $key ]] && continue
# Remove quotes if present
value="${value%\"}"
value="${value#\"}"
value="${value%\'}"
value="${value#\'}"
# Add the key-value pair to config.env.js
echo " $key: \"$value\"," >> config.env.js
done < .env
echo "};" >> config.env.js
echo "config.env.js generated successfully!"

View File

@@ -154,6 +154,9 @@
</div>
</div>
<!-- Load environment configuration first -->
<script src="/config.env.js"></script>
<!-- Main application script -->
<script type="module" src="/js/app.js"></script>
<script>
@@ -214,7 +217,7 @@
let backendUrl;
try {
const configModule = await import('/js/config.js');
backendUrl = configModule.BACKEND_URL;
backendUrl = configModule.getBackendUrl();
} catch (error) {
output.textContent = 'Failed to load backend URL. Please check configuration.\n';
return;

View File

@@ -4,7 +4,6 @@ import * as state from './core/state.js';
import * as ui from './ui/ui.js';
import * as timer from './core/timer.js';
import camera from './ui/camera.js'; // Default export
import { initEnv } from './env-loader.js';
import * as pushSettingsUI from './ui/pushSettingsUI.js'; // Import the new push settings UI module
// Import externalized modules
@@ -21,8 +20,13 @@ async function initialize() {
// 0. Wait for environment variables to load
try {
await initEnv();
console.log("Environment variables loaded");
// Use the ensureEnvLoaded function from config.js to make sure environment variables are loaded
await config.ensureEnvLoaded();
console.log("Environment variables loaded and verified");
// Log the loaded environment variables for debugging
console.log("BACKEND_URL:", config.getBackendUrl());
console.log("PUBLIC_VAPID_KEY:", config.getPublicVapidKey());
} catch (error) {
console.warn("Failed to load environment variables, using defaults:", error);
}

View File

@@ -1,16 +1,36 @@
// config.js
import { getEnv } from './env-loader.js';
import { getEnv, waitForEnv } from './env-loader.js';
// Initialize environment variables
let envInitialized = false;
let initPromise = null;
// Function to ensure environment variables are loaded
export async function ensureEnvLoaded() {
if (envInitialized) return;
if (!initPromise) {
initPromise = waitForEnv().then(() => {
envInitialized = true;
console.log('Environment variables loaded in config.js');
});
}
return initPromise;
}
// Initialize immediately
ensureEnvLoaded();
// Direct access to environment variables (synchronous, may return default values if called too early)
export function getPublicVapidKey() {
// Get the VAPID key from environment variables through the env-loader
return getEnv('PUBLIC_VAPID_KEY');
}
// The VAPID key should not be exposed directly in the source code
// Use the getter function instead: getPublicVapidKey()
export function getBackendUrl() {
return getEnv('BACKEND_URL');
}
// Get backend URL from environment variables
export const BACKEND_URL = getEnv('BACKEND_URL');
export const FLIC_BUTTON_ID = 'game-button'; // Example ID, might need configuration
export const LOCAL_STORAGE_KEY = 'gameTimerData';

View File

@@ -1,71 +1,47 @@
// env-loader.js
// This module is responsible for loading environment variables from .env file
// This module is responsible for loading environment variables for the PWA
// Store environment variables in a global object
window.ENV_CONFIG = {};
// Function to load environment variables from .env file
async function loadEnvVariables() {
try {
// Fetch the .env file as text
const response = await fetch('/.env');
if (!response.ok) {
console.warn('Could not load .env file. Using default values.');
setDefaultEnvValues();
return;
}
const envText = await response.text();
// Parse the .env file content
const envVars = parseEnvFile(envText);
// Store in the global ENV_CONFIG object
window.ENV_CONFIG = { ...window.ENV_CONFIG, ...envVars };
console.log('Environment variables loaded successfully');
} catch (error) {
console.error('Error loading environment variables:', error);
setDefaultEnvValues();
}
}
// Parse .env file content into key-value pairs
function parseEnvFile(envText) {
const envVars = {};
// Split by lines and process each line
envText.split('\n').forEach(line => {
// Skip empty lines and comments
if (!line || line.trim().startsWith('#')) return;
// Extract key-value pairs
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
if (match) {
const key = match[1];
let value = match[2] || '';
// Remove quotes if present
if (value.startsWith('"') && value.endsWith('"')) {
value = value.slice(1, -1);
}
envVars[key] = value;
}
});
return envVars;
}
// Set default values for required environment variables
function setDefaultEnvValues() {
window.ENV_CONFIG = {
...window.ENV_CONFIG,
// Default values that will be overridden when config.env.js loads
PUBLIC_VAPID_KEY: 'your_public_vapid_key_here',
BACKEND_URL: 'https://your-push-server.example.com'
};
console.log('Using default environment values');
// Function to load environment variables from config.env.js
async function loadEnvVariables() {
try {
// Try to fetch the config.env.js file which will be generated at build time or deployment
const response = await fetch('/config.env.js');
if (!response.ok) {
console.warn('Could not load config.env.js file. Using default values.');
return;
}
const configText = await response.text();
// Extract the configuration object from the JavaScript file
// The file should be in format: window.ENV_CONFIG = { key: "value" };
try {
// Create a safe way to evaluate the config file
const configScript = document.createElement('script');
configScript.textContent = configText;
document.head.appendChild(configScript);
document.head.removeChild(configScript);
console.log('Environment variables loaded successfully from config.env.js');
// Dispatch an event to notify that environment variables have been loaded
window.dispatchEvent(new CustomEvent('env-config-loaded', {
detail: { config: window.ENV_CONFIG }
}));
} catch (parseError) {
console.error('Error parsing config.env.js:', parseError);
}
} catch (error) {
console.error('Error loading environment variables:', error);
}
}
// Export function to initialize environment variables
@@ -74,7 +50,7 @@ export async function initEnv() {
return window.ENV_CONFIG;
}
// Auto-initialize when imported
// Start loading environment variables immediately
initEnv();
// Export access functions for environment variables
@@ -82,7 +58,30 @@ export function getEnv(key, defaultValue = '') {
return window.ENV_CONFIG[key] || defaultValue;
}
// Export a function to wait for environment variables to be loaded
export function waitForEnv() {
return new Promise((resolve) => {
// If we already have non-default values, resolve immediately
if (window.ENV_CONFIG.BACKEND_URL !== 'https://your-push-server.example.com') {
resolve(window.ENV_CONFIG);
return;
}
// Otherwise, wait for the env-config-loaded event
window.addEventListener('env-config-loaded', (event) => {
resolve(event.detail.config);
}, { once: true });
// Set a timeout to resolve with current values if loading takes too long
setTimeout(() => {
console.warn('Environment loading timed out, using current values');
resolve(window.ENV_CONFIG);
}, 3000);
});
}
export default {
initEnv,
getEnv
getEnv,
waitForEnv
};

View File

@@ -1,5 +1,5 @@
// pushFlicIntegration.js
import { getPublicVapidKey, BACKEND_URL, FLIC_BUTTON_ID, FLIC_ACTIONS } from '../config.js';
import { getPublicVapidKey, getBackendUrl, FLIC_BUTTON_ID} from '../config.js';
let pushSubscription = null; // Keep track locally if needed
let actionHandlers = {}; // Store handlers for different Flic actions
@@ -28,19 +28,6 @@ function getBasicAuthCredentials() {
return null;
}
// Prompt the user for credentials after permissions are granted
function promptForCredentials() {
console.log('Prompting user for auth credentials.');
const username = prompt('Please enter your username for backend authentication:');
if (!username) return null;
const password = prompt('Please enter your password:');
if (!password) return null;
const credentials = { username, password };
localStorage.setItem('basicAuthCredentials', JSON.stringify(credentials));
return credentials;
}
// Create Basic Auth header string
function createBasicAuthHeader(credentials) {
if (!credentials?.username || !credentials.password) return null;
@@ -167,7 +154,9 @@ async function sendSubscriptionToServer(subscription, buttonId) {
try {
// Add support for handling CORS preflight with credentials
const response = await fetch(`${BACKEND_URL}/subscribe`, {
console.log("BACKEND_URL Key: " + getBackendUrl());
console.log("FLIC_BUTTON_ID Key: " + FLIC_BUTTON_ID);
const response = await fetch(`${getBackendUrl()}/subscribe`, {
method: 'POST',
body: JSON.stringify({ button_id: buttonId, subscription: subscription }),
headers: headers,

View File

@@ -1,5 +1,4 @@
// serviceWorkerManager.js - Service worker registration and Flic integration
import * as config from '../config.js';
import * as pushFlic from './pushFlicIntegration.js';
// Store the action handlers passed from app.js

View File

@@ -1,6 +1,6 @@
// pushSettingsUI.js - UI handling for push notification settings
import { setupPushNotifications } from '../services/serviceWorkerManager.js';
import { FLIC_BUTTON_ID } from '../config.js';
import { FLIC_BUTTON_ID, getBackendUrl} from '../config.js';
// --- DOM Elements ---
const elements = {
@@ -381,20 +381,9 @@ export async function sendSubscriptionToServer() {
'Authorization': createBasicAuthHeader(credentials)
};
// Import the backend URL from config
let backendUrl;
try {
const configModule = await import('../config.js');
backendUrl = configModule.BACKEND_URL;
} catch (error) {
// No alert, just log the error and return
console.error('Could not get backend URL from config:', error);
return;
}
try {
// Make the request to the server
const response = await fetch(`${backendUrl}/subscribe`, {
const response = await fetch(`${getBackendUrl()}/subscribe`, {
method: 'POST',
body: JSON.stringify({
button_id: FLIC_BUTTON_ID,

View File

@@ -7,7 +7,9 @@
"docker:build": "docker build -t 'game-timer:latest' .",
"start": "docker run -d -p 80:80 --name game-timer game-timer:latest",
"stop": "docker stop game-timer && docker rm game-timer",
"rebuild": "npm run stop || true && npm run docker:build && npm run start"
"rebuild": "npm run stop || true && npm run docker:build && npm run start",
"generate-config": "./generate-config.sh",
"dev": "./dev-start.sh"
},
"keywords": [
"timer",

View File

@@ -163,8 +163,8 @@
// Get backend URL from config or use a default
let backendUrl;
try {
const configModule = await import('./src/js/config.js');
backendUrl = configModule.BACKEND_URL;
const configModule = await import('./js/config.js');
backendUrl = configModule.getBackendUrl();
} catch (error) {
backendUrl = prompt('Enter backend URL:', 'https://your-backend-url.com');
if (!backendUrl) return;