From 9b4bf1e2553c8900c463c98243317195bdb1dc2e Mon Sep 17 00:00:00 2001 From: cpu Date: Wed, 26 Mar 2025 19:12:43 +0100 Subject: [PATCH] flask and node.js solution --- .dockerignore | 8 + .env | 29 +- .env.example | 30 ++ .gitignore | 19 +- Dockerfile | 33 +- README.md | 288 ++++++++----- app.py | 273 ------------ generate_vapid_keys.py | 103 ----- labels.example | 29 ++ package-lock.json | 926 +++++++++++++++++++++++++++++++++++++++++ package.json | 25 ++ requirements.txt | 4 - server.js | 193 +++++++++ 13 files changed, 1445 insertions(+), 515 deletions(-) create mode 100644 .dockerignore create mode 100644 .env.example delete mode 100644 app.py delete mode 100644 generate_vapid_keys.py create mode 100644 labels.example create mode 100644 package-lock.json create mode 100644 package.json delete mode 100644 requirements.txt create mode 100644 server.js diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8b30b24 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +node_modules +npm-debug.log +Dockerfile +.dockerignore +.git +.gitignore +README.md +*.example \ No newline at end of file diff --git a/.env b/.env index 3f76dfe..1869866 100644 --- a/.env +++ b/.env @@ -1,6 +1,14 @@ -# VAPID Keys for Web Push -VAPID_PRIVATE_KEY= -VAPID_PUBLIC_KEY= +# --- Application Configuration --- + +# --- VAPID Keys (REQUIRED for Web Push) --- +# Generate these once using npx web-push generate-vapid-keys (or other tools) +# Keep the private key SECRET! +VAPID_PUBLIC_KEY="BKfRJXjSQmAJ452gLwlK_8scGrW6qMU1mBRp39ONtcQHkSsQgmLAaODIyGbgHyRpnDEv3HfXV1oGh3SC0fHxY0E" +VAPID_PRIVATE_KEY="ErEgsDKYQi5j2KPERC_gCtrEALAD0k-dWSwrrcD0-JU" + +# Subject claim for VAPID. Use a 'mailto:' URI or an 'https:' URL identifying your application. +# Example: mailto:admin@yourdomain.com or https://yourdomain.com/contact +VAPID_SUBJECT="mailto:admin@virtonline.eu" # Flic Button Configuration FLIC_BUTTON1_SERIAL=your_button1_serial @@ -8,10 +16,17 @@ FLIC_BUTTON2_SERIAL=your_button2_serial FLIC_BUTTON3_SERIAL=your_button3_serial # Subscription Storage -SUBSCRIPTIONS_FILE=data/subscriptions.json +SUBSCRIPTIONS_FILE=subscriptions.json + +# CORS +ALLOWED_ORIGINS=https://game-timer.virtonline.eu +ALLOWED_METHODS=POST,OPTIONS +ALLOWED_HEADERS=Content-Type,Authorization # Logging Configuration -LOG_LEVEL=INFO +LOG_LEVEL=DEBUG -# VAPID Claim Email -VAPID_CLAIM_EMAIL=mailto:your-email@example.com +# --- Security (Optional) --- +# If you want to add a simple security layer between Flic and this app. +# If set, configure Flic's HTTP request to include an "Authorization: Bearer YOUR_SECRET_VALUE" header. +# FLIC_SECRET="replace_with_a_strong_secret_if_needed" \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..29bb1bf --- /dev/null +++ b/.env.example @@ -0,0 +1,30 @@ +# --- VAPID Keys --- +# Generate using: npx web-push generate-vapid-keys +# The Public Key is needed by your PWA to subscribe. +VAPID_PUBLIC_KEY=YOUR_VAPID_PUBLIC_KEY +# The Private Key MUST be kept secret on the server. +VAPID_PRIVATE_KEY=YOUR_VAPID_PRIVATE_KEY +# A contact URL for the push service (mailto: or https:) +VAPID_SUBJECT=mailto:admin@yourdomain.com + +# --- Application Settings --- +# Port the Node.js server will listen on inside the container +PORT=3000 +# Path to the JSON file storing Flic button serial -> PWA subscription mappings +SUBSCRIPTIONS_FILE=/app/subscriptions.json + +# --- Security --- +# (Optional) A secret bearer token. If set, Flic requests must include "Authorization: Bearer " header. +# Generate a strong secret, e.g., using: openssl rand -hex 32 +FLIC_SECRET=YOUR_OPTIONAL_FLIC_SECRET_TOKEN + +# --- CORS Settings --- +# Comma-separated list of allowed origins for CORS requests (e.g., your PWA's domain) +# Leave empty or unset to allow any origin (less secure, useful for testing) +# Example: ALLOWED_ORIGINS=https://pwa.yourdomain.com,http://localhost:8080 +ALLOWED_ORIGINS=https://game-timer.virtonline.eu +# Comma-separated list of allowed HTTP methods +ALLOWED_METHODS=POST,OPTIONS +# Comma-separated list of allowed HTTP headers +ALLOWED_HEADERS=Content-Type,Authorization + diff --git a/.gitignore b/.gitignore index 0be424f..2d96022 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,20 @@ myenv .vscode -subscriptions.json \ No newline at end of file + +# Node.js +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +*.env +subscriptions.json +labels + +# OS generated files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index eb52393..43ad70b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,26 +1,23 @@ -FROM python:3.11-slim +# Use an official Node.js runtime as a parent image +# Alpine Linux is chosen for its small size +FROM node:20-alpine -# Set working directory +# Set the working directory in the container WORKDIR /app -# Install system dependencies -RUN apt-get update && apt-get install -y \ - && rm -rf /var/lib/apt/lists/* +# Copy package.json and package-lock.json (if available) +COPY package*.json ./ -# Copy requirements file -COPY requirements.txt . +# Install app dependencies using npm ci for faster, reliable builds +# Use --only=production to avoid installing devDependencies +RUN npm ci --only=production -# Install Python dependencies -RUN pip install --no-cache-dir -r requirements.txt - -# Copy application files +# Copy the rest of the application code COPY . . -# Generate VAPID keys if .env doesn't exist -RUN if [ ! -f .env ]; then python generate_vapid_keys.py; fi +# Make port 3000 available to the world outside this container +# This is the port our Node.js app will listen on +EXPOSE 3000 -# Expose the application port -EXPOSE 8080 - -# Command to run the application -CMD ["python", "app.py"] +# Define the command to run your app using CMD which defines your runtime +CMD [ "node", "server.js" ] \ No newline at end of file diff --git a/README.md b/README.md index 5c87b07..50d3601 100644 --- a/README.md +++ b/README.md @@ -1,133 +1,203 @@ -# Flic Button Web Push Notification Service +# Flic to PWA WebPush Backend -## Overview -This application provides a dockerized solution for handling Flic smart button events and sending web push notifications to a Progressive Web App (PWA). +This project provides a self-hosted backend service that listens for HTTP requests from Flic smart buttons and triggers Web Push notifications to specific Progressive Web App (PWA) instances. The goal is to allow a Flic button press (Single Click, Double Click, Hold) to trigger actions within the PWA via push messages handled by a Service Worker. + +It's designed to be run as a Docker container and integrated with Traefik v3 for SSL termination and routing. ## Features -- Webhook endpoint for Flic button events -- Web Push notification support -- Configurable button actions -- Subscription management + +* Receives POST requests on `/flic-webhook`. +* Parses `button_id` and `click_type` from the Flic request body. +* Looks up the target PWA push subscription based on `button_id` in a JSON file. +* Sends a Web Push notification containing the click details (action, button, timestamp) to the corresponding PWA subscription. +* Integrates with Traefik v3 via Docker labels. +* Configurable via environment variables (`.env` file). +* Optional bearer token authentication for securing the Flic webhook endpoint. +* CORS configuration for allowing requests (needed if your PWA management interface interacts with this service, although not strictly necessary for the Flic->Backend->PWA push flow itself). ## Prerequisites -- Docker -- Docker Compose -- Traefik network -- Curl or Postman for testing + +* **Docker:** [Install Docker](https://docs.docker.com/engine/install/) +* **Traefik:** A running Traefik v3 instance configured with SSL (Let's Encrypt recommended) and connected to a Docker network named `traefik`. You need to know your certificate resolver name. +* **Domain Name:** A domain or subdomain pointing to your Traefik instance (e.g., `webpush.virtonline.eu`). This will be used for the webhook URL. +* **Flic Hub/Service:** Configured to send HTTP requests for button actions. You'll need the serial number(s) of your Flic button(s). +* **Node.js & npm/npx (Optional):** Needed only locally to generate VAPID keys easily. Not required for running the container. +* **PWA Push Subscription Details:** You need to obtain the Push Subscription object (containing `endpoint`, `keys.p256dh`, `keys.auth`) from your PWA after the user grants notification permission. + +## Project Structure ## Setup -### 1. Generate VAPID Keys -Run the VAPID key generation script: -```bash -python generate_vapid_keys.py -``` -This will create a `.env` file with VAPID keys. +1. **Clone the Repository:** + ```bash + git clone https://gitea.virtonline.eu/2HoursProject/flic-webhook-webpush.git + cd flic-webhook-webpush + ``` -### 2. Configure Flic Buttons -Edit the `.env` file to add your Flic button serial numbers: -``` -FLIC_BUTTON1_SERIAL=your_button1_serial -FLIC_BUTTON2_SERIAL=your_button2_serial -FLIC_BUTTON3_SERIAL=your_button3_serial -``` +2. **Generate VAPID Keys:** + Web Push requires VAPID keys for security. Generate them once and store them into `.env`. You can use `npx`: + ```bash + npx web-push generate-vapid-keys + ``` + This will output a Public Key and a Private Key. -### 3. Docker Compose Configuration -```yaml -version: '3' -services: - flic-webpush: - build: . - volumes: - - ./subscriptions.json:/app/subscriptions.json - networks: - - traefik - labels: - - "traefik.enable=true" - - "traefik.http.routers.flic-webpush.rule=Host(`flic.yourdomain.com`)" +3. **Obtain PWA Push Subscription Details:** + * Your PWA needs to use the Push API to request notification permission from the user. + * When permission is granted, the browser's push service provides a `PushSubscription` object. + * This object typically looks like: + ```json + { + "endpoint": "https://updates.push.services.mozilla.com/...", + "expirationTime": null, + "keys": { + "p256dh": "...", + "auth": "..." + } + } + ``` + * You need to get this JSON object from your PWA (e.g., display it to the user to copy, send it to a setup endpoint - though that's more complex). -networks: - traefik: - external: true -``` +4. **Configure Environment Variables:** + * Copy the example `.env` file: + ```bash + cp .env.example .env + ``` + * Edit the `.env` file with your specific values: + * `VAPID_PUBLIC_KEY`: The public key generated in step 2. **Your PWA will also need this key** when it subscribes to push notifications. + * `VAPID_PRIVATE_KEY`: The private key generated in step 2. **Keep this secret!** + * `VAPID_SUBJECT`: A `mailto:` or `https:` URL identifying you or your application (e.g., `mailto:admin@yourdomain.com`). Used by push services to contact you. + * `PORT`: (Default: `3000`) The internal port the Node.js app listens on. Traefik will map to this. + * `SUBSCRIPTIONS_FILE`: (Default: `/app/subscriptions.json`) The path *inside the container* where the button-to-subscription mapping is stored. + * `FLIC_SECRET`: (Optional) Set a strong, random secret string if you want to secure the webhook endpoint using Bearer token authentication. Generate with `openssl rand -hex 32` or a password manager. + * `ALLOWED_ORIGINS`: Comma-separated list of domains allowed by CORS. Include your PWA's domain if it needs to interact directly (e.g., for setup). Example: `https://my-pwa.com`. + * `ALLOWED_METHODS`: (Default: `POST,OPTIONS`) Standard methods needed. + * `ALLOWED_HEADERS`: (Default: `Content-Type,Authorization`) Standard headers needed. + * `TRAEFIK_SERVICE_HOST`: Your public domain for this service (e.g., `webpush.virtonline.eu`). + * `TRAEFIK_CERT_RESOLVER`: The name of your TLS certificate resolver configured in Traefik (e.g., `le`, `myresolver`). -### 4. Endpoints -- `/flic-webhook`: Receive Flic button events -- `/subscribe`: Add web push subscriptions +5. **Configure Traefik Labels:** + * Copy the example `labels` file: + ```bash + cp labels.example labels + ``` + * **Important:** Edit the `labels` file. Replace `${TRAEFIK_SERVICE_HOST}`, `${TRAEFIK_CERT_RESOLVER}`, and `${PORT}` with the *actual values* from your `.env` file, as `docker run` does not substitute variables in label files. + * Example replacement: `Host(\`${TRAEFIK_SERVICE_HOST}\`)` becomes `Host(`webpush.virtonline.eu`)`. + * `traefik.http.routers.flic-webhook.tls.certresolver=${TRAEFIK_CERT_RESOLVER}` becomes `traefik.http.routers.flic-webhook.tls.certresolver=myresolver`. + * `traefik.http.services.flic-webhook.loadbalancer.server.port=${PORT}` becomes `traefik.http.services.flic-webhook.loadbalancer.server.port=3000`. -## Testing Webhooks +6. **Prepare Subscription Mapping File:** + * Create the `subscriptions.json` file (or edit the template provided). + * Add entries mapping your Flic button's serial number (as a lowercase string key) to the PWA `PushSubscription` object obtained in step 3. + ```json + { + "80:e4:da:70:xx:xx:xx:xx": { // <-- Replace with your actual Flic Button Serial (lowercase recommended) + "endpoint": "https://your_pwa_push_endpoint...", + "expirationTime": null, + "keys": { + "p256dh": "YOUR_PWA_SUBSCRIPTION_P256DH_KEY", + "auth": "YOUR_PWA_SUBSCRIPTION_AUTH_KEY" + } + } + // Add more entries for other buttons if needed + } + ``` + * Ensure this file contains valid JSON. -### Simulating Flic Button Events -You can test the webhook endpoint using curl or Postman. Here are example requests: +## Running the Service -#### Button 1 Event (Home Lights On) -```bash -curl -X POST http://localhost:8080/flic-webhook \ - -H "Content-Type: application/json" \ - -d '{ - "serial": "your_button1_serial", - "event": "click", - "timestamp": "'$(date -u +"%Y-%m-%dT%H:%M:%SZ")'" - }' -``` +1. **Build the Docker Image:** + Make sure you are in the `flic-webhook-webpush` directory. + ```bash + docker build -t flic-webhook-webpush:latest . + ``` -#### Button 2 Event (Security System Arm) -```bash -curl -X POST http://localhost:8080/flic-webhook \ - -H "Content-Type: application/json" \ - -d '{ - "serial": "your_button2_serial", - "event": "double_click", - "timestamp": "'$(date -u +"%Y-%m-%dT%H:%M:%SZ")'" - }' -``` +2. **Run the Container:** + This command runs the container in detached mode (`-d`), names it, connects it to the `traefik` network, passes environment variables from the `.env` file, applies the Traefik labels from the `labels` file, and mounts the `subscriptions.json` file into the container. -#### Button 3 Event (Panic Alert) -```bash -curl -X POST http://localhost:8080/flic-webhook \ - -H "Content-Type: application/json" \ - -d '{ - "serial": "your_button3_serial", - "event": "long_press", - "timestamp": "'$(date -u +"%Y-%m-%dT%H:%M:%SZ")'" - }' -``` + ```bash + docker run -d --name flic-webhook-webpush \ + --network traefik \ + --env-file .env \ + --label-file labels \ + --mount type=bind,src=./subscriptions.json,dst=/app/subscriptions.json,readonly \ + flic-webhook-webpush:latest + ``` + * `--network traefik`: Connects to the Traefik network. + * `--env-file .env`: Loads configuration from your `.env` file. + * `--label-file labels`: Applies the Traefik routing rules from your edited `labels` file. + * `--mount ...`: Makes your local `subscriptions.json` available inside the container at `/app/subscriptions.json`. `readonly` is recommended as the app only reads it. + * `flic-webhook-webpush:latest`: The image built in the previous step. -### Adding a Web Push Subscription -To test the subscription endpoint: -```bash -curl -X POST http://localhost:8080/subscribe \ - -H "Content-Type: application/json" \ - -d '{ - "endpoint": "https://example.com/push-endpoint", - "keys": { - "p256dh": "base64-public-key", - "auth": "base64-auth-secret" - } - }' -``` +3. **Check Logs:** + Monitor the container logs to ensure it started correctly and to see incoming webhook requests or errors. + ```bash + docker logs -f flic-webhook-webpush + ``` + You should see messages indicating the server started, configuration details, and subscription loading status. -### Debugging Tips -- Check container logs: `docker logs flic-webpush` -- Verify subscription file: `cat subscriptions.json` -- Ensure correct button serial numbers in `.env` +4. **Verify Traefik:** Check your Traefik dashboard to ensure the `flic-webhook-webpush` service and router are discovered and healthy. -## Button Actions -- Button 1: Home Lights On -- Button 2: Security System Arm -- Button 3: Panic Alert +## Flic Button Configuration -## Logging -Configurable via `LOG_LEVEL` in `.env` +In your Flic app or Flic Hub SDK interface: -## Security Considerations -- Keep VAPID keys secret -- Use HTTPS -- Validate and sanitize all incoming webhook requests -- Implement proper authentication for production use +1. Select your Flic button. +2. Add an "Internet Request" action (or similar HTTP request action) for Single Click, Double Click, and/or Hold events. +3. **URL:** `https:///flic-webhook` (e.g., `https://webpush.virtonline.eu/flic-webhook`) +4. **Method:** `POST` +5. **Body Type:** `JSON` (or `application/json`) +6. **Body:** Configure the JSON body to include the button's serial number and the click type. Flic usually provides variables for these. The backend expects `button_id` and `click_type`. Adapt the keys if needed, or modify `server.js` to expect different keys (e.g., `serialNumber`). + ```json + { + "button_id": "{serialNumber}", + "click_type": "{clickType}", + "timestamp": "{timestamp}" + } + ``` + *(Verify the exact variable names like `{serialNumber}`, `{clickType}`, `{timestamp}` within your specific Flic interface.)* +7. **Headers:** + * Add `Content-Type: application/json`. + * **(Optional - if `FLIC_SECRET` is set):** Add an `Authorization` header: + * Key: `Authorization` + * Value: `Bearer ` (Replace `` with the actual secret from your `.env` file). + +## API Endpoint + +* **`POST /flic-webhook`** + * **Description:** Receives Flic button events. + * **Authentication:** Optional Bearer token via `Authorization` header if `FLIC_SECRET` is configured. + * **Request Body (JSON):** + ```json + { + "button_id": "SERIAL_NUMBER_OF_FLIC_BUTTON", + "click_type": "SingleClick | DoubleClick | Hold", + "timestamp": "ISO_8601_TIMESTAMP_STRING (Optional)" + } + ``` + * **Responses:** + * `200 OK`: Webhook received, push notification sent successfully. + * `400 Bad Request`: Missing `button_id` or `click_type` in the request body. + * `401 Unauthorized`: Missing or invalid Bearer token (if `FLIC_SECRET` is enabled). + * `404 Not Found`: No subscription found in `subscriptions.json` for the given `button_id`. + * `410 Gone`: The push subscription associated with the button was rejected by the push service (likely expired or revoked). + * `500 Internal Server Error`: Failed to send the push notification for other reasons. + +* **`GET /health`** (Optional) + * **Description:** Simple health check endpoint. + * **Response:** + ```json + { + "status": "UP", + "timestamp": "ISO_8601_TIMESTAMP_STRING" + } + ``` ## Troubleshooting -- Ensure all environment variables are correctly set -- Check network connectivity -- Verify Traefik configuration -- Validate button serial numbers match between configuration and webhook \ No newline at end of file + +* **Check Backend Logs:** `docker logs flic-webhook-webpush`. Look for errors related to configuration, file access, JSON parsing, authentication, or sending push notifications. +* **Check Traefik Logs:** `docker logs traefik`. Look for routing errors or certificate issues. +* **Verify `.env`:** Ensure all required variables are set correctly, especially VAPID keys and Traefik settings. +* **Verify `labels`:** Double-check that variables were correctly substituted manually and match your `.env` and Traefik setup. +* **Verify `subscriptions.json`:** Ensure it's valid JSON and the button serial number (key) matches exactly what Flic sends (check backend logs for "Received webhook: Button=..."). Check if the subscription details are correct. Case sensitivity matters for the JSON keys (button serials). +* **Check Flic Configuration:** Ensure the URL, Method, Body, and Headers (especially `Content-Type` and `Authorization` if used) are correct in the Flic action setup. Use `curl` or Postman to test the endpoint manually first. +* **PWA Service Worker:** Remember that the PWA needs a correctly registered Service Worker to receive and handle the incoming push messages. Ensure the PWA subscribes using the *same* `VAPID_PUBLIC_KEY` configured in the backend's `.env`. \ No newline at end of file diff --git a/app.py b/app.py deleted file mode 100644 index 9c54d3f..0000000 --- a/app.py +++ /dev/null @@ -1,273 +0,0 @@ -import asyncio -import json -import logging -import os -import base64 -from typing import Dict, List -import signal -import pathlib - -import aiohttp -from aiohttp import web -from dotenv import load_dotenv -from pywebpush import webpush, WebPushException -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.asymmetric import ec - -# Load environment variables -load_dotenv() - -# Configure logging -logging.basicConfig( - level=getattr(logging, os.getenv('LOG_LEVEL', 'INFO')), - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' -) -logger = logging.getLogger(__name__) - -# CORS Configuration -ALLOWED_ORIGINS = [ - "https://game-timer.virtonline.eu", - # Add other allowed origins if needed -] -ALLOWED_METHODS = ["POST", "OPTIONS"] -ALLOWED_HEADERS = ["Content-Type"] - -class FlicButtonHandler: - def __init__(self): - # Load button configurations - self.button_configs = { - os.getenv('FLIC_BUTTON1_SERIAL'): self.handle_button1, - os.getenv('FLIC_BUTTON2_SERIAL'): self.handle_button2, - os.getenv('FLIC_BUTTON3_SERIAL'): self.handle_button3 - } - - # Ensure subscriptions file and directory exist - self.subscriptions_file = os.getenv('SUBSCRIPTIONS_FILE', 'app/subscriptions.json') - self._ensure_subscriptions_file() - - # Load subscriptions - self.subscriptions = self.load_subscriptions() - - # Prepare VAPID keys - self.vapid_private_key = self._decode_vapid_private_key() - - def _ensure_subscriptions_file(self): - """ - Ensure the subscriptions file and its parent directory exist. - Create them if they don't. - """ - try: - # Create parent directory if it doesn't exist - pathlib.Path(self.subscriptions_file).parent.mkdir(parents=True, exist_ok=True) - - # Create file if it doesn't exist - if not os.path.exists(self.subscriptions_file): - with open(self.subscriptions_file, 'w') as f: - json.dump([], f) - except Exception as e: - logger.error(f"Error ensuring subscriptions file: {e}") - raise - - def _decode_vapid_private_key(self): - """ - Load the VAPID private key from environment variable. - Handles the \n escaped format from .env file. - """ - try: - # Get the key from environment - env_key = os.getenv('VAPID_PRIVATE_KEY', '').strip() - - # Convert escaped newlines back to actual newlines - private_pem = env_key.replace('\\n', '\n') - - # Verify PEM format - if not private_pem.startswith('-----BEGIN PRIVATE KEY-----'): - raise ValueError("Invalid PEM format") - - # Validate the key - serialization.load_pem_private_key( - private_pem.encode('utf-8'), - password=None - ) - - return private_pem - - except Exception as e: - logger.error(f"VAPID key error: {str(e)}") - raise - - def load_subscriptions(self) -> List[Dict]: - """Load web push subscriptions from file.""" - try: - with open(self.subscriptions_file, 'r') as f: - # Handle empty file case - content = f.read().strip() - return json.loads(content) if content else [] - except json.JSONDecodeError: - logger.error(f"Error decoding subscriptions from {self.subscriptions_file}") - return [] - - def save_subscriptions(self): - """Save web push subscriptions to file.""" - try: - with open(self.subscriptions_file, 'w') as f: - json.dump(self.subscriptions, f, indent=2) - except Exception as e: - logger.error(f"Error saving subscriptions: {e}") - - async def send_push_notification(self, subscription: Dict, message: str): - """Send a web push notification.""" - try: - if not self.subscriptions: - logger.warning("No subscriptions available") - return - - webpush( - subscription_info=subscription, - data=message, - vapid_private_key=self.vapid_private_key, - vapid_claims={"sub": "mailto:your-email@example.com"} - ) - except WebPushException as e: - logger.error(f"Push notification error: {e}") - # Remove invalid subscription - self.subscriptions = [s for s in self.subscriptions if s != subscription] - self.save_subscriptions() - - async def handle_button1(self): - """Handle first button action - e.g., Home Lights On""" - logger.info("Button 1 pressed: Home Lights On") - message = json.dumps({"action": "home_lights_on"}) - await self.broadcast_notification(message) - - async def handle_button2(self): - """Handle second button action - e.g., Security System Arm""" - logger.info("Button 2 pressed: Security System Arm") - message = json.dumps({"action": "security_arm"}) - await self.broadcast_notification(message) - - async def handle_button3(self): - """Handle third button action - e.g., Panic Button""" - logger.info("Button 3 pressed: Panic Alert") - message = json.dumps({"action": "panic_alert"}) - await self.broadcast_notification(message) - - async def broadcast_notification(self, message: str): - """Broadcast notification to all subscriptions.""" - if not self.subscriptions: - logger.warning("No subscriptions to broadcast to") - return - - tasks = [ - self.send_push_notification(subscription, message) - for subscription in self.subscriptions - ] - await asyncio.gather(*tasks) - - async def handle_flic_webhook(self, request): - """Webhook endpoint for Flic button events.""" - try: - data = await request.json() - button_serial = data.get('serial') - - # Validate button serial - if button_serial not in self.button_configs: - logger.warning(f"Unknown button serial: {button_serial}") - return web.Response(status=400) - - # Call the corresponding button handler - handler = self.button_configs[button_serial] - await handler() - - return web.Response(status=200) - except Exception as e: - logger.error(f"Error processing Flic webhook: {e}") - return web.Response(status=500) - - async def handle_subscribe(self, request): - """Add a new web push subscription.""" - try: - subscription = await request.json() - - # Check if subscription already exists - if subscription not in self.subscriptions: - self.subscriptions.append(subscription) - self.save_subscriptions() - logger.info("New subscription added") - - return web.Response(status=200) - except Exception as e: - logger.error(f"Subscription error: {e}") - return web.Response(status=500) - -def create_app(): - """Create and configure the aiohttp application.""" - app = web.Application() - handler = FlicButtonHandler() - - async def options_handler(request): - """Handle OPTIONS requests for CORS preflight.""" - origin = request.headers.get('Origin', '') - if origin in ALLOWED_ORIGINS: - headers = { - 'Access-Control-Allow-Origin': origin, - 'Access-Control-Allow-Methods': ', '.join(ALLOWED_METHODS), - 'Access-Control-Allow-Headers': ', '.join(ALLOWED_HEADERS), - 'Access-Control-Max-Age': '86400', # 24 hours - } - return web.Response(status=200, headers=headers) - return web.Response(status=403) # Forbidden origin - - async def add_cors_headers(request, response): - """Add CORS headers to normal responses.""" - origin = request.headers.get('Origin', '') - if origin in ALLOWED_ORIGINS: - response.headers['Access-Control-Allow-Origin'] = origin - response.headers['Access-Control-Expose-Headers'] = 'Content-Type' - return response - - # Register middleware - app.on_response_prepare.append(add_cors_headers) - - # Setup routes with OPTIONS handlers - app.router.add_route('OPTIONS', '/flic-webhook', options_handler) - app.router.add_route('OPTIONS', '/subscribe', options_handler) - - # Original routes - app.router.add_post('/flic-webhook', handler.handle_flic_webhook) - app.router.add_post('/subscribe', handler.handle_subscribe) - - return app - -async def main(): - """Main application entry point.""" - app = create_app() - runner = web.AppRunner(app) - await runner.setup() - site = web.TCPSite(runner, '0.0.0.0', 8080) - await site.start() - - logger.info("Application started on port 8080") - - # Create an event to keep the application running - stop_event = asyncio.Event() - - def signal_handler(): - """Handle interrupt signals to gracefully stop the application.""" - logger.info("Received shutdown signal") - stop_event.set() - - # Register signal handlers - loop = asyncio.get_running_loop() - for sig in (signal.SIGINT, signal.SIGTERM): - loop.add_signal_handler(sig, signal_handler) - - # Wait until stop event is set - await stop_event.wait() - - # Cleanup - await runner.cleanup() - logger.info("Application shutting down") - -if __name__ == '__main__': - asyncio.run(main()) \ No newline at end of file diff --git a/generate_vapid_keys.py b/generate_vapid_keys.py deleted file mode 100644 index 43074f7..0000000 --- a/generate_vapid_keys.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python3 -import os -import base64 -from cryptography.hazmat.primitives.asymmetric import ec -from cryptography.hazmat.primitives import serialization - -def generate_vapid_keys(): - """ - Generate VAPID keys and update .env file, preserving existing variables. - Only regenerates keys if they are missing or empty. - """ - # Read existing .env file if it exists - env_vars = {} - if os.path.exists('.env'): - with open('.env', 'r') as f: - for line in f: - line = line.strip() - if line and not line.startswith('#') and '=' in line: - key, value = line.split('=', 1) - env_vars[key.strip()] = value.strip() - - # Check if we need to generate new keys - need_new_keys = ( - 'VAPID_PRIVATE_KEY' not in env_vars or - 'VAPID_PUBLIC_KEY' not in env_vars or - not env_vars.get('VAPID_PRIVATE_KEY') or - not env_vars.get('VAPID_PUBLIC_KEY') - ) - - if need_new_keys: - # Generate EC private key - private_key = ec.generate_private_key(ec.SECP256R1()) - - # Serialize private key to PEM format - private_pem = private_key.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.PKCS8, - encryption_algorithm=serialization.NoEncryption() - ).decode('utf-8') - - # Format for .env file (replace newlines with \n) - env_private_key = private_pem.strip().replace('\n', '\\n') - - # Get public key - public_key = private_key.public_key() - public_key_bytes = public_key.public_bytes( - encoding=serialization.Encoding.X962, - format=serialization.PublicFormat.UncompressedPoint - ) - - # Store keys - env_vars['VAPID_PRIVATE_KEY'] = env_private_key # Single-line format - env_vars['VAPID_PUBLIC_KEY'] = base64.urlsafe_b64encode(public_key_bytes).decode('utf-8') - - print("New VAPID keys generated in .env-compatible format.") - else: - print("Existing VAPID keys found - no changes made.") - # Verify existing key format - if '-----BEGIN PRIVATE KEY-----' not in env_vars['VAPID_PRIVATE_KEY']: - print("Warning: Existing private key doesn't appear to be in PEM format!") - - # Ensure we have all required configuration variables with defaults if missing - defaults = { - # Flic Button Configuration - 'FLIC_BUTTON1_SERIAL': env_vars.get('FLIC_BUTTON1_SERIAL', 'your_button1_serial'), - 'FLIC_BUTTON2_SERIAL': env_vars.get('FLIC_BUTTON2_SERIAL', 'your_button2_serial'), - 'FLIC_BUTTON3_SERIAL': env_vars.get('FLIC_BUTTON3_SERIAL', 'your_button3_serial'), - - # Subscription Storage - 'SUBSCRIPTIONS_FILE': env_vars.get('SUBSCRIPTIONS_FILE', 'data/subscriptions.json'), - - # Logging Configuration - 'LOG_LEVEL': env_vars.get('LOG_LEVEL', 'INFO'), - - # VAPID Claim (email) - 'VAPID_CLAIM_EMAIL': env_vars.get('VAPID_CLAIM_EMAIL', 'mailto:your-email@example.com') - } - - # Update env_vars with defaults for any missing keys - env_vars.update({k: v for k, v in defaults.items() if k not in env_vars}) - - # Write back to .env file - with open('.env', 'w') as f: - f.write("# VAPID Keys for Web Push\n") - f.write(f"VAPID_PRIVATE_KEY={env_vars['VAPID_PRIVATE_KEY']}\n") - f.write(f"VAPID_PUBLIC_KEY={env_vars['VAPID_PUBLIC_KEY']}\n\n") - - f.write("# Flic Button Configuration\n") - f.write(f"FLIC_BUTTON1_SERIAL={env_vars['FLIC_BUTTON1_SERIAL']}\n") - f.write(f"FLIC_BUTTON2_SERIAL={env_vars['FLIC_BUTTON2_SERIAL']}\n") - f.write(f"FLIC_BUTTON3_SERIAL={env_vars['FLIC_BUTTON3_SERIAL']}\n\n") - - f.write("# Subscription Storage\n") - f.write(f"SUBSCRIPTIONS_FILE={env_vars['SUBSCRIPTIONS_FILE']}\n\n") - - f.write("# Logging Configuration\n") - f.write(f"LOG_LEVEL={env_vars['LOG_LEVEL']}\n\n") - - f.write("# VAPID Claim Email\n") - f.write(f"VAPID_CLAIM_EMAIL={env_vars['VAPID_CLAIM_EMAIL']}\n") - -if __name__ == '__main__': - generate_vapid_keys() \ No newline at end of file diff --git a/labels.example b/labels.example new file mode 100644 index 0000000..88fce42 --- /dev/null +++ b/labels.example @@ -0,0 +1,29 @@ +# Traefik v3 Labels for flic-webhook-webpush service + +# Enable Traefik for this container +traefik.enable=true + +# --- HTTP Router Definition --- +# Define an HTTP router named 'flic-webhook-http' +# Route requests based on Host and PathPrefix +traefik.http.routers.flic-webhook.rule=Host(`webpush.virtonline.eu`) +# Specify the entrypoint (e.g., 'websecure' for HTTPS) +traefik.http.routers.flic-webhook.entrypoints=websecure +# Specify the TLS certificate resolver +traefik.http.routers.flic-webhook.tls.certresolver=default +# Link this router to the service defined below +traefik.http.routers.flic-webhook.service=flic-webhook + +# --- HTTP Service Definition --- +# Define an HTTP service named 'flic-webhook' +# Point the service to the container's port (default 3000) +traefik.http.services.flic-webhook.loadbalancer.server.port=3000 + +# --- Middleware (Optional Example: Rate Limiting - Uncomment to enable) --- +# traefik.http.middlewares.flic-ratelimit.ratelimit.average=10 # requests per second +# traefik.http.middlewares.flic-ratelimit.ratelimit.burst=20 +# traefik.http.routers.flic-webhook.middlewares=flic-ratelimit + +# --- Docker Network --- +# Ensure Traefik uses the correct network to communicate with the container +traefik.docker.network=traefik \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..f0ce88d --- /dev/null +++ b/package-lock.json @@ -0,0 +1,926 @@ +{ + "name": "flic-webhook-webpush", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "flic-webhook-webpush", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "web-push": "^3.6.7" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/asn1.js": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", + "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "safer-buffer": "^2.1.0" + } + }, + "node_modules/bn.js": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.1.tgz", + "integrity": "sha512-k8TVBiPkPJT9uHLdOKfFpqcfprwBFOAAXXozRubr7R7PfIuKvQlzcI4M0pALeqXN09vdaMbUdUj+pass+uULAg==" + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dotenv": { + "version": "16.4.7", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", + "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http_ece": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz", + "integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==", + "engines": { + "node": ">=16" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent/node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/https-proxy-agent/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/jwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "dependencies": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==" + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/web-push": { + "version": "3.6.7", + "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz", + "integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==", + "dependencies": { + "asn1.js": "^5.3.0", + "http_ece": "1.2.0", + "https-proxy-agent": "^7.0.0", + "jws": "^4.0.0", + "minimist": "^1.2.5" + }, + "bin": { + "web-push": "src/cli.js" + }, + "engines": { + "node": ">= 16" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..81120fa --- /dev/null +++ b/package.json @@ -0,0 +1,25 @@ +{ + "name": "flic-webhook-webpush", + "version": "1.0.0", + "description": "Backend to receive Flic webhooks and send Web Push notifications", + "main": "server.js", + "scripts": { + "start": "node server.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [ + "flic", + "webpush", + "pwa", + "webhook", + "docker" + ], + "author": "Your Name", + "license": "MIT", + "dependencies": { + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "web-push": "^3.6.7" + } + } \ No newline at end of file diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 835412f..0000000 --- a/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -aiohttp==3.9.3 -pywebpush==2.0.0 -python-dotenv==1.0.0 -cryptography==42.0.4 \ No newline at end of file diff --git a/server.js b/server.js new file mode 100644 index 0000000..903f081 --- /dev/null +++ b/server.js @@ -0,0 +1,193 @@ +const express = require('express'); +const webpush = require('web-push'); +const cors = require('cors'); +const fs = require('fs'); +const path = require('path'); + +// Load environment variables from .env file +require('dotenv').config(); + +// --- Configuration --- +const port = process.env.PORT || 3000; +const vapidPublicKey = process.env.VAPID_PUBLIC_KEY; +const vapidPrivateKey = process.env.VAPID_PRIVATE_KEY; +const vapidSubject = process.env.VAPID_SUBJECT; // mailto: or https: +const subscriptionsFilePath = process.env.SUBSCRIPTIONS_FILE || path.join(__dirname, 'subscriptions.json'); +const flicSecret = process.env.FLIC_SECRET; // Optional Bearer token secret +const allowedOrigins = (process.env.ALLOWED_ORIGINS || "").split(',').map(origin => origin.trim()).filter(origin => origin); +const allowedMethods = (process.env.ALLOWED_METHODS || "POST,OPTIONS").split(',').map(method => method.trim()).filter(method => method); +const allowedHeaders = (process.env.ALLOWED_HEADERS || "Content-Type,Authorization").split(',').map(header => header.trim()).filter(header => header); + + +// --- Validation --- +if (!vapidPublicKey || !vapidPrivateKey || !vapidSubject) { + console.error('Error: VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, and VAPID_SUBJECT must be set in the environment variables.'); + process.exit(1); +} + +if (!fs.existsSync(subscriptionsFilePath)) { + console.warn(`Warning: Subscriptions file not found at ${subscriptionsFilePath}. Creating an empty file.`); + try { + fs.writeFileSync(subscriptionsFilePath, '{}', 'utf8'); + } catch (err) { + console.error(`Error: Could not create subscriptions file at ${subscriptionsFilePath}.`, err); + process.exit(1); + } +} + +// --- Web Push Setup --- +webpush.setVapidDetails( + vapidSubject, + vapidPublicKey, + vapidPrivateKey +); + +// --- Subscription Loading --- +let subscriptions = {}; +try { + const data = fs.readFileSync(subscriptionsFilePath, 'utf8'); + subscriptions = JSON.parse(data); + console.log(`Loaded ${Object.keys(subscriptions).length} subscriptions from ${subscriptionsFilePath}`); +} catch (err) { + console.error(`Error reading or parsing subscriptions file at ${subscriptionsFilePath}. Please ensure it's valid JSON.`, err); + // Continue with empty subscriptions, but log the error + subscriptions = {}; +} + +// --- Express App Setup --- +const app = express(); + +// --- CORS Middleware --- +const corsOptions = { + origin: (origin, callback) => { + // Allow requests with no origin (like curl requests, mobile apps, etc) or from allowed list + if (!origin || allowedOrigins.length === 0 || allowedOrigins.includes(origin)) { + callback(null, true); + } else { + console.warn(`CORS: Blocked origin: ${origin}`); + callback(new Error('Not allowed by CORS')); + } + }, + methods: allowedMethods, + allowedHeaders: allowedHeaders, + optionsSuccessStatus: 204 // For pre-flight requests +}; +app.use(cors(corsOptions)); +app.options('/flic-webhook', cors(corsOptions)); // Enable pre-flight for the webhook route + +// --- Body Parsing Middleware --- +app.use(express.json()); + +// --- Authentication Middleware (Optional) --- +const authenticateFlicRequest = (req, res, next) => { + if (!flicSecret) { + return next(); // No secret configured, skip authentication + } + + const authHeader = req.headers.authorization; + if (!authHeader || !authHeader.startsWith('Bearer ')) { + console.warn('Auth: Missing or malformed Authorization header'); + return res.status(401).json({ message: 'Unauthorized: Missing or malformed Bearer token' }); + } + + const token = authHeader.split(' ')[1]; + if (token !== flicSecret) { + console.warn('Auth: Invalid Bearer token received'); + return res.status(401).json({ message: 'Unauthorized: Invalid token' }); + } + + next(); +}; + +// --- Webhook Endpoint --- +app.post('/flic-webhook', authenticateFlicRequest, async (req, res) => { + const { button_id, click_type, timestamp } = req.body; // Flic might send serialNumber, check Flic docs/logs + + console.log(`Received webhook: Button=${button_id}, Type=${click_type}, Timestamp=${timestamp || 'N/A'}`); + + // Basic validation + if (!button_id || !click_type) { + return res.status(400).json({ message: 'Bad Request: Missing button_id or click_type' }); + } + + // Find the subscription associated with this button ID (case-insensitive compare might be safer) + const subscription = subscriptions[button_id.toLowerCase()] || subscriptions[button_id]; // Check both cases just in case + + + if (!subscription) { + console.warn(`No subscription found for button ID: ${button_id}`); + return res.status(404).json({ message: `Not Found: No subscription configured for button ${button_id}` }); + } + + // --- Send Web Push Notification --- + const payload = JSON.stringify({ + title: 'Flic Button Action', + body: `Button ${button_id} - ${click_type}`, + data: { // Send structured data to the PWA + action: click_type, // e.g., "SingleClick", "DoubleClick", "Hold" + button: button_id, + timestamp: timestamp || new Date().toISOString() + } + // icon: '/path/to/icon.png' // Optional: Add an icon URL accessible by the PWA + }); + + try { + console.log(`Sending push notification to endpoint: ${subscription.endpoint.substring(0, 30)}...`); + await webpush.sendNotification(subscription, payload); + console.log(`Push notification sent successfully for button ${button_id}.`); + res.status(200).json({ message: 'Push notification sent successfully' }); + } catch (error) { + console.error(`Error sending push notification for button ${button_id}:`, error); + + if (error.statusCode === 404 || error.statusCode === 410) { + console.warn(`Subscription for button ${button_id} is invalid or expired (404/410). Consider removing it.`); + // Optionally, you could implement logic here to remove the stale subscription + // delete subscriptions[button_id]; + // fs.writeFileSync(subscriptionsFilePath, JSON.stringify(subscriptions, null, 2), 'utf8'); + res.status(410).json({ message: 'Subscription Gone' }); + } else { + res.status(500).json({ message: 'Internal Server Error: Failed to send push notification' }); + } + } +}); + +// --- Health Check Endpoint (Optional) --- +app.get('/health', (req, res) => { + res.status(200).json({ status: 'UP', timestamp: new Date().toISOString() }); +}); + +// --- Start Server --- +app.listen(port, () => { + console.log(`Flic Webhook to WebPush server listening on port ${port}`); + console.log(`Allowed Origins: ${allowedOrigins.length > 0 ? allowedOrigins.join(', ') : '*'}`); + console.log(`Allowed Methods: ${allowedMethods.join(', ')}`); + console.log(`Allowed Headers: ${allowedHeaders.join(', ')}`); + console.log(`Authentication: ${flicSecret ? 'Enabled (Bearer Token)' : 'Disabled'}`); + console.log(`Subscriptions File: ${subscriptionsFilePath}`); +}); + +// --- Graceful Shutdown (Optional but Recommended) --- +process.on('SIGTERM', () => { + console.log('SIGTERM signal received: closing HTTP server'); + app.close(() => { // Doesn't work directly with app.listen, need http.createServer + console.log('HTTP server closed'); + process.exit(0); + }); + // If server.close doesn't exit quickly, force exit after timeout + setTimeout(() => { + console.error('Could not close connections in time, forcefully shutting down'); + process.exit(1); + }, 10000); // 10 seconds timeout +}); + +process.on('SIGINT', () => { + console.log('SIGINT signal received: closing HTTP server'); + app.close(() => { + console.log('HTTP server closed'); + process.exit(0); + }); + setTimeout(() => { + console.error('Could not close connections in time, forcefully shutting down'); + process.exit(1); + }, 10000); +}); \ No newline at end of file