Skip to content

Robmobius/push-notifications-api

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

136 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Push Notifications API

Installation

⚑ Quick Installation (One Command)

Install everything in one command:

bash <(curl -fsSL https://raw.githubusercontent.com/Robmobius/push-notifications-api/main/quick-install.sh)

This single command will:

  • βœ… Install system dependencies (build-essential)
  • βœ… Create 2GB swap file for memory management
  • βœ… Install Node.js (if not present)
  • βœ… Clone the repository
  • βœ… Install all Node.js dependencies
  • βœ… Run security audit fixes
  • βœ… Generate sample API key
  • βœ… Create .env configuration file
  • βœ… Display next steps

Perfect for VPS deployment!

Alternative: Local Setup Script

If you prefer to download and inspect the script first:

# Download the script
wget https://raw.githubusercontent.com/Robmobius/push-notifications-api/main/quick-install.sh

# Make it executable
chmod +x quick-install.sh

# Run it
./quick-install.sh

What the Script Does

  1. System Setup

    • Updates package lists
    • Installs build-essential for native compilation
    • Creates 2GB swap file for memory management
  2. Node.js Setup

    • Installs Node.js LTS if not present
    • Verifies Node.js installation
  3. Application Setup

    • Clones the repository from GitHub
    • Installs all Node.js dependencies
    • Runs npm audit fix for security
  4. Configuration

    • Generates secure API key
    • Creates .env file with sample configuration
    • Displays connection information

Ready to use in under 5 minutes!

Android App

You can download the Android app through Google Play or download the latest apk from the releases.

Connect

In the configuration tab type in the /events endpoint on your server

You can find the IP-address in the server log

animated

Complete System Setup

Automated Setup (Recommended)

The repository includes setup scripts for easy installation:

# Clone the repository
git clone https://github.com/Robmobius/push-notifications-api.git
cd push-notifications-api

# Run the complete setup script
chmod +x setup.sh
./setup.sh

This script will:

  • Install build-essential package
  • Create a 2GB swap file (important for low-memory systems)
  • Install Node.js dependencies
  • Run security audit fixes

Server-Only Setup

If you only need to set up the server environment:

cd push-notifications-api/server
chmod +x setup-server.sh
./setup-server.sh

Manual Setup Steps

If you prefer manual setup, follow these steps:

1. Install System Dependencies

sudo apt update
sudo apt install build-essential

2. Setup Swap File (Recommended for low-memory systems)

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

3. Install Node.js Dependencies

cd server
npm install
npm audit fix

System Requirements Details

Why build-essential is needed

The build-essential package provides:

  • GCC compiler
  • Make utility
  • Development libraries
  • Other essential build tools

These are required for compiling native Node.js addons that some dependencies may use.

Server

If you haven't already, install Node.

Clone the Project

git clone git@github.com:viktorholk/push-notifications-api.git
cd push-notifications-api/server
npm i

Start the Server

npm run start

The app will by default run on port 3000 and the endpoint for the notification events are /events

The port can be changed in the server/.env file

API Reference

Replace 127.0.0.1:3000 with your IP and port

Push Notification

POST http://127.0.0.1:3000
Example Curl
curl '127.0.0.1:3000' \
--header 'Content-Type: application/json' \
--data '{
   "title": "Foo Bar Baz!",
    "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    "url": "http://example.com",
    "icon": "suitcase.png",
    "color": "#1554F0"
}'
Property Type Description Required
title String The title of the notification Yes
message String The longer text that will be included in the notification No
url String Open the URL on notifcation press No
icon String 24x24 icon file located in server/src/icons No
color String Customize the notification color. See supported colors No
Response

Created 201

Get All Notifications

GET http://127.0.0.1:3000
Response
[
  {
    "title": "Foo Bar Baz!",
    "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    "url": "http://example.com",
    "icon": "base64encoded...",
    "color": "#1554F0"
  },
  ...
]

Get The Latest Notification

GET http://127.0.0.1:3000/latest
Response
{
  "title": "Foo Bar Baz!",
  "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
  "url": "http://example.com",
  "icon": "base64encoded...",
  "color": "#1554F0"
}

Common Asked Questions

Notifications are not showing up

Make sure notifications are enabled in your settings

Settings > Notifications > App notifications

image

Issues

Please report issues using GitHub's issues tab.

License

Push Notifications API is under the MIT LICENSE.

πŸš€ Recent Updates - Connection Stability Improvements

Version 1.3.0 - Keep-Alive Enhancement

Problem Solved: The Android app connection was dropping after several minutes of inactivity.

Solution Implemented:

  • βœ… Keep-alive heartbeat system (30-second intervals)
  • βœ… Enhanced socket configuration with TCP keep-alive
  • βœ… Automatic cleanup of dead connections
  • βœ… Extended socket timeout (5 minutes)
  • βœ… Graceful shutdown handling

