rewritten

This commit is contained in:
cpu
2025-03-26 09:36:58 +01:00
parent b87e30f6b4
commit fc7f4f4b7a
2 changed files with 23 additions and 26 deletions

35
app.py
View File

@@ -73,21 +73,15 @@ class FlicButtonHandler:
"""Load and strictly validate VAPID private key."""
try:
# Get and clean the key
env_key = os.getenv('VAPID_PRIVATE_KEY', '').strip().strip('"\'')
env_key = os.getenv('VAPID_PRIVATE_KEY', '').strip()
# Convert to clean PEM format
if '\\n' in env_key:
private_pem = env_key.replace('\\n', '\n')
else:
private_pem = env_key
# Ensure proper PEM headers
if not private_pem.startswith('-----BEGIN PRIVATE KEY-----'):
private_pem = f"-----BEGIN PRIVATE KEY-----\n{private_pem}\n-----END PRIVATE KEY-----"
# Strict validation
# Reconstruct PEM format if missing headers
if not env_key.startswith('-----BEGIN PRIVATE KEY-----'):
env_key = f"-----BEGIN PRIVATE KEY-----\n{env_key}\n-----END PRIVATE KEY-----"
# Strict validation and key preparation
key = serialization.load_pem_private_key(
private_pem.encode('utf-8'),
env_key.encode('utf-8'),
password=None,
backend=default_backend()
)
@@ -124,14 +118,16 @@ class FlicButtonHandler:
async def send_push_notification(self, subscription: Dict, message: str):
try:
# Get endpoint base for aud claim
# Determine audience (aud) claim for VAPID
endpoint = subscription['endpoint']
aud = endpoint.split('/send')[0] if '/send' in endpoint else endpoint.split('/fcm/send')[0]
aud = (endpoint.split('/send')[0] if '/send' in endpoint
else endpoint.split('/fcm/send')[0])
logger.debug(f"Sending to: {endpoint[:50]}...")
logger.debug(f"Using aud: {aud}")
webpush(
# Perform web push
result = webpush(
subscription_info=subscription,
data=message,
vapid_private_key=self.vapid_private_key,
@@ -145,6 +141,8 @@ class FlicButtonHandler:
return True
except Exception as e:
logger.error(f"Push failed: {str(e)}")
logger.error(f"Endpoint details: {subscription['endpoint']}")
logger.error(f"Keys: {subscription.get('keys', 'No keys found')}")
return False
async def handle_button1(self):
@@ -174,8 +172,9 @@ class FlicButtonHandler:
success_count = 0
for subscription in self.subscriptions:
try:
await self.send_push_notification(subscription, message)
success_count += 1
success = await self.send_push_notification(subscription, message)
if success:
success_count += 1
except Exception as e:
logger.error(f"Failed to send to {subscription['endpoint'][:30]}...: {str(e)}")