change schema final

This commit is contained in:
satr14washere 2026-03-22 12:43:47 +07:00
commit 550ca5228c
31 changed files with 470 additions and 396 deletions

View file

@ -1,49 +1,76 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "satr14washere"; description = "Example domain configuration for dns.nix"; # optional, description of use
email = "admin@satr14.my.id"; proxy = false; # optional, defaults to false. proxy through Cloudflare
owner = { # add extra contacts if needed
username = "satr14washere"; # required, github username
email = "admin@satr14.my.id";
};
}; };
proxy = false; records = with dns.lib.combinators; { # full list of records supported: https://github.com/nix-community/dns.nix/tree/master/dns/types/records
records = { # dns.lib.combinators is optional but provides a lot of useful shortcuts:
# https://github.com/nix-community/dns.nix/blob/master/dns/combinators.nix
A = [ A = [
{ "203.0.113.50"
address = "203.0.113.1"; "198.51.100.50"
ttl = 60 * 60;
} # or:
"203.0.113.2"
(ttl (60 * 60) (a "203.0.113.3")) { address = "203.0.113.50"; ttl = 60 * 60; } # TTL is optional
{ address = "198.51.100.50"; ttl = 60 * 60; }
# using dns.lib.combinators:
(ttl (60 * 60) (a "203.0.113.50")) # standalone A record
(ttl (60 * 60) (a "2198.51.100.50")) # record with TTL
]; ];
AAAA = [
"4321:0:1:2:3:4:567:89ab" AAAA = [ # mostly same as above
"2001:db8::1"
"2001:db8::2"
# or:
{ address = "2001:db8::1"; ttl = 60 * 60; }
{ address = "2001:db8::2"; ttl = 60 * 60; }
# using dns.lib.combinators:
(ttl (60 * 60) (aaaa "2001:db8::1"))
(ttl (60 * 60) (aaaa "2001:db8::2"))
]; ];
MX = mx.google;
TXT = [ TXT = [
( "v=spf1 include:mailgun.org ~all"
with spf; "dh=some-long-random-string"
strict [
"a:mail.example.com"
google
]
)
]; ];
CNAME = [ "example.com." ];
DMARC = [ (dmarc.postmarkapp "mailto:re+abcdefghijk@dmarc.postmarkapp.com") ]; MX = [
CAA = letsEncrypt "admin@example.com";
SRV = [
{ {
service = "sip"; preference = 10;
proto = "tcp"; exchange = "mail.protonmail.ch.";
port = 5060;
target = "sip.example.com";
} }
];
TLSA = [
{ {
certUsage = "dane-ee"; preference = 20;
selector = "spki"; exchange = "mailsec.protonmail.ch.";
matchingType = "sha256";
certificate = "899EB4AC9285578AFDA3CCBE152EE78D8618B8F3862FEF2703E1FC7011E9B8AA";
} }
# using dns.lib.combinators:
(mx.mx 10 "mail.protonmail.ch.")
(mx.mx 20 "mailsec.protonmail.ch.")
]; ];
# a few notes about CNAME records:
# - value must end with a dot (.)
# - cannot coexist with other record types (e.g. A, AAAA, MX) for the same subdomain
# - can only be one despite being a list (this example defined multiple only for demonstrating valid values)
CNAME = [
"edge.redirect.pizza."
"username.github.io."
"site.pages.dev."
];
}; };
} }

View file

