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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(extensions): authoritative DNS server extension
Juan Denise3b69da3c425
diff --git a/backend/tests/test_dns_server_extension.py b/backend/tests/test_dns_server_extension.pynew file mode 100644index 00000000..3816fcfd--- /dev/null+++ b/backend/tests/test_dns_server_extension.py@@ -0,0 +1,674 @@+"""serverkit-dns-server extension tests (Panel Improvements #28).++Covers: manifest validity, install argv construction (docker stubbed) incl.+the localhost-only API binding and generated-api-key persistence, zone+creation SOA/NS bootstrap, rrset upsert/delete PowerDNS API call shapes+(requests stubbed), record-type/name validation, DNSSEC enable returning DS+records, the hand-rolled delegation-check DNS parser on fixture packet+bytes, and blueprint auth/503/happy paths with the service stubbed.++The extension backend is loaded exactly the way production loads builtins:+``plugin_service._ensure_builtin_backend_importable`` registers+``builtin-extensions/serverkit-dns-server/backend`` as+``app.plugins.serverkit-dns-server``.+"""+import importlib+import json+import os+import struct+from types import SimpleNamespace++import pytest++from app.services import plugin_service++SLUG = 'serverkit-dns-server'+EXT_DIR = os.path.join(+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),+ 'builtin-extensions', SLUG,+)+++def _load_ext():+ assert plugin_service._ensure_builtin_backend_importable(SLUG), (+ f'builtin extension backend not importable from {EXT_DIR}')+ svc_mod = importlib.import_module(f'app.plugins.{SLUG}.dns_server_service')+ bp_mod = importlib.import_module(f'app.plugins.{SLUG}.dns_server')+ return svc_mod, bp_mod+++svc_mod, bp_mod = _load_ext()+DnsServerService = svc_mod.DnsServerService++CFG = {+ 'api_key': 'test-api-key',+ 'ns_hostname': 'ns1.example.com',+ 'admin_email': '[email protected]',+}+++def _proc(returncode=0, stdout='', stderr=''):+ return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)+++class FakeResponse:+ def __init__(self, status_code=200, data=None, text=''):+ self.status_code = status_code+ self._data = data+ self.text = text or (json.dumps(data) if data is not None else '')+ self.content = self.text.encode()++ def json(self):+ if self._data is None:+ raise ValueError('no json')+ return self._data+++def linux(monkeypatch):+ """Pretend we're on Linux with docker installed and config saved."""+ monkeypatch.setattr(svc_mod.os, 'name', 'posix')+ monkeypatch.setattr(svc_mod, 'is_command_available', lambda c: True)+ monkeypatch.setattr(DnsServerService, '_config', classmethod(lambda cls: dict(CFG)))+++def api_calls(monkeypatch, linux):+ """Capture every PowerDNS API request; return success with empty body."""+ seen = []++ def fake_request(method, url, headers=None, json=None, timeout=None):+ seen.append({'method': method, 'url': url, 'headers': headers, 'json': json})+ return FakeResponse(204, None, '')++ monkeypatch.setattr(svc_mod.requests, 'request', fake_request)+ return seen+++# ---------------------------------------------------------------------------+# manifest+# ---------------------------------------------------------------------------++def test_manifest_passes_validator():+ with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:+ manifest = json.load(f)+ assert plugin_service._validate_manifest(manifest) is True+ assert manifest['name'] == SLUG+ assert manifest['category'] == 'networking'+ assert set(manifest['permissions']) == {'shell', 'docker'}+ assert manifest['entry_point'] == 'dns_server:dns_server_bp'+ assert manifest['url_prefix'] == '/api/v1/dns-server'+ nav = manifest['contributions']['nav'][0]+ assert nav['route'] == '/dns-server'+ routes = manifest['contributions']['routes']+ assert {'path': 'dns-server', 'component': 'DnsServerPage'} in routes+ assert manifest['contributions']['page_titles']['/dns-server'] == 'DNS Server'+++def test_manifest_permissions_are_known():+ from app.plugins_sdk import permissions as sdk_perms+ with open(os.path.join(EXT_DIR, 'plugin.json'), encoding='utf-8') as f:+ manifest = json.load(f)+ assert sdk_perms.unknown_permissions(manifest['permissions']) == []+++def test_entry_point_resolves_to_blueprint():+ assert getattr(bp_mod, 'dns_server_bp', None) is not None+ assert bp_mod.dns_server_bp.name == 'dns_server'+++def test_frontend_exports_route_component():+ with open(os.path.join(EXT_DIR, 'frontend', 'index.jsx'), encoding='utf-8') as f:+ src = f.read()+ assert 'export { default as DnsServerPage }' in src+ # No module-level default export: PluginLoader legacy-auto-renders those.+ assert 'export default' not in src+++# ---------------------------------------------------------------------------+# service: install / uninstall argv+# ---------------------------------------------------------------------------++def test_install_builds_correct_docker_run(monkeypatch, linux):+ calls = []+ saved = {}++ def fake_run(cmd, timeout=None, **kwargs):+ calls.append(list(cmd))+ if cmd[:2] == ['docker', 'inspect']:+ return _proc(returncode=1, stderr='No such object')+ return _proc(stdout='abc123\n')++ monkeypatch.setattr(svc_mod, 'run_privileged', fake_run)+ monkeypatch.setattr(DnsServerService, '_save_config',+ classmethod(lambda cls, updates: saved.update(updates) or True))++ result = DnsServerService.install('NS1.Example.COM.', '[email protected]')+ assert result['success'] is True, result++ # Data dir created, container started.+ assert ['mkdir', '-p', svc_mod.DATA_DIR] in calls+ run_cmd = next(c for c in calls if c[:2] == ['docker', 'run'])++ # Port 53 published tcp+udp; API published on loopback ONLY.+ assert '53:53/udp' in run_cmd+ assert '53:53/tcp' in run_cmd+ assert '127.0.0.1:8081:8081' in run_cmd+ assert not any(a == '8081:8081' for a in run_cmd)++ # SQLite volume + official image.+ assert f'{svc_mod.DATA_DIR}:{svc_mod.CONTAINER_DB_DIR}' in run_cmd+ assert svc_mod.IMAGE in run_cmd+ assert '--restart' in run_cmd++ # API enabled with a generated key... that was persisted to the config store.+ assert '--api=yes' in run_cmd+ key_args = [a for a in run_cmd if a.startswith('--api-key=')]+ assert len(key_args) == 1+ generated = key_args[0].split('=', 1)[1]+ assert len(generated) == 48 # token_hex(24)+ assert saved['api_key'] == generated+ assert saved['ns_hostname'] == 'ns1.example.com'+ assert saved['admin_email'] == '[email protected]'+++def test_install_rejects_bad_params(monkeypatch, linux):+ monkeypatch.setattr(+ svc_mod, 'run_privileged',+ lambda *a, **kw: pytest.fail('docker must not run on invalid input'))+ assert DnsServerService.install('', '[email protected]')['success'] is False+ assert DnsServerService.install('not a hostname!', '[email protected]')['success'] is False+ assert DnsServerService.install('ns1.example.com', 'not-an-email')['success'] is False+ assert DnsServerService.install('ns1.example.com', '')['success'] is False+++def test_install_refuses_when_container_exists(monkeypatch, linux):+ monkeypatch.setattr(+ svc_mod, 'run_privileged',+ lambda cmd, timeout=None, **kw: _proc(stdout='true\n')) # inspect succeeds+ result = DnsServerService.install('ns1.example.com', '[email protected]')+ assert result['success'] is False+ assert 'already exists' in result['error']+++def test_uninstall_keep_data_leaves_data_dir(monkeypatch, linux):+ calls = []++ def fake_run(cmd, timeout=None, **kwargs):+ calls.append(list(cmd))+ return _proc()++ monkeypatch.setattr(svc_mod, 'run_privileged', fake_run)+ monkeypatch.setattr(DnsServerService, '_save_config',+ classmethod(lambda cls, updates: True))++ result = DnsServerService.uninstall(keep_data=True)+ assert result['success'] is True+ assert ['docker', 'rm', '-f', svc_mod.CONTAINER_NAME] in calls+ assert not any(c[:1] == ['rm'] for c in calls)++ calls.clear()+ result = DnsServerService.uninstall(keep_data=False)+ assert result['success'] is True+ assert ['rm', '-rf', svc_mod.DATA_DIR] in calls+++def test_windows_is_unsupported(monkeypatch):+ monkeypatch.setattr(svc_mod.os, 'name', 'nt')+ assert DnsServerService.is_installed() is False+ result = DnsServerService.install('ns1.example.com', '[email protected]')+ assert result['success'] is False+ assert 'Windows' in result['error']+ status = DnsServerService.get_status()+ assert status['installed'] is False+ assert status['authoritative_only'] is True+++# ---------------------------------------------------------------------------+# service: status+# ---------------------------------------------------------------------------++def test_status_running_reads_version_from_api(monkeypatch, linux):+ monkeypatch.setattr(+ svc_mod, 'run_privileged',+ lambda cmd, timeout=None, **kw: _proc(stdout='true\n'))+ monkeypatch.setattr(+ svc_mod.requests, 'request',+ lambda method, url, **kw: FakeResponse(200, {'version': '4.9.3'}))+ status = DnsServerService.get_status()+ assert status['installed'] is True+ assert status['running'] is True+ assert status['version'] == '4.9.3'+ assert status['ns_hostname'] == 'ns1.example.com'+++def test_status_not_installed(monkeypatch, linux):+ monkeypatch.setattr(+ svc_mod, 'run_privileged',+ lambda cmd, timeout=None, **kw: _proc(returncode=1, stderr='No such object'))+ status = DnsServerService.get_status()+ assert status['installed'] is False+ assert status['running'] is False+++# ---------------------------------------------------------------------------+# service: zones + rrsets (PowerDNS API call shapes)+# ---------------------------------------------------------------------------++def test_create_zone_bootstraps_soa_and_ns(api_calls):+ result = DnsServerService.create_zone('Example.COM')+ assert result['success'] is True, result+ assert len(api_calls) == 1+ call = api_calls[0]+ assert call['method'] == 'POST'+ assert call['url'].endswith('/servers/localhost/zones')+ assert call['url'].startswith('http://127.0.0.1:8081')+ assert call['headers']['X-API-Key'] == 'test-api-key'++ payload = call['json']+ assert payload['name'] == 'example.com.'+ assert payload['kind'] == 'Native'+ rrsets = {r['type']: r for r in payload['rrsets']}+ assert rrsets['SOA']['records'][0]['content'] == (+ 'ns1.example.com. hostmaster.example.com. 1 10800 3600 604800 3600')+ assert rrsets['NS']['records'][0]['content'] == 'ns1.example.com.'+ assert all(r['name'] == 'example.com.' for r in payload['rrsets'])+++def test_create_zone_rejects_junk(api_calls):+ assert DnsServerService.create_zone('')['success'] is False+ assert DnsServerService.create_zone('no spaces allowed.com')['success'] is False+ assert DnsServerService.create_zone('*.example.com')['success'] is False+ assert api_calls == []+++def test_upsert_rrset_builds_replace_patch(api_calls):+ result = DnsServerService.upsert_rrset(+ 'example.com', 'www', 'a', 300, ['203.0.113.7', '203.0.113.8'])+ assert result['success'] is True, result+ call = api_calls[0]+ assert call['method'] == 'PATCH'+ assert call['url'].endswith('/servers/localhost/zones/example.com.')+ rrset = call['json']['rrsets'][0]+ assert rrset['name'] == 'www.example.com.'+ assert rrset['type'] == 'A'+ assert rrset['ttl'] == 300+ assert rrset['changetype'] == 'REPLACE'+ assert rrset['records'] == [+ {'content': '203.0.113.7', 'disabled': False},+ {'content': '203.0.113.8', 'disabled': False},+ ]+++def test_upsert_rrset_apex_and_absolute_names(api_calls):+ assert DnsServerService.upsert_rrset(+ 'example.com', '@', 'TXT', 3600, ['"v=spf1 -all"'])['success'] is True+ assert api_calls[-1]['json']['rrsets'][0]['name'] == 'example.com.'++ assert DnsServerService.upsert_rrset(+ 'example.com', 'mail.example.com.', 'MX', 3600,+ ['10 mail.example.com.'])['success'] is True+ assert api_calls[-1]['json']['rrsets'][0]['name'] == 'mail.example.com.'+++def test_rrset_validation_rejects_junk(api_calls):+ # Unknown record type.+ assert DnsServerService.upsert_rrset(+ 'example.com', 'www', 'ANAME', 300, ['x'])['success'] is False+ # Out-of-zone absolute name.+ assert DnsServerService.upsert_rrset(+ 'example.com', 'www.other.org.', 'A', 300, ['1.2.3.4'])['success'] is False+ # Bad label characters.+ assert DnsServerService.upsert_rrset(+ 'example.com', 'bad label', 'A', 300, ['1.2.3.4'])['success'] is False+ # Bad TTL / empty records.+ assert DnsServerService.upsert_rrset(+ 'example.com', 'www', 'A', 'soon', ['1.2.3.4'])['success'] is False+ assert DnsServerService.upsert_rrset(+ 'example.com', 'www', 'A', 300, [])['success'] is False+ # SOA delete is refused.+ assert DnsServerService.delete_rrset(+ 'example.com', '@', 'SOA')['success'] is False+ assert api_calls == [] # nothing ever reached the PowerDNS API+++def test_delete_rrset_builds_delete_patch(api_calls):+ result = DnsServerService.delete_rrset('example.com', 'www', 'A')+ assert result['success'] is True+ rrset = api_calls[0]['json']['rrsets'][0]+ assert rrset['changetype'] == 'DELETE'+ assert rrset['name'] == 'www.example.com.'+ assert rrset['records'] == []+++def test_wildcard_record_names_allowed(api_calls):+ result = DnsServerService.upsert_rrset(+ 'example.com', '*', 'A', 300, ['203.0.113.7'])+ assert result['success'] is True+ assert api_calls[0]['json']['rrsets'][0]['name'] == '*.example.com.'+++# ---------------------------------------------------------------------------+# service: DNSSEC+# ---------------------------------------------------------------------------++def test_dnssec_enable_returns_ds_records(monkeypatch, linux):+ calls = []+ DS = ['12345 13 2 aabbccdd...', '12345 13 4 eeff0011...']++ def fake_request(method, url, headers=None, json=None, timeout=None):+ calls.append({'method': method, 'url': url, 'json': json})+ if method == 'GET' and url.endswith('/cryptokeys'):+ return FakeResponse(200, [+ {'active': True, 'ds': DS},+ {'active': False, 'ds': ['ignored inactive key']},+ ])+ return FakeResponse(204, None, '')++ monkeypatch.setattr(svc_mod.requests, 'request', fake_request)+ result = DnsServerService.set_dnssec('example.com', True)+ assert result['success'] is True+ assert result['dnssec'] is True+ assert result['ds_records'] == DS++ put = calls[0]+ assert put['method'] == 'PUT'+ assert put['url'].endswith('/servers/localhost/zones/example.com.')+ assert put['json'] == {'dnssec': True, 'api_rectify': True}+++def test_dnssec_disable(api_calls):+ result = DnsServerService.set_dnssec('example.com', False)+ assert result['success'] is True+ assert result['dnssec'] is False+ assert api_calls[0]['json'] == {'dnssec': False}+++def test_api_error_is_clean(monkeypatch, linux):+ monkeypatch.setattr(+ svc_mod.requests, 'request',+ lambda method, url, **kw: FakeResponse(422, {'error': 'Domain already exists'}))+ result = DnsServerService.create_zone('example.com')+ assert result['success'] is False+ assert 'Domain already exists' in result['error']+++def test_api_requires_key(monkeypatch, linux):+ monkeypatch.setattr(DnsServerService, '_config', classmethod(lambda cls: {}))+ monkeypatch.setattr(+ svc_mod.requests, 'request',+ lambda *a, **kw: pytest.fail('API must not be called without a key'))+ result = DnsServerService.list_zones()+ assert result['success'] is False+ assert 'API key' in result['error']+++# ---------------------------------------------------------------------------+# service: delegation check (mini DNS client)+# ---------------------------------------------------------------------------++def _ns_response_packet(query_id):+ """A DNS response for `example.com NS` with two compressed NS answers."""+ header = struct.pack('>HHHHHH', query_id, 0x8180, 1, 2, 0, 0)+ qname = b'\x07example\x03com\x00'+ question = qname + struct.pack('>HH', 2, 1)+ # Answers use a compression pointer back to offset 12 for both the owner+ # name and the rdata suffix.+ ptr = b'\xc0\x0c'+ answer1 = ptr + struct.pack('>HHIH', 2, 1, 3600, 6) + b'\x03ns1' + ptr+ answer2 = ptr + struct.pack('>HHIH', 2, 1, 3600, 6) + b'\x03ns2' + ptr+ return header + question + answer1 + answer2+++def test_parse_ns_response_fixture_packet():+ packet = _ns_response_packet(0x1234)+ names = DnsServerService._parse_ns_response(packet, 0x1234)+ assert names == ['ns1.example.com', 'ns2.example.com']+++def test_parse_ns_response_rejects_id_mismatch():+ packet = _ns_response_packet(0x1234)+ with pytest.raises(ValueError):+ DnsServerService._parse_ns_response(packet, 0x9999)+++def test_parse_ns_response_rejects_truncated():+ with pytest.raises(ValueError):+ DnsServerService._parse_ns_response(b'\x00\x01\x02', 1)+++def test_build_ns_query_roundtrip():+ packet = DnsServerService._build_ns_query('example.com.', 0x4242)+ rid, flags, qdcount, ancount, _, _ = struct.unpack('>HHHHHH', packet[:12])+ assert rid == 0x4242+ assert flags == 0x0100 # RD+ assert (qdcount, ancount) == (1, 0)+ assert b'\x07example\x03com\x00' in packet+ assert packet.endswith(struct.pack('>HH', 2, 1))+++def test_check_delegation_match(monkeypatch, linux):+ monkeypatch.setattr(+ DnsServerService, 'get_zone',+ classmethod(lambda cls, z: {'success': True, 'zone': {'rrsets': [+ {'name': 'example.com.', 'type': 'NS',+ 'records': ['ns1.example.com.', 'ns2.example.com.']},+ ]}}))+ monkeypatch.setattr(+ DnsServerService, '_query_public_ns',+ classmethod(lambda cls, z: ['ns2.example.com', 'ns1.example.com']))+ result = DnsServerService.check_delegation('example.com')+ assert result['success'] is True+ assert result['checked'] is True+ assert result['delegated'] is True+ assert result['zone_ns'] == ['ns1.example.com', 'ns2.example.com']+++def test_check_delegation_mismatch_and_unreachable(monkeypatch, linux):+ monkeypatch.setattr(+ DnsServerService, 'get_zone',+ classmethod(lambda cls, z: {'success': True, 'zone': {'rrsets': [+ {'name': 'example.com.', 'type': 'NS', 'records': ['ns1.example.com.']},+ ]}}))+ monkeypatch.setattr(+ DnsServerService, '_query_public_ns',+ classmethod(lambda cls, z: ['dns1.registrar-parking.net']))+ result = DnsServerService.check_delegation('example.com')+ assert result['delegated'] is False+ assert result['note']++ def boom(cls, z):+ raise OSError('network down')++ monkeypatch.setattr(DnsServerService, '_query_public_ns', classmethod(boom))+ result = DnsServerService.check_delegation('example.com')+ assert result['success'] is True # best-effort, never a hard failure+ assert result['checked'] is False+ assert 'network down' in result['note']+++# ---------------------------------------------------------------------------+# blueprint routes+# ---------------------------------------------------------------------------++def dns_app(app):+ """Register the extension blueprint on the test app (name-guarded)."""+ if 'dns_server' not in app.blueprints:+ app.register_blueprint(bp_mod.dns_server_bp, url_prefix='/api/v1/dns-server')+ return app+++def dns_client(dns_app):+ return dns_app.test_client()+++def test_routes_require_auth(dns_client):+ assert dns_client.get('/api/v1/dns-server/status').status_code == 401+ assert dns_client.post('/api/v1/dns-server/install', json={}).status_code == 401+ assert dns_client.get('/api/v1/dns-server/zones').status_code == 401+ assert dns_client.post('/api/v1/dns-server/zones', json={}).status_code == 401+++def test_status_route(dns_client, auth_headers, monkeypatch):+ monkeypatch.setattr(+ DnsServerService, 'get_status',+ classmethod(lambda cls: {+ 'installed': True, 'running': True, 'version': '4.9.3',+ 'image': svc_mod.IMAGE, 'container': svc_mod.CONTAINER_NAME,+ 'ns_hostname': 'ns1.example.com', 'authoritative_only': True,+ 'docs_url': svc_mod.DOCS_URL,+ }))+ resp = dns_client.get('/api/v1/dns-server/status', headers=auth_headers)+ assert resp.status_code == 200+ data = resp.get_json()+ assert data['installed'] is True+ assert data['version'] == '4.9.3'+ assert data['authoritative_only'] is True+++def test_install_route(dns_client, auth_headers, monkeypatch):+ captured = {}++ def fake_install(cls, ns_hostname, admin_email):+ captured.update(ns=ns_hostname, email=admin_email)+ return {'success': True, 'message': 'ok', 'container': svc_mod.CONTAINER_NAME}++ monkeypatch.setattr(DnsServerService, 'install', classmethod(fake_install))+ resp = dns_client.post(+ '/api/v1/dns-server/install',+ json={'ns_hostname': 'ns1.example.com', 'admin_email': '[email protected]'},+ headers=auth_headers)+ assert resp.status_code == 201+ assert captured == {'ns': 'ns1.example.com', 'email': '[email protected]'}++ # Missing fields are a 400 before the service is touched.+ resp = dns_client.post('/api/v1/dns-server/install', json={}, headers=auth_headers)+ assert resp.status_code == 400+ assert 'error' in resp.get_json()+++def test_uninstall_route_parses_keep_data(dns_client, auth_headers, monkeypatch):+ seen = {}+ monkeypatch.setattr(+ DnsServerService, 'uninstall',+ classmethod(lambda cls, keep_data=True: seen.update(keep=keep_data)+ or {'success': True, 'message': 'removed'}))+ resp = dns_client.delete('/api/v1/dns-server/install?keep_data=false',+ headers=auth_headers)+ assert resp.status_code == 200+ assert seen['keep'] is False+ dns_client.delete('/api/v1/dns-server/install', headers=auth_headers)+ assert seen['keep'] is True+++def test_routes_report_not_installed(dns_client, auth_headers, monkeypatch):+ monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: False))+ for method, path in [+ ('get', '/api/v1/dns-server/zones'),+ ('post', '/api/v1/dns-server/zones'),+ ('get', '/api/v1/dns-server/zones/example.com'),+ ('delete', '/api/v1/dns-server/zones/example.com'),+ ('post', '/api/v1/dns-server/zones/example.com/rrsets'),+ ('delete', '/api/v1/dns-server/zones/example.com/rrsets'),+ ('post', '/api/v1/dns-server/zones/example.com/dnssec'),+ ]:+ resp = getattr(dns_client, method)(path, headers=auth_headers, json={})+ assert resp.status_code == 503, path+ assert 'error' in resp.get_json()+++def test_zones_routes_happy_path(dns_client, auth_headers, monkeypatch):+ monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: True))+ monkeypatch.setattr(+ DnsServerService, 'list_zones',+ classmethod(lambda cls: {'success': True, 'zones': [+ {'name': 'example.com.', 'kind': 'Native', 'serial': 1, 'dnssec': False},+ ]}))+ resp = dns_client.get('/api/v1/dns-server/zones', headers=auth_headers)+ assert resp.status_code == 200+ assert resp.get_json()['zones'][0]['name'] == 'example.com.'++ monkeypatch.setattr(+ DnsServerService, 'create_zone',+ classmethod(lambda cls, name: {'success': True, 'zone': 'example.com.',+ 'message': 'created'}))+ resp = dns_client.post('/api/v1/dns-server/zones',+ json={'name': 'example.com'}, headers=auth_headers)+ assert resp.status_code == 201++ resp = dns_client.post('/api/v1/dns-server/zones', json={}, headers=auth_headers)+ assert resp.status_code == 400+++def test_zone_detail_route_includes_ds_and_delegation(dns_client, auth_headers, monkeypatch):+ monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: True))+ monkeypatch.setattr(+ DnsServerService, 'get_zone',+ classmethod(lambda cls, z: {'success': True, 'zone': {+ 'name': 'example.com.', 'kind': 'Native', 'serial': 1,+ 'dnssec': True, 'rrsets': [],+ }}))+ monkeypatch.setattr(+ DnsServerService, 'get_ds_records',+ classmethod(lambda cls, z: {'success': True, 'ds_records': ['12345 13 2 aa']}))+ monkeypatch.setattr(+ DnsServerService, 'check_delegation',+ classmethod(lambda cls, z: {'success': True, 'checked': True,+ 'delegated': True, 'zone_ns': [],+ 'public_ns': [], 'note': None}))+ resp = dns_client.get('/api/v1/dns-server/zones/example.com', headers=auth_headers)+ assert resp.status_code == 200+ data = resp.get_json()+ assert data['zone']['dnssec'] is True+ assert data['ds_records'] == ['12345 13 2 aa']+ assert data['delegation']['delegated'] is True+++def test_rrset_routes(dns_client, auth_headers, monkeypatch):+ monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: True))+ captured = {}++ def fake_upsert(cls, zone, name, rtype, ttl, records):+ captured.update(zone=zone, name=name, rtype=rtype, ttl=ttl, records=records)+ return {'success': True, 'message': 'saved'}++ monkeypatch.setattr(DnsServerService, 'upsert_rrset', classmethod(fake_upsert))+ resp = dns_client.post(+ '/api/v1/dns-server/zones/example.com/rrsets',+ json={'name': 'www', 'type': 'A', 'ttl': 300, 'records': ['203.0.113.7']},+ headers=auth_headers)+ assert resp.status_code == 200+ assert captured == {'zone': 'example.com', 'name': 'www', 'rtype': 'A',+ 'ttl': 300, 'records': ['203.0.113.7']}++ resp = dns_client.post('/api/v1/dns-server/zones/example.com/rrsets',+ json={'name': 'www'}, headers=auth_headers)+ assert resp.status_code == 400 # type is required++ monkeypatch.setattr(+ DnsServerService, 'delete_rrset',+ classmethod(lambda cls, zone, name, rtype: {'success': True, 'message': 'gone'}))+ resp = dns_client.delete(+ '/api/v1/dns-server/zones/example.com/rrsets?name=www&type=A',+ headers=auth_headers)+ assert resp.status_code == 200+++def test_dnssec_route(dns_client, auth_headers, monkeypatch):+ monkeypatch.setattr(DnsServerService, 'is_installed', classmethod(lambda cls: True))+ monkeypatch.setattr(+ DnsServerService, 'set_dnssec',+ classmethod(lambda cls, zone, enabled: {+ 'success': True, 'dnssec': enabled,+ 'ds_records': ['12345 13 2 aa'] if enabled else [],+ }))+ resp = dns_client.post('/api/v1/dns-server/zones/example.com/dnssec',+ json={'action': 'enable'}, headers=auth_headers)+ assert resp.status_code == 200+ assert resp.get_json()['ds_records'] == ['12345 13 2 aa']++ resp = dns_client.post('/api/v1/dns-server/zones/example.com/dnssec',+ json={'action': 'sideways'}, headers=auth_headers)+ assert resp.status_code == 400diff --git a/builtin-extensions/serverkit-dns-server/backend/__init__.py b/builtin-extensions/serverkit-dns-server/backend/__init__.pynew file mode 100644index 00000000..041f76f3--- /dev/null+++ b/builtin-extensions/serverkit-dns-server/backend/__init__.py@@ -0,0 +1 @@+"""ServerKit DNS Server extension backend package."""diff --git a/builtin-extensions/serverkit-dns-server/backend/dns_server.py b/builtin-extensions/serverkit-dns-server/backend/dns_server.pynew file mode 100644index 00000000..e41d54ee--- /dev/null+++ b/builtin-extensions/serverkit-dns-server/backend/dns_server.py@@ -0,0 +1,187 @@+"""DNS Server API endpoints (serverkit-dns-server extension).++Mounted under ``/api/v1/dns-server`` via the manifest's ``url_prefix``. Thin+routing layer over :class:`DnsServerService` — all Docker and PowerDNS API+work happens in the service. Reads need viewer, mutations need admin (same+split as the serverkit-crowdsec extension).+"""+from flask import Blueprint, jsonify, request++from app.middleware.rbac import admin_required, viewer_required+from .dns_server_service import DnsServerService++dns_server_bp = Blueprint('dns_server', __name__)++_NOT_INSTALLED = (+ 'The DNS server is not installed. Install it from the DNS Server page '+ '(admin only).'+)+++def _installed_or_error():+ """Return an error response tuple when the container is absent, else None."""+ if not DnsServerService.is_installed():+ return jsonify({'error': _NOT_INSTALLED}), 503+ return None+++# ── Status / lifecycle ──++@dns_server_bp.route('/status', methods=['GET'])+@viewer_required+def get_status():+ """Installed / running / version / nameserver hostname summary."""+ return jsonify(DnsServerService.get_status()), 200+++@dns_server_bp.route('/install', methods=['POST'])+@admin_required+def install():+ """Run the PowerDNS container: {ns_hostname, admin_email}."""+ data = request.get_json() or {}+ ns_hostname = (data.get('ns_hostname') or '').strip()+ admin_email = (data.get('admin_email') or '').strip()+ if not ns_hostname:+ return jsonify({'error': 'ns_hostname is required'}), 400+ if not admin_email:+ return jsonify({'error': 'admin_email is required'}), 400+ result = DnsServerService.install(ns_hostname, admin_email)+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Install failed')}), 400+ return jsonify(result), 201+++@dns_server_bp.route('/install', methods=['DELETE'])+@admin_required+def uninstall():+ """Remove the container (?keep_data=true keeps the SQLite zone data)."""+ keep_data = (request.args.get('keep_data', 'true').lower()+ not in ('false', '0', 'no'))+ result = DnsServerService.uninstall(keep_data=keep_data)+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Uninstall failed')}), 400+ return jsonify(result), 200+++# ── Zones ──++@dns_server_bp.route('/zones', methods=['GET'])+@viewer_required+def list_zones():+ guard = _installed_or_error()+ if guard:+ return guard+ result = DnsServerService.list_zones()+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Failed to list zones')}), 500+ return jsonify({'zones': result['zones']}), 200+++@dns_server_bp.route('/zones', methods=['POST'])+@admin_required+def create_zone():+ """Create a zone: {name}. SOA/NS are bootstrapped from install params."""+ guard = _installed_or_error()+ if guard:+ return guard+ data = request.get_json() or {}+ name = (data.get('name') or '').strip()+ if not name:+ return jsonify({'error': 'name is required'}), 400+ result = DnsServerService.create_zone(name)+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Failed to create zone')}), 400+ return jsonify(result), 201+++@dns_server_bp.route('/zones/<path:zone>', methods=['GET'])+@viewer_required+def get_zone(zone):+ """Zone detail: rrsets + DNSSEC status (+DS) + delegation check."""+ guard = _installed_or_error()+ if guard:+ return guard+ result = DnsServerService.get_zone(zone)+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Failed to load zone')}), 404+ payload = {'zone': result['zone']}+ if result['zone'].get('dnssec'):+ ds = DnsServerService.get_ds_records(zone)+ payload['ds_records'] = ds.get('ds_records', []) if ds.get('success') else []+ payload['delegation'] = DnsServerService.check_delegation(zone)+ return jsonify(payload), 200+++@dns_server_bp.route('/zones/<path:zone>', methods=['DELETE'])+@admin_required+def delete_zone(zone):+ guard = _installed_or_error()+ if guard:+ return guard+ result = DnsServerService.delete_zone(zone)+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Failed to delete zone')}), 400+ return jsonify(result), 200+++# ── Record sets ──++@dns_server_bp.route('/zones/<path:zone>/rrsets', methods=['POST'])+@admin_required+def upsert_rrset(zone):+ """Create or replace a record set: {name, type, ttl, records: [...]}."""+ guard = _installed_or_error()+ if guard:+ return guard+ data = request.get_json() or {}+ rtype = (data.get('type') or '').strip()+ if not rtype:+ return jsonify({'error': 'type is required'}), 400+ result = DnsServerService.upsert_rrset(+ zone,+ data.get('name'),+ rtype,+ data.get('ttl', 3600),+ data.get('records') or [],+ )+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Failed to save record set')}), 400+ return jsonify(result), 200+++@dns_server_bp.route('/zones/<path:zone>/rrsets', methods=['DELETE'])+@admin_required+def delete_rrset(zone):+ """Delete a record set — name/type via query params or JSON body."""+ guard = _installed_or_error()+ if guard:+ return guard+ data = request.get_json(silent=True) or {}+ name = request.args.get('name', data.get('name'))+ rtype = (request.args.get('type') or data.get('type') or '').strip()+ if not rtype:+ return jsonify({'error': 'type is required'}), 400+ result = DnsServerService.delete_rrset(zone, name, rtype)+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Failed to delete record set')}), 400+ return jsonify(result), 200+++# ── DNSSEC ──++@dns_server_bp.route('/zones/<path:zone>/dnssec', methods=['POST'])+@admin_required+def set_dnssec(zone):+ """Enable/disable DNSSEC: {action: 'enable'|'disable'}. Enable returns+ the DS records to publish at the registrar."""+ guard = _installed_or_error()+ if guard:+ return guard+ data = request.get_json() or {}+ action = (data.get('action') or '').strip().lower()+ if action not in ('enable', 'disable'):+ return jsonify({'error': "action must be 'enable' or 'disable'"}), 400+ result = DnsServerService.set_dnssec(zone, action == 'enable')+ if not result.get('success'):+ return jsonify({'error': result.get('error', 'Failed to update DNSSEC')}), 400+ return jsonify(result), 200diff --git a/builtin-extensions/serverkit-dns-server/backend/dns_server_service.py b/builtin-extensions/serverkit-dns-server/backend/dns_server_service.pynew file mode 100644index 00000000..a67fd003--- /dev/null+++ b/builtin-extensions/serverkit-dns-server/backend/dns_server_service.py@@ -0,0 +1,634 @@+"""Authoritative DNS hosting service (serverkit-dns-server extension).++Runs PowerDNS Authoritative Server (SQLite backend) in a managed Docker+container so a ServerKit box can BE the nameserver for its domains. Built+for homelab / air-gapped setups; it complements the provider-based DNS+integrations (Cloudflare etc.) and never replaces them.++Design notes, mirroring the serverkit-crowdsec extension:++* **Two choke-points** — every Docker invocation goes through+ :meth:`_docker` (privilege escalation, timeouts, error shaping) and every+ PowerDNS HTTP API call goes through :meth:`_api` (auth header, JSON,+ error shaping). Nothing else shells out or talks HTTP.+* **Authoritative only** — ``pdns-auth`` does not recurse, by design. This+ extension will never answer recursive queries for clients; it only serves+ the zones the operator creates. Point resolvers elsewhere.+* **Best-effort, Linux-only** — on Windows (dev) or when Docker is absent,+ calls return a clean error dict instead of raising.+* **State lives in PowerDNS** — zone data is PowerDNS's own SQLite file+ under ``/var/serverkit/dns-server``; the extension's few settings+ (generated API key, NS hostname, hostmaster email) live in the plugin+ config store (``plugins_sdk.config``). No core models, no migrations.+"""+import json+import logging+import os+import re+import secrets+import socket+import struct+import subprocess++import requests++from app.utils.system import run_privileged, is_command_available++logger = logging.getLogger(__name__)++SLUG = 'serverkit-dns-server'++# Official PowerDNS Authoritative Server image, 4.9.x line.+IMAGE = 'powerdns/pdns-auth-49'+CONTAINER_NAME = 'serverkit-dns-server'+DATA_DIR = '/var/serverkit/dns-server'+# SQLite path *inside* the container (DATA_DIR is bind-mounted there).+CONTAINER_DB_DIR = '/var/lib/powerdns'++API_HOST = '127.0.0.1'+API_PORT = 8081+API_BASE = f'http://{API_HOST}:{API_PORT}/api/v1'+API_TIMEOUT = 10+DOCKER_TIMEOUT = 120++DOCS_URL = 'https://doc.powerdns.com/authoritative/'++# Record types the panel will read/write. Anything else is rejected.+ALLOWED_RECORD_TYPES = frozenset(+ ('A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SRV', 'CAA', 'PTR', 'SOA'))++# Hostname labels: letters/digits/hyphen, plus '_' (SRV/TXT conventions) and a+# lone '*' for wildcards. No leading/trailing hyphen.+_LABEL_RE = re.compile(r'^(?:\*|_?[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)$')+_HOSTNAME_RE = re.compile(+ r'^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?'+ r'(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+\.?$')+_EMAIL_RE = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')++# Public resolvers asked during the best-effort delegation check.+DELEGATION_RESOLVERS = ('1.1.1.1', '8.8.8.8')+_QTYPE_NS = 2+_QCLASS_IN = 1+++def _canonical_zone(zone):+ """Normalize a zone name to lowercase, dot-terminated. None if invalid."""+ if not zone or not isinstance(zone, str):+ return None+ z = zone.strip().lower().rstrip('.')+ if not z or not _HOSTNAME_RE.match(z + '.') or '*' in z:+ return None+ return z + '.'+++def _valid_record_name(name):+ """True when every label of *name* (dot-terminated FQDN) is well-formed."""+ labels = name.rstrip('.').split('.')+ return all(_LABEL_RE.match(lbl) for lbl in labels)+++class DnsServerService:+ """Stateless wrapper around Docker + the PowerDNS HTTP API."""++ # ---------- config (plugin config store) ----------++ @classmethod+ def _config(cls):+ """Saved extension settings from the plugin config store."""+ from app.plugins_sdk import config as plugin_config+ return plugin_config(SLUG)++ @classmethod+ def _save_config(cls, updates):+ """Merge *updates* into the plugin's stored config.++ The SDK ``config()`` helper is read-only (the panel owns writes), so+ the generated API key is persisted through the InstalledPlugin row+ directly. Returns False when the plugin row is absent (dev shells).+ """+ from app import db+ from app.models.plugin import InstalledPlugin+ row = InstalledPlugin.query.filter_by(slug=SLUG).first()+ if not row:+ logger.warning('%s: no InstalledPlugin row; config not persisted', SLUG)+ return False+ merged = dict(row.config or {})+ merged.update(updates)+ row.config = merged+ db.session.commit()+ return True++ # ---------- docker choke-point ----------++ @classmethod+ def _docker(cls, args, timeout=DOCKER_TIMEOUT):+ """Run ``docker <args>`` and return a normalized result dict."""+ if os.name == 'nt':+ return {'success': False,+ 'error': 'The DNS server extension is not supported on Windows.'}+ if not is_command_available('docker'):+ return {'success': False, 'not_installed': True,+ 'error': 'Docker is not installed on this host.'}+ cmd = ['docker'] + list(args)+ try:+ result = run_privileged(cmd, timeout=timeout)+ except subprocess.TimeoutExpired:+ return {'success': False, 'error': f'docker timed out after {timeout}s'}+ except (OSError, subprocess.SubprocessError) as e:+ return {'success': False, 'error': f'Failed to run docker: {e}'}+ out = {+ 'success': result.returncode == 0,+ 'returncode': result.returncode,+ 'stdout': result.stdout or '',+ 'stderr': result.stderr or '',+ }+ if not out['success']:+ out['error'] = (out['stderr'] or out['stdout'] or 'docker failed').strip()+ return out++ # ---------- PowerDNS API choke-point ----------++ @classmethod+ def _api(cls, method, path, payload=None):+ """Call the container's PowerDNS HTTP API (loopback only).++ Returns ``{'success': True, 'data': <json-or-None>}`` or an error+ dict. The web server is published on 127.0.0.1 exclusively, so this+ never leaves the host.+ """+ api_key = cls._config().get('api_key')+ if not api_key:+ return {'success': False,+ 'error': 'PowerDNS API key is not configured. Reinstall the DNS server.'}+ try:+ resp = requests.request(+ method, API_BASE + path,+ headers={'X-API-Key': api_key},+ json=payload,+ timeout=API_TIMEOUT,+ )+ except requests.RequestException as e:+ return {'success': False,+ 'error': f'PowerDNS API is unreachable: {e}'}+ if resp.status_code >= 400:+ try:+ detail = resp.json().get('error') or resp.text+ except ValueError:+ detail = resp.text+ return {'success': False,+ 'error': f'PowerDNS API error ({resp.status_code}): {detail}'.strip()}+ if not resp.content:+ return {'success': True, 'data': None}+ try:+ return {'success': True, 'data': resp.json()}+ except ValueError:+ return {'success': False, 'error': 'PowerDNS API returned invalid JSON'}++ # ---------- container lifecycle ----------++ @classmethod+ def is_installed(cls):+ """True when the managed container exists (running or not)."""+ if os.name == 'nt':+ return False+ res = cls._docker(['inspect', '--format', '{{.State.Running}}',+ CONTAINER_NAME], timeout=20)+ return bool(res.get('success'))++ @classmethod+ def get_status(cls):+ """Installed / running / version / config summary, best-effort."""+ status = {+ 'installed': False,+ 'running': False,+ 'version': None,+ 'image': IMAGE,+ 'container': CONTAINER_NAME,+ 'ns_hostname': cls._config().get('ns_hostname') if os.name != 'nt' else None,+ 'authoritative_only': True,+ 'docs_url': DOCS_URL,+ }+ if os.name == 'nt':+ return status+ res = cls._docker(['inspect', '--format', '{{.State.Running}}',+ CONTAINER_NAME], timeout=20)+ if not res.get('success'):+ return status+ status['installed'] = True+ status['running'] = res.get('stdout', '').strip() == 'true'+ if status['running']:+ info = cls._api('GET', '/servers/localhost')+ if info.get('success') and isinstance(info.get('data'), dict):+ status['version'] = info['data'].get('version')+ return status++ @classmethod+ def install(cls, ns_hostname, admin_email):+ """Create and start the PowerDNS container.++ * SQLite state bind-mounted at ``DATA_DIR`` (the official image+ bootstraps the schema on first start).+ * Port 53 published on tcp+udp (the box becomes a nameserver).+ * HTTP API enabled with a generated key, web server published on+ **127.0.0.1 only** — never reachable off-host.+ """+ if os.name == 'nt':+ return {'success': False,+ 'error': 'The DNS server extension is not supported on Windows.'}+ ns_hostname = (ns_hostname or '').strip().lower().rstrip('.')+ admin_email = (admin_email or '').strip()+ if not ns_hostname or not _HOSTNAME_RE.match(ns_hostname):+ return {'success': False,+ 'error': f'Invalid nameserver hostname: {ns_hostname!r}'}+ if not admin_email or not _EMAIL_RE.match(admin_email):+ return {'success': False,+ 'error': f'Invalid hostmaster email: {admin_email!r}'}+ if cls.is_installed():+ return {'success': False,+ 'error': 'The DNS server container already exists. Uninstall it first.'}++ dir_res = run_privileged(['mkdir', '-p', DATA_DIR])+ if getattr(dir_res, 'returncode', 1) != 0:+ return {'success': False,+ 'error': f'Could not create data directory {DATA_DIR}: '+ f'{(dir_res.stderr or "").strip()}'}++ api_key = secrets.token_hex(24)+ run_args = [+ 'run', '-d',+ '--name', CONTAINER_NAME,+ '--restart', 'unless-stopped',+ '-p', '53:53/udp',+ '-p', '53:53/tcp',+ '-p', f'{API_HOST}:{API_PORT}:{API_PORT}',+ '-v', f'{DATA_DIR}:{CONTAINER_DB_DIR}',+ IMAGE,+ # pdns_server flags (the image forwards container args to pdns):+ '--api=yes',+ f'--api-key={api_key}',+ '--webserver=yes',+ '--webserver-address=0.0.0.0',+ f'--webserver-port={API_PORT}',+ '--webserver-allow-from=0.0.0.0/0',+ '--launch=gsqlite3',+ f'--gsqlite3-database={CONTAINER_DB_DIR}/pdns.sqlite3',+ '--gsqlite3-dnssec=yes',+ ]+ res = cls._docker(run_args)+ if not res.get('success'):+ return {'success': False,+ 'error': res.get('error', 'Failed to start the PowerDNS container')}++ persisted = cls._save_config({+ 'api_key': api_key,+ 'ns_hostname': ns_hostname,+ 'admin_email': admin_email,+ })+ result = {'success': True,+ 'message': 'PowerDNS authoritative server installed',+ 'container': CONTAINER_NAME}+ if not persisted:+ result['warning'] = ('Container started but the API key could not be '+ 'persisted to the plugin config store.')+ return result++ @classmethod+ def uninstall(cls, keep_data=True):+ """Remove the container; optionally delete the SQLite zone data."""+ if os.name == 'nt':+ return {'success': False,+ 'error': 'The DNS server extension is not supported on Windows.'}+ res = cls._docker(['rm', '-f', CONTAINER_NAME])+ if not res.get('success'):+ return {'success': False,+ 'error': res.get('error', 'Failed to remove the PowerDNS container')}+ if not keep_data:+ rm = run_privileged(['rm', '-rf', DATA_DIR])+ if getattr(rm, 'returncode', 1) != 0:+ return {'success': True,+ 'warning': f'Container removed but zone data at {DATA_DIR} '+ f'could not be deleted: {(rm.stderr or "").strip()}'}+ cls._save_config({'api_key': None})+ return {'success': True,+ 'message': 'DNS server removed'+ + ('' if keep_data else ' (zone data deleted)')}++ # ---------- zones ----------++ @classmethod+ def list_zones(cls):+ res = cls._api('GET', '/servers/localhost/zones')+ if not res.get('success'):+ return res+ zones = [{+ 'name': z.get('name'),+ 'kind': z.get('kind'),+ 'serial': z.get('serial'),+ 'dnssec': bool(z.get('dnssec')),+ } for z in (res.get('data') or [])]+ return {'success': True, 'zones': zones}++ @classmethod+ def create_zone(cls, zone):+ """Create a Native zone with a bootstrap SOA + NS from install params."""+ canonical = _canonical_zone(zone)+ if not canonical:+ return {'success': False, 'error': f'Invalid zone name: {zone!r}'}+ cfg = cls._config()+ ns_hostname = (cfg.get('ns_hostname') or '').rstrip('.')+ admin_email = cfg.get('admin_email') or ''+ if not ns_hostname or not admin_email:+ return {'success': False,+ 'error': 'Nameserver hostname / hostmaster email are not '+ 'configured. Reinstall the DNS server.'}+ hostmaster = admin_email.replace('@', '.').rstrip('.') + '.'+ soa_content = f'{ns_hostname}. {hostmaster} 1 10800 3600 604800 3600'+ payload = {+ 'name': canonical,+ 'kind': 'Native',+ 'rrsets': [+ {+ 'name': canonical, 'type': 'SOA', 'ttl': 3600,+ 'changetype': 'REPLACE',+ 'records': [{'content': soa_content, 'disabled': False}],+ },+ {+ 'name': canonical, 'type': 'NS', 'ttl': 3600,+ 'changetype': 'REPLACE',+ 'records': [{'content': f'{ns_hostname}.', 'disabled': False}],+ },+ ],+ }+ res = cls._api('POST', '/servers/localhost/zones', payload)+ if not res.get('success'):+ return res+ return {'success': True, 'zone': canonical,+ 'message': f'Zone {canonical} created'}++ @classmethod+ def delete_zone(cls, zone):+ canonical = _canonical_zone(zone)+ if not canonical:+ return {'success': False, 'error': f'Invalid zone name: {zone!r}'}+ res = cls._api('DELETE', f'/servers/localhost/zones/{canonical}')+ if not res.get('success'):+ return res+ return {'success': True, 'message': f'Zone {canonical} deleted'}++ @classmethod+ def get_zone(cls, zone):+ """Zone detail: normalized rrsets + dnssec flag."""+ canonical = _canonical_zone(zone)+ if not canonical:+ return {'success': False, 'error': f'Invalid zone name: {zone!r}'}+ res = cls._api('GET', f'/servers/localhost/zones/{canonical}')+ if not res.get('success'):+ return res+ data = res.get('data') or {}+ rrsets = [{+ 'name': r.get('name'),+ 'type': r.get('type'),+ 'ttl': r.get('ttl'),+ 'records': [rec.get('content') for rec in (r.get('records') or [])+ if not rec.get('disabled')],+ } for r in (data.get('rrsets') or [])]+ return {'success': True, 'zone': {+ 'name': data.get('name'),+ 'kind': data.get('kind'),+ 'serial': data.get('serial'),+ 'dnssec': bool(data.get('dnssec')),+ 'rrsets': rrsets,+ }}++ # ---------- rrsets ----------++ @classmethod+ def _rrset_target(cls, zone, name, rtype):+ """Validate + canonicalize an rrset target. Returns (zone, fqdn) or error dict."""+ canonical = _canonical_zone(zone)+ if not canonical:+ return {'success': False, 'error': f'Invalid zone name: {zone!r}'}+ rtype = (rtype or '').strip().upper()+ if rtype not in ALLOWED_RECORD_TYPES:+ allowed = ', '.join(sorted(ALLOWED_RECORD_TYPES))+ return {'success': False,+ 'error': f'Unsupported record type {rtype!r}. Allowed: {allowed}'}+ raw = (name or '').strip().lower()+ if raw in ('', '@', canonical.rstrip('.')):+ fqdn = canonical+ elif raw.endswith('.'):+ fqdn = raw+ else:+ fqdn = f'{raw}.{canonical}'+ if not (fqdn == canonical or fqdn.endswith('.' + canonical)):+ return {'success': False,+ 'error': f'{name!r} is not inside zone {canonical}'}+ if not _valid_record_name(fqdn):+ return {'success': False, 'error': f'Invalid record name: {name!r}'}+ return canonical, fqdn, rtype++ @classmethod+ def upsert_rrset(cls, zone, name, rtype, ttl, records):+ target = cls._rrset_target(zone, name, rtype)+ if isinstance(target, dict):+ return target+ canonical, fqdn, rtype = target+ try:+ ttl = int(ttl)+ except (TypeError, ValueError):+ return {'success': False, 'error': f'Invalid TTL: {ttl!r}'}+ if not (1 <= ttl <= 604800):+ return {'success': False, 'error': 'TTL must be between 1 and 604800'}+ values = [str(r).strip() for r in (records or []) if str(r).strip()]+ if not values:+ return {'success': False, 'error': 'At least one record value is required'}+ payload = {'rrsets': [{+ 'name': fqdn, 'type': rtype, 'ttl': ttl, 'changetype': 'REPLACE',+ 'records': [{'content': v, 'disabled': False} for v in values],+ }]}+ res = cls._api('PATCH', f'/servers/localhost/zones/{canonical}', payload)+ if not res.get('success'):+ return res+ return {'success': True, 'message': f'{rtype} record set saved for {fqdn}'}++ @classmethod+ def delete_rrset(cls, zone, name, rtype):+ target = cls._rrset_target(zone, name, rtype)+ if isinstance(target, dict):+ return target+ canonical, fqdn, rtype = target+ if rtype == 'SOA':+ return {'success': False,+ 'error': 'The SOA record cannot be deleted (edit it instead).'}+ payload = {'rrsets': [{+ 'name': fqdn, 'type': rtype, 'changetype': 'DELETE', 'records': [],+ }]}+ res = cls._api('PATCH', f'/servers/localhost/zones/{canonical}', payload)+ if not res.get('success'):+ return res+ return {'success': True, 'message': f'{rtype} record set deleted for {fqdn}'}++ # ---------- DNSSEC ----------++ @classmethod+ def get_ds_records(cls, zone):+ """DS records (paste at the registrar/parent) from active cryptokeys."""+ canonical = _canonical_zone(zone)+ if not canonical:+ return {'success': False, 'error': f'Invalid zone name: {zone!r}'}+ res = cls._api('GET', f'/servers/localhost/zones/{canonical}/cryptokeys')+ if not res.get('success'):+ return res+ ds = []+ for key in res.get('data') or []:+ if key.get('active'):+ ds.extend(key.get('ds') or [])+ return {'success': True, 'ds_records': ds}++ @classmethod+ def set_dnssec(cls, zone, enabled):+ """Enable/disable DNSSEC. PowerDNS generates the keys server-side;+ enabling returns the DS records for the parent zone."""+ canonical = _canonical_zone(zone)+ if not canonical:+ return {'success': False, 'error': f'Invalid zone name: {zone!r}'}+ payload = {'dnssec': bool(enabled)}+ if enabled:+ payload['api_rectify'] = True+ res = cls._api('PUT', f'/servers/localhost/zones/{canonical}', payload)+ if not res.get('success'):+ return res+ if not enabled:+ return {'success': True, 'dnssec': False,+ 'message': f'DNSSEC disabled for {canonical}. Remove the DS '+ f'records at your registrar.'}+ ds = cls.get_ds_records(canonical)+ return {'success': True, 'dnssec': True,+ 'ds_records': ds.get('ds_records', []) if ds.get('success') else [],+ 'message': f'DNSSEC enabled for {canonical}. Publish the DS '+ f'records at your registrar to complete the chain.'}++ # ---------- delegation check (minimal stdlib DNS client) ----------++ @staticmethod+ def _build_ns_query(zone, query_id):+ """Build a DNS query packet asking for the NS records of *zone*."""+ header = struct.pack('>HHHHHH', query_id, 0x0100, 1, 0, 0, 0)+ question = b''+ for label in zone.rstrip('.').split('.'):+ encoded = label.encode('idna') if not label.isascii() else label.encode()+ question += struct.pack('>B', len(encoded)) + encoded+ question += b'\x00' + struct.pack('>HH', _QTYPE_NS, _QCLASS_IN)+ return header + question++ @staticmethod+ def _parse_name(data, offset):+ """Decode a (possibly compressed) DNS name. Returns (name, next_offset)."""+ labels = []+ jumped = False+ next_offset = offset+ hops = 0+ while True:+ if offset >= len(data):+ raise ValueError('truncated DNS name')+ length = data[offset]+ if length & 0xC0 == 0xC0: # compression pointer+ if offset + 1 >= len(data):+ raise ValueError('truncated compression pointer')+ pointer = struct.unpack('>H', data[offset:offset + 2])[0] & 0x3FFF+ if not jumped:+ next_offset = offset + 2+ jumped = True+ offset = pointer+ hops += 1+ if hops > 32:+ raise ValueError('compression loop')+ continue+ if length == 0:+ if not jumped:+ next_offset = offset + 1+ break+ offset += 1+ labels.append(data[offset:offset + length].decode('ascii', 'replace'))+ offset += length+ return '.'.join(labels).lower(), next_offset++ @classmethod+ def _parse_ns_response(cls, data, query_id):+ """Extract NS names from a DNS response (answer + authority sections)."""+ if len(data) < 12:+ raise ValueError('truncated DNS header')+ rid, flags, qdcount, ancount, nscount, _ = struct.unpack('>HHHHHH', data[:12])+ if rid != query_id:+ raise ValueError('DNS response id mismatch')+ rcode = flags & 0x000F+ if rcode not in (0, 3): # NOERROR or NXDOMAIN+ raise ValueError(f'DNS query failed with rcode {rcode}')+ offset = 12+ for _ in range(qdcount):+ _, offset = cls._parse_name(data, offset)+ offset += 4 # qtype + qclass+ ns_names = []+ for _ in range(ancount + nscount):+ _, offset = cls._parse_name(data, offset)+ if offset + 10 > len(data):+ raise ValueError('truncated resource record')+ rtype, _, _, rdlength = struct.unpack('>HHIH', data[offset:offset + 10])+ offset += 10+ if rtype == _QTYPE_NS:+ name, _ = cls._parse_name(data, offset)+ ns_names.append(name)+ offset += rdlength+ return ns_names++ @classmethod+ def _query_public_ns(cls, zone):+ """Ask public resolvers for the NS set the world sees for *zone*."""+ query_id = secrets.randbelow(0x10000)+ packet = cls._build_ns_query(zone, query_id)+ last_error = None+ for resolver in DELEGATION_RESOLVERS:+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ sock.settimeout(4)+ sock.sendto(packet, (resolver, 53))+ data, _ = sock.recvfrom(4096)+ return cls._parse_ns_response(data, query_id)+ except (OSError, ValueError) as e:+ last_error = e+ finally:+ sock.close()+ raise OSError(f'All resolvers failed: {last_error}')++ @classmethod+ def check_delegation(cls, zone):+ """Best-effort: does the public NS set for the zone match ours?"""+ canonical = _canonical_zone(zone)+ if not canonical:+ return {'success': False, 'error': f'Invalid zone name: {zone!r}'}++ zone_ns = []+ detail = cls.get_zone(canonical)+ if detail.get('success'):+ for rrset in detail['zone'].get('rrsets', []):+ if rrset.get('type') == 'NS' and rrset.get('name') == canonical:+ zone_ns = sorted(v.rstrip('.').lower() for v in rrset['records'])++ try:+ public_ns = sorted(set(cls._query_public_ns(canonical)))+ except (OSError, ValueError) as e:+ return {'success': True, 'checked': False, 'zone_ns': zone_ns,+ 'public_ns': [], 'delegated': None,+ 'note': f'Could not query public resolvers: {e}'}++ delegated = bool(public_ns) and set(public_ns) == set(zone_ns)+ note = None+ if not public_ns:+ note = ('No public NS records found — the domain is not delegated '+ 'to any nameserver yet. Set the NS (glue) records at your '+ 'registrar.')+ elif not delegated:+ note = ('The public NS set differs from this zone\'s NS records. '+ 'Update the nameservers at your registrar.')+ return {'success': True, 'checked': True, 'zone_ns': zone_ns,+ 'public_ns': public_ns, 'delegated': delegated, 'note': note}diff --git a/builtin-extensions/serverkit-dns-server/frontend/components/DnsServerPage.jsx b/builtin-extensions/serverkit-dns-server/frontend/components/DnsServerPage.jsxnew file mode 100644index 00000000..ef0a4caa--- /dev/null+++ b/builtin-extensions/serverkit-dns-server/frontend/components/DnsServerPage.jsx@@ -0,0 +1,381 @@+import { useCallback, useEffect, useState } from 'react';+import { Globe, RefreshCw, Plus, Trash2, Server } from 'lucide-react';+import api from '@/services/api';+import { PageTopbar, Pill } from '@/components/ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import Modal from '@/components/Modal';+import ConfirmDialog from '@/components/ConfirmDialog';+import EmptyState from '@/components/EmptyState';+import { useToast } from '@/contexts/ToastContext';+import ZoneDetail from './ZoneDetail.jsx';++const DnsServerPage = () => {+ const toast = useToast();++ const [status, setStatus] = useState(null);+ const [zones, setZones] = useState([]);+ const [loading, setLoading] = useState(true);+ const [actionLoading, setActionLoading] = useState(false);+ const [confirmDialog, setConfirmDialog] = useState(null);+ const [selectedZone, setSelectedZone] = useState(null);++ // Install form+ const [installForm, setInstallForm] = useState({ ns_hostname: '', admin_email: '' });++ // New zone modal+ const [showZoneModal, setShowZoneModal] = useState(false);+ const [zoneName, setZoneName] = useState('');++ const loadData = useCallback(async () => {+ setLoading(true);+ try {+ const statusData = await api.request('/dns-server/status');+ setStatus(statusData);+ if (statusData?.installed) {+ const z = await api.request('/dns-server/zones').catch(() => ({ zones: [] }));+ setZones(z.zones || []);+ }+ } catch (error) {+ toast.error(`Failed to load DNS server status: ${error.message}`);+ } finally {+ setLoading(false);+ }+ }, [toast]);++ useEffect(() => {+ loadData();+ }, [loadData]);++ const handleInstall = async () => {+ if (!installForm.ns_hostname.trim() || !installForm.admin_email.trim()) return;+ setActionLoading(true);+ try {+ await api.request('/dns-server/install', {+ method: 'POST',+ body: {+ ns_hostname: installForm.ns_hostname.trim(),+ admin_email: installForm.admin_email.trim(),+ },+ });+ toast.success('PowerDNS authoritative server installed');+ await loadData();+ } catch (error) {+ toast.error(`Install failed: ${error.message}`);+ } finally {+ setActionLoading(false);+ }+ };++ const handleUninstall = (keepData) => {+ setConfirmDialog({+ title: 'Remove DNS server',+ message: keepData+ ? 'Remove the PowerDNS container? Zone data stays on disk and a reinstall picks it back up.'+ : 'Remove the PowerDNS container AND delete all zone data? This cannot be undone.',+ confirmText: 'Remove',+ variant: 'danger',+ onConfirm: async () => {+ try {+ await api.request(`/dns-server/install?keep_data=${keepData}`, { method: 'DELETE' });+ toast.success('DNS server removed');+ setSelectedZone(null);+ await loadData();+ } catch (error) {+ toast.error(`Uninstall failed: ${error.message}`);+ }+ setConfirmDialog(null);+ },+ onCancel: () => setConfirmDialog(null),+ });+ };++ const handleCreateZone = async () => {+ if (!zoneName.trim()) return;+ setActionLoading(true);+ try {+ await api.request('/dns-server/zones', {+ method: 'POST',+ body: { name: zoneName.trim() },+ });+ toast.success(`Zone ${zoneName} created`);+ setShowZoneModal(false);+ setZoneName('');+ await loadData();+ } catch (error) {+ toast.error(`Failed to create zone: ${error.message}`);+ } finally {+ setActionLoading(false);+ }+ };++ const handleDeleteZone = (name) => {+ setConfirmDialog({+ title: 'Delete zone',+ message: `Delete zone ${name} and all of its records?`,+ confirmText: 'Delete',+ variant: 'danger',+ onConfirm: async () => {+ try {+ await api.request(`/dns-server/zones/${encodeURIComponent(name)}`, { method: 'DELETE' });+ toast.success(`Zone ${name} deleted`);+ if (selectedZone === name) setSelectedZone(null);+ await loadData();+ } catch (error) {+ toast.error(`Failed to delete zone: ${error.message}`);+ }+ setConfirmDialog(null);+ },+ onCancel: () => setConfirmDialog(null),+ });+ };++ if (loading) {+ return (+ <div className="page-container dns-server-page">+ <PageTopbar icon={<Globe size={18} />} title="DNS Server" />+ <EmptyState loading title="Loading DNS server status..." />+ </div>+ );+ }++ // ── Not installed: explainer + install form ──+ if (!status?.installed) {+ return (+ <div className="page-container dns-server-page">+ <PageTopbar icon={<Globe size={18} />} title="DNS Server" />+ <div className="card">+ <div className="card-header">+ <h3>Host Your Own Nameserver</h3>+ </div>+ <div className="card-body">+ <p>+ Run PowerDNS (authoritative, SQLite backend) in a managed Docker+ container so this box answers DNS for your domains directly —+ handy for homelabs and air-gapped networks where a hosted DNS+ provider is not an option.+ </p>+ <ul className="dns-explainer">+ <li>+ <strong>Authoritative only.</strong> This serves the zones you+ create; it never resolves other names for clients. Keep using+ your normal resolver.+ </li>+ <li>+ <strong>Port 53 must be free</strong> on this host (tcp + udp).+ systemd-resolved or another DNS service will conflict.+ </li>+ <li>+ <strong>Delegation happens at your registrar.</strong> Point the+ domain's NS (and glue) records at this box's nameserver+ hostname so the world finds it.+ </li>+ <li>+ This complements provider integrations (Cloudflare etc.) — it+ does not replace them.+ </li>+ </ul>+ <div className="dns-install-form">+ <div className="form-group">+ <Label>Nameserver hostname</Label>+ <Input+ type="text"+ value={installForm.ns_hostname}+ onChange={(e) => setInstallForm((f) => ({ ...f, ns_hostname: e.target.value }))}+ placeholder="ns1.example.com"+ />+ <p className="text-muted">+ The hostname other resolvers will use to reach this server.+ It should resolve (via glue records) to this box's public IP.+ </p>+ </div>+ <div className="form-group">+ <Label>Hostmaster email</Label>+ <Input+ type="email"+ value={installForm.admin_email}+ onChange={(e) => setInstallForm((f) => ({ ...f, admin_email: e.target.value }))}+ placeholder="[email protected]"+ />+ <p className="text-muted">Used in each zone's SOA record.</p>+ </div>+ <div className="dns-install-actions">+ <Button+ variant="default"+ onClick={handleInstall}+ disabled={actionLoading || !installForm.ns_hostname.trim() || !installForm.admin_email.trim()}+ >+ {actionLoading ? 'Installing...' : 'Install DNS Server'}+ </Button>+ <Button variant="outline" onClick={loadData}>+ <RefreshCw size={14} /> Re-check+ </Button>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+ }++ return (+ <div className="page-container dns-server-page">+ <PageTopbar+ icon={<Globe size={18} />}+ title="DNS Server"+ actions={+ <>+ <Button variant="default" size="sm" onClick={() => setShowZoneModal(true)}>+ <Plus size={14} /> New Zone+ </Button>+ <Button variant="outline" size="sm" onClick={loadData}>+ <RefreshCw size={14} /> Refresh+ </Button>+ </>+ }+ />++ {/* ── Status ── */}+ <div className="card">+ <div className="card-header">+ <h3>Server Status</h3>+ <div className="card-actions">+ <Button variant="secondary" size="sm" onClick={() => handleUninstall(true)}>+ Remove (keep data)+ </Button>+ <Button variant="destructive" size="sm" onClick={() => handleUninstall(false)}>+ <Trash2 size={14} /> Remove + data+ </Button>+ </div>+ </div>+ <div className="card-body">+ <div className="sec-rows">+ <div className="sk-info-row">+ <span className="k">Container</span>+ <Pill kind={status.running ? 'green' : 'red'}>+ {status.running ? 'Running' : 'Stopped'}+ </Pill>+ </div>+ <div className="sk-info-row">+ <span className="k">Engine</span>+ <span className="v">+ PowerDNS Authoritative {status.version ? `v${status.version}` : '(version unavailable)'}+ </span>+ </div>+ <div className="sk-info-row">+ <span className="k">Nameserver</span>+ <span className="v sk-cell-mono">{status.ns_hostname || '—'}</span>+ </div>+ <div className="sk-info-row">+ <span className="k">Mode</span>+ <span className="v">Authoritative only — no recursion, by design.</span>+ </div>+ </div>+ </div>+ </div>++ {/* ── Zones ── */}+ <div className="card sec-flush">+ <div className="card-header">+ <h3>Zones {zones.length > 0 && <span className="sec-count">· {zones.length}</span>}</h3>+ </div>+ {zones.length === 0 ? (+ <div className="card-body">+ <p className="text-muted">+ No zones yet. Create one, then point the domain's nameservers here+ at your registrar.+ </p>+ </div>+ ) : (+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Zone</th>+ <th>Kind</th>+ <th>Serial</th>+ <th>DNSSEC</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {zones.map((z) => (+ <tr key={z.name}>+ <td className="sk-cell-mono">+ <button+ type="button"+ className="dns-zone-link"+ onClick={() => setSelectedZone(z.name)}+ >+ {z.name}+ </button>+ </td>+ <td>{z.kind || '—'}</td>+ <td>{z.serial ?? '—'}</td>+ <td>+ <Pill kind={z.dnssec ? 'green' : 'gray'}>+ {z.dnssec ? 'Signed' : 'Off'}+ </Pill>+ </td>+ <td>+ <Button variant="secondary" size="sm" onClick={() => setSelectedZone(z.name)}>+ <Server size={14} /> Manage+ </Button>{' '}+ <Button variant="secondary" size="sm" onClick={() => handleDeleteZone(z.name)}>+ Delete+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>++ {/* ── Zone detail ── */}+ {selectedZone && (+ <ZoneDetail+ zoneName={selectedZone}+ onClose={() => setSelectedZone(null)}+ onChanged={loadData}+ />+ )}++ {/* ── New zone modal ── */}+ <Modal open={showZoneModal} onClose={() => setShowZoneModal(false)} title="New Zone">+ <div className="form-group">+ <Label>Zone name</Label>+ <Input+ type="text"+ value={zoneName}+ onChange={(e) => setZoneName(e.target.value)}+ placeholder="example.com"+ />+ <p className="text-muted">+ SOA and NS records are bootstrapped from the nameserver hostname and+ hostmaster email you provided at install.+ </p>+ </div>+ <div className="modal-footer">+ <Button variant="outline" onClick={() => setShowZoneModal(false)}>Cancel</Button>+ <Button variant="default" onClick={handleCreateZone} disabled={actionLoading || !zoneName.trim()}>+ {actionLoading ? 'Creating...' : 'Create Zone'}+ </Button>+ </div>+ </Modal>++ {confirmDialog && (+ <ConfirmDialog+ title={confirmDialog.title}+ message={confirmDialog.message}+ confirmText={confirmDialog.confirmText}+ variant={confirmDialog.variant}+ onConfirm={confirmDialog.onConfirm}+ onCancel={confirmDialog.onCancel}+ />+ )}+ </div>+ );+};++export default DnsServerPage;diff --git a/builtin-extensions/serverkit-dns-server/frontend/components/ZoneDetail.jsx b/builtin-extensions/serverkit-dns-server/frontend/components/ZoneDetail.jsxnew file mode 100644index 00000000..4d9a1fb3--- /dev/null+++ b/builtin-extensions/serverkit-dns-server/frontend/components/ZoneDetail.jsx@@ -0,0 +1,333 @@+import { useCallback, useEffect, useState } from 'react';+import { RefreshCw, Plus, ShieldCheck, X } from 'lucide-react';+import api from '@/services/api';+import { Pill } from '@/components/ds';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';+import Modal from '@/components/Modal';+import ConfirmDialog from '@/components/ConfirmDialog';+import { useToast } from '@/contexts/ToastContext';++const RECORD_TYPES = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SRV', 'CAA', 'PTR'];+const EMPTY_FORM = { name: '', type: 'A', ttl: 3600, records: '' };++const ZoneDetail = ({ zoneName, onClose, onChanged }) => {+ const toast = useToast();++ const [zone, setZone] = useState(null);+ const [dsRecords, setDsRecords] = useState([]);+ const [delegation, setDelegation] = useState(null);+ const [loading, setLoading] = useState(true);+ const [actionLoading, setActionLoading] = useState(false);+ const [confirmDialog, setConfirmDialog] = useState(null);++ // Record editor modal (add or edit — edit pre-fills, save is an upsert)+ const [showRecordModal, setShowRecordModal] = useState(false);+ const [recordForm, setRecordForm] = useState(EMPTY_FORM);++ const loadZone = useCallback(async () => {+ setLoading(true);+ try {+ const data = await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}`);+ setZone(data.zone || null);+ setDsRecords(data.ds_records || []);+ setDelegation(data.delegation || null);+ } catch (error) {+ toast.error(`Failed to load zone: ${error.message}`);+ } finally {+ setLoading(false);+ }+ }, [zoneName, toast]);++ useEffect(() => {+ loadZone();+ }, [loadZone]);++ const openAdd = () => {+ setRecordForm(EMPTY_FORM);+ setShowRecordModal(true);+ };++ const openEdit = (rrset) => {+ setRecordForm({+ name: rrset.name,+ type: rrset.type,+ ttl: rrset.ttl ?? 3600,+ records: (rrset.records || []).join('\n'),+ });+ setShowRecordModal(true);+ };++ const handleSaveRecord = async () => {+ const values = recordForm.records.split('\n').map((v) => v.trim()).filter(Boolean);+ if (!values.length) return;+ setActionLoading(true);+ try {+ await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}/rrsets`, {+ method: 'POST',+ body: {+ name: recordForm.name.trim(),+ type: recordForm.type,+ ttl: Number(recordForm.ttl) || 3600,+ records: values,+ },+ });+ toast.success(`${recordForm.type} record set saved`);+ setShowRecordModal(false);+ await loadZone();+ onChanged?.();+ } catch (error) {+ toast.error(`Failed to save record set: ${error.message}`);+ } finally {+ setActionLoading(false);+ }+ };++ const handleDeleteRecord = (rrset) => {+ setConfirmDialog({+ title: 'Delete record set',+ message: `Delete the ${rrset.type} record set for ${rrset.name}?`,+ confirmText: 'Delete',+ variant: 'danger',+ onConfirm: async () => {+ try {+ const qs = `name=${encodeURIComponent(rrset.name)}&type=${encodeURIComponent(rrset.type)}`;+ await api.request(+ `/dns-server/zones/${encodeURIComponent(zoneName)}/rrsets?${qs}`,+ { method: 'DELETE' }+ );+ toast.success(`${rrset.type} record set deleted`);+ await loadZone();+ onChanged?.();+ } catch (error) {+ toast.error(`Failed to delete record set: ${error.message}`);+ }+ setConfirmDialog(null);+ },+ onCancel: () => setConfirmDialog(null),+ });+ };++ const handleDnssec = async (enable) => {+ setActionLoading(true);+ try {+ const res = await api.request(`/dns-server/zones/${encodeURIComponent(zoneName)}/dnssec`, {+ method: 'POST',+ body: { action: enable ? 'enable' : 'disable' },+ });+ toast.success(res.message || `DNSSEC ${enable ? 'enabled' : 'disabled'}`);+ await loadZone();+ onChanged?.();+ } catch (error) {+ toast.error(`DNSSEC update failed: ${error.message}`);+ } finally {+ setActionLoading(false);+ }+ };++ return (+ <div className="card dns-zone-detail">+ <div className="card-header">+ <h3 className="sk-cell-mono">{zoneName}</h3>+ <div className="card-actions">+ <Button variant="default" size="sm" onClick={openAdd}>+ <Plus size={14} /> Add Record+ </Button>+ <Button variant="outline" size="sm" onClick={loadZone}>+ <RefreshCw size={14} /> Refresh+ </Button>+ <Button variant="secondary" size="sm" onClick={onClose}>+ <X size={14} /> Close+ </Button>+ </div>+ </div>+ <div className="card-body">+ {loading ? (+ <p className="text-muted">Loading zone...</p>+ ) : !zone ? (+ <p className="text-muted">Zone could not be loaded.</p>+ ) : (+ <>+ {/* ── Delegation banner ── */}+ {delegation && (+ <div+ className={`dns-delegation dns-delegation--${+ delegation.checked === false ? 'unknown' : delegation.delegated ? 'ok' : 'warn'+ }`}+ >+ {delegation.checked === false ? (+ <span>Delegation check unavailable: {delegation.note}</span>+ ) : delegation.delegated ? (+ <span>+ Delegation looks correct — the public NS set matches this+ zone ({(delegation.public_ns || []).join(', ')}).+ </span>+ ) : (+ <span>+ {delegation.note}{' '}+ {delegation.public_ns?.length > 0 && (+ <>Public: {delegation.public_ns.join(', ')} · Zone:{' '}+ {(delegation.zone_ns || []).join(', ') || 'none'}</>+ )}+ </span>+ )}+ </div>+ )}++ {/* ── Records ── */}+ <table className="sk-dtable">+ <thead>+ <tr>+ <th>Name</th>+ <th>Type</th>+ <th>TTL</th>+ <th>Values</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {(zone.rrsets || []).map((r) => (+ <tr key={`${r.name}|${r.type}`}>+ <td className="sk-cell-mono">{r.name}</td>+ <td><span className="sk-tag">{r.type}</span></td>+ <td>{r.ttl ?? '—'}</td>+ <td className="sk-cell-mono dns-values">+ {(r.records || []).map((v) => <div key={v}>{v}</div>)}+ </td>+ <td>+ <Button variant="secondary" size="sm" onClick={() => openEdit(r)}>+ Edit+ </Button>{' '}+ {r.type !== 'SOA' && (+ <Button variant="secondary" size="sm" onClick={() => handleDeleteRecord(r)}>+ Delete+ </Button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>++ {/* ── DNSSEC ── */}+ <div className="dns-dnssec">+ <div className="dns-dnssec__head">+ <h4><ShieldCheck size={16} /> DNSSEC</h4>+ <Pill kind={zone.dnssec ? 'green' : 'gray'}>+ {zone.dnssec ? 'Enabled' : 'Disabled'}+ </Pill>+ <Button+ variant={zone.dnssec ? 'secondary' : 'default'}+ size="sm"+ disabled={actionLoading}+ onClick={() => handleDnssec(!zone.dnssec)}+ >+ {zone.dnssec ? 'Disable' : 'Enable'}+ </Button>+ </div>+ {zone.dnssec && (+ dsRecords.length > 0 ? (+ <div className="dns-ds">+ <p className="text-muted">+ Publish these DS records at your registrar (the parent+ zone) to complete the chain of trust:+ </p>+ {dsRecords.map((ds) => (+ <code key={ds} className="dns-ds__record">{ds}</code>+ ))}+ </div>+ ) : (+ <p className="text-muted">+ DNSSEC is enabled but no DS records were returned yet —+ refresh in a moment.+ </p>+ )+ )}+ </div>+ </>+ )}+ </div>++ {/* ── Record editor ── */}+ <Modal+ open={showRecordModal}+ onClose={() => setShowRecordModal(false)}+ title={`${recordForm.name ? 'Edit' : 'Add'} Record Set`}+ >+ <div className="form-group">+ <Label>Name</Label>+ <Input+ type="text"+ value={recordForm.name}+ onChange={(e) => setRecordForm((f) => ({ ...f, name: e.target.value }))}+ placeholder={`@ or www (relative to ${zoneName})`}+ />+ </div>+ <div className="form-group">+ <Label>Type</Label>+ <Select+ value={recordForm.type}+ onValueChange={(v) => setRecordForm((f) => ({ ...f, type: v }))}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {RECORD_TYPES.map((t) => (+ <SelectItem key={t} value={t}>{t}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="form-group">+ <Label>TTL (seconds)</Label>+ <Input+ type="number"+ min={1}+ max={604800}+ value={recordForm.ttl}+ onChange={(e) => setRecordForm((f) => ({ ...f, ttl: e.target.value }))}+ />+ </div>+ <div className="form-group">+ <Label>Values (one per line)</Label>+ <textarea+ className="dns-record-values"+ rows={4}+ value={recordForm.records}+ onChange={(e) => setRecordForm((f) => ({ ...f, records: e.target.value }))}+ placeholder={'203.0.113.7\n203.0.113.8'}+ />+ <p className="text-muted">+ Saving replaces the whole record set for this name + type.+ </p>+ </div>+ <div className="modal-footer">+ <Button variant="outline" onClick={() => setShowRecordModal(false)}>Cancel</Button>+ <Button+ variant="default"+ onClick={handleSaveRecord}+ disabled={actionLoading || !recordForm.records.trim()}+ >+ {actionLoading ? 'Saving...' : 'Save Record Set'}+ </Button>+ </div>+ </Modal>++ {confirmDialog && (+ <ConfirmDialog+ title={confirmDialog.title}+ message={confirmDialog.message}+ confirmText={confirmDialog.confirmText}+ variant={confirmDialog.variant}+ onConfirm={confirmDialog.onConfirm}+ onCancel={confirmDialog.onCancel}+ />+ )}+ </div>+ );+};++export default ZoneDetail;diff --git a/builtin-extensions/serverkit-dns-server/frontend/index.jsx b/builtin-extensions/serverkit-dns-server/frontend/index.jsxnew file mode 100644index 00000000..8e9bc6b1--- /dev/null+++ b/builtin-extensions/serverkit-dns-server/frontend/index.jsx@@ -0,0 +1,8 @@+// Authoritative DNS hosting UI, contributed through the extension system.+// Fully self-contained in the extension — no core page to wrap. After sync+// this folder lives at frontend/src/plugins/serverkit-dns-server/, so '@/…'+// host aliases resolve.+export { default as DnsServerPage } from './components/DnsServerPage.jsx';++// No default export on purpose: PluginLoader legacy-auto-renders any plugin+// default export globally. The route contribution resolves the NAMED export.diff --git a/builtin-extensions/serverkit-dns-server/frontend/styles/dns-server.css b/builtin-extensions/serverkit-dns-server/frontend/styles/dns-server.cssnew file mode 100644index 00000000..738c42fa--- /dev/null+++ b/builtin-extensions/serverkit-dns-server/frontend/styles/dns-server.css@@ -0,0 +1,92 @@+/* DNS Server extension — layout-only styles; colors/typography inherit from+ the host design system (card, sk-dtable, sk-info-row, empty-state…). */++.dns-server-page .dns-explainer {+ margin: 12px 0;+ padding-left: 20px;+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.dns-server-page .dns-install-form {+ max-width: 480px;+ margin-top: 16px;+}++.dns-server-page .dns-install-actions {+ display: flex;+ gap: 8px;+ margin-top: 12px;+}++.dns-server-page .dns-zone-link {+ background: none;+ border: none;+ padding: 0;+ cursor: pointer;+ font: inherit;+ color: inherit;+ text-decoration: underline;+}++.dns-server-page .dns-delegation {+ border-radius: 8px;+ padding: 10px 12px;+ margin-bottom: 12px;+ border: 1px solid currentColor;+}++.dns-server-page .dns-delegation--ok { opacity: 0.9; }+.dns-server-page .dns-delegation--warn { font-weight: 500; }+.dns-server-page .dns-delegation--unknown { opacity: 0.7; }++.dns-server-page .dns-values div {+ line-height: 1.5;+ word-break: break-all;+}++.dns-server-page .dns-dnssec {+ margin-top: 16px;+ padding-top: 12px;+ border-top: 1px solid rgba(128, 128, 128, 0.25);+}++.dns-server-page .dns-dnssec__head {+ display: flex;+ align-items: center;+ gap: 10px;+}++.dns-server-page .dns-dnssec__head h4 {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0;+}++.dns-server-page .dns-ds {+ margin-top: 10px;+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.dns-server-page .dns-ds__record {+ display: block;+ padding: 6px 8px;+ border-radius: 6px;+ word-break: break-all;+ background: rgba(128, 128, 128, 0.12);+}++.dns-server-page .dns-record-values {+ width: 100%;+ font-family: inherit;+ border-radius: 6px;+ padding: 8px;+ resize: vertical;+ background: transparent;+ color: inherit;+ border: 1px solid rgba(128, 128, 128, 0.35);+}diff --git a/builtin-extensions/serverkit-dns-server/plugin.json b/builtin-extensions/serverkit-dns-server/plugin.jsonnew file mode 100644index 00000000..4af5c7ca--- /dev/null+++ b/builtin-extensions/serverkit-dns-server/plugin.json@@ -0,0 +1,40 @@+{+ "name": "serverkit-dns-server",+ "display_name": "DNS Server",+ "version": "1.0.0",+ "description": "Host authoritative DNS on this box with PowerDNS (SQLite backend) in a managed Docker container — zones, records, DNSSEC, and delegation checks from the panel. Authoritative only (no recursion); complements provider integrations like Cloudflare, never replaces them. Built for homelab and air-gapped setups.",+ "author": "ServerKit",+ "license": "MIT",+ "category": "networking",+ "homepage": "https://github.com/jhd3197/ServerKit",+ "permissions": ["shell", "docker"],+ "min_panel_version": "1.7.0",+ "entry_point": "dns_server:dns_server_bp",+ "url_prefix": "/api/v1/dns-server",+ "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>",+ "contributions": {+ "nav": [+ {+ "id": "dns-server",+ "label": "DNS Server",+ "route": "/dns-server",+ "category": "operations",+ "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>"+ }+ ],+ "routes": [+ { "path": "dns-server", "component": "DnsServerPage" }+ ],+ "page_titles": {+ "/dns-server": "DNS Server"+ },+ "command_palette": [+ {+ "label": "DNS Server",+ "path": "/dns-server",+ "category": "Pages",+ "keywords": "dns server powerdns authoritative nameserver zones records dnssec delegation hosting"+ }+ ]+ }+}