πŸ”§ Technical Improvements

Keep-Alive Mechanism

// Sends keep-alive messages every 30 seconds
const HEARTBEAT_INTERVAL = 30000;

Enhanced Socket Configuration

  • Socket Timeout: Extended to 5 minutes (300,000ms)
  • TCP Keep-Alive: Enabled at socket level with 30-second intervals
  • Nagle's Algorithm: Disabled for better real-time performance
  • Connection Validation: Automatic cleanup of broken connections

New Endpoints

Health Check
GET /health

Response:

{
  "status": "healthy",
  "uptime": 12345.67,
  "activeConnections": 3,
  "totalNotifications": 42,
  "timestamp": "2025-07-20T18:29:00.000Z"
}

πŸ“Š Connection Management

The server now actively manages connections with:

  • Real-time monitoring of active connections
  • Automatic cleanup of dead/broken connections
  • Enhanced logging for connection events
  • Connection state validation before sending data

πŸ§ͺ Testing Connection Stability

Use the included test script to verify connection stability:

cd server
./test-connection.sh

This will monitor the /events endpoint for 2 minutes and show keep-alive messages.

πŸ” Monitoring

System Requirements

Before installing the Node server, ensure your system has the necessary build tools:

Ubuntu/Debian Systems

sudo apt update
sudo apt install build-essential

Alternative: Use the Setup Script

# Run the included setup script
chmod +x setup.sh
./setup.sh

Complete System Setup

Automated Setup (Recommended)

The repository includes setup scripts for easy installation:

# Clone the repository
git clone https://github.com/Robmobius/push-notifications-api.git
cd push-notifications-api

# Run the complete setup script
chmod +x setup.sh
./setup.sh

This script will:

  • Install build-essential package
  • Create a 2GB swap file (important for low-memory systems)
  • Install Node.js dependencies
  • Run security audit fixes

Server-Only Setup

If you only need to set up the server environment:

cd push-notifications-api/server
chmod +x setup-server.sh
./setup-server.sh

Manual Setup Steps

If you prefer manual setup, follow these steps:

1. Install System Dependencies

sudo apt update
sudo apt install build-essential

2. Setup Swap File (Recommended for low-memory systems)

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

3. Install Node.js Dependencies

cd server
npm install
npm audit fix

System Requirements Details

Why build-essential is needed

The build-essential package provides:

  • GCC compiler
  • Make utility
  • Development libraries
  • Other essential build tools

These are required for compiling native Node.js addons that some dependencies may use.

Server Logs

The server now provides detailed logging:

[20/7/2025 18:26:41] INFO Server is running on http://127.0.0.1:3000
[20/7/2025 18:26:41] INFO Heartbeat interval: 30000ms
[20/7/2025 18:27:11] INFO Sent keep-alive to 192.168.1.100
[20/7/2025 18:27:11] INFO Active connections: 2

Connection Events

  • Client connections and disconnections
  • Keep-alive message delivery
  • Connection cleanup operations
  • Error handling and recovery

πŸ› Bug Fixes

  • Connection Drops: Resolved through keep-alive heartbeat mechanism
  • Dead Connections: Automatic cleanup prevents memory leaks
  • Network Timeouts: Extended socket timeouts handle mobile network behavior
  • Error Handling: Improved error recovery for network issues

πŸ“± Android App Compatibility

The improvements are transparent to the Android app:

  • No app changes required
  • Maintains existing API compatibility
  • Enhanced connection stability
  • Better handling of mobile network conditions

πŸš€ Performance Improvements

  • Reduced Connection Overhead: Efficient keep-alive mechanism
  • Better Resource Management: Automatic cleanup of dead connections
  • Improved Logging: Better debugging and monitoring capabilities
  • Graceful Shutdown: Proper resource cleanup on server termination

⚠️ Memory Requirements and Troubleshooting

Why Swap File is Important

Node.js applications can be memory-intensive, especially during:

  • npm package installation
  • TypeScript compilation
  • Running with multiple connections

Without adequate memory, you may encounter:

  • FATAL ERROR: Ineffective mark-compacts near heap limit
  • npm install failures
  • Server crashes under load

Swap File Benefits

  • Prevents out-of-memory errors during installation
  • Improves stability under high load
  • Essential for VPS with limited RAM (1GB or less)

Verify Swap is Active

# Check current swap usage
swapon --show

# Check memory and swap status
free -h

Security Audit

The setup automatically runs npm audit fix to:

  • Fix known security vulnerabilities
  • Update packages to secure versions

🎯 Production Deployment (systemd Service)

For production environments, you can run the Push Notifications API as a systemd service to ensure automatic startup, restart on failure, and proper system integration.

Quick Service Installation