@ -1,9 +1,12 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "ColinLeDev"; description = "Discord verification";
proxy = false;
owner = {
username = "ColinLeDev";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
TXT = [ "dh=279643a6f8677dedb1c5c63d007fc4516149679c" ]; TXT = [ "dh=279643a6f8677dedb1c5c63d007fc4516149679c" ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "CuteDog5695"; proxy = false;
email = "cutedog5695@gmail.com"; owner = {
repo = "https://github.com/CuteDog5695/cutedog5695.github.io"; username = "CuteDog5695";
email = "cutedog5695@gmail.com";
repo = "https://github.com/CuteDog5695/cutedog5695.github.io";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
TXT = [ "dh=a7c19efb0f6bc38b97a33760f6c1ee84df4151b1" ]; TXT = [ "dh=a7c19efb0f6bc38b97a33760f6c1ee84df4151b1" ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "JustDeveloper1"; proxy = false;
email = "justdeveloper@juststudio.is-a.dev"; owner = {
repo = "https://github.com/JustDeveloper1/Website"; username = "JustDeveloper1";
email = "justdeveloper@juststudio.is-a.dev";
repo = "https://github.com/JustDeveloper1/Website";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
TXT = [ "dh=6024027bc233825451e290ac37a4b4a1f838ee70" ]; TXT = [ "dh=6024027bc233825451e290ac37a4b4a1f838ee70" ];
}; };
} }

View file

@ -1,9 +1,11 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "satr14washere"; proxy = false;
owner = {
username = "satr14washere";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
TXT = [ "dh=d509fc9014e196311ed887c2e410cdefa833436e" ]; TXT = [ "dh=d509fc9014e196311ed887c2e410cdefa833436e" ];
}; };
} }

View file

@ -1,9 +1,11 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "Roki100"; owner = {
discord = "289479495444987904"; username = "Roki100";
discord = "289479495444987904";
};
}; };
records = { records = with dns.lib.combinators; {
TXT = [ "dh=5633078cd5bfd347a896ddb0f0de017c5423aa06" ]; TXT = [ "dh=5633078cd5bfd347a896ddb0f0de017c5423aa06" ];
}; };
} }

View file

@ -1,9 +1,11 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "shadowe1ite"; proxy = true;
owner = {
username = "shadowe1ite";
};
}; };
proxy = true; records = with dns.lib.combinators; {
records = {
CNAME = [ "shadowe1ite.github.io." ]; CNAME = [ "shadowe1ite.github.io." ];
}; };
} }

View file

