Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(dns): dynamic DNS — token-authenticated A/AAAA updates

Juan Denis5f28f3e70006
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 2c146e1a..9f74c333 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -303,6 +303,10 @@ def create_app(config_name=None):
from app.api.dns_zones import dns_zones_bp
app.register_blueprint(dns_zones_bp, url_prefix='/api/v1/dns')
+ # Register blueprints - Dynamic DNS
+ from app.api.ddns import ddns_bp
+ app.register_blueprint(ddns_bp, url_prefix='/api/v1/ddns')
+
# Register blueprints - Nginx Advanced
from app.api.nginx_advanced import nginx_advanced_bp
app.register_blueprint(nginx_advanced_bp, url_prefix='/api/v1/nginx/advanced')
diff --git a/backend/app/api/ddns.py b/backend/app/api/ddns.py
new file mode 100644
index 00000000..26531f1d
--- /dev/null
+++ b/backend/app/api/ddns.py
@@ -0,0 +1,84 @@
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required, get_jwt_identity
+from app.models.user import User
+from app.services.ddns_service import DdnsService
+
+ddns_bp = Blueprint('ddns', __name__)
+
+
+def _admin():
+ user = User.query.get(get_jwt_identity())
+ return user if user and user.is_admin else None
+
+
+# --- Management (authenticated, admin) ---
+
+@ddns_bp.route('/hosts', methods=['GET'])
+@jwt_required()
+def list_hosts():
+ hosts = DdnsService.list_hosts()
+ return jsonify({'hosts': [h.to_dict() for h in hosts]})
+
+
+@ddns_bp.route('/hosts', methods=['POST'])
+@jwt_required()
+def create_host():
+ if not _admin():
+ return jsonify({'error': 'Admin access required'}), 403
+ try:
+ host = DdnsService.create_host(request.get_json() or {})
+ # Return the token once, on creation — it is masked everywhere else.
+ return jsonify(host.to_dict(include_token=True)), 201
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+
+
+@ddns_bp.route('/hosts/<int:host_id>', methods=['DELETE'])
+@jwt_required()
+def delete_host(host_id):
+ if not _admin():
+ return jsonify({'error': 'Admin access required'}), 403
+ if not DdnsService.delete_host(host_id):
+ return jsonify({'error': 'Host not found'}), 404
+ return jsonify({'message': 'Host deleted'})
+
+
+@ddns_bp.route('/hosts/<int:host_id>/regenerate-token', methods=['POST'])
+@jwt_required()
+def regenerate_token(host_id):
+ if not _admin():
+ return jsonify({'error': 'Admin access required'}), 403
+ host = DdnsService.regenerate_token(host_id)
+ if not host:
+ return jsonify({'error': 'Host not found'}), 404
+ return jsonify(host.to_dict(include_token=True))
+
+
+# --- Update endpoint (public, token-authenticated) ---
+
+def _client_ip():
+ forwarded = request.headers.get('X-Forwarded-For', '')
+ if forwarded:
+ return forwarded.split(',')[0].strip()
+ return request.remote_addr
+
+
+@ddns_bp.route('/update', methods=['GET', 'POST'])
+def update():
+ """Called by a router or cron when its public IP changes. There is no JWT
+ here — the per-host token is the credential. The IP can be passed explicitly
+ (?ip=) or inferred from the request source address."""
+ body = request.get_json(silent=True) or {}
+ token = request.args.get('token') or request.headers.get('X-DDNS-Token') or body.get('token')
+ if not token:
+ return jsonify({'error': 'token required'}), 401
+
+ ip = request.args.get('ip') or body.get('ip') or _client_ip()
+ try:
+ status, host = DdnsService.update_ip(token, ip)
+ except ValueError as e:
+ message = str(e)
+ code = 401 if 'token' in message.lower() else 400
+ return jsonify({'error': message}), code
+
+ return jsonify({'status': status, 'hostname': host.hostname, 'ip': ip})
diff --git a/backend/app/models/ddns_host.py b/backend/app/models/ddns_host.py
new file mode 100644
index 00000000..1ea084f7
--- /dev/null
+++ b/backend/app/models/ddns_host.py
@@ -0,0 +1,54 @@
+from datetime import datetime
+import secrets
+from app import db
+
+
+class DdnsHost(db.Model):
+ """A dynamic-DNS binding: a hostname whose A/AAAA record is updated on
+ demand through a secret token — the URL a home router or cron job calls
+ whenever its public IP changes."""
+ __tablename__ = 'ddns_hosts'
+
+ id = db.Column(db.Integer, primary_key=True)
+ zone_id = db.Column(db.Integer, db.ForeignKey('dns_zones.id'), nullable=False)
+ # Record name within the zone: '@' for the apex, or e.g. 'home' for
+ # home.example.com. Matches DNSRecord.name.
+ record_name = db.Column(db.String(256), nullable=False, default='@')
+ label = db.Column(db.String(128))
+ token = db.Column(db.String(64), nullable=False, unique=True, index=True)
+
+ last_ip = db.Column(db.String(45)) # last IP applied (IPv4 or IPv6)
+ last_update_at = db.Column(db.DateTime)
+ enabled = db.Column(db.Boolean, default=True, nullable=False)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ zone = db.relationship('DNSZone')
+
+ @staticmethod
+ def generate_token():
+ return secrets.token_urlsafe(32)
+
+ @property
+ def hostname(self):
+ domain = self.zone.domain if self.zone else ''
+ if self.record_name in ('@', '', None):
+ return domain
+ return f'{self.record_name}.{domain}'
+
+ def to_dict(self, include_token=False):
+ data = {
+ 'id': self.id,
+ 'zone_id': self.zone_id,
+ 'record_name': self.record_name,
+ 'label': self.label,
+ 'hostname': self.hostname,
+ 'last_ip': self.last_ip,
+ 'last_update_at': self.last_update_at.isoformat() if self.last_update_at else None,
+ 'enabled': self.enabled,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ }
+ # The token is a credential — only return it when it was just minted.
+ if include_token:
+ data['token'] = self.token
+ return data
diff --git a/backend/app/services/ddns_service.py b/backend/app/services/ddns_service.py
new file mode 100644
index 00000000..b4fa374f
--- /dev/null
+++ b/backend/app/services/ddns_service.py
@@ -0,0 +1,97 @@
+import ipaddress
+import logging
+from datetime import datetime
+from app import db
+from app.models.ddns_host import DdnsHost
+from app.models.dns_zone import DNSZone, DNSRecord
+from app.services.dns_zone_service import DNSZoneService
+
+logger = logging.getLogger(__name__)
+
+
+class DdnsService:
+ """Dynamic DNS: token-authenticated A/AAAA record updates for hosts whose
+ public IP changes (home servers, residential connections, etc.)."""
+
+ @staticmethod
+ def list_hosts():
+ return DdnsHost.query.order_by(DdnsHost.created_at.desc()).all()
+
+ @staticmethod
+ def get_host(host_id):
+ return DdnsHost.query.get(host_id)
+
+ @staticmethod
+ def create_host(data):
+ zone_id = data.get('zone_id')
+ zone = DNSZone.query.get(zone_id) if zone_id else None
+ if not zone:
+ raise ValueError('Valid zone_id required')
+
+ record_name = (data.get('record_name') or '@').strip() or '@'
+ host = DdnsHost(
+ zone_id=zone.id,
+ record_name=record_name,
+ label=(data.get('label') or '').strip() or None,
+ token=DdnsHost.generate_token(),
+ enabled=bool(data.get('enabled', True)),
+ )
+ db.session.add(host)
+ db.session.commit()
+ return host
+
+ @staticmethod
+ def delete_host(host_id):
+ host = DdnsHost.query.get(host_id)
+ if not host:
+ return False
+ db.session.delete(host)
+ db.session.commit()
+ return True
+
+ @staticmethod
+ def regenerate_token(host_id):
+ host = DdnsHost.query.get(host_id)
+ if not host:
+ return None
+ host.token = DdnsHost.generate_token()
+ db.session.commit()
+ return host
+
+ @staticmethod
+ def _record_type_for(ip):
+ # Raises ValueError on anything that isn't a valid IP.
+ return 'AAAA' if ipaddress.ip_address(ip).version == 6 else 'A'
+
+ @staticmethod
+ def update_ip(token, ip):
+ """Apply a new IP to the host's record and return (status, host) where
+ status is 'updated' or 'unchanged'. Reuses DNSZoneService so any
+ configured provider (e.g. Cloudflare) is synced automatically."""
+ host = DdnsHost.query.filter_by(token=token, enabled=True).first()
+ if not host:
+ raise ValueError('Invalid or disabled token')
+
+ ip = (ip or '').strip()
+ record_type = DdnsService._record_type_for(ip) # validates the IP
+
+ record = DNSRecord.query.filter_by(
+ zone_id=host.zone_id, record_type=record_type, name=host.record_name
+ ).first()
+
+ changed = False
+ if record is None:
+ DNSZoneService.create_record(host.zone_id, {
+ 'record_type': record_type, 'name': host.record_name,
+ 'content': ip, 'ttl': 60,
+ })
+ changed = True
+ elif record.content != ip:
+ DNSZoneService.update_record(record.id, {'content': ip})
+ changed = True
+
+ host.last_ip = ip
+ host.last_update_at = datetime.utcnow()
+ db.session.commit()
+ logger.info('DDNS %s -> %s (%s)', host.hostname, ip, 'changed' if changed else 'noop')
+ return ('updated' if changed else 'unchanged', host)
diff --git a/backend/tests/test_ddns.py b/backend/tests/test_ddns.py
new file mode 100644
index 00000000..db6efb03
--- /dev/null
+++ b/backend/tests/test_ddns.py
@@ -0,0 +1,91 @@
+"""Tests for Dynamic DNS — token-authenticated A/AAAA record updates."""
+import pytest
+
+from app import db
+from app.models.dns_zone import DNSZone, DNSRecord
+from app.services.ddns_service import DdnsService
+
+
+def _manual_zone(domain='example.com'):
+ zone = DNSZone(domain=domain, provider='manual')
+ db.session.add(zone)
+ db.session.commit()
+ return zone
+
+
+class TestDdnsService:
+ def test_update_creates_then_reports_unchanged_then_updates(self, app):
+ zone = _manual_zone()
+ host = DdnsService.create_host({'zone_id': zone.id, 'record_name': 'home'})
+
+ status, h = DdnsService.update_ip(host.token, '203.0.113.7')
+ assert status == 'updated'
+ rec = DNSRecord.query.filter_by(zone_id=zone.id, record_type='A', name='home').first()
+ assert rec is not None and rec.content == '203.0.113.7'
+ assert h.last_ip == '203.0.113.7'
+
+ # Same IP → no-op.
+ status2, _ = DdnsService.update_ip(host.token, '203.0.113.7')
+ assert status2 == 'unchanged'
+
+ # New IP → updated in place, never a duplicate record.
+ status3, _ = DdnsService.update_ip(host.token, '203.0.113.9')
+ assert status3 == 'updated'
+ recs = DNSRecord.query.filter_by(zone_id=zone.id, record_type='A', name='home').all()
+ assert len(recs) == 1 and recs[0].content == '203.0.113.9'
+
+ def test_ipv6_uses_aaaa_record(self, app):
+ zone = _manual_zone('v6.example.com')
+ host = DdnsService.create_host({'zone_id': zone.id, 'record_name': '@'})
+ status, _ = DdnsService.update_ip(host.token, '2001:db8::1')
+ assert status == 'updated'
+ assert DNSRecord.query.filter_by(zone_id=zone.id, record_type='AAAA', name='@').first()
+
+ def test_invalid_token_rejected(self, app):
+ with pytest.raises(ValueError):
+ DdnsService.update_ip('nope', '203.0.113.1')
+
+ def test_invalid_ip_rejected(self, app):
+ zone = _manual_zone('bad.example.com')
+ host = DdnsService.create_host({'zone_id': zone.id})
+ with pytest.raises(ValueError):
+ DdnsService.update_ip(host.token, 'not-an-ip')
+
+ def test_disabled_host_rejected(self, app):
+ zone = _manual_zone('off.example.com')
+ host = DdnsService.create_host({'zone_id': zone.id, 'enabled': False})
+ with pytest.raises(ValueError):
+ DdnsService.update_ip(host.token, '203.0.113.1')
+
+
+class TestDdnsApi:
+ def test_create_returns_token_but_list_masks_it(self, client, auth_headers, app):
+ zone = _manual_zone('api.example.com')
+ resp = client.post('/api/v1/ddns/hosts',
+ json={'zone_id': zone.id, 'record_name': 'home'},
+ headers=auth_headers)
+ assert resp.status_code == 201
+ body = resp.get_json()
+ assert body['token'] and body['hostname'] == 'home.api.example.com'
+
+ listed = client.get('/api/v1/ddns/hosts', headers=auth_headers).get_json()
+ assert listed['hosts'] and 'token' not in listed['hosts'][0]
+
+ def test_public_update_endpoint(self, client, auth_headers, app):
+ zone = _manual_zone('pub.example.com')
+ created = client.post('/api/v1/ddns/hosts',
+ json={'zone_id': zone.id, 'record_name': 'nas'},
+ headers=auth_headers).get_json()
+ token = created['token']
+
+ ok = client.get(f'/api/v1/ddns/update?token={token}&ip=203.0.113.50')
+ assert ok.status_code == 200
+ assert ok.get_json()['status'] == 'updated'
+ assert ok.get_json()['hostname'] == 'nas.pub.example.com'
+
+ # Wrong token → 401; bad IP → 400.
+ assert client.get('/api/v1/ddns/update?token=wrong&ip=203.0.113.1').status_code == 401
+ assert client.get(f'/api/v1/ddns/update?token={token}&ip=xxx').status_code == 400
+
+ def test_create_requires_auth(self, client, app):
+ assert client.post('/api/v1/ddns/hosts', json={'zone_id': 1}).status_code == 401