# Run the automated installation script
sudo ./systemd/install-service.sh

Manual Service Installation

If you prefer manual installation:

  1. Copy the service file:

    sudo cp systemd/push-notifications.service /etc/systemd/system/
  2. Edit paths in the service file (if needed):

    sudo nano /etc/systemd/system/push-notifications.service
    # Update WorkingDirectory, ExecStart paths as needed
  3. Enable and start the service:

    sudo systemctl daemon-reload
    sudo systemctl enable push-notifications.service
    sudo systemctl start push-notifications.service

Service Management

# Check service status
sudo systemctl status push-notifications

# Start the service
sudo systemctl start push-notifications

# Stop the service
sudo systemctl stop push-notifications

# Restart the service
sudo systemctl restart push-notifications

# View logs
sudo journalctl -u push-notifications -f

# View log files
sudo tail -f /var/log/push-notifications.log
sudo tail -f /var/log/push-notifications-error.log

Service Features

  • Auto-restart: Service automatically restarts if it crashes
  • Boot startup: Service starts automatically on system boot
  • Log management: Separate log files for output and errors
  • Security: Runs with restricted permissions
  • Monitoring: Easy status monitoring with systemctl

Troubleshooting

If the service fails to start:

  1. Check service status:

    sudo systemctl status push-notifications --no-pager
  2. Check logs:

    sudo journalctl -u push-notifications --no-pager -n 50
  3. Verify Node.js and npm paths:

    which node
    which npm
  4. Test manual startup:

    cd server && npm start

  • Ensure production-ready deployment

πŸ” API Security & Authentication

Authentication Overview

The API supports optional API key authentication for enhanced security. When enabled, it protects your notification endpoints from unauthorized access.

Quick Setup

1. Enable Authentication

# Add to server/.env
API_KEY=your-secure-api-key-here

2. Generate Secure API Key

# Using OpenSSL
openssl rand -base64 32

# Using Node.js
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"

# Example result: 
# sk_live_abc123def456ghi789jkl012mno345pqr678stu901vwx234yz

Authentication Methods

The API supports multiple authentication methods:

Method 1: X-API-Key Header (Recommended)

curl -X POST "http://your-server:3000/" \
     -H "Content-Type: application/json" \
     -H "X-API-Key: your-secure-api-key-here" \
     -d '{"title": "Test Notification", "message": "Hello World!"}'

Method 2: Authorization Bearer Header

curl -X POST "http://your-server:3000/" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer your-secure-api-key-here" \
     -d '{"title": "Test Notification", "message": "Hello World!"}'

Method 3: Query Parameter

curl -X POST "http://your-server:3000/?api_key=your-secure-api-key-here" \
     -H "Content-Type: application/json" \
     -d '{"title": "Test Notification", "message": "Hello World!"}'

Protected vs Public Endpoints

πŸ”’ Protected Endpoints (Require Authentication)

  • POST / - Create notification
  • GET / - Get all notifications
  • GET /latest - Get latest notification

🌐 Public Endpoints (No Authentication Required)

  • GET /health - Health check and server status
  • GET /events - Server-Sent Events (SSE) connection*

*The /events endpoint supports optional authentication. If no API key is provided, access is allowed but logged with warnings.

Android App Configuration

To use authentication with your Android app, include the API key in your requests:

Option 1: Header Authentication

// In your Android app HTTP connection
connection.setRequestProperty("X-API-Key", "your-secure-api-key-here");

Option 2: Query Parameter

// Append to your SSE connection URL
String url = "http://your-server:3000/events?api_key=your-secure-api-key-here";

Security Status Check

Check if authentication is enabled:

curl http://your-server:3000/health

Response includes authentication status:

{
  "status": "healthy",
  "authentication": "enabled",
  "activeConnections": 0,
  "totalNotifications": 0
}

Error Handling

Missing API Key (HTTP 401)

{
  "error": "Authentication required",
  "message": "API key must be provided via X-API-Key header, Authorization: Bearer header, or api_key query parameter"
}

Invalid API Key (HTTP 401)

{
  "error": "Authentication failed",
  "message": "Invalid API key provided"
}

πŸ“– Complete Security Documentation

For detailed security documentation, see:

  • server/API_SECURITY.md - Complete authentication guide
  • Security best practices
  • Production deployment recommendations
  • Android app integration examples

πŸ”§ Disabling Authentication

To run without authentication (NOT recommended for production):

# Comment out or remove API_KEY from server/.env
# API_KEY=your-secure-api-key-here

Server will show warning:

⚠️  WARNING: API Key authentication is DISABLED - set API_KEY environment variable

About

πŸ“± Send Instant Push Notifications to your Android Phone through a REST-API.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java 44.4%
  • TypeScript 32.0%
  • Shell 23.6%