@ -1,10 +1,12 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "orangci"; proxy = false;
email = "c@orangc.xyz"; owner = {
username = "orangci";
email = "c@orangc.xyz";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,9 +1,12 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "ColinLeDev"; description = "My personal portfolio hosted on my server";
proxy = false;
owner = {
username = "ColinLeDev";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "proxy.col1n.fr." ]; CNAME = [ "proxy.col1n.fr." ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "CuteDog5695"; proxy = false;
email = "cutedog5695@gmail.com"; owner = {
repo = "https://github.com/CuteDog5695/cutedog5695.github.io"; username = "CuteDog5695";
email = "cutedog5695@gmail.com";
repo = "https://github.com/CuteDog5695/cutedog5695.github.io";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,8 +1,10 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "elkhaff"; owner = {
username = "elkhaff";
};
}; };
records = { records = with dns.lib.combinators; {
CNAME = [ "portofolio-pixel.pages.dev." ]; CNAME = [ "portofolio-pixel.pages.dev." ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "JustDeveloper1"; proxy = false;
email = "support@juststudio.is-a.dev"; owner = {
repo = "https://github.com/JustStudio7/Website"; username = "JustDeveloper1";
email = "support@juststudio.is-a.dev";
repo = "https://github.com/JustStudio7/Website";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,9 +1,11 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "jacobrdale"; proxy = false;
owner = {
username = "jacobrdale";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "hexon404.onrender.com." ]; CNAME = [ "hexon404.onrender.com." ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "JustDeveloper1"; proxy = false;
email = "justdeveloper@juststudio.is-a.dev"; owner = {
repo = "https://github.com/JustDeveloper1/Website"; username = "JustDeveloper1";
email = "justdeveloper@juststudio.is-a.dev";
repo = "https://github.com/JustDeveloper1/Website";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,9 +1,11 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "FWEEaaaa1"; proxy = false;
owner = {
username = "FWEEaaaa1";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
A = [ "128.204.223.115" ]; A = [ "128.204.223.115" ];
}; };
} }

View file

@ -1,16 +1,18 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "joestr"; proxy = false;
email = "strasser999@gmail.com"; owner = {
username = "joestr";
email = "strasser999@gmail.com";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
A = [ "142.132.173.34" ]; A = [ "142.132.173.34" ];
AAAA = [ "2a01:4f8:1c0c:6cc0::1" ]; AAAA = [ "2a01:4f8:1c0c:6cc0::1" ];
MX = [ MX = [
{ {
exchange = "achlys.infra.joestr.at.";
preference = 10; preference = 10;
exchange = "achlys.infra.joestr.at.";
} }
]; ];
}; };

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "JustDeveloper1"; proxy = false;
email = "support@juststudio.is-a.dev"; owner = {
repo = "https://github.com/JustStudio7/Website"; username = "JustDeveloper1";
email = "support@juststudio.is-a.dev";
repo = "https://github.com/JustStudio7/Website";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "JustDeveloper1"; proxy = false;
email = "justdeveloper@juststudio.is-a.dev"; owner = {
repo = "https://github.com/JustDeveloper1/Website"; username = "JustDeveloper1";
email = "justdeveloper@juststudio.is-a.dev";
repo = "https://github.com/JustDeveloper1/Website";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "JustDeveloper1"; proxy = false;
email = "justdeveloper@juststudio.is-a.dev"; owner = {
repo = "https://github.com/JustDeveloper1/Website"; username = "JustDeveloper1";
email = "justdeveloper@juststudio.is-a.dev";
repo = "https://github.com/JustDeveloper1/Website";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "JustDeveloper1"; proxy = false;
email = "justdeveloper@juststudio.is-a.dev"; owner = {
repo = "https://github.com/JustDeveloper1/Website"; username = "JustDeveloper1";
email = "justdeveloper@juststudio.is-a.dev";
repo = "https://github.com/JustDeveloper1/Website";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,11 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "JustDeveloper1"; proxy = false;
email = "support@juststudio.is-a.dev"; owner = {
repo = "https://github.com/JustStudio7/Website"; username = "JustDeveloper1";
email = "support@juststudio.is-a.dev";
repo = "https://github.com/JustStudio7/Website";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,9 +1,11 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "Bananalolok"; proxy = false;
owner = {
username = "Bananalolok";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
A = [ "69.197.135.205" ]; A = [ "69.197.135.205" ];
}; };
} }

View file

@ -1,10 +1,12 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "EducatedSuddenBucket"; proxy = false;
email = "me@esb.is-a.dev"; owner = {
username = "EducatedSuddenBucket";
email = "me@esb.is-a.dev";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "educatedsuddenbucket-github-io.onrender.com." ]; CNAME = [ "educatedsuddenbucket-github-io.onrender.com." ];
}; };
} }

View file

@ -1,9 +1,11 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "heypxl"; proxy = false;
owner = {
username = "heypxl";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "heypxl.github.io." ]; CNAME = [ "heypxl.github.io." ];
}; };
} }

View file

@ -1,9 +1,11 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "vortexprime24"; proxy = false;
owner = {
username = "vortexprime24";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "fire.hackclub.app." ]; CNAME = [ "fire.hackclub.app." ];
}; };
} }

View file

@ -1,10 +1,12 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "Roki100"; proxy = false;
discord = "289479495444987904"; owner = {
username = "Roki100";
discord = "289479495444987904";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "edge.redirect.pizza." ]; CNAME = [ "edge.redirect.pizza." ];
}; };
} }

View file

@ -1,8 +1,10 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "satr14washere"; owner = {
username = "satr14washere";
};
}; };
records = { records = with dns.lib.combinators; {
CNAME = [ "5th-site.pages.dev." ]; CNAME = [ "5th-site.pages.dev." ];
}; };
} }

View file

@ -1,10 +1,12 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "Stef-00012"; proxy = false;
email = "admin@stefdp.lol"; owner = {
username = "Stef-00012";
email = "admin@stefdp.lol";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "proxy.stefdp.lol." ]; CNAME = [ "proxy.stefdp.lol." ];
}; };
} }

View file

@ -1,10 +1,13 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "ukriu"; description = "my website";
email = "partofmyid@ukriu.com"; proxy = false;
owner = {
username = "ukriu";
email = "partofmyid@ukriu.com";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "ukriu.pages.dev." ]; CNAME = [ "ukriu.pages.dev." ];
}; };
} }

View file

@ -1,10 +1,12 @@
{ dns, ... }: with dns.lib.combinators; { { dns, ... }: {
owner = { metadata = {
username = "Stef-00012"; proxy = false;
email = "admin@stefdp.com"; owner = {
username = "Stef-00012";
email = "admin@stefdp.com";
};
}; };
proxy = false; records = with dns.lib.combinators; {
records = {
CNAME = [ "proxy.stefdp.com." ]; CNAME = [ "proxy.stefdp.com." ];
}; };
} }

View file

@ -1,16 +1,29 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
Migration script to convert domains/*.json to domains/*.nix Migrate domains/*.json to domains/*.nix
Reads each JSON domain config and generates a corresponding .nix file Converts each JSON domain config into a .nix file matching the format
following the format from docs/example.nix. from docs/example.nix:
{ dns, ... }: {
metadata = {
description = "...";
proxy = false;
owner = {
username = "...";
};
};
records = with dns.lib.combinators; {
CNAME = [ "example.com." ];
};
}
Usage: Usage:
python3 scripts/migrate-nix.py [--dry-run] [--delete-json] python3 scripts/migrate-nix.py [--dry-run] [--delete-json]
Options: Options:
--dry-run Print generated .nix content to stdout without writing files --dry-run Print generated .nix to stdout without writing files
--delete-json Delete the original .json files after successful conversion --delete-json Delete the .json files after successful conversion
""" """
import json import json
@ -20,224 +33,198 @@ from pathlib import Path
DOMAINS_DIR = Path(__file__).resolve().parent.parent / "domains" DOMAINS_DIR = Path(__file__).resolve().parent.parent / "domains"
def json_to_nix(data: dict) -> str: # --- Nix string helpers ---
"""Convert a single domain JSON config to a .nix file string."""
def escape(s: str) -> str:
"""Escape a string for use inside Nix double quotes."""
return s.replace("\\", "\\\\").replace('"', '\\"').replace("${", "\\${")
def fqdn(s: str) -> str:
"""Ensure a domain string ends with a trailing dot."""
return s if s.endswith(".") else s + "."
# --- Block builders ---
def build_metadata(data: dict) -> list[str]:
"""Build the metadata = { ... }; block."""
owner = data.get("owner", {}) owner = data.get("owner", {})
description = data.get("description") description = data.get("description")
record = data.get("record", {})
# Some files use "proxy", others use "proxied"
proxy = data.get("proxied", data.get("proxy")) proxy = data.get("proxied", data.get("proxy"))
lines = [] lines = [" metadata = {"]
# Header — no let block, just the function head with `with`
lines.append("{ dns, ... }: with dns.lib.combinators; {")
# Owner block as a top-level attribute
lines.append(" owner = {")
if owner.get("username"):
lines.append(f' username = "{escape_nix_string(owner["username"])}";')
if owner.get("email"):
lines.append(f' email = "{escape_nix_string(owner["email"])}";')
if owner.get("discord"):
lines.append(f' discord = "{escape_nix_string(owner["discord"])}";')
if owner.get("repo"):
lines.append(f' repo = "{escape_nix_string(owner["repo"])}";')
lines.append(" };")
# Description as a top-level attribute
if description is not None: if description is not None:
lines.append(f' description = "{escape_nix_string(description)}";') lines.append(f' description = "{escape(description)}";')
# Proxy as a top-level attribute
if proxy is not None: if proxy is not None:
lines.append(f" proxy = {'true' if proxy else 'false'};") lines.append(f" proxy = {'true' if proxy else 'false'};")
# Records nested under `records` owner_keys = ["username", "email", "discord", "repo"]
record_lines = build_record_lines(record) owner_fields = [(k, owner[k]) for k in owner_keys if owner.get(k)]
if record_lines:
lines.append(" records = {")
for rl in record_lines:
lines.append(rl)
lines.append(" };")
lines.append("}") if owner_fields:
lines.append("") lines.append(" owner = {")
for key, val in owner_fields:
return "\n".join(lines) lines.append(f' {key} = "{escape(val)}";')
lines.append(" };")
def escape_nix_string(s: str) -> str:
"""Escape special characters for a Nix double-quoted string."""
s = s.replace("\\", "\\\\")
s = s.replace('"', '\\"')
s = s.replace("${", "\\${")
return s
def build_record_lines(record: dict) -> list[str]:
"""Build the Nix record lines from the JSON record dict.
These are indented with 4 spaces since they sit inside `records = { ... };`.
"""
lines = []
if "A" in record:
values = record["A"]
if isinstance(values, list):
if len(values) == 1:
lines.append(f' A = [ "{values[0]}" ];')
else:
lines.append(" A = [")
for v in values:
lines.append(f' "{v}"')
lines.append(" ];")
else:
lines.append(f' A = [ "{values}" ];')
if "AAAA" in record:
values = record["AAAA"]
if isinstance(values, list):
if len(values) == 1:
lines.append(f' AAAA = [ "{values[0]}" ];')
else:
lines.append(" AAAA = [")
for v in values:
lines.append(f' "{v}"')
lines.append(" ];")
else:
lines.append(f' AAAA = [ "{values}" ];')
if "CNAME" in record:
value = record["CNAME"]
if isinstance(value, list):
value = value[0]
lines.append(f' CNAME = [ "{ensure_fqdn(value)}" ];')
if "ALIAS" in record:
value = record["ALIAS"]
if isinstance(value, list):
value = value[0]
# ALIAS is typically handled as CNAME in dns.nix
lines.append(f' CNAME = [ "{ensure_fqdn(value)}" ];')
if "MX" in record:
values = record["MX"]
if isinstance(values, list):
lines.append(" MX = [")
for i, v in enumerate(values):
priority = (i + 1) * 10
lines.append(" {")
lines.append(f' exchange = "{ensure_fqdn(v)}";')
lines.append(f" preference = {priority};")
lines.append(" }")
lines.append(" ];")
else:
lines.append(" MX = [")
lines.append(" {")
lines.append(f' exchange = "{ensure_fqdn(values)}";')
lines.append(" preference = 10;")
lines.append(" }")
lines.append(" ];")
if "TXT" in record:
values = record["TXT"]
if isinstance(values, list):
if len(values) == 1:
lines.append(f' TXT = [ "{escape_nix_string(values[0])}" ];')
else:
lines.append(" TXT = [")
for v in values:
lines.append(f' "{escape_nix_string(v)}"')
lines.append(" ];")
else:
lines.append(f' TXT = [ "{escape_nix_string(values)}" ];')
if "NS" in record:
values = record["NS"]
if isinstance(values, list):
if len(values) == 1:
lines.append(f' NS = [ "{ensure_fqdn(values[0])}" ];')
else:
lines.append(" NS = [")
for v in values:
lines.append(f' "{ensure_fqdn(v)}"')
lines.append(" ];")
else:
lines.append(f' NS = [ "{ensure_fqdn(values)}" ];')
if "SRV" in record:
values = record["SRV"]
if isinstance(values, list):
lines.append(" SRV = [")
for srv in values:
lines.append(" {")
if "service" in srv:
lines.append(f' service = "{srv["service"]}";')
if "proto" in srv:
lines.append(f' proto = "{srv["proto"]}";')
if "port" in srv:
lines.append(f" port = {srv['port']};")
if "priority" in srv:
lines.append(f" priority = {srv['priority']};")
if "weight" in srv:
lines.append(f" weight = {srv['weight']};")
if "target" in srv:
lines.append(f' target = "{ensure_fqdn(srv["target"])}";')
lines.append(" }")
lines.append(" ];")
if "CAA" in record:
values = record["CAA"]
if isinstance(values, list):
lines.append(" CAA = [")
for caa in values:
lines.append(" {")
if "flags" in caa:
lines.append(f" flags = {caa['flags']};")
if "tag" in caa:
lines.append(f' tag = "{caa["tag"]}";')
if "value" in caa:
lines.append(f' value = "{escape_nix_string(caa["value"])}";')
lines.append(" }")
lines.append(" ];")
lines.append(" };")
return lines return lines
def ensure_fqdn(domain: str) -> str: def build_records(record: dict) -> list[str]:
"""Ensure a domain name ends with a dot (FQDN).""" """Build the records = with dns.lib.combinators; { ... }; block."""
if not domain.endswith("."): entries = []
return domain + "."
return domain # A records
if "A" in record:
entries.extend(string_list_record("A", as_list(record["A"])))
# AAAA records
if "AAAA" in record:
entries.extend(string_list_record("AAAA", as_list(record["AAAA"])))
# CNAME (also handles ALIAS → CNAME)
cname = record.get("CNAME") or record.get("ALIAS")
if cname is not None:
val = cname[0] if isinstance(cname, list) else cname
entries.append(f' CNAME = [ "{fqdn(val)}" ];')
# MX records
if "MX" in record:
entries.extend(build_mx(as_list(record["MX"])))
# TXT records
if "TXT" in record:
escaped = [escape(v) for v in as_list(record["TXT"])]
entries.extend(string_list_record("TXT", escaped))
# NS records
if "NS" in record:
fqdns = [fqdn(v) for v in as_list(record["NS"])]
entries.extend(string_list_record("NS", fqdns))
# SRV records
if "SRV" in record:
entries.extend(build_srv(as_list(record["SRV"])))
# CAA records
if "CAA" in record:
entries.extend(build_caa(as_list(record["CAA"])))
if not entries:
return [" records = with dns.lib.combinators; {};"]
lines = [" records = with dns.lib.combinators; {"]
lines.extend(entries)
lines.append(" };")
return lines
def migrate_file(json_path: Path, dry_run: bool = False, delete_json: bool = False) -> bool: # --- Record type formatters ---
"""Migrate a single JSON file to .nix. Returns True on success."""
def as_list(value) -> list:
"""Wrap a scalar in a list if it isn't one already."""
return value if isinstance(value, list) else [value]
def string_list_record(rtype: str, values: list[str]) -> list[str]:
"""Format a record type whose values are plain strings."""
if len(values) == 1:
return [f' {rtype} = [ "{values[0]}" ];']
lines = [f" {rtype} = ["]
for v in values:
lines.append(f' "{v}"')
lines.append(" ];")
return lines
def build_mx(values: list) -> list[str]:
"""Format MX records as attrsets with preference + exchange."""
lines = [" MX = ["]
for i, v in enumerate(values):
pref = (i + 1) * 10
lines.append(" {")
lines.append(f" preference = {pref};")
lines.append(f' exchange = "{fqdn(v)}";')
lines.append(" }")
lines.append(" ];")
return lines
def build_srv(values: list[dict]) -> list[str]:
"""Format SRV records."""
lines = [" SRV = ["]
for srv in values:
lines.append(" {")
for key in ("service", "proto"):
if key in srv:
lines.append(f' {key} = "{srv[key]}";')
for key in ("priority", "weight", "port"):
if key in srv:
lines.append(f" {key} = {srv[key]};")
if "target" in srv:
lines.append(f' target = "{fqdn(srv["target"])}";')
lines.append(" }")
lines.append(" ];")
return lines
def build_caa(values: list[dict]) -> list[str]:
"""Format CAA records."""
lines = [" CAA = ["]
for caa in values:
lines.append(" {")
if "flags" in caa:
lines.append(f" flags = {caa['flags']};")
if "tag" in caa:
lines.append(f' tag = "{caa["tag"]}";')
if "value" in caa:
lines.append(f' value = "{escape(caa["value"])}";')
lines.append(" }")
lines.append(" ];")
return lines
# --- Top-level conversion ---
def json_to_nix(data: dict) -> str:
"""Convert a parsed JSON domain config to a complete .nix file string."""
lines = ["{ dns, ... }: {"]
lines.extend(build_metadata(data))
lines.extend(build_records(data.get("record", {})))
lines.append("}")
lines.append("")
return "\n".join(lines)
# --- File operations ---
def migrate_file(path: Path, *, dry_run: bool, delete_json: bool) -> bool:
"""Migrate a single .json file. Returns True on success."""
try: try:
with open(json_path, "r") as f: data = json.loads(path.read_text())
data = json.load(f)
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
print(f" ERROR: Failed to parse {json_path.name}: {e}", file=sys.stderr) print(f" ERROR: {path.name}: {e}", file=sys.stderr)
return False return False
nix_content = json_to_nix(data) nix = json_to_nix(data)
nix_filename = json_path.stem + ".nix" nix_path = path.with_suffix(".nix")
nix_path = json_path.parent / nix_filename
if dry_run: if dry_run:
print(f"--- {nix_filename} ---") print(f"--- {nix_path.name} ---")
print(nix_content) print(nix)
return True return True
with open(nix_path, "w") as f: nix_path.write_text(nix)
f.write(nix_content)
print(f" Created {nix_path.name}") print(f" Created {nix_path.name}")
if delete_json: if delete_json:
json_path.unlink() path.unlink()
print(f" Deleted {json_path.name}") print(f" Deleted {path.name}")
return True return True
@ -247,31 +234,30 @@ def main():
delete_json = "--delete-json" in sys.argv delete_json = "--delete-json" in sys.argv
if not DOMAINS_DIR.exists(): if not DOMAINS_DIR.exists():
print(f"Error: domains directory not found at {DOMAINS_DIR}", file=sys.stderr) print(f"Error: {DOMAINS_DIR} not found", file=sys.stderr)
sys.exit(1) sys.exit(1)
json_files = sorted(DOMAINS_DIR.glob("*.json")) files = sorted(DOMAINS_DIR.glob("*.json"))
if not files:
if not json_files: print("No .json files found in domains/")
print("No JSON files found in domains/")
sys.exit(0) sys.exit(0)
print(f"Found {len(json_files)} JSON file(s) to migrate") print(f"Found {len(files)} JSON file(s) to migrate")
if dry_run: if dry_run:
print("(dry run — no files will be written)\n") print("(dry run — no files will be written)\n")
success = 0 success = 0
failed = 0 failed = 0
for json_path in json_files: for f in files:
print(f"Migrating {json_path.name}...") print(f"Migrating {f.name}...")
if migrate_file(json_path, dry_run=dry_run, delete_json=delete_json): if migrate_file(f, dry_run=dry_run, delete_json=delete_json):
success += 1 success += 1
else: else:
failed += 1 failed += 1
print(f"\nDone: {success} succeeded, {failed} failed") print(f"\nDone: {success} succeeded, {failed} failed")
if failed > 0: if failed:
sys.exit(1) sys.exit(1)