summary refs log tree commit diff
path: root/nixos/modules/services
diff options
context:
space:
mode:
authorRobert Hensing <robert@roberthensing.nl>2022-12-02 18:12:14 +0000
committerRobert Hensing <robert@roberthensing.nl>2022-12-02 18:12:14 +0000
commit7bfbf037d7fea8edca0ef75edd15ce4534052c5c (patch)
tree114669c9b210ea663710cd403350a43288b60e51 /nixos/modules/services
parent4e502a1c4d207610b0964b92bb41e574ed62e9c9 (diff)
parentfad052f056576d04a8eb7a6b374584a740e10706 (diff)
downloadnixpkgs-7bfbf037d7fea8edca0ef75edd15ce4534052c5c.tar
nixpkgs-7bfbf037d7fea8edca0ef75edd15ce4534052c5c.tar.gz
nixpkgs-7bfbf037d7fea8edca0ef75edd15ce4534052c5c.tar.bz2
nixpkgs-7bfbf037d7fea8edca0ef75edd15ce4534052c5c.tar.lz
nixpkgs-7bfbf037d7fea8edca0ef75edd15ce4534052c5c.tar.xz
nixpkgs-7bfbf037d7fea8edca0ef75edd15ce4534052c5c.tar.zst
nixpkgs-7bfbf037d7fea8edca0ef75edd15ce4534052c5c.zip
Merge remote-tracking branch 'upstream/master' into allow-configuration-of-roles
Diffstat (limited to 'nixos/modules/services')
-rw-r--r--nixos/modules/services/admin/meshcentral.nix16
-rw-r--r--nixos/modules/services/admin/oxidized.nix12
-rw-r--r--nixos/modules/services/admin/pgadmin.nix82
-rw-r--r--nixos/modules/services/admin/salt/master.nix4
-rw-r--r--nixos/modules/services/admin/salt/minion.nix6
-rw-r--r--nixos/modules/services/amqp/activemq/default.nix16
-rw-r--r--nixos/modules/services/amqp/rabbitmq.nix40
-rw-r--r--nixos/modules/services/audio/alsa.nix12
-rw-r--r--nixos/modules/services/audio/botamusique.nix18
-rw-r--r--nixos/modules/services/audio/hqplayerd.nix14
-rw-r--r--nixos/modules/services/audio/icecast.nix20
-rw-r--r--nixos/modules/services/audio/jack.nix24
-rw-r--r--nixos/modules/services/audio/jmusicbot.nix6
-rw-r--r--nixos/modules/services/audio/liquidsoap.nix2
-rw-r--r--nixos/modules/services/audio/mopidy.nix12
-rw-r--r--nixos/modules/services/audio/mpd.nix39
-rw-r--r--nixos/modules/services/audio/mpdscribble.nix28
-rw-r--r--nixos/modules/services/audio/navidrome.nix11
-rw-r--r--nixos/modules/services/audio/networkaudiod.nix2
-rw-r--r--nixos/modules/services/audio/roon-bridge.nix8
-rw-r--r--nixos/modules/services/audio/roon-server.nix12
-rw-r--r--nixos/modules/services/audio/slimserver.nix6
-rw-r--r--nixos/modules/services/audio/snapserver.nix72
-rw-r--r--nixos/modules/services/audio/spotifyd.nix10
-rw-r--r--nixos/modules/services/audio/squeezelite.nix6
-rw-r--r--nixos/modules/services/audio/ympd.nix10
-rw-r--r--nixos/modules/services/backup/automysqlbackup.nix10
-rw-r--r--nixos/modules/services/backup/bacula.nix88
-rw-r--r--nixos/modules/services/backup/borgbackup.nix194
-rw-r--r--nixos/modules/services/backup/borgmatic.nix13
-rw-r--r--nixos/modules/services/backup/btrbk.nix184
-rw-r--r--nixos/modules/services/backup/duplicati.nix22
-rw-r--r--nixos/modules/services/backup/duplicity.nix56
-rw-r--r--nixos/modules/services/backup/mysql-backup.nix12
-rw-r--r--nixos/modules/services/backup/postgresql-backup.nix49
-rw-r--r--nixos/modules/services/backup/postgresql-wal-receiver.nix50
-rw-r--r--nixos/modules/services/backup/restic-rest-server.nix16
-rw-r--r--nixos/modules/services/backup/restic.nix249
-rw-r--r--nixos/modules/services/backup/rsnapshot.nix8
-rw-r--r--nixos/modules/services/backup/sanoid.nix43
-rw-r--r--nixos/modules/services/backup/syncoid.nix113
-rw-r--r--nixos/modules/services/backup/tarsnap.nix81
-rw-r--r--nixos/modules/services/backup/tsm.nix30
-rw-r--r--nixos/modules/services/backup/zfs-replication.nix16
-rw-r--r--nixos/modules/services/backup/znapzend.nix146
-rw-r--r--nixos/modules/services/backup/zrepl.nix21
-rw-r--r--nixos/modules/services/blockchain/ethereum/erigon.nix120
-rw-r--r--nixos/modules/services/blockchain/ethereum/geth.nix80
-rw-r--r--nixos/modules/services/blockchain/ethereum/lighthouse.nix315
-rw-r--r--nixos/modules/services/cluster/corosync/default.nix16
-rw-r--r--nixos/modules/services/cluster/hadoop/conf.nix3
-rw-r--r--nixos/modules/services/cluster/hadoop/default.nix46
-rw-r--r--nixos/modules/services/cluster/hadoop/hbase.nix196
-rw-r--r--nixos/modules/services/cluster/hadoop/hdfs.nix26
-rw-r--r--nixos/modules/services/cluster/hadoop/yarn.nix36
-rw-r--r--nixos/modules/services/cluster/k3s/default.nix90
-rw-r--r--nixos/modules/services/cluster/kubernetes/addon-manager.nix6
-rw-r--r--nixos/modules/services/cluster/kubernetes/addons/dns.nix24
-rw-r--r--nixos/modules/services/cluster/kubernetes/apiserver.nix107
-rw-r--r--nixos/modules/services/cluster/kubernetes/controller-manager.nix37
-rw-r--r--nixos/modules/services/cluster/kubernetes/default.nix32
-rw-r--r--nixos/modules/services/cluster/kubernetes/flannel.nix3
-rw-r--r--nixos/modules/services/cluster/kubernetes/kubelet.nix83
-rw-r--r--nixos/modules/services/cluster/kubernetes/pki.nix24
-rw-r--r--nixos/modules/services/cluster/kubernetes/proxy.nix14
-rw-r--r--nixos/modules/services/cluster/kubernetes/scheduler.nix16
-rw-r--r--nixos/modules/services/cluster/pacemaker/default.nix4
-rw-r--r--nixos/modules/services/cluster/patroni/default.nix268
-rw-r--r--nixos/modules/services/cluster/spark/default.nix24
-rw-r--r--nixos/modules/services/computing/boinc/client.nix55
-rw-r--r--nixos/modules/services/computing/foldingathome/client.nix14
-rw-r--r--nixos/modules/services/computing/slurm/slurm.nix89
-rw-r--r--nixos/modules/services/computing/torque/mom.nix4
-rw-r--r--nixos/modules/services/computing/torque/server.nix2
-rw-r--r--nixos/modules/services/continuous-integration/buildbot/master.nix58
-rw-r--r--nixos/modules/services/continuous-integration/buildbot/worker.nix32
-rw-r--r--nixos/modules/services/continuous-integration/buildkite-agents.nix30
-rw-r--r--nixos/modules/services/continuous-integration/github-runner.nix315
-rw-r--r--nixos/modules/services/continuous-integration/github-runner/options.nix173
-rw-r--r--nixos/modules/services/continuous-integration/github-runner/service.nix257
-rw-r--r--nixos/modules/services/continuous-integration/github-runners.nix56
-rw-r--r--nixos/modules/services/continuous-integration/gitlab-runner.nix273
-rw-r--r--nixos/modules/services/continuous-integration/gocd-agent/default.nix28
-rw-r--r--nixos/modules/services/continuous-integration/gocd-server/default.nix38
-rw-r--r--nixos/modules/services/continuous-integration/hail.nix10
-rw-r--r--nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix61
-rw-r--r--nixos/modules/services/continuous-integration/hydra/default.nix65
-rw-r--r--nixos/modules/services/continuous-integration/jenkins/default.nix48
-rw-r--r--nixos/modules/services/continuous-integration/jenkins/job-builder.nix50
-rw-r--r--nixos/modules/services/continuous-integration/jenkins/slave.nix24
-rw-r--r--nixos/modules/services/databases/aerospike.nix10
-rw-r--r--nixos/modules/services/databases/cassandra.nix137
-rw-r--r--nixos/modules/services/databases/clickhouse.nix4
-rw-r--r--nixos/modules/services/databases/cockroachdb.nix100
-rw-r--r--nixos/modules/services/databases/couchdb.nix44
-rw-r--r--nixos/modules/services/databases/dgraph.nix148
-rw-r--r--nixos/modules/services/databases/dragonflydb.nix152
-rw-r--r--nixos/modules/services/databases/firebird.nix14
-rw-r--r--nixos/modules/services/databases/foundationdb.nix80
-rw-r--r--nixos/modules/services/databases/hbase-standalone.nix (renamed from nixos/modules/services/databases/hbase.nix)39
-rw-r--r--nixos/modules/services/databases/influxdb.nix18
-rw-r--r--nixos/modules/services/databases/influxdb2.nix7
-rw-r--r--nixos/modules/services/databases/memcached.nix16
-rw-r--r--nixos/modules/services/databases/monetdb.nix14
-rw-r--r--nixos/modules/services/databases/mongodb.nix26
-rw-r--r--nixos/modules/services/databases/mysql.nix84
-rw-r--r--nixos/modules/services/databases/neo4j.nix272
-rw-r--r--nixos/modules/services/databases/openldap.nix217
-rw-r--r--nixos/modules/services/databases/opentsdb.nix20
-rw-r--r--nixos/modules/services/databases/pgmanage.nix38
-rw-r--r--nixos/modules/services/databases/postgresql.nix72
-rw-r--r--nixos/modules/services/databases/postgresql.xml33
-rw-r--r--nixos/modules/services/databases/redis.nix115
-rw-r--r--nixos/modules/services/databases/rethinkdb.nix10
-rw-r--r--nixos/modules/services/databases/riak.nix162
-rw-r--r--nixos/modules/services/databases/surrealdb.nix79
-rw-r--r--nixos/modules/services/databases/victoriametrics.nix16
-rw-r--r--nixos/modules/services/desktops/accountsservice.nix2
-rw-r--r--nixos/modules/services/desktops/bamf.nix2
-rw-r--r--nixos/modules/services/desktops/blueman.nix2
-rw-r--r--nixos/modules/services/desktops/cpupower-gui.nix2
-rw-r--r--nixos/modules/services/desktops/dleyna-renderer.nix2
-rw-r--r--nixos/modules/services/desktops/dleyna-server.nix2
-rw-r--r--nixos/modules/services/desktops/espanso.nix2
-rw-r--r--nixos/modules/services/desktops/flatpak.nix2
-rw-r--r--nixos/modules/services/desktops/geoclue2.nix34
-rw-r--r--nixos/modules/services/desktops/gnome/at-spi2-core.nix9
-rw-r--r--nixos/modules/services/desktops/gnome/chrome-gnome-shell.nix41
-rw-r--r--nixos/modules/services/desktops/gnome/evolution-data-server.nix8
-rw-r--r--nixos/modules/services/desktops/gnome/glib-networking.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/gnome-browser-connector.nix47
-rw-r--r--nixos/modules/services/desktops/gnome/gnome-initial-setup.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/gnome-keyring.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/gnome-online-accounts.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/gnome-online-miners.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/gnome-remote-desktop.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/gnome-settings-daemon.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/gnome-user-share.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/rygel.nix4
-rw-r--r--nixos/modules/services/desktops/gnome/sushi.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/tracker-miners.nix2
-rw-r--r--nixos/modules/services/desktops/gnome/tracker.nix4
-rw-r--r--nixos/modules/services/desktops/gsignond.nix4
-rw-r--r--nixos/modules/services/desktops/gvfs.nix6
-rw-r--r--nixos/modules/services/desktops/malcontent.nix2
-rw-r--r--nixos/modules/services/desktops/neard.nix2
-rw-r--r--nixos/modules/services/desktops/pipewire/daemon/filter-chain.conf.json28
-rw-r--r--nixos/modules/services/desktops/pipewire/daemon/minimal.conf.json2
-rw-r--r--nixos/modules/services/desktops/pipewire/daemon/pipewire-avb.conf.json38
-rw-r--r--nixos/modules/services/desktops/pipewire/daemon/pipewire-pulse.conf.json20
-rw-r--r--nixos/modules/services/desktops/pipewire/daemon/pipewire.conf.json1
-rw-r--r--nixos/modules/services/desktops/pipewire/pipewire-media-session.nix20
-rw-r--r--nixos/modules/services/desktops/pipewire/pipewire.nix37
-rw-r--r--nixos/modules/services/desktops/pipewire/wireplumber.nix27
-rw-r--r--nixos/modules/services/desktops/profile-sync-daemon.nix4
-rw-r--r--nixos/modules/services/desktops/system-config-printer.nix5
-rw-r--r--nixos/modules/services/desktops/telepathy.nix2
-rw-r--r--nixos/modules/services/desktops/tumbler.nix2
-rw-r--r--nixos/modules/services/desktops/zeitgeist.nix2
-rw-r--r--nixos/modules/services/development/blackfire.nix8
-rw-r--r--nixos/modules/services/development/bloop.nix4
-rw-r--r--nixos/modules/services/development/distccd.nix24
-rw-r--r--nixos/modules/services/development/hoogle.nix14
-rw-r--r--nixos/modules/services/development/jupyter/default.nix39
-rw-r--r--nixos/modules/services/development/jupyter/kernel-options.nix32
-rw-r--r--nixos/modules/services/development/jupyterhub/default.nix22
-rw-r--r--nixos/modules/services/development/lorri.nix4
-rw-r--r--nixos/modules/services/development/rstudio-server/default.nix12
-rw-r--r--nixos/modules/services/development/zammad.nix48
-rw-r--r--nixos/modules/services/display-managers/greetd.nix14
-rw-r--r--nixos/modules/services/editors/emacs.nix16
-rw-r--r--nixos/modules/services/editors/haste.nix86
-rw-r--r--nixos/modules/services/editors/infinoted.nix26
-rw-r--r--nixos/modules/services/finance/odoo.nix12
-rw-r--r--nixos/modules/services/games/asf.nix117
-rw-r--r--nixos/modules/services/games/crossfire-server.nix20
-rw-r--r--nixos/modules/services/games/deliantra-server.nix14
-rw-r--r--nixos/modules/services/games/factorio.nix68
-rw-r--r--nixos/modules/services/games/freeciv.nix28
-rw-r--r--nixos/modules/services/games/minecraft-server.nix78
-rw-r--r--nixos/modules/services/games/minetest-server.nix12
-rw-r--r--nixos/modules/services/games/openarena.nix6
-rw-r--r--nixos/modules/services/games/quake3-server.nix12
-rw-r--r--nixos/modules/services/games/teeworlds.nix22
-rw-r--r--nixos/modules/services/games/terraria.nix38
-rw-r--r--nixos/modules/services/hardware/acpid.nix22
-rw-r--r--nixos/modules/services/hardware/actkbd.nix26
-rw-r--r--nixos/modules/services/hardware/argonone.nix58
-rw-r--r--nixos/modules/services/hardware/auto-cpufreq.nix2
-rw-r--r--nixos/modules/services/hardware/bluetooth.nix20
-rw-r--r--nixos/modules/services/hardware/bolt.nix2
-rw-r--r--nixos/modules/services/hardware/brltty.nix2
-rw-r--r--nixos/modules/services/hardware/ddccontrol.nix2
-rw-r--r--nixos/modules/services/hardware/fancontrol.nix4
-rw-r--r--nixos/modules/services/hardware/freefall.nix6
-rw-r--r--nixos/modules/services/hardware/fwupd.nix59
-rw-r--r--nixos/modules/services/hardware/illum.nix3
-rw-r--r--nixos/modules/services/hardware/interception-tools.nix6
-rw-r--r--nixos/modules/services/hardware/irqbalance.nix2
-rw-r--r--nixos/modules/services/hardware/joycond.nix12
-rw-r--r--nixos/modules/services/hardware/kanata.nix215
-rw-r--r--nixos/modules/services/hardware/lcd.nix43
-rw-r--r--nixos/modules/services/hardware/lirc.nix8
-rw-r--r--nixos/modules/services/hardware/nvidia-optimus.nix2
-rw-r--r--nixos/modules/services/hardware/openrgb.nix52
-rw-r--r--nixos/modules/services/hardware/pcscd.nix19
-rw-r--r--nixos/modules/services/hardware/pommed.nix12
-rw-r--r--nixos/modules/services/hardware/power-profiles-daemon.nix2
-rw-r--r--nixos/modules/services/hardware/rasdaemon.nix14
-rw-r--r--nixos/modules/services/hardware/ratbagd.nix2
-rw-r--r--nixos/modules/services/hardware/sane.nix62
-rw-r--r--nixos/modules/services/hardware/sane_extra_backends/brscan4.nix14
-rw-r--r--nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix3
-rw-r--r--nixos/modules/services/hardware/sane_extra_backends/brscan5.nix12
-rw-r--r--nixos/modules/services/hardware/sane_extra_backends/dsseries.nix4
-rw-r--r--nixos/modules/services/hardware/spacenavd.nix2
-rw-r--r--nixos/modules/services/hardware/tcsd.nix18
-rw-r--r--nixos/modules/services/hardware/thermald.nix8
-rw-r--r--nixos/modules/services/hardware/thinkfan.nix86
-rw-r--r--nixos/modules/services/hardware/throttled.nix4
-rw-r--r--nixos/modules/services/hardware/tlp.nix6
-rw-r--r--nixos/modules/services/hardware/trezord.nix6
-rw-r--r--nixos/modules/services/hardware/triggerhappy.nix22
-rw-r--r--nixos/modules/services/hardware/udev.nix207
-rw-r--r--nixos/modules/services/hardware/udisks2.nix49
-rw-r--r--nixos/modules/services/hardware/undervolt.nix32
-rw-r--r--nixos/modules/services/hardware/upower.nix90
-rw-r--r--nixos/modules/services/hardware/usbmuxd.nix6
-rw-r--r--nixos/modules/services/hardware/usbrelayd.nix43
-rw-r--r--nixos/modules/services/hardware/vdr.nix10
-rw-r--r--nixos/modules/services/hardware/xow.nix20
-rw-r--r--nixos/modules/services/home-automation/evcc.nix92
-rw-r--r--nixos/modules/services/home-automation/home-assistant.nix142
-rw-r--r--nixos/modules/services/home-automation/zigbee2mqtt.nix12
-rw-r--r--nixos/modules/services/logging/SystemdJournal2Gelf.nix10
-rw-r--r--nixos/modules/services/logging/awstats.nix38
-rw-r--r--nixos/modules/services/logging/filebeat.nix71
-rw-r--r--nixos/modules/services/logging/fluentd.nix12
-rw-r--r--nixos/modules/services/logging/graylog.nix26
-rw-r--r--nixos/modules/services/logging/heartbeat.nix22
-rw-r--r--nixos/modules/services/logging/journalbeat.nix14
-rw-r--r--nixos/modules/services/logging/journaldriver.nix12
-rw-r--r--nixos/modules/services/logging/journalwatch.nix40
-rw-r--r--nixos/modules/services/logging/klogd.nix41
-rw-r--r--nixos/modules/services/logging/logcheck.nix38
-rw-r--r--nixos/modules/services/logging/logrotate.nix337
-rw-r--r--nixos/modules/services/logging/logstash.nix28
-rw-r--r--nixos/modules/services/logging/promtail.nix6
-rw-r--r--nixos/modules/services/logging/rsyslogd.nix18
-rw-r--r--nixos/modules/services/logging/syslog-ng.nix19
-rw-r--r--nixos/modules/services/logging/syslogd.nix22
-rw-r--r--nixos/modules/services/logging/vector.nix12
-rw-r--r--nixos/modules/services/mail/clamsmtp.nix28
-rw-r--r--nixos/modules/services/mail/davmail.nix10
-rw-r--r--nixos/modules/services/mail/dkimproxy-out.nix12
-rw-r--r--nixos/modules/services/mail/dovecot.nix70
-rw-r--r--nixos/modules/services/mail/dspam.nix14
-rw-r--r--nixos/modules/services/mail/exim.nix14
-rw-r--r--nixos/modules/services/mail/listmonk.nix222
-rw-r--r--nixos/modules/services/mail/maddy.nix31
-rw-r--r--nixos/modules/services/mail/mail.nix2
-rw-r--r--nixos/modules/services/mail/mailcatcher.nix12
-rw-r--r--nixos/modules/services/mail/mailhog.nix12
-rw-r--r--nixos/modules/services/mail/mailman.nix282
-rw-r--r--nixos/modules/services/mail/mlmmj.nix15
-rw-r--r--nixos/modules/services/mail/nullmailer.nix46
-rw-r--r--nixos/modules/services/mail/offlineimap.nix14
-rw-r--r--nixos/modules/services/mail/opendkim.nix18
-rw-r--r--nixos/modules/services/mail/opensmtpd.nix12
-rw-r--r--nixos/modules/services/mail/pfix-srsd.nix8
-rw-r--r--nixos/modules/services/mail/postfix.nix229
-rw-r--r--nixos/modules/services/mail/postfixadmin.nix30
-rw-r--r--nixos/modules/services/mail/postgrey.nix38
-rw-r--r--nixos/modules/services/mail/postsrsd.nix20
-rw-r--r--nixos/modules/services/mail/public-inbox.nix577
-rw-r--r--nixos/modules/services/mail/roundcube.nix34
-rw-r--r--nixos/modules/services/mail/rspamd.nix60
-rw-r--r--nixos/modules/services/mail/rss2email.nix31
-rw-r--r--nixos/modules/services/mail/schleuder.nix162
-rw-r--r--nixos/modules/services/mail/spamassassin.nix29
-rw-r--r--nixos/modules/services/mail/sympa.nix84
-rw-r--r--nixos/modules/services/matrix/appservice-discord.nix (renamed from nixos/modules/services/misc/matrix-appservice-discord.nix)35
-rw-r--r--nixos/modules/services/matrix/appservice-irc.nix (renamed from nixos/modules/services/misc/matrix-appservice-irc.nix)37
-rw-r--r--nixos/modules/services/matrix/conduit.nix (renamed from nixos/modules/services/misc/matrix-conduit.nix)30
-rw-r--r--nixos/modules/services/matrix/dendrite.nix (renamed from nixos/modules/services/misc/dendrite.nix)118
-rw-r--r--nixos/modules/services/matrix/mautrix-facebook.nix (renamed from nixos/modules/services/misc/mautrix-facebook.nix)34
-rw-r--r--nixos/modules/services/matrix/mautrix-telegram.nix (renamed from nixos/modules/services/misc/mautrix-telegram.nix)75
-rw-r--r--nixos/modules/services/matrix/mjolnir.nix44
-rw-r--r--nixos/modules/services/matrix/pantalaimon-options.nix20
-rw-r--r--nixos/modules/services/matrix/pantalaimon.nix4
-rw-r--r--nixos/modules/services/matrix/synapse-log_config.yaml (renamed from nixos/modules/services/matrix/matrix-synapse-log_config.yaml)0
-rw-r--r--nixos/modules/services/matrix/synapse.nix (renamed from nixos/modules/services/matrix/matrix-synapse.nix)140
-rw-r--r--nixos/modules/services/matrix/synapse.xml (renamed from nixos/modules/services/matrix/matrix-synapse.xml)237
-rw-r--r--nixos/modules/services/misc/airsonic.nix26
-rw-r--r--nixos/modules/services/misc/ananicy.nix14
-rw-r--r--nixos/modules/services/misc/ankisyncd.nix12
-rw-r--r--nixos/modules/services/misc/apache-kafka.nix26
-rw-r--r--nixos/modules/services/misc/autofs.nix10
-rw-r--r--nixos/modules/services/misc/autorandr.nix68
-rw-r--r--nixos/modules/services/misc/bazarr.nix10
-rw-r--r--nixos/modules/services/misc/beanstalkd.nix10
-rw-r--r--nixos/modules/services/misc/bees.nix21
-rw-r--r--nixos/modules/services/misc/bepasty.nix26
-rw-r--r--nixos/modules/services/misc/calibre-server.nix8
-rw-r--r--nixos/modules/services/misc/canto-daemon.nix2
-rw-r--r--nixos/modules/services/misc/cfdyndns.nix8
-rw-r--r--nixos/modules/services/misc/cgminer.nix12
-rw-r--r--nixos/modules/services/misc/clipcat.nix4
-rw-r--r--nixos/modules/services/misc/clipmenu.nix4
-rwxr-xr-xnixos/modules/services/misc/confd.nix18
-rw-r--r--nixos/modules/services/misc/cpuminer-cryptonight.nix10
-rw-r--r--nixos/modules/services/misc/devmon.nix2
-rw-r--r--nixos/modules/services/misc/dictd.nix8
-rw-r--r--nixos/modules/services/misc/disnix.nix12
-rw-r--r--nixos/modules/services/misc/docker-registry.nix25
-rw-r--r--nixos/modules/services/misc/domoticz.nix8
-rw-r--r--nixos/modules/services/misc/duckling.nix4
-rw-r--r--nixos/modules/services/misc/dwm-status.nix8
-rw-r--r--nixos/modules/services/misc/dysnomia.nix22
-rw-r--r--nixos/modules/services/misc/errbot.nix16
-rw-r--r--nixos/modules/services/misc/etcd.nix42
-rw-r--r--nixos/modules/services/misc/etebase-server.nix42
-rw-r--r--nixos/modules/services/misc/etesync-dav.nix14
-rw-r--r--nixos/modules/services/misc/ethminer.nix117
-rw-r--r--nixos/modules/services/misc/exhibitor.nix87
-rw-r--r--nixos/modules/services/misc/felix.nix8
-rw-r--r--nixos/modules/services/misc/freeswitch.nix24
-rw-r--r--nixos/modules/services/misc/fstrim.nix7
-rw-r--r--nixos/modules/services/misc/gammu-smsd.nix48
-rw-r--r--nixos/modules/services/misc/geoipupdate.nix88
-rw-r--r--nixos/modules/services/misc/gitea.nix275
-rw-r--r--nixos/modules/services/misc/gitit.nix134
-rw-r--r--nixos/modules/services/misc/gitlab.nix345
-rw-r--r--nixos/modules/services/misc/gitolite.nix51
-rw-r--r--nixos/modules/services/misc/gitweb.nix8
-rw-r--r--nixos/modules/services/misc/gogs.nix52
-rw-r--r--nixos/modules/services/misc/gollum.nix59
-rw-r--r--nixos/modules/services/misc/gpsd.nix14
-rw-r--r--nixos/modules/services/misc/greenclip.nix4
-rw-r--r--nixos/modules/services/misc/headphones.nix14
-rw-r--r--nixos/modules/services/misc/heisenbridge.nix26
-rw-r--r--nixos/modules/services/misc/ihaskell.nix6
-rw-r--r--nixos/modules/services/misc/input-remapper.nix6
-rw-r--r--nixos/modules/services/misc/irkerd.nix8
-rw-r--r--nixos/modules/services/misc/jackett.nix12
-rw-r--r--nixos/modules/services/misc/jellyfin.nix80
-rw-r--r--nixos/modules/services/misc/klipper.nix181
-rw-r--r--nixos/modules/services/misc/languagetool.nix78
-rw-r--r--nixos/modules/services/misc/leaps.nix8
-rw-r--r--nixos/modules/services/misc/libreddit.nix52
-rw-r--r--nixos/modules/services/misc/lidarr.nix12
-rw-r--r--nixos/modules/services/misc/lifecycled.nix30
-rw-r--r--nixos/modules/services/misc/logkeys.nix4
-rw-r--r--nixos/modules/services/misc/mame.nix10
-rw-r--r--nixos/modules/services/misc/mbpfan.nix32
-rw-r--r--nixos/modules/services/misc/mediatomb.nix56
-rw-r--r--nixos/modules/services/misc/metabase.nix16
-rw-r--r--nixos/modules/services/misc/moonraker.nix34
-rw-r--r--nixos/modules/services/misc/mx-puppet-discord.nix16
-rw-r--r--nixos/modules/services/misc/n8n.nix8
-rw-r--r--nixos/modules/services/misc/nitter.nix77
-rw-r--r--nixos/modules/services/misc/nix-daemon.nix260
-rw-r--r--nixos/modules/services/misc/nix-gc.nix20
-rw-r--r--nixos/modules/services/misc/nix-optimise.nix7
-rw-r--r--nixos/modules/services/misc/nix-ssh-serve.nix8
-rw-r--r--nixos/modules/services/misc/novacomd.nix2
-rw-r--r--nixos/modules/services/misc/ntfy-sh.nix100
-rw-r--r--nixos/modules/services/misc/nzbget.nix10
-rw-r--r--nixos/modules/services/misc/nzbhydra2.nix8
-rw-r--r--nixos/modules/services/misc/octoprint.nix30
-rw-r--r--nixos/modules/services/misc/ombi.nix16
-rw-r--r--nixos/modules/services/misc/osrm.nix16
-rw-r--r--nixos/modules/services/misc/owncast.nix16
-rw-r--r--nixos/modules/services/misc/packagekit.nix8
-rw-r--r--nixos/modules/services/misc/paperless.nix (renamed from nixos/modules/services/misc/paperless-ng.nix)167
-rw-r--r--nixos/modules/services/misc/parsoid.nix14
-rw-r--r--nixos/modules/services/misc/persistent-evdev.nix60
-rw-r--r--nixos/modules/services/misc/pinnwand.nix105
-rw-r--r--nixos/modules/services/misc/plex.nix17
-rw-r--r--nixos/modules/services/misc/plikd.nix8
-rw-r--r--nixos/modules/services/misc/podgrab.nix8
-rw-r--r--nixos/modules/services/misc/polaris.nix151
-rw-r--r--nixos/modules/services/misc/portunus.nix288
-rw-r--r--nixos/modules/services/misc/prowlarr.nix4
-rw-r--r--nixos/modules/services/misc/pykms.nix16
-rw-r--r--nixos/modules/services/misc/radarr.nix20
-rw-r--r--nixos/modules/services/misc/redmine.nix131
-rw-r--r--nixos/modules/services/misc/ripple-data-api.nix30
-rw-r--r--nixos/modules/services/misc/rippled.nix74
-rw-r--r--nixos/modules/services/misc/rmfakecloud.nix16
-rw-r--r--nixos/modules/services/misc/safeeyes.nix4
-rw-r--r--nixos/modules/services/misc/sdrplay.nix10
-rw-r--r--nixos/modules/services/misc/serviio.nix4
-rw-r--r--nixos/modules/services/misc/sickbeard.nix16
-rw-r--r--nixos/modules/services/misc/signald.nix8
-rw-r--r--nixos/modules/services/misc/siproxd.nix28
-rw-r--r--nixos/modules/services/misc/snapper.nix22
-rw-r--r--nixos/modules/services/misc/sonarr.nix21
-rw-r--r--nixos/modules/services/misc/sourcehut/builds.nix236
-rw-r--r--nixos/modules/services/misc/sourcehut/default.nix329
-rw-r--r--nixos/modules/services/misc/sourcehut/dispatch.nix127
-rw-r--r--nixos/modules/services/misc/sourcehut/git.nix217
-rw-r--r--nixos/modules/services/misc/sourcehut/hg.nix175
-rw-r--r--nixos/modules/services/misc/sourcehut/hub.nix120
-rw-r--r--nixos/modules/services/misc/sourcehut/lists.nix187
-rw-r--r--nixos/modules/services/misc/sourcehut/man.nix124
-rw-r--r--nixos/modules/services/misc/sourcehut/meta.nix213
-rw-r--r--nixos/modules/services/misc/sourcehut/paste.nix135
-rw-r--r--nixos/modules/services/misc/sourcehut/service.nix22
-rw-r--r--nixos/modules/services/misc/sourcehut/todo.nix163
-rw-r--r--nixos/modules/services/misc/spice-vdagentd.nix2
-rw-r--r--nixos/modules/services/misc/spice-webdavd.nix38
-rw-r--r--nixos/modules/services/misc/ssm-agent.nix4
-rw-r--r--nixos/modules/services/misc/sssd.nix86
-rw-r--r--nixos/modules/services/misc/subsonic.nix22
-rw-r--r--nixos/modules/services/misc/sundtek.nix2
-rw-r--r--nixos/modules/services/misc/svnserve.nix4
-rw-r--r--nixos/modules/services/misc/synergy.nix24
-rw-r--r--nixos/modules/services/misc/sysprof.nix2
-rw-r--r--nixos/modules/services/misc/tandoor-recipes.nix144
-rw-r--r--nixos/modules/services/misc/taskserver/default.nix119
-rw-r--r--nixos/modules/services/misc/taskserver/helper-tool.py10
-rw-r--r--nixos/modules/services/misc/tautulli.nix24
-rw-r--r--nixos/modules/services/misc/tiddlywiki.nix8
-rw-r--r--nixos/modules/services/misc/tp-auto-kbbl.nix10
-rw-r--r--nixos/modules/services/misc/tzupdate.nix2
-rw-r--r--nixos/modules/services/misc/uhub.nix28
-rw-r--r--nixos/modules/services/misc/weechat.nix8
-rw-r--r--nixos/modules/services/misc/xmr-stak.nix10
-rw-r--r--nixos/modules/services/misc/xmrig.nix8
-rw-r--r--nixos/modules/services/misc/zoneminder.nix36
-rw-r--r--nixos/modules/services/misc/zookeeper.nix37
-rw-r--r--nixos/modules/services/monitoring/alerta.nix22
-rw-r--r--nixos/modules/services/monitoring/apcupsd.nix6
-rw-r--r--nixos/modules/services/monitoring/arbtt.nix14
-rw-r--r--nixos/modules/services/monitoring/bosun.nix28
-rw-r--r--nixos/modules/services/monitoring/cadvisor.nix42
-rw-r--r--nixos/modules/services/monitoring/collectd.nix76
-rw-r--r--nixos/modules/services/monitoring/das_watchdog.nix2
-rw-r--r--nixos/modules/services/monitoring/datadog-agent.nix38
-rw-r--r--nixos/modules/services/monitoring/dd-agent/dd-agent-defaults.nix8
-rw-r--r--nixos/modules/services/monitoring/dd-agent/dd-agent.nix236
-rwxr-xr-xnixos/modules/services/monitoring/dd-agent/update-dd-agent-defaults9
-rw-r--r--nixos/modules/services/monitoring/do-agent.nix2
-rw-r--r--nixos/modules/services/monitoring/fusion-inventory.nix6
-rw-r--r--nixos/modules/services/monitoring/grafana-agent.nix157
-rw-r--r--nixos/modules/services/monitoring/grafana-image-renderer.nix54
-rw-r--r--nixos/modules/services/monitoring/grafana-reporter.nix18
-rw-r--r--nixos/modules/services/monitoring/grafana.nix1549
-rw-r--r--nixos/modules/services/monitoring/graphite.nix210
-rw-r--r--nixos/modules/services/monitoring/hdaps.nix4
-rw-r--r--nixos/modules/services/monitoring/heapster.nix14
-rw-r--r--nixos/modules/services/monitoring/incron.nix16
-rw-r--r--nixos/modules/services/monitoring/kapacitor.nix36
-rw-r--r--nixos/modules/services/monitoring/karma.nix128
-rw-r--r--nixos/modules/services/monitoring/kthxbye.nix166
-rw-r--r--nixos/modules/services/monitoring/loki.nix14
-rw-r--r--nixos/modules/services/monitoring/longview.nix26
-rw-r--r--nixos/modules/services/monitoring/mackerel-agent.nix22
-rw-r--r--nixos/modules/services/monitoring/metricbeat.nix38
-rw-r--r--nixos/modules/services/monitoring/mimir.nix67
-rw-r--r--nixos/modules/services/monitoring/monit.nix4
-rw-r--r--nixos/modules/services/monitoring/munin.nix60
-rw-r--r--nixos/modules/services/monitoring/nagios.nix40
-rw-r--r--nixos/modules/services/monitoring/netdata.nix36
-rw-r--r--nixos/modules/services/monitoring/parsedmarc.nix242
-rw-r--r--nixos/modules/services/monitoring/prometheus/alertmanager.nix28
-rw-r--r--nixos/modules/services/monitoring/prometheus/default.nix268
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters.nix43
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters.xml21
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/apcupsd.nix4
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/artifactory.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/bind.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/bird.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/bitcoin.nix14
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/blackbox.nix4
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/buildkite-agent.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/collectd.nix16
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/dmarc.nix24
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/dnsmasq.nix6
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/dovecot.nix22
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/fastly.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/flow.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/fritzbox.nix4
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/influxdb.nix4
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/ipmi.nix41
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/jitsi.nix4
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/json.nix2
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/kea.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/knot.nix11
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/lnd.nix6
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/mail.nix62
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/mikrotik.nix10
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/minio.nix12
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/modemmanager.nix2
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/nextcloud.nix10
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/nginx.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/nginxlog.nix4
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/node.nix14
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/openldap.nix20
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/openvpn.nix6
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/pihole.nix12
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/postfix.nix24
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/postgres.nix18
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/process.nix4
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/pve.nix26
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/py-air-control.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/rspamd.nix2
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/rtl_433.nix14
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/script.nix10
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/smartctl.nix11
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/smokeping.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/snmp.nix8
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/sql.nix24
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/surfboard.nix2
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/tor.nix6
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/unbound.nix6
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/unifi-poller.nix11
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/unifi.nix10
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/v2ray.nix29
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/varnish.nix16
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/wireguard.nix28
-rw-r--r--nixos/modules/services/monitoring/prometheus/exporters/zfs.nix44
-rw-r--r--nixos/modules/services/monitoring/prometheus/pushgateway.nix48
-rw-r--r--nixos/modules/services/monitoring/prometheus/sachet.nix88
-rw-r--r--nixos/modules/services/monitoring/prometheus/xmpp-alerts.nix6
-rw-r--r--nixos/modules/services/monitoring/riemann-dash.nix6
-rw-r--r--nixos/modules/services/monitoring/riemann-tools.nix6
-rw-r--r--nixos/modules/services/monitoring/riemann.nix21
-rw-r--r--nixos/modules/services/monitoring/scollector.nix16
-rw-r--r--nixos/modules/services/monitoring/smartd.nix51
-rw-r--r--nixos/modules/services/monitoring/statsd.nix18
-rw-r--r--nixos/modules/services/monitoring/sysstat.nix6
-rw-r--r--nixos/modules/services/monitoring/teamviewer.nix4
-rw-r--r--nixos/modules/services/monitoring/telegraf.nix10
-rw-r--r--nixos/modules/services/monitoring/thanos.nix148
-rw-r--r--nixos/modules/services/monitoring/tremor-rs.nix129
-rw-r--r--nixos/modules/services/monitoring/tuptime.nix19
-rw-r--r--nixos/modules/services/monitoring/unifi-poller.nix70
-rw-r--r--nixos/modules/services/monitoring/ups.nix24
-rw-r--r--nixos/modules/services/monitoring/uptime-kuma.nix76
-rw-r--r--nixos/modules/services/monitoring/uptime.nix10
-rw-r--r--nixos/modules/services/monitoring/vmagent.nix100
-rw-r--r--nixos/modules/services/monitoring/vnstat.nix2
-rw-r--r--nixos/modules/services/monitoring/zabbix-agent.nix22
-rw-r--r--nixos/modules/services/monitoring/zabbix-proxy.nix40
-rw-r--r--nixos/modules/services/monitoring/zabbix-server.nix40
-rw-r--r--nixos/modules/services/network-filesystems/cachefilesd.nix6
-rw-r--r--nixos/modules/services/network-filesystems/ceph.nix60
-rw-r--r--nixos/modules/services/network-filesystems/davfs2.nix8
-rw-r--r--nixos/modules/services/network-filesystems/diod.nix26
-rw-r--r--nixos/modules/services/network-filesystems/drbd.nix6
-rw-r--r--nixos/modules/services/network-filesystems/glusterfs.nix27
-rw-r--r--nixos/modules/services/network-filesystems/kbfs.nix10
-rw-r--r--nixos/modules/services/network-filesystems/kubo.nix (renamed from nixos/modules/services/network-filesystems/ipfs.nix)177
-rw-r--r--nixos/modules/services/network-filesystems/litestream/default.nix18
-rw-r--r--nixos/modules/services/network-filesystems/litestream/litestream.xml2
-rw-r--r--nixos/modules/services/network-filesystems/moosefs.nix36
-rw-r--r--nixos/modules/services/network-filesystems/netatalk.nix14
-rw-r--r--nixos/modules/services/network-filesystems/nfsd.nix30
-rw-r--r--nixos/modules/services/network-filesystems/openafs/client.nix50
-rw-r--r--nixos/modules/services/network-filesystems/openafs/lib.nix4
-rw-r--r--nixos/modules/services/network-filesystems/openafs/server.nix44
-rw-r--r--nixos/modules/services/network-filesystems/orangefs/client.nix14
-rw-r--r--nixos/modules/services/network-filesystems/orangefs/server.nix32
-rw-r--r--nixos/modules/services/network-filesystems/rsyncd.nix11
-rw-r--r--nixos/modules/services/network-filesystems/samba-wsdd.nix32
-rw-r--r--nixos/modules/services/network-filesystems/samba.nix35
-rw-r--r--nixos/modules/services/network-filesystems/tahoe.nix50
-rw-r--r--nixos/modules/services/network-filesystems/u9fs.nix12
-rw-r--r--nixos/modules/services/network-filesystems/webdav-server-rs.nix12
-rw-r--r--nixos/modules/services/network-filesystems/webdav.nix20
-rw-r--r--nixos/modules/services/network-filesystems/xtreemfs.nix52
-rw-r--r--nixos/modules/services/network-filesystems/yandex-disk.nix14
-rw-r--r--nixos/modules/services/networking/3proxy.nix130
-rw-r--r--nixos/modules/services/networking/adguardhome.nix102
-rw-r--r--nixos/modules/services/networking/amuled.nix6
-rw-r--r--nixos/modules/services/networking/antennas.nix10
-rw-r--r--nixos/modules/services/networking/aria2.nix14
-rw-r--r--nixos/modules/services/networking/asterisk.nix84
-rw-r--r--nixos/modules/services/networking/atftpd.nix6
-rw-r--r--nixos/modules/services/networking/autossh.nix10
-rw-r--r--nixos/modules/services/networking/avahi-daemon.nix51
-rw-r--r--nixos/modules/services/networking/babeld.nix14
-rw-r--r--nixos/modules/services/networking/bee-clef.nix10
-rw-r--r--nixos/modules/services/networking/bee.nix14
-rw-r--r--nixos/modules/services/networking/biboumi.nix42
-rw-r--r--nixos/modules/services/networking/bind.nix60
-rw-r--r--nixos/modules/services/networking/bird-lg.nix269
-rw-r--r--nixos/modules/services/networking/bird.nix17
-rw-r--r--nixos/modules/services/networking/bitcoind.nix42
-rw-r--r--nixos/modules/services/networking/bitlbee.nix31
-rw-r--r--nixos/modules/services/networking/blockbook-frontend.nix60
-rw-r--r--nixos/modules/services/networking/blocky.nix6
-rw-r--r--nixos/modules/services/networking/charybdis.nix12
-rw-r--r--nixos/modules/services/networking/chisel-server.nix99
-rw-r--r--nixos/modules/services/networking/cjdns.nix36
-rw-r--r--nixos/modules/services/networking/cloudflare-dyndns.nix93
-rw-r--r--nixos/modules/services/networking/cntlm.nix20
-rw-r--r--nixos/modules/services/networking/connman.nix16
-rw-r--r--nixos/modules/services/networking/consul.nix72
-rw-r--r--nixos/modules/services/networking/coredns.nix9
-rw-r--r--nixos/modules/services/networking/corerad.nix10
-rw-r--r--nixos/modules/services/networking/coturn.nix67
-rw-r--r--nixos/modules/services/networking/create_ap.nix50
-rw-r--r--nixos/modules/services/networking/croc.nix12
-rw-r--r--nixos/modules/services/networking/dante.nix4
-rw-r--r--nixos/modules/services/networking/ddclient.nix49
-rw-r--r--nixos/modules/services/networking/dhcpcd.nix16
-rw-r--r--nixos/modules/services/networking/dhcpd.nix28
-rw-r--r--nixos/modules/services/networking/dnscache.nix10
-rw-r--r--nixos/modules/services/networking/dnscrypt-proxy2.nix17
-rw-r--r--nixos/modules/services/networking/dnscrypt-wrapper.nix26
-rw-r--r--nixos/modules/services/networking/dnsdist.nix8
-rw-r--r--nixos/modules/services/networking/dnsmasq.nix12
-rw-r--r--nixos/modules/services/networking/doh-proxy-rust.nix6
-rw-r--r--nixos/modules/services/networking/ejabberd.nix20
-rw-r--r--nixos/modules/services/networking/envoy.nix84
-rw-r--r--nixos/modules/services/networking/epmd.nix6
-rw-r--r--nixos/modules/services/networking/ergo.nix22
-rw-r--r--nixos/modules/services/networking/ergochat.nix10
-rw-r--r--nixos/modules/services/networking/eternal-terminal.nix12
-rw-r--r--nixos/modules/services/networking/expressvpn.nix29
-rw-r--r--nixos/modules/services/networking/fakeroute.nix4
-rw-r--r--nixos/modules/services/networking/ferm.nix8
-rw-r--r--nixos/modules/services/networking/firefox-syncserver.md55
-rw-r--r--nixos/modules/services/networking/firefox-syncserver.nix317
-rw-r--r--nixos/modules/services/networking/firefox-syncserver.xml77
-rw-r--r--nixos/modules/services/networking/fireqos.nix4
-rw-r--r--nixos/modules/services/networking/firewall.nix74
-rw-r--r--nixos/modules/services/networking/flannel.nix51
-rw-r--r--nixos/modules/services/networking/freenet.nix4
-rw-r--r--nixos/modules/services/networking/freeradius.nix6
-rw-r--r--nixos/modules/services/networking/frr.nix23
-rw-r--r--nixos/modules/services/networking/gateone.nix10
-rw-r--r--nixos/modules/services/networking/gdomap.nix2
-rw-r--r--nixos/modules/services/networking/ghostunnel.nix44
-rw-r--r--nixos/modules/services/networking/git-daemon.nix18
-rw-r--r--nixos/modules/services/networking/globalprotect-vpn.nix31
-rw-r--r--nixos/modules/services/networking/gnunet.nix18
-rw-r--r--nixos/modules/services/networking/go-autoconfig.nix66
-rw-r--r--nixos/modules/services/networking/go-neb.nix20
-rw-r--r--nixos/modules/services/networking/go-shadowsocks2.nix4
-rw-r--r--nixos/modules/services/networking/gobgpd.nix6
-rw-r--r--nixos/modules/services/networking/gvpe.nix14
-rw-r--r--nixos/modules/services/networking/hans.nix22
-rw-r--r--nixos/modules/services/networking/haproxy.nix10
-rw-r--r--nixos/modules/services/networking/headscale.nix112
-rw-r--r--nixos/modules/services/networking/hostapd.nix44
-rw-r--r--nixos/modules/services/networking/htpdate.nix8
-rw-r--r--nixos/modules/services/networking/https-dns-proxy.nix52
-rw-r--r--nixos/modules/services/networking/hylafax/options.nix102
-rw-r--r--nixos/modules/services/networking/i2p.nix2
-rw-r--r--nixos/modules/services/networking/i2pd.nix169
-rw-r--r--nixos/modules/services/networking/icecream/daemon.nix26
-rw-r--r--nixos/modules/services/networking/icecream/scheduler.nix16
-rw-r--r--nixos/modules/services/networking/inspircd.nix16
-rw-r--r--nixos/modules/services/networking/iodine.nix24
-rw-r--r--nixos/modules/services/networking/iperf3.nix22
-rw-r--r--nixos/modules/services/networking/ircd-hybrid/default.nix34
-rw-r--r--nixos/modules/services/networking/ircd-hybrid/ircd.conf2
-rw-r--r--nixos/modules/services/networking/iscsi/initiator.nix16
-rw-r--r--nixos/modules/services/networking/iscsi/root-initiator.nix16
-rw-r--r--nixos/modules/services/networking/iscsi/target.nix4
-rw-r--r--nixos/modules/services/networking/iwd.nix23
-rw-r--r--nixos/modules/services/networking/jibri/default.nix42
-rw-r--r--nixos/modules/services/networking/jicofo.nix22
-rw-r--r--nixos/modules/services/networking/jitsi-videobridge.nix36
-rw-r--r--nixos/modules/services/networking/kea.nix124
-rw-r--r--nixos/modules/services/networking/keepalived/default.nix60
-rw-r--r--nixos/modules/services/networking/keepalived/virtual-ip-options.nix10
-rw-r--r--nixos/modules/services/networking/keepalived/vrrp-instance-options.nix28
-rw-r--r--nixos/modules/services/networking/keepalived/vrrp-script-options.nix18
-rw-r--r--nixos/modules/services/networking/keybase.nix2
-rw-r--r--nixos/modules/services/networking/knot.nix12
-rw-r--r--nixos/modules/services/networking/kresd.nix18
-rw-r--r--nixos/modules/services/networking/lambdabot.nix6
-rw-r--r--nixos/modules/services/networking/libreswan.nix20
-rw-r--r--nixos/modules/services/networking/lldpd.nix4
-rw-r--r--nixos/modules/services/networking/logmein-hamachi.nix2
-rw-r--r--nixos/modules/services/networking/lokinet.nix157
-rw-r--r--nixos/modules/services/networking/lxd-image-server.nix30
-rw-r--r--nixos/modules/services/networking/magic-wormhole-mailbox-server.nix2
-rw-r--r--nixos/modules/services/networking/matterbridge.nix14
-rw-r--r--nixos/modules/services/networking/minidlna.nix251
-rw-r--r--nixos/modules/services/networking/miniupnpd.nix12
-rw-r--r--nixos/modules/services/networking/miredo.nix12
-rw-r--r--nixos/modules/services/networking/mjpg-streamer.nix12
-rw-r--r--nixos/modules/services/networking/monero.nix46
-rw-r--r--nixos/modules/services/networking/morty.nix16
-rw-r--r--nixos/modules/services/networking/mosquitto.nix101
-rw-r--r--nixos/modules/services/networking/mozillavpn.nix14
-rw-r--r--nixos/modules/services/networking/mstpd.nix2
-rw-r--r--nixos/modules/services/networking/mtprotoproxy.nix14
-rw-r--r--nixos/modules/services/networking/mtr-exporter.nix12
-rw-r--r--nixos/modules/services/networking/mullvad-vpn.nix48
-rw-r--r--nixos/modules/services/networking/multipath.nix110
-rw-r--r--nixos/modules/services/networking/murmur.nix87
-rw-r--r--nixos/modules/services/networking/mxisd.nix31
-rw-r--r--nixos/modules/services/networking/namecoind.nix24
-rw-r--r--nixos/modules/services/networking/nar-serve.nix6
-rw-r--r--nixos/modules/services/networking/nat.nix39
-rw-r--r--nixos/modules/services/networking/nats.nix22
-rw-r--r--nixos/modules/services/networking/nbd.nix65
-rw-r--r--nixos/modules/services/networking/ncdns.nix70
-rw-r--r--nixos/modules/services/networking/ndppd.nix32
-rw-r--r--nixos/modules/services/networking/nebula.nix35
-rw-r--r--nixos/modules/services/networking/netbird.nix64
-rw-r--r--nixos/modules/services/networking/networkmanager.nix232
-rw-r--r--nixos/modules/services/networking/nextdns.nix4
-rw-r--r--nixos/modules/services/networking/nftables.nix17
-rw-r--r--nixos/modules/services/networking/nghttpx/backend-params-submodule.nix16
-rw-r--r--nixos/modules/services/networking/nghttpx/backend-submodule.nix6
-rw-r--r--nixos/modules/services/networking/nghttpx/frontend-params-submodule.nix10
-rw-r--r--nixos/modules/services/networking/nghttpx/frontend-submodule.nix4
-rw-r--r--nixos/modules/services/networking/nghttpx/nghttpx-options.nix26
-rw-r--r--nixos/modules/services/networking/nghttpx/server-options.nix4
-rw-r--r--nixos/modules/services/networking/nghttpx/tls-submodule.nix4
-rw-r--r--nixos/modules/services/networking/ngircd.nix6
-rw-r--r--nixos/modules/services/networking/nix-serve.nix25
-rw-r--r--nixos/modules/services/networking/nix-store-gcs-proxy.nix8
-rw-r--r--nixos/modules/services/networking/nixops-dns.nix8
-rw-r--r--nixos/modules/services/networking/nntp-proxy.nix38
-rw-r--r--nixos/modules/services/networking/nomad.nix38
-rw-r--r--nixos/modules/services/networking/nsd.nix183
-rw-r--r--nixos/modules/services/networking/ntopng.nix22
-rw-r--r--nixos/modules/services/networking/ntp/chrony.nix26
-rw-r--r--nixos/modules/services/networking/ntp/ntpd.nix29
-rw-r--r--nixos/modules/services/networking/ntp/openntpd.nix8
-rw-r--r--nixos/modules/services/networking/nullidentdmod.nix4
-rw-r--r--nixos/modules/services/networking/nylon.nix22
-rw-r--r--nixos/modules/services/networking/ocserv.nix4
-rw-r--r--nixos/modules/services/networking/ofono.nix4
-rw-r--r--nixos/modules/services/networking/oidentd.nix2
-rw-r--r--nixos/modules/services/networking/onedrive.nix8
-rw-r--r--nixos/modules/services/networking/openconnect.nix143
-rw-r--r--nixos/modules/services/networking/openfire.nix56
-rw-r--r--nixos/modules/services/networking/openvpn.nix26
-rw-r--r--nixos/modules/services/networking/ostinato.nix14
-rw-r--r--nixos/modules/services/networking/owamp.nix2
-rw-r--r--nixos/modules/services/networking/pdns-recursor.nix57
-rw-r--r--nixos/modules/services/networking/pdnsd.nix16
-rw-r--r--nixos/modules/services/networking/pixiecore.nix26
-rw-r--r--nixos/modules/services/networking/pleroma.nix32
-rw-r--r--nixos/modules/services/networking/polipo.nix20
-rw-r--r--nixos/modules/services/networking/powerdns.nix10
-rw-r--r--nixos/modules/services/networking/pppd.nix14
-rw-r--r--nixos/modules/services/networking/pptpd.nix16
-rw-r--r--nixos/modules/services/networking/prayer.nix8
-rw-r--r--nixos/modules/services/networking/privoxy.nix60
-rw-r--r--nixos/modules/services/networking/prosody.nix260
-rw-r--r--nixos/modules/services/networking/quassel.nix20
-rw-r--r--nixos/modules/services/networking/quicktun.nix24
-rw-r--r--nixos/modules/services/networking/quorum.nix40
-rw-r--r--nixos/modules/services/networking/r53-ddns.nix72
-rw-r--r--nixos/modules/services/networking/radicale.nix30
-rw-r--r--nixos/modules/services/networking/radvd.nix23
-rw-r--r--nixos/modules/services/networking/rdnssd.nix6
-rw-r--r--nixos/modules/services/networking/redsocks.nix32
-rw-r--r--nixos/modules/services/networking/resilio.nix89
-rw-r--r--nixos/modules/services/networking/robustirc-bridge.nix4
-rw-r--r--nixos/modules/services/networking/routedns.nix84
-rw-r--r--nixos/modules/services/networking/rpcbind.nix2
-rw-r--r--nixos/modules/services/networking/rxe.nix6
-rw-r--r--nixos/modules/services/networking/sabnzbd.nix10
-rw-r--r--nixos/modules/services/networking/seafile.nix50
-rw-r--r--nixos/modules/services/networking/searx.nix66
-rw-r--r--nixos/modules/services/networking/shadowsocks.nix28
-rw-r--r--nixos/modules/services/networking/shairport-sync.nix10
-rw-r--r--nixos/modules/services/networking/shellhub-agent.nix53
-rw-r--r--nixos/modules/services/networking/shorewall.nix19
-rw-r--r--nixos/modules/services/networking/shorewall6.nix19
-rw-r--r--nixos/modules/services/networking/shout.nix20
-rw-r--r--nixos/modules/services/networking/skydns.nix20
-rw-r--r--nixos/modules/services/networking/smartdns.nix10
-rw-r--r--nixos/modules/services/networking/smokeping.nix72
-rw-r--r--nixos/modules/services/networking/sniproxy.nix8
-rw-r--r--nixos/modules/services/networking/snowflake-proxy.nix12
-rw-r--r--nixos/modules/services/networking/softether.nix24
-rw-r--r--nixos/modules/services/networking/soju.nix38
-rw-r--r--nixos/modules/services/networking/solanum.nix12
-rw-r--r--nixos/modules/services/networking/spacecookie.nix32
-rw-r--r--nixos/modules/services/networking/spiped.nix58
-rw-r--r--nixos/modules/services/networking/squid.nix12
-rw-r--r--nixos/modules/services/networking/ssh/lshd.nix26
-rw-r--r--nixos/modules/services/networking/ssh/sshd.nix120
-rw-r--r--nixos/modules/services/networking/sslh.nix16
-rw-r--r--nixos/modules/services/networking/strongswan-swanctl/module.nix8
-rw-r--r--nixos/modules/services/networking/strongswan-swanctl/param-constructors.nix17
-rw-r--r--nixos/modules/services/networking/strongswan-swanctl/swanctl-params.nix622
-rw-r--r--nixos/modules/services/networking/strongswan.nix26
-rw-r--r--nixos/modules/services/networking/stubby.nix36
-rw-r--r--nixos/modules/services/networking/stunnel.nix168
-rw-r--r--nixos/modules/services/networking/supplicant.nix62
-rw-r--r--nixos/modules/services/networking/supybot.nix16
-rw-r--r--nixos/modules/services/networking/syncplay.nix32
-rw-r--r--nixos/modules/services/networking/syncthing-relay.nix24
-rw-r--r--nixos/modules/services/networking/syncthing.nix196
-rw-r--r--nixos/modules/services/networking/tailscale.nix62
-rw-r--r--nixos/modules/services/networking/tayga.nix195
-rw-r--r--nixos/modules/services/networking/tcpcrypt.nix2
-rw-r--r--nixos/modules/services/networking/teamspeak3.nix23
-rw-r--r--nixos/modules/services/networking/tedicross.nix12
-rw-r--r--nixos/modules/services/networking/teleport.nix26
-rw-r--r--nixos/modules/services/networking/tetrd.nix2
-rw-r--r--nixos/modules/services/networking/tftpd.nix4
-rw-r--r--nixos/modules/services/networking/thelounge.nix24
-rw-r--r--nixos/modules/services/networking/tinc.nix64
-rw-r--r--nixos/modules/services/networking/tinydns.nix6
-rw-r--r--nixos/modules/services/networking/tmate-ssh-server.nix122
-rw-r--r--nixos/modules/services/networking/tox-bootstrapd.nix14
-rw-r--r--nixos/modules/services/networking/tox-node.nix18
-rw-r--r--nixos/modules/services/networking/toxvpn.nix10
-rw-r--r--nixos/modules/services/networking/trickster.nix38
-rw-r--r--nixos/modules/services/networking/tvheadend.nix6
-rw-r--r--nixos/modules/services/networking/ucarp.nix36
-rw-r--r--nixos/modules/services/networking/unbound.nix31
-rw-r--r--nixos/modules/services/networking/unifi.nix20
-rw-r--r--nixos/modules/services/networking/uptermd.nix109
-rw-r--r--nixos/modules/services/networking/v2ray.nix30
-rw-r--r--nixos/modules/services/networking/vdirsyncer.nix214
-rw-r--r--nixos/modules/services/networking/vsftpd.nix65
-rw-r--r--nixos/modules/services/networking/wasabibackend.nix26
-rw-r--r--nixos/modules/services/networking/websockify.nix8
-rw-r--r--nixos/modules/services/networking/wg-netmanager.nix2
-rw-r--r--nixos/modules/services/networking/wg-quick.nix90
-rw-r--r--nixos/modules/services/networking/wireguard.nix190
-rw-r--r--nixos/modules/services/networking/wpa_supplicant.nix139
-rw-r--r--nixos/modules/services/networking/x2goserver.nix12
-rw-r--r--nixos/modules/services/networking/xandikos.nix18
-rw-r--r--nixos/modules/services/networking/xinetd.nix28
-rw-r--r--nixos/modules/services/networking/xl2tpd.nix18
-rw-r--r--nixos/modules/services/networking/xray.nix96
-rw-r--r--nixos/modules/services/networking/xrdp.nix20
-rw-r--r--nixos/modules/services/networking/yggdrasil.nix100
-rw-r--r--nixos/modules/services/networking/yggdrasil.xml4
-rw-r--r--nixos/modules/services/networking/zerobin.nix14
-rw-r--r--nixos/modules/services/networking/zeronet.nix29
-rw-r--r--nixos/modules/services/networking/zerotierone.nix10
-rw-r--r--nixos/modules/services/networking/znc/default.nix63
-rw-r--r--nixos/modules/services/networking/znc/options.nix55
-rw-r--r--nixos/modules/services/printing/cupsd.nix60
-rw-r--r--nixos/modules/services/scheduling/atd.nix12
-rw-r--r--nixos/modules/services/scheduling/cron.nix10
-rw-r--r--nixos/modules/services/scheduling/fcron.nix14
-rw-r--r--nixos/modules/services/search/elasticsearch-curator.nix10
-rw-r--r--nixos/modules/services/search/elasticsearch.nix28
-rw-r--r--nixos/modules/services/search/hound.nix17
-rw-r--r--nixos/modules/services/search/kibana.nix50
-rw-r--r--nixos/modules/services/search/meilisearch.nix20
-rw-r--r--nixos/modules/services/search/solr.nix16
-rw-r--r--nixos/modules/services/security/aesmd.nix22
-rw-r--r--nixos/modules/services/security/certmgr.nix36
-rw-r--r--nixos/modules/services/security/cfssl.nix58
-rw-r--r--nixos/modules/services/security/clamav.nix16
-rw-r--r--nixos/modules/services/security/endlessh-go.nix138
-rw-r--r--nixos/modules/services/security/endlessh.nix99
-rw-r--r--nixos/modules/services/security/fail2ban.nix63
-rw-r--r--nixos/modules/services/security/fprintd.nix8
-rw-r--r--nixos/modules/services/security/haka.nix22
-rw-r--r--nixos/modules/services/security/haveged.nix6
-rw-r--r--nixos/modules/services/security/hockeypuck.nix14
-rw-r--r--nixos/modules/services/security/hologram-agent.nix6
-rw-r--r--nixos/modules/services/security/hologram-server.nix30
-rw-r--r--nixos/modules/services/security/infnoise.nix60
-rw-r--r--nixos/modules/services/security/kanidm.nix355
-rw-r--r--nixos/modules/services/security/munge.nix4
-rw-r--r--nixos/modules/services/security/nginx-sso.nix8
-rw-r--r--nixos/modules/services/security/oauth2_proxy.nix119
-rw-r--r--nixos/modules/services/security/oauth2_proxy_nginx.nix4
-rw-r--r--nixos/modules/services/security/opensnitch.nix83
-rw-r--r--nixos/modules/services/security/pass-secret-service.nix27
-rw-r--r--nixos/modules/services/security/physlock.nix32
-rw-r--r--nixos/modules/services/security/privacyidea.nix207
-rw-r--r--nixos/modules/services/security/shibboleth-sp.nix10
-rw-r--r--nixos/modules/services/security/sks.nix16
-rw-r--r--nixos/modules/services/security/sshguard.nix18
-rw-r--r--nixos/modules/services/security/sslmate-agent.nix32
-rw-r--r--nixos/modules/services/security/step-ca.nix60
-rw-r--r--nixos/modules/services/security/tor.nix341
-rw-r--r--nixos/modules/services/security/torify.nix20
-rw-r--r--nixos/modules/services/security/torsocks.nix22
-rw-r--r--nixos/modules/services/security/usbguard.nix32
-rw-r--r--nixos/modules/services/security/vault.nix77
-rw-r--r--nixos/modules/services/security/vaultwarden/default.nix108
-rw-r--r--nixos/modules/services/security/yubikey-agent.nix4
-rw-r--r--nixos/modules/services/system/automatic-timezoned.nix92
-rw-r--r--nixos/modules/services/system/cachix-agent/default.nix38
-rw-r--r--nixos/modules/services/system/cachix-watch-store.nix87
-rw-r--r--nixos/modules/services/system/cloud-init.nix13
-rw-r--r--nixos/modules/services/system/dbus.nix196
-rw-r--r--nixos/modules/services/system/earlyoom.nix48
-rw-r--r--nixos/modules/services/system/kerberos/default.nix12
-rw-r--r--nixos/modules/services/system/localtime.nix49
-rw-r--r--nixos/modules/services/system/localtimed.nix66
-rw-r--r--nixos/modules/services/system/nscd.nix108
-rw-r--r--nixos/modules/services/system/saslauthd.nix8
-rw-r--r--nixos/modules/services/system/self-deploy.nix20
-rw-r--r--nixos/modules/services/system/systembus-notify.nix4
-rw-r--r--nixos/modules/services/system/uptimed.nix4
-rw-r--r--nixos/modules/services/torrent/deluge.nix56
-rw-r--r--nixos/modules/services/torrent/flexget.nix12
-rw-r--r--nixos/modules/services/torrent/magnetico.nix54
-rw-r--r--nixos/modules/services/torrent/opentracker.nix6
-rw-r--r--nixos/modules/services/torrent/peerflix.nix6
-rw-r--r--nixos/modules/services/torrent/rtorrent.nix24
-rw-r--r--nixos/modules/services/torrent/transmission.nix134
-rw-r--r--nixos/modules/services/tracing/tempo.nix68
-rw-r--r--nixos/modules/services/ttys/getty.nix23
-rw-r--r--nixos/modules/services/ttys/gpm.nix4
-rw-r--r--nixos/modules/services/ttys/kmscon.nix39
-rw-r--r--nixos/modules/services/video/epgstation/default.nix50
-rw-r--r--nixos/modules/services/video/mirakurun.nix39
-rw-r--r--nixos/modules/services/video/replay-sorcery.nix10
-rw-r--r--nixos/modules/services/video/rtsp-simple-server.nix8
-rw-r--r--nixos/modules/services/video/unifi-video.nix168
-rw-r--r--nixos/modules/services/wayland/cage.nix10
-rw-r--r--nixos/modules/services/web-apps/alps.nix132
-rw-r--r--nixos/modules/services/web-apps/atlassian/confluence.nix99
-rw-r--r--nixos/modules/services/web-apps/atlassian/crowd.nix67
-rw-r--r--nixos/modules/services/web-apps/atlassian/jira.nix89
-rw-r--r--nixos/modules/services/web-apps/baget.nix8
-rw-r--r--nixos/modules/services/web-apps/bookstack.nix83
-rw-r--r--nixos/modules/services/web-apps/calibre-web.nix28
-rw-r--r--nixos/modules/services/web-apps/changedetection-io.nix220
-rw-r--r--nixos/modules/services/web-apps/code-server.nix30
-rw-r--r--nixos/modules/services/web-apps/convos.nix12
-rw-r--r--nixos/modules/services/web-apps/cryptpad.nix54
-rw-r--r--nixos/modules/services/web-apps/dex.nix36
-rw-r--r--nixos/modules/services/web-apps/discourse.nix176
-rw-r--r--nixos/modules/services/web-apps/documize.nix65
-rw-r--r--nixos/modules/services/web-apps/dokuwiki.nix103
-rw-r--r--nixos/modules/services/web-apps/dolibarr.nix320
-rw-r--r--nixos/modules/services/web-apps/engelsystem.nix12
-rw-r--r--nixos/modules/services/web-apps/ethercalc.nix10
-rw-r--r--nixos/modules/services/web-apps/fluidd.nix8
-rw-r--r--nixos/modules/services/web-apps/freshrss.nix282
-rw-r--r--nixos/modules/services/web-apps/galene.nix57
-rw-r--r--nixos/modules/services/web-apps/gerrit.nix32
-rw-r--r--nixos/modules/services/web-apps/gotify-server.nix8
-rw-r--r--nixos/modules/services/web-apps/grocy.nix26
-rw-r--r--nixos/modules/services/web-apps/healthchecks.nix249
-rw-r--r--nixos/modules/services/web-apps/hedgedoc.nix370
-rw-r--r--nixos/modules/services/web-apps/hledger-web.nix24
-rw-r--r--nixos/modules/services/web-apps/icingaweb2/icingaweb2.nix32
-rw-r--r--nixos/modules/services/web-apps/icingaweb2/module-monitoring.nix38
-rw-r--r--nixos/modules/services/web-apps/ihatemoney/default.nix30
-rw-r--r--nixos/modules/services/web-apps/invidious.nix38
-rw-r--r--nixos/modules/services/web-apps/invoiceplane.nix107
-rw-r--r--nixos/modules/services/web-apps/isso.nix32
-rw-r--r--nixos/modules/services/web-apps/jirafeau.nix30
-rw-r--r--nixos/modules/services/web-apps/jitsi-meet.nix78
-rw-r--r--nixos/modules/services/web-apps/keycloak.nix924
-rw-r--r--nixos/modules/services/web-apps/keycloak.xml142
-rw-r--r--nixos/modules/services/web-apps/komga.nix99
-rw-r--r--nixos/modules/services/web-apps/lemmy.md3
-rw-r--r--nixos/modules/services/web-apps/lemmy.nix84
-rw-r--r--nixos/modules/services/web-apps/lemmy.xml7
-rw-r--r--nixos/modules/services/web-apps/limesurvey.nix34
-rw-r--r--nixos/modules/services/web-apps/mastodon.nix235
-rw-r--r--nixos/modules/services/web-apps/matomo.nix28
-rw-r--r--nixos/modules/services/web-apps/mattermost.nix38
-rw-r--r--nixos/modules/services/web-apps/mediawiki.nix59
-rw-r--r--nixos/modules/services/web-apps/miniflux.nix10
-rw-r--r--nixos/modules/services/web-apps/moodle.nix45
-rw-r--r--nixos/modules/services/web-apps/netbox.nix270
-rw-r--r--nixos/modules/services/web-apps/nextcloud.nix423
-rw-r--r--nixos/modules/services/web-apps/nextcloud.xml16
-rw-r--r--nixos/modules/services/web-apps/nexus.nix16
-rw-r--r--nixos/modules/services/web-apps/nifi.nix318
-rw-r--r--nixos/modules/services/web-apps/node-red.nix25
-rw-r--r--nixos/modules/services/web-apps/onlyoffice.nix291
-rw-r--r--nixos/modules/services/web-apps/openwebrx.nix8
-rw-r--r--nixos/modules/services/web-apps/outline.nix788
-rw-r--r--nixos/modules/services/web-apps/peertube.nix388
-rw-r--r--nixos/modules/services/web-apps/pgpkeyserver-lite.nix18
-rw-r--r--nixos/modules/services/web-apps/phylactery.nix51
-rw-r--r--nixos/modules/services/web-apps/pict-rs.nix8
-rw-r--r--nixos/modules/services/web-apps/plantuml-server.nix28
-rw-r--r--nixos/modules/services/web-apps/plausible.nix68
-rw-r--r--nixos/modules/services/web-apps/powerdns-admin.nix12
-rw-r--r--nixos/modules/services/web-apps/prosody-filer.nix8
-rw-r--r--nixos/modules/services/web-apps/restya-board.nix52
-rw-r--r--nixos/modules/services/web-apps/rss-bridge.nix18
-rw-r--r--nixos/modules/services/web-apps/selfoss.nix20
-rw-r--r--nixos/modules/services/web-apps/shiori.nix10
-rw-r--r--nixos/modules/services/web-apps/snipe-it.nix509
-rw-r--r--nixos/modules/services/web-apps/sogo.nix14
-rw-r--r--nixos/modules/services/web-apps/timetagger.nix80
-rw-r--r--nixos/modules/services/web-apps/trilium.nix29
-rw-r--r--nixos/modules/services/web-apps/tt-rss.nix91
-rw-r--r--nixos/modules/services/web-apps/vikunja.nix36
-rw-r--r--nixos/modules/services/web-apps/virtlyst.nix73
-rw-r--r--nixos/modules/services/web-apps/whitebophir.nix8
-rw-r--r--nixos/modules/services/web-apps/wiki-js.nix49
-rw-r--r--nixos/modules/services/web-apps/wordpress.nix103
-rw-r--r--nixos/modules/services/web-apps/writefreely.nix485
-rw-r--r--nixos/modules/services/web-apps/youtrack.nix24
-rw-r--r--nixos/modules/services/web-apps/zabbix.nix38
-rw-r--r--nixos/modules/services/web-servers/agate.nix18
-rw-r--r--nixos/modules/services/web-servers/apache-httpd/default.nix109
-rw-r--r--nixos/modules/services/web-servers/apache-httpd/location-options.nix16
-rw-r--r--nixos/modules/services/web-servers/apache-httpd/vhost-options.nix108
-rw-r--r--nixos/modules/services/web-servers/caddy/default.nix145
-rw-r--r--nixos/modules/services/web-servers/caddy/vhost-options.nix22
-rw-r--r--nixos/modules/services/web-servers/darkhttpd.nix12
-rw-r--r--nixos/modules/services/web-servers/fcgiwrap.nix12
-rw-r--r--nixos/modules/services/web-servers/garage.nix91
-rw-r--r--nixos/modules/services/web-servers/hitch/default.nix20
-rw-r--r--nixos/modules/services/web-servers/hydron.nix25
-rw-r--r--nixos/modules/services/web-servers/jboss/default.nix16
-rw-r--r--nixos/modules/services/web-servers/keter/bundle.nix40
-rw-r--r--nixos/modules/services/web-servers/keter/default.nix162
-rw-r--r--nixos/modules/services/web-servers/lighttpd/cgit.nix6
-rw-r--r--nixos/modules/services/web-servers/lighttpd/collectd.nix8
-rw-r--r--nixos/modules/services/web-servers/lighttpd/default.nix26
-rw-r--r--nixos/modules/services/web-servers/lighttpd/gitweb.nix2
-rw-r--r--nixos/modules/services/web-servers/merecat.nix55
-rw-r--r--nixos/modules/services/web-servers/mighttpd2.nix8
-rw-r--r--nixos/modules/services/web-servers/minio.nix28
-rw-r--r--nixos/modules/services/web-servers/molly-brown.nix20
-rw-r--r--nixos/modules/services/web-servers/nginx/default.nix296
-rw-r--r--nixos/modules/services/web-servers/nginx/gitweb.nix12
-rw-r--r--nixos/modules/services/web-servers/nginx/location-options.nix37
-rw-r--r--nixos/modules/services/web-servers/nginx/vhost-options.nix117
-rw-r--r--nixos/modules/services/web-servers/phpfpm/default.nix55
-rw-r--r--nixos/modules/services/web-servers/pomerium.nix14
-rw-r--r--nixos/modules/services/web-servers/tomcat.nix50
-rw-r--r--nixos/modules/services/web-servers/traefik.nix22
-rw-r--r--nixos/modules/services/web-servers/trafficserver/default.nix94
-rw-r--r--nixos/modules/services/web-servers/ttyd.nix42
-rw-r--r--nixos/modules/services/web-servers/unit/default.nix14
-rw-r--r--nixos/modules/services/web-servers/uwsgi.nix53
-rw-r--r--nixos/modules/services/web-servers/varnish/default.nix26
-rw-r--r--nixos/modules/services/web-servers/zope2.nix16
-rw-r--r--nixos/modules/services/x11/clight.nix20
-rw-r--r--nixos/modules/services/x11/colord.nix2
-rw-r--r--nixos/modules/services/x11/desktop-managers/cde.nix4
-rw-r--r--nixos/modules/services/x11/desktop-managers/cinnamon.nix76
-rw-r--r--nixos/modules/services/x11/desktop-managers/default.nix32
-rw-r--r--nixos/modules/services/x11/desktop-managers/enlightenment.nix7
-rw-r--r--nixos/modules/services/x11/desktop-managers/gnome.nix182
-rw-r--r--nixos/modules/services/x11/desktop-managers/kodi.nix4
-rw-r--r--nixos/modules/services/x11/desktop-managers/lumina.nix6
-rw-r--r--nixos/modules/services/x11/desktop-managers/lxqt.nix16
-rw-r--r--nixos/modules/services/x11/desktop-managers/mate.nix43
-rw-r--r--nixos/modules/services/x11/desktop-managers/none.nix49
-rw-r--r--nixos/modules/services/x11/desktop-managers/pantheon.nix93
-rw-r--r--nixos/modules/services/x11/desktop-managers/pantheon.xml6
-rw-r--r--nixos/modules/services/x11/desktop-managers/phosh.nix223
-rw-r--r--nixos/modules/services/x11/desktop-managers/plasma5.nix306
-rw-r--r--nixos/modules/services/x11/desktop-managers/retroarch.nix6
-rw-r--r--nixos/modules/services/x11/desktop-managers/surf-display.nix20
-rw-r--r--nixos/modules/services/x11/desktop-managers/xfce.nix40
-rw-r--r--nixos/modules/services/x11/desktop-managers/xterm.nix2
-rw-r--r--nixos/modules/services/x11/display-managers/default.nix56
-rw-r--r--nixos/modules/services/x11/display-managers/gdm.nix25
-rw-r--r--nixos/modules/services/x11/display-managers/lightdm-greeters/enso-os.nix20
-rw-r--r--nixos/modules/services/x11/display-managers/lightdm-greeters/gtk.nix24
-rw-r--r--nixos/modules/services/x11/display-managers/lightdm-greeters/mini.nix8
-rw-r--r--nixos/modules/services/x11/display-managers/lightdm-greeters/mobile.nix26
-rw-r--r--nixos/modules/services/x11/display-managers/lightdm-greeters/pantheon.nix2
-rw-r--r--nixos/modules/services/x11/display-managers/lightdm-greeters/slick.nix118
-rw-r--r--nixos/modules/services/x11/display-managers/lightdm-greeters/tiny.nix10
-rw-r--r--nixos/modules/services/x11/display-managers/lightdm.nix21
-rw-r--r--nixos/modules/services/x11/display-managers/sddm.nix37
-rw-r--r--nixos/modules/services/x11/display-managers/startx.nix2
-rw-r--r--nixos/modules/services/x11/display-managers/sx.nix4
-rw-r--r--nixos/modules/services/x11/display-managers/xpra.nix19
-rw-r--r--nixos/modules/services/x11/extra-layouts.nix30
-rw-r--r--nixos/modules/services/x11/fractalart.nix6
-rw-r--r--nixos/modules/services/x11/gdk-pixbuf.nix31
-rw-r--r--nixos/modules/services/x11/hardware/cmt.nix6
-rw-r--r--nixos/modules/services/x11/hardware/digimend.nix2
-rw-r--r--nixos/modules/services/x11/hardware/libinput.nix70
-rw-r--r--nixos/modules/services/x11/hardware/synaptics.nix38
-rw-r--r--nixos/modules/services/x11/hardware/wacom.nix4
-rw-r--r--nixos/modules/services/x11/imwheel.nix10
-rw-r--r--nixos/modules/services/x11/picom.nix92
-rw-r--r--nixos/modules/services/x11/redshift.nix26
-rw-r--r--nixos/modules/services/x11/touchegg.nix4
-rw-r--r--nixos/modules/services/x11/unclutter-xfixes.nix10
-rw-r--r--nixos/modules/services/x11/unclutter.nix14
-rw-r--r--nixos/modules/services/x11/urserver.nix2
-rw-r--r--nixos/modules/services/x11/urxvtd.nix4
-rw-r--r--nixos/modules/services/x11/window-managers/2bwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/afterstep.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/awesome.nix10
-rw-r--r--nixos/modules/services/x11/window-managers/berry.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/bspwm.nix10
-rw-r--r--nixos/modules/services/x11/window-managers/clfswm.nix4
-rw-r--r--nixos/modules/services/x11/window-managers/cwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/default.nix13
-rw-r--r--nixos/modules/services/x11/window-managers/dwm.nix24
-rw-r--r--nixos/modules/services/x11/window-managers/e16.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/evilwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/exwm.nix10
-rw-r--r--nixos/modules/services/x11/window-managers/fluxbox.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/fvwm.nix41
-rw-r--r--nixos/modules/services/x11/window-managers/fvwm2.nix47
-rw-r--r--nixos/modules/services/x11/window-managers/fvwm3.nix35
-rw-r--r--nixos/modules/services/x11/window-managers/hackedbox.nix25
-rw-r--r--nixos/modules/services/x11/window-managers/herbstluftwm.nix6
-rw-r--r--nixos/modules/services/x11/window-managers/hypr.nix25
-rw-r--r--nixos/modules/services/x11/window-managers/i3.nix10
-rw-r--r--nixos/modules/services/x11/window-managers/icewm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/jwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/leftwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/lwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/metacity.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/mlvwm.nix4
-rw-r--r--nixos/modules/services/x11/window-managers/mwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/notion.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/openbox.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/oroborus.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/pekwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/qtile.nix15
-rw-r--r--nixos/modules/services/x11/window-managers/ratpoison.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/sawfish.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/smallwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/spectrwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/stumpwm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/tinywm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/twm.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/windowlab.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/windowmaker.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/wmderland.nix6
-rw-r--r--nixos/modules/services/x11/window-managers/wmii.nix2
-rw-r--r--nixos/modules/services/x11/window-managers/xmonad.nix69
-rw-r--r--nixos/modules/services/x11/window-managers/yeahwm.nix2
-rw-r--r--nixos/modules/services/x11/xautolock.nix30
-rw-r--r--nixos/modules/services/x11/xbanish.nix4
-rw-r--r--nixos/modules/services/x11/xfs.nix2
-rw-r--r--nixos/modules/services/x11/xserver.nix151
1134 files changed, 34570 insertions, 20295 deletions
diff --git a/nixos/modules/services/admin/meshcentral.nix b/nixos/modules/services/admin/meshcentral.nix
index 92762d2037c..22f31e95262 100644
--- a/nixos/modules/services/admin/meshcentral.nix
+++ b/nixos/modules/services/admin/meshcentral.nix
@@ -5,23 +5,21 @@ let
   configFile = configFormat.generate "meshcentral-config.json" cfg.settings;
 in with lib; {
   options.services.meshcentral = with types; {
-    enable = mkEnableOption "MeshCentral computer management server";
+    enable = mkEnableOption (lib.mdDoc "MeshCentral computer management server");
     package = mkOption {
-      description = "MeshCentral package to use. Replacing this may be necessary to add dependencies for extra functionality.";
+      description = lib.mdDoc "MeshCentral package to use. Replacing this may be necessary to add dependencies for extra functionality.";
       type = types.package;
       default = pkgs.meshcentral;
       defaultText = literalExpression "pkgs.meshcentral";
     };
     settings = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Settings for MeshCentral. Refer to upstream documentation for details:
 
-        <itemizedlist>
-          <listitem><para><link xlink:href="https://github.com/Ylianst/MeshCentral/blob/master/meshcentral-config-schema.json">JSON Schema definition</link></para></listitem>
-          <listitem><para><link xlink:href="https://github.com/Ylianst/MeshCentral/blob/master/sample-config.json">simple sample configuration</link></para></listitem>
-          <listitem><para><link xlink:href="https://github.com/Ylianst/MeshCentral/blob/master/sample-config-advanced.json">complex sample configuration</link></para></listitem>
-          <listitem><para><link xlink:href="https://www.meshcommander.com/meshcentral2">Old homepage) with documentation link</link></para></listitem>
-        </itemizedlist>
+        - [JSON Schema definition](https://github.com/Ylianst/MeshCentral/blob/master/meshcentral-config-schema.json)
+        - [simple sample configuration](https://github.com/Ylianst/MeshCentral/blob/master/sample-config.json)
+        - [complex sample configuration](https://github.com/Ylianst/MeshCentral/blob/master/sample-config-advanced.json)
+        - [Old homepage with documentation link](https://www.meshcommander.com/meshcentral2)
       '';
       type = types.submodule {
         freeformType = configFormat.type;
diff --git a/nixos/modules/services/admin/oxidized.nix b/nixos/modules/services/admin/oxidized.nix
index 49ea3ced76a..56f33031498 100644
--- a/nixos/modules/services/admin/oxidized.nix
+++ b/nixos/modules/services/admin/oxidized.nix
@@ -7,12 +7,12 @@ let
 in
 {
   options.services.oxidized = {
-    enable = mkEnableOption "the oxidized configuration backup service";
+    enable = mkEnableOption (lib.mdDoc "the oxidized configuration backup service");
 
     user = mkOption {
       type = types.str;
       default = "oxidized";
-      description = ''
+      description = lib.mdDoc ''
         User under which the oxidized service runs.
       '';
     };
@@ -20,7 +20,7 @@ in
     group = mkOption {
       type = types.str;
       default = "oxidized";
-      description = ''
+      description = lib.mdDoc ''
         Group under which the oxidized service runs.
       '';
     };
@@ -28,7 +28,7 @@ in
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/oxidized";
-      description = "State directory for the oxidized service.";
+      description = lib.mdDoc "State directory for the oxidized service.";
     };
 
     configFile = mkOption {
@@ -62,7 +62,7 @@ in
           # ... additional config
         ''';
       '';
-      description = ''
+      description = lib.mdDoc ''
         Path to the oxidized configuration file.
       '';
     };
@@ -76,7 +76,7 @@ in
           # ... additional hosts
         '''
       '';
-      description = ''
+      description = lib.mdDoc ''
         Path to the file/database which contains the targets for oxidized.
       '';
     };
diff --git a/nixos/modules/services/admin/pgadmin.nix b/nixos/modules/services/admin/pgadmin.nix
index 80b68145410..390c80d1a2d 100644
--- a/nixos/modules/services/admin/pgadmin.nix
+++ b/nixos/modules/services/admin/pgadmin.nix
@@ -28,36 +28,85 @@ let
 in
 {
   options.services.pgadmin = {
-    enable = mkEnableOption "PostgreSQL Admin 4";
+    enable = mkEnableOption (lib.mdDoc "PostgreSQL Admin 4");
 
     port = mkOption {
-      description = "Port for pgadmin4 to run on";
+      description = lib.mdDoc "Port for pgadmin4 to run on";
       type = types.port;
       default = 5050;
     };
 
     initialEmail = mkOption {
-      description = "Initial email for the pgAdmin account.";
+      description = lib.mdDoc "Initial email for the pgAdmin account";
       type = types.str;
     };
 
     initialPasswordFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Initial password file for the pgAdmin account.
-        NOTE: Should be string not a store path, to prevent the password from being world readable.
+        NOTE: Should be string not a store path, to prevent the password from being world readable
       '';
       type = types.path;
     };
 
-    openFirewall = mkEnableOption "firewall passthrough for pgadmin4";
+    emailServer = {
+      enable = mkOption {
+        description = lib.mdDoc ''
+          Enable SMTP email server. This is necessary, if you want to use password recovery or change your own password
+        '';
+        type = types.bool;
+        default = false;
+      };
+      address = mkOption {
+        description = lib.mdDoc "SMTP server for email delivery";
+        type = types.str;
+        default = "localhost";
+      };
+      port = mkOption {
+        description = lib.mdDoc "SMTP server port for email delivery";
+        type = types.port;
+        default = 25;
+      };
+      useSSL = mkOption {
+        description = lib.mdDoc "SMTP server should use SSL";
+        type = types.bool;
+        default = false;
+      };
+      useTLS = mkOption {
+        description = lib.mdDoc "SMTP server should use TLS";
+        type = types.bool;
+        default = false;
+      };
+      username = mkOption {
+        description = lib.mdDoc "SMTP server username for email delivery";
+        type = types.nullOr types.str;
+        default = null;
+      };
+      sender = mkOption {
+        description = lib.mdDoc ''
+          SMTP server sender email for email delivery. Some servers require this to be a valid email address from that server
+        '';
+        type = types.str;
+        example = "noreply@example.com";
+      };
+      passwordFile = mkOption {
+        description = lib.mdDoc ''
+          Password for SMTP email account.
+          NOTE: Should be string not a store path, to prevent the password from being world readable
+        '';
+        type = types.path;
+      };
+    };
+
+    openFirewall = mkEnableOption (lib.mdDoc "firewall passthrough for pgadmin4");
 
     settings = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Settings for pgadmin4.
-        <link xlink:href="https://www.pgadmin.org/docs/pgadmin4/development/config_py.html">Documentation</link>.
+        [Documentation](https://www.pgadmin.org/docs/pgadmin4/development/config_py.html)
       '';
       type = pyType;
-      default= {};
+      default = { };
     };
   };
 
@@ -69,6 +118,13 @@ in
       SERVER_MODE = true;
     } // (optionalAttrs cfg.openFirewall {
       DEFAULT_SERVER = mkDefault "::";
+    }) // (optionalAttrs cfg.emailServer.enable {
+      MAIL_SERVER = cfg.emailServer.address;
+      MAIL_PORT = cfg.emailServer.port;
+      MAIL_USE_SSL = cfg.emailServer.useSSL;
+      MAIL_USE_TLS = cfg.emailServer.useTLS;
+      MAIL_USERNAME = cfg.emailServer.username;
+      SECURITY_EMAIL_SENDER = cfg.emailServer.sender;
     });
 
     systemd.services.pgadmin = {
@@ -115,10 +171,14 @@ in
       group = "pgadmin";
     };
 
-    users.groups.pgadmin = {};
+    users.groups.pgadmin = { };
 
     environment.etc."pgadmin/config_system.py" = {
-      text = formatPy cfg.settings;
+      text = lib.optionalString cfg.emailServer.enable ''
+        with open("${cfg.emailServer.passwordFile}") as f:
+          pw = f.read()
+        MAIL_PASSWORD = pw
+      '' + formatPy cfg.settings;
       mode = "0600";
       user = "pgadmin";
       group = "pgadmin";
diff --git a/nixos/modules/services/admin/salt/master.nix b/nixos/modules/services/admin/salt/master.nix
index a3069c81c19..4346022970e 100644
--- a/nixos/modules/services/admin/salt/master.nix
+++ b/nixos/modules/services/admin/salt/master.nix
@@ -20,11 +20,11 @@ in
 {
   options = {
     services.salt.master = {
-      enable = mkEnableOption "Salt master service";
+      enable = mkEnableOption (lib.mdDoc "Salt master service");
       configuration = mkOption {
         type = types.attrs;
         default = {};
-        description = "Salt master configuration as Nix attribute set.";
+        description = lib.mdDoc "Salt master configuration as Nix attribute set.";
       };
     };
   };
diff --git a/nixos/modules/services/admin/salt/minion.nix b/nixos/modules/services/admin/salt/minion.nix
index ac124c570d8..3ae02a4cc5d 100644
--- a/nixos/modules/services/admin/salt/minion.nix
+++ b/nixos/modules/services/admin/salt/minion.nix
@@ -21,13 +21,13 @@ in
 {
   options = {
     services.salt.minion = {
-      enable = mkEnableOption "Salt minion service";
+      enable = mkEnableOption (lib.mdDoc "Salt minion service");
       configuration = mkOption {
         type = types.attrs;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Salt minion configuration as Nix attribute set.
-          See <link xlink:href="https://docs.saltstack.com/en/latest/ref/configuration/minion.html"/>
+          See <https://docs.saltstack.com/en/latest/ref/configuration/minion.html>
           for details.
         '';
       };
diff --git a/nixos/modules/services/amqp/activemq/default.nix b/nixos/modules/services/amqp/activemq/default.nix
index 47669b05aa9..bd37fe3b557 100644
--- a/nixos/modules/services/amqp/activemq/default.nix
+++ b/nixos/modules/services/amqp/activemq/default.nix
@@ -27,7 +27,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the Apache ActiveMQ message broker service.
         '';
       };
@@ -35,7 +35,7 @@ in {
         default = "${activemq}/conf";
         defaultText = literalExpression ''"''${pkgs.activemq}/conf"'';
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The base directory for ActiveMQ's configuration.
           By default, this directory is searched for a file named activemq.xml,
           which should contain the configuration for the broker service.
@@ -44,21 +44,21 @@ in {
       configurationURI = mkOption {
         type = types.str;
         default = "xbean:activemq.xml";
-        description = ''
+        description = lib.mdDoc ''
           The URI that is passed along to the BrokerFactory to
           set up the configuration of the ActiveMQ broker service.
           You should not need to change this. For custom configuration,
-          set the <literal>configurationDir</literal> instead, and create
+          set the `configurationDir` instead, and create
           an activemq.xml configuration file in it.
         '';
       };
       baseDir = mkOption {
         type = types.str;
         default = "/var/activemq";
-        description = ''
+        description = lib.mdDoc ''
           The base directory where ActiveMQ stores its persistent data and logs.
           This will be overridden if you set "activemq.base" and "activemq.data"
-          in the <literal>javaProperties</literal> option. You can also override
+          in the `javaProperties` option. You can also override
           this in activemq.xml.
         '';
       };
@@ -76,7 +76,7 @@ in {
           "activemq.conf" = "${cfg.configurationDir}";
           "activemq.home" = "${activemq}";
         } // attrs;
-        description = ''
+        description = lib.mdDoc ''
           Specifies Java properties that are sent to the ActiveMQ
           broker service with the "-D" option. You can set properties
           here to change the behaviour and configuration of the broker.
@@ -88,7 +88,7 @@ in {
         type = types.separatedString " ";
         default = "";
         example = "-Xmx2G -Xms2G -XX:MaxPermSize=512M";
-        description = ''
+        description = lib.mdDoc ''
           Add extra options here that you want to be sent to the
           Java runtime when the broker service is started.
         '';
diff --git a/nixos/modules/services/amqp/rabbitmq.nix b/nixos/modules/services/amqp/rabbitmq.nix
index 3255942fe43..11dabf0b51c 100644
--- a/nixos/modules/services/amqp/rabbitmq.nix
+++ b/nixos/modules/services/amqp/rabbitmq.nix
@@ -20,7 +20,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the RabbitMQ server, an Advanced Message
           Queuing Protocol (AMQP) broker.
         '';
@@ -30,7 +30,7 @@ in
         default = pkgs.rabbitmq-server;
         type = types.package;
         defaultText = literalExpression "pkgs.rabbitmq-server";
-        description = ''
+        description = lib.mdDoc ''
           Which rabbitmq package to use.
         '';
       };
@@ -38,12 +38,12 @@ in
       listenAddress = mkOption {
         default = "127.0.0.1";
         example = "";
-        description = ''
+        description = lib.mdDoc ''
           IP address on which RabbitMQ will listen for AMQP
           connections.  Set to the empty string to listen on all
           interfaces.  Note that RabbitMQ creates a user named
-          <literal>guest</literal> with password
-          <literal>guest</literal> by default, so you should delete
+          `guest` with password
+          `guest` by default, so you should delete
           this user if you intend to allow external access.
 
           Together with 'port' setting it's mostly an alias for
@@ -55,7 +55,7 @@ in
 
       port = mkOption {
         default = 5672;
-        description = ''
+        description = lib.mdDoc ''
           Port on which RabbitMQ will listen for AMQP connections.
         '';
         type = types.port;
@@ -64,7 +64,7 @@ in
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/rabbitmq";
-        description = ''
+        description = lib.mdDoc ''
           Data directory for rabbitmq.
         '';
       };
@@ -72,7 +72,7 @@ in
       cookie = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Erlang cookie is a string of arbitrary length which must
           be the same for several nodes to be allowed to communicate.
           Leave empty to generate automatically.
@@ -88,15 +88,15 @@ in
             "auth_backends.1.authz" = "rabbit_auth_backend_internal";
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Configuration options in RabbitMQ's new config file format,
           which is a simple key-value format that can not express nested
-          data structures. This is known as the <literal>rabbitmq.conf</literal> file,
+          data structures. This is known as the `rabbitmq.conf` file,
           although outside NixOS that filename may have Erlang syntax, particularly
           prior to RabbitMQ 3.7.0.
 
           If you do need to express nested data structures, you can use
-          <literal>config</literal> option. Configuration from <literal>config</literal>
+          `config` option. Configuration from `config`
           will be merged into these options by RabbitMQ at runtime to
           form the final configuration.
 
@@ -108,14 +108,14 @@ in
       config = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Verbatim advanced configuration file contents using the Erlang syntax.
-          This is also known as the <literal>advanced.config</literal> file or the old config format.
+          This is also known as the `advanced.config` file or the old config format.
 
-          <literal>configItems</literal> is preferred whenever possible. However, nested
-          data structures can only be expressed properly using the <literal>config</literal> option.
+          `configItems` is preferred whenever possible. However, nested
+          data structures can only be expressed properly using the `config` option.
 
-          The contents of this option will be merged into the <literal>configItems</literal>
+          The contents of this option will be merged into the `configItems`
           by RabbitMQ at runtime to form the final configuration.
 
           See the second table on https://www.rabbitmq.com/configure.html#config-items
@@ -126,21 +126,21 @@ in
       plugins = mkOption {
         default = [ ];
         type = types.listOf types.str;
-        description = "The names of plugins to enable";
+        description = lib.mdDoc "The names of plugins to enable";
       };
 
       pluginDirs = mkOption {
         default = [ ];
         type = types.listOf types.path;
-        description = "The list of directories containing external plugins";
+        description = lib.mdDoc "The list of directories containing external plugins";
       };
 
       managementPlugin = {
-        enable = mkEnableOption "the management plugin";
+        enable = mkEnableOption (lib.mdDoc "the management plugin");
         port = mkOption {
           default = 15672;
           type = types.port;
-          description = ''
+          description = lib.mdDoc ''
             On which port to run the management plugin
           '';
         };
diff --git a/nixos/modules/services/audio/alsa.nix b/nixos/modules/services/audio/alsa.nix
index 0d743ed31da..155780199fd 100644
--- a/nixos/modules/services/audio/alsa.nix
+++ b/nixos/modules/services/audio/alsa.nix
@@ -25,7 +25,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable ALSA sound.
         '';
       };
@@ -33,7 +33,7 @@ in
       enableOSSEmulation = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable ALSA OSS emulation (with certain cards sound mixing may not work!).
         '';
       };
@@ -44,7 +44,7 @@ in
         example = ''
           defaults.pcm.!card 3
         '';
-        description = ''
+        description = lib.mdDoc ''
           Set addition configuration for system-wide alsa.
         '';
       };
@@ -54,7 +54,7 @@ in
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable volume and capture control with keyboard media keys.
 
             You want to leave this disabled if you run a desktop environment
@@ -62,7 +62,7 @@ in
             You might want to enable this if you run a minimalistic desktop
             environment or work from bare linux ttys/framebuffers.
 
-            Enabling this will turn on <option>services.actkbd</option>.
+            Enabling this will turn on {option}`services.actkbd`.
           '';
         };
 
@@ -70,7 +70,7 @@ in
           type = types.str;
           default = "1";
           example = "1%";
-          description = ''
+          description = lib.mdDoc ''
             The value by which to increment/decrement volume on media keys.
 
             See amixer(1) for allowed values.
diff --git a/nixos/modules/services/audio/botamusique.nix b/nixos/modules/services/audio/botamusique.nix
index f4fa0ead4f0..4cd900f945c 100644
--- a/nixos/modules/services/audio/botamusique.nix
+++ b/nixos/modules/services/audio/botamusique.nix
@@ -12,13 +12,13 @@ in
   meta.maintainers = with lib.maintainers; [ hexa ];
 
   options.services.botamusique = {
-    enable = mkEnableOption "botamusique, a bot to play audio streams on mumble";
+    enable = mkEnableOption (lib.mdDoc "botamusique, a bot to play audio streams on mumble");
 
     package = mkOption {
       type = types.package;
       default = pkgs.botamusique;
       defaultText = literalExpression "pkgs.botamusique";
-      description = "The botamusique package to use.";
+      description = lib.mdDoc "The botamusique package to use.";
     };
 
     settings = mkOption {
@@ -29,32 +29,32 @@ in
             type = types.str;
             default = "localhost";
             example = "mumble.example.com";
-            description = "Hostname of the mumble server to connect to.";
+            description = lib.mdDoc "Hostname of the mumble server to connect to.";
           };
 
           server.port = mkOption {
             type = types.port;
             default = 64738;
-            description = "Port of the mumble server to connect to.";
+            description = lib.mdDoc "Port of the mumble server to connect to.";
           };
 
           bot.username = mkOption {
             type = types.str;
             default = "botamusique";
-            description = "Name the bot should appear with.";
+            description = lib.mdDoc "Name the bot should appear with.";
           };
 
           bot.comment = mkOption {
             type = types.str;
             default = "Hi, I'm here to play radio, local music or youtube/soundcloud music. Have fun!";
-            description = "Comment displayed for the bot.";
+            description = lib.mdDoc "Comment displayed for the bot.";
           };
         };
       };
       default = {};
-      description = ''
-        Your <filename>configuration.ini</filename> as a Nix attribute set. Look up
-        possible options in the <link xlink:href="https://github.com/azlux/botamusique/blob/master/configuration.example.ini">configuration.example.ini</link>.
+      description = lib.mdDoc ''
+        Your {file}`configuration.ini` as a Nix attribute set. Look up
+        possible options in the [configuration.example.ini](https://github.com/azlux/botamusique/blob/master/configuration.example.ini).
       '';
     };
   };
diff --git a/nixos/modules/services/audio/hqplayerd.nix b/nixos/modules/services/audio/hqplayerd.nix
index 416d12ce217..eff1549380c 100644
--- a/nixos/modules/services/audio/hqplayerd.nix
+++ b/nixos/modules/services/audio/hqplayerd.nix
@@ -12,13 +12,13 @@ in
 {
   options = {
     services.hqplayerd = {
-      enable = mkEnableOption "HQPlayer Embedded";
+      enable = mkEnableOption (lib.mdDoc "HQPlayer Embedded");
 
       auth = {
         username = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Username used for HQPlayer's WebUI.
 
             Without this you will need to manually create the credentials after
@@ -29,7 +29,7 @@ in
         password = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Password used for HQPlayer's WebUI.
 
             Without this you will need to manually create the credentials after
@@ -41,7 +41,7 @@ in
       licenseFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to the HQPlayer license key file.
 
           Without this, the service will run in trial mode and restart every 30
@@ -52,7 +52,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Opens ports needed for the WebUI and controller API.
         '';
       };
@@ -60,7 +60,7 @@ in
       config = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           HQplayer daemon configuration, written to /etc/hqplayer/hqplayerd.xml.
 
           Refer to share/doc/hqplayerd/readme.txt in the hqplayerd derivation for possible values.
@@ -133,7 +133,7 @@ in
     users.users = {
       hqplayer = {
         description = "hqplayer daemon user";
-        extraGroups = [ "audio" ];
+        extraGroups = [ "audio" "video" ];
         group = "hqplayer";
         uid = config.ids.uids.hqplayer;
       };
diff --git a/nixos/modules/services/audio/icecast.nix b/nixos/modules/services/audio/icecast.nix
index 5ee5bd745f9..759f1ab0db9 100644
--- a/nixos/modules/services/audio/icecast.nix
+++ b/nixos/modules/services/audio/icecast.nix
@@ -44,11 +44,11 @@ in {
 
     services.icecast = {
 
-      enable = mkEnableOption "Icecast server";
+      enable = mkEnableOption (lib.mdDoc "Icecast server");
 
       hostname = mkOption {
         type = types.nullOr types.str;
-        description = "DNS name or IP address that will be used for the stream directory lookups or possibily the playlist generation if a Host header is not provided.";
+        description = lib.mdDoc "DNS name or IP address that will be used for the stream directory lookups or possibily the playlist generation if a Host header is not provided.";
         default = config.networking.domain;
         defaultText = literalExpression "config.networking.domain";
       };
@@ -56,51 +56,51 @@ in {
       admin = {
         user = mkOption {
           type = types.str;
-          description = "Username used for all administration functions.";
+          description = lib.mdDoc "Username used for all administration functions.";
           default = "admin";
         };
 
         password = mkOption {
           type = types.str;
-          description = "Password used for all administration functions.";
+          description = lib.mdDoc "Password used for all administration functions.";
         };
       };
 
       logDir = mkOption {
         type = types.path;
-        description = "Base directory used for logging.";
+        description = lib.mdDoc "Base directory used for logging.";
         default = "/var/log/icecast";
       };
 
       listen = {
         port = mkOption {
           type = types.int;
-          description = "TCP port that will be used to accept client connections.";
+          description = lib.mdDoc "TCP port that will be used to accept client connections.";
           default = 8000;
         };
 
         address = mkOption {
           type = types.str;
-          description = "Address Icecast will listen on.";
+          description = lib.mdDoc "Address Icecast will listen on.";
           default = "::";
         };
       };
 
       user = mkOption {
         type = types.str;
-        description = "User privileges for the server.";
+        description = lib.mdDoc "User privileges for the server.";
         default = "nobody";
       };
 
       group = mkOption {
         type = types.str;
-        description = "Group privileges for the server.";
+        description = lib.mdDoc "Group privileges for the server.";
         default = "nogroup";
       };
 
       extraConf = mkOption {
         type = types.lines;
-        description = "icecast.xml content.";
+        description = lib.mdDoc "icecast.xml content.";
         default = "";
       };
 
diff --git a/nixos/modules/services/audio/jack.nix b/nixos/modules/services/audio/jack.nix
index 84fc9957b87..105e99cb2f5 100644
--- a/nixos/modules/services/audio/jack.nix
+++ b/nixos/modules/services/audio/jack.nix
@@ -16,9 +16,9 @@ in {
   options = {
     services.jack = {
       jackd = {
-        enable = mkEnableOption ''
+        enable = mkEnableOption (lib.mdDoc ''
           JACK Audio Connection Kit. You need to add yourself to the "jackaudio" group
-        '';
+        '');
 
         package = mkOption {
           # until jack1 promiscuous mode is fixed
@@ -27,7 +27,7 @@ in {
           default = pkgs.jack2;
           defaultText = literalExpression "pkgs.jack2";
           example = literalExpression "pkgs.jack1";
-          description = ''
+          description = lib.mdDoc ''
             The JACK package to use.
           '';
         };
@@ -40,14 +40,14 @@ in {
           example = literalExpression ''
             [ "-dalsa" "--device" "hw:1" ];
           '';
-          description = ''
+          description = lib.mdDoc ''
             Specifies startup command line arguments to pass to JACK server.
           '';
         };
 
         session = mkOption {
           type = types.lines;
-          description = ''
+          description = lib.mdDoc ''
             Commands to run after JACK is started.
           '';
         };
@@ -58,7 +58,7 @@ in {
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Route audio to/from generic ALSA-using applications using ALSA JACK PCM plugin.
           '';
         };
@@ -66,7 +66,7 @@ in {
         support32Bit = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether to support sound for 32-bit ALSA applications on 64-bit system.
           '';
         };
@@ -76,7 +76,7 @@ in {
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Create ALSA loopback device, instead of using PCM plugin. Has broader
             application support (things like Steam will work), but may need fine-tuning
             for concrete hardware.
@@ -86,14 +86,14 @@ in {
         index = mkOption {
           type = types.int;
           default = 10;
-          description = ''
+          description = lib.mdDoc ''
             Index of an ALSA loopback device.
           '';
         };
 
         config = mkOption {
           type = types.lines;
-          description = ''
+          description = lib.mdDoc ''
             ALSA config for loopback device.
           '';
         };
@@ -105,7 +105,7 @@ in {
             period_size 2048
             periods 2
           '';
-          description = ''
+          description = lib.mdDoc ''
             For music production software that still doesn't support JACK natively you
             would like to put buffer/period adjustments here
             to decrease dmix device latency.
@@ -114,7 +114,7 @@ in {
 
         session = mkOption {
           type = types.lines;
-          description = ''
+          description = lib.mdDoc ''
             Additional commands to run to setup loopback device.
           '';
         };
diff --git a/nixos/modules/services/audio/jmusicbot.nix b/nixos/modules/services/audio/jmusicbot.nix
index e0f8d461af0..c6392c679c0 100644
--- a/nixos/modules/services/audio/jmusicbot.nix
+++ b/nixos/modules/services/audio/jmusicbot.nix
@@ -7,18 +7,18 @@ in
 {
   options = {
     services.jmusicbot = {
-      enable = mkEnableOption "jmusicbot, a Discord music bot that's easy to set up and run yourself";
+      enable = mkEnableOption (lib.mdDoc "jmusicbot, a Discord music bot that's easy to set up and run yourself");
 
       package = mkOption {
         type = types.package;
         default = pkgs.jmusicbot;
         defaultText = literalExpression "pkgs.jmusicbot";
-        description = "JMusicBot package to use";
+        description = lib.mdDoc "JMusicBot package to use";
       };
 
       stateDir = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The directory where config.txt and serversettings.json is saved.
           If left as the default value this directory will automatically be created before JMusicBot starts, otherwise the sysadmin is responsible for ensuring the directory exists with appropriate ownership and permissions.
           Untouched by the value of this option config.txt needs to be placed manually into this directory.
diff --git a/nixos/modules/services/audio/liquidsoap.nix b/nixos/modules/services/audio/liquidsoap.nix
index ffeefc0f988..c313104c460 100644
--- a/nixos/modules/services/audio/liquidsoap.nix
+++ b/nixos/modules/services/audio/liquidsoap.nix
@@ -31,7 +31,7 @@ in
     services.liquidsoap.streams = mkOption {
 
       description =
-        ''
+        lib.mdDoc ''
           Set of Liquidsoap streams to start,
           one systemd service per stream.
         '';
diff --git a/nixos/modules/services/audio/mopidy.nix b/nixos/modules/services/audio/mopidy.nix
index 9937feadaeb..40e8679f53d 100644
--- a/nixos/modules/services/audio/mopidy.nix
+++ b/nixos/modules/services/audio/mopidy.nix
@@ -14,7 +14,7 @@ let
     name = "mopidy-with-extensions-${mopidy.version}";
     paths = closePropagation cfg.extensionPackages;
     pathsToLink = [ "/${mopidyPackages.python.sitePackages}" ];
-    buildInputs = [ makeWrapper ];
+    nativeBuildInputs = [ makeWrapper ];
     postBuild = ''
       makeWrapper ${mopidy}/bin/mopidy $out/bin/mopidy \
         --prefix PYTHONPATH : $out/${mopidyPackages.python.sitePackages}
@@ -26,12 +26,12 @@ in {
 
     services.mopidy = {
 
-      enable = mkEnableOption "Mopidy, a music player daemon";
+      enable = mkEnableOption (lib.mdDoc "Mopidy, a music player daemon");
 
       dataDir = mkOption {
         default = "/var/lib/mopidy";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The directory where Mopidy stores its state.
         '';
       };
@@ -40,7 +40,7 @@ in {
         default = [];
         type = types.listOf types.package;
         example = literalExpression "[ pkgs.mopidy-spotify ]";
-        description = ''
+        description = lib.mdDoc ''
           Mopidy extensions that should be loaded by the service.
         '';
       };
@@ -48,7 +48,7 @@ in {
       configuration = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           The configuration that Mopidy should use.
         '';
       };
@@ -56,7 +56,7 @@ in {
       extraConfigFiles = mkOption {
         default = [];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Extra config file read by Mopidy when the service starts.
           Later files in the list overrides earlier configuration.
         '';
diff --git a/nixos/modules/services/audio/mpd.nix b/nixos/modules/services/audio/mpd.nix
index 586b9ffa688..bbfccec98c4 100644
--- a/nixos/modules/services/audio/mpd.nix
+++ b/nixos/modules/services/audio/mpd.nix
@@ -56,7 +56,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable MPD, the music player daemon.
         '';
       };
@@ -64,8 +64,8 @@ in {
       startWhenNeeded = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          If set, <command>mpd</command> is socket-activated; that
+        description = lib.mdDoc ''
+          If set, {command}`mpd` is socket-activated; that
           is, instead of having it permanently running as a daemon,
           systemd will start it on the first incoming connection.
         '';
@@ -75,7 +75,7 @@ in {
         type = with types; either path (strMatching "(http|https|nfs|smb)://.+");
         default = "${cfg.dataDir}/music";
         defaultText = literalExpression ''"''${dataDir}/music"'';
-        description = ''
+        description = lib.mdDoc ''
           The directory or NFS/SMB network share where MPD reads music from. If left
           as the default value this directory will automatically be created before
           the MPD server starts, otherwise the sysadmin is responsible for ensuring
@@ -87,7 +87,7 @@ in {
         type = types.path;
         default = "${cfg.dataDir}/playlists";
         defaultText = literalExpression ''"''${dataDir}/playlists"'';
-        description = ''
+        description = lib.mdDoc ''
           The directory where MPD stores playlists. If left as the default value
           this directory will automatically be created before the MPD server starts,
           otherwise the sysadmin is responsible for ensuring the directory exists
@@ -98,18 +98,18 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra directives added to to the end of MPD's configuration file,
           mpd.conf. Basic configuration like file location and uid/gid
           is added automatically to the beginning of the file. For available
-          options see <literal>man 5 mpd.conf</literal>'.
+          options see `man 5 mpd.conf`'.
         '';
       };
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/${name}";
-        description = ''
+        description = lib.mdDoc ''
           The directory where MPD stores its state, tag cache, playlists etc. If
           left as the default value this directory will automatically be created
           before the MPD server starts, otherwise the sysadmin is responsible for
@@ -120,13 +120,13 @@ in {
       user = mkOption {
         type = types.str;
         default = name;
-        description = "User account under which MPD runs.";
+        description = lib.mdDoc "User account under which MPD runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = name;
-        description = "Group account under which MPD runs.";
+        description = lib.mdDoc "Group account under which MPD runs.";
       };
 
       network = {
@@ -135,16 +135,16 @@ in {
           type = types.str;
           default = "127.0.0.1";
           example = "any";
-          description = ''
+          description = lib.mdDoc ''
             The address for the daemon to listen on.
-            Use <literal>any</literal> to listen on all addresses.
+            Use `any` to listen on all addresses.
           '';
         };
 
         port = mkOption {
           type = types.int;
           default = 6600;
-          description = ''
+          description = lib.mdDoc ''
             This setting is the TCP port that is desired for the daemon to get assigned
             to.
           '';
@@ -156,8 +156,8 @@ in {
         type = types.nullOr types.str;
         default = "${cfg.dataDir}/tag_cache";
         defaultText = literalExpression ''"''${dataDir}/tag_cache"'';
-        description = ''
-          The path to MPD's database. If set to <literal>null</literal> the
+        description = lib.mdDoc ''
+          The path to MPD's database. If set to `null` the
           parameter is omitted from the configuration.
         '';
       };
@@ -167,7 +167,7 @@ in {
           options = {
             passwordFile = mkOption {
               type = types.path;
-              description = ''
+              description = lib.mdDoc ''
                 Path to file containing the password.
               '';
             };
@@ -176,14 +176,14 @@ in {
             in mkOption {
               type = types.listOf (types.enum perms);
               default = [ "read" ];
-              description = ''
+              description = lib.mdDoc ''
                 List of permissions that are granted with this password.
                 Permissions can be "${concatStringsSep "\", \"" perms}".
               '';
             };
           };
         });
-        description = ''
+        description = lib.mdDoc ''
           Credentials and permissions for accessing the mpd server.
         '';
         default = [];
@@ -196,7 +196,7 @@ in {
       fluidsynth = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If set, add fluidsynth soundfont and configure the plugin.
         '';
       };
@@ -215,6 +215,7 @@ in {
     systemd.sockets.mpd = mkIf cfg.startWhenNeeded {
       wantedBy = [ "sockets.target" ];
       listenStreams = [
+        ""  # Note: this is needed to override the upstream unit
         (if pkgs.lib.hasPrefix "/" cfg.network.listenAddress
           then cfg.network.listenAddress
           else "${optionalString (cfg.network.listenAddress != "any") "${cfg.network.listenAddress}:"}${toString cfg.network.port}")
diff --git a/nixos/modules/services/audio/mpdscribble.nix b/nixos/modules/services/audio/mpdscribble.nix
index 333ffb70941..132d9ad3258 100644
--- a/nixos/modules/services/audio/mpdscribble.nix
+++ b/nixos/modules/services/audio/mpdscribble.nix
@@ -77,12 +77,12 @@ in {
 
   options.services.mpdscribble = {
 
-    enable = mkEnableOption "mpdscribble";
+    enable = mkEnableOption (lib.mdDoc "mpdscribble");
 
     proxy = mkOption {
       default = null;
       type = types.nullOr types.str;
-      description = ''
+      description = lib.mdDoc ''
         HTTP proxy URL.
       '';
     };
@@ -90,7 +90,7 @@ in {
     verbose = mkOption {
       default = 1;
       type = types.int;
-      description = ''
+      description = lib.mdDoc ''
         Log level for the mpdscribble daemon.
       '';
     };
@@ -99,7 +99,7 @@ in {
       default = 600;
       example = 60;
       type = types.int;
-      description = ''
+      description = lib.mdDoc ''
         How often should mpdscribble save the journal file? [seconds]
       '';
     };
@@ -115,7 +115,7 @@ in {
         else "localhost"
       '';
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Host for the mpdscribble daemon to search for a mpd daemon on.
       '';
     };
@@ -128,14 +128,14 @@ in {
           mpdCfg.credentials).passwordFile
       else
         null;
-      defaultText = literalDocBook ''
+      defaultText = literalMD ''
         The first password file with read access configured for MPD when using a local instance,
-        otherwise <literal>null</literal>.
+        otherwise `null`.
       '';
       type = types.nullOr types.str;
-      description = ''
+      description = lib.mdDoc ''
         File containing the password for the mpd daemon.
-        If there is a local mpd configured using <option>services.mpd.credentials</option>
+        If there is a local mpd configured using {option}`services.mpd.credentials`
         the default is automatically set to a matching passwordFile of the local mpd.
       '';
     };
@@ -144,7 +144,7 @@ in {
       default = mpdCfg.network.port;
       defaultText = literalExpression "config.${mpdOpt.network.port}";
       type = types.port;
-      description = ''
+      description = lib.mdDoc ''
         Port for the mpdscribble daemon to search for a mpd daemon on.
       '';
     };
@@ -157,18 +157,18 @@ in {
               type = types.str;
               default = endpointUrls.${name} or "";
               description =
-                "The url endpoint where the scrobble API is listening.";
+                lib.mdDoc "The url endpoint where the scrobble API is listening.";
             };
             username = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Username for the scrobble service.
               '';
             };
             passwordFile = mkOption {
               type = types.nullOr types.str;
               description =
-                "File containing the password, either as MD5SUM or cleartext.";
+                lib.mdDoc "File containing the password, either as MD5SUM or cleartext.";
             };
           };
         };
@@ -180,7 +180,7 @@ in {
           passwordFile = "/run/secrets/lastfm_password";
         };
       };
-      description = ''
+      description = lib.mdDoc ''
         Endpoints to scrobble to.
         If the endpoint is one of "${
           concatStringsSep "\", \"" (attrNames endpointUrls)
diff --git a/nixos/modules/services/audio/navidrome.nix b/nixos/modules/services/audio/navidrome.nix
index 3660e05310b..e73828081d4 100644
--- a/nixos/modules/services/audio/navidrome.nix
+++ b/nixos/modules/services/audio/navidrome.nix
@@ -9,7 +9,7 @@ in {
   options = {
     services.navidrome = {
 
-      enable = mkEnableOption "Navidrome music server";
+      enable = mkEnableOption (lib.mdDoc "Navidrome music server");
 
       settings = mkOption rec {
         type = settingsFormat.type;
@@ -21,8 +21,8 @@ in {
         example = {
           MusicFolder = "/mnt/music";
         };
-        description = ''
-          Configuration for Navidrome, see <link xlink:href="https://www.navidrome.org/docs/usage/configuration-options/"/> for supported values.
+        description = lib.mdDoc ''
+          Configuration for Navidrome, see <https://www.navidrome.org/docs/usage/configuration-options/> for supported values.
         '';
       };
 
@@ -45,7 +45,10 @@ in {
         RootDirectory = "/run/navidrome";
         ReadWritePaths = "";
         BindReadOnlyPaths = [
+          # navidrome uses online services to download additional album metadata / covers
+          "${config.environment.etc."ssl/certs/ca-certificates.crt".source}:/etc/ssl/certs/ca-certificates.crt"
           builtins.storeDir
+          "/etc"
         ] ++ lib.optional (cfg.settings ? MusicFolder) cfg.settings.MusicFolder;
         CapabilityBoundingSet = "";
         RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
@@ -59,7 +62,7 @@ in {
         ProtectKernelModules = true;
         ProtectKernelTunables = true;
         SystemCallArchitectures = "native";
-        SystemCallFilter = [ "@system-service" "~@privileged" "~@resources" ];
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
         RestrictRealtime = true;
         LockPersonality = true;
         MemoryDenyWriteExecute = true;
diff --git a/nixos/modules/services/audio/networkaudiod.nix b/nixos/modules/services/audio/networkaudiod.nix
index 265a4e1d95d..11486429e66 100644
--- a/nixos/modules/services/audio/networkaudiod.nix
+++ b/nixos/modules/services/audio/networkaudiod.nix
@@ -8,7 +8,7 @@ let
 in {
   options = {
     services.networkaudiod = {
-      enable = mkEnableOption "Networkaudiod (NAA)";
+      enable = mkEnableOption (lib.mdDoc "Networkaudiod (NAA)");
     };
   };
 
diff --git a/nixos/modules/services/audio/roon-bridge.nix b/nixos/modules/services/audio/roon-bridge.nix
index e08f8a4f9e7..db84ba28622 100644
--- a/nixos/modules/services/audio/roon-bridge.nix
+++ b/nixos/modules/services/audio/roon-bridge.nix
@@ -8,25 +8,25 @@ let
 in {
   options = {
     services.roon-bridge = {
-      enable = mkEnableOption "Roon Bridge";
+      enable = mkEnableOption (lib.mdDoc "Roon Bridge");
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for the bridge.
         '';
       };
       user = mkOption {
         type = types.str;
         default = "roon-bridge";
-        description = ''
+        description = lib.mdDoc ''
           User to run the Roon bridge as.
         '';
       };
       group = mkOption {
         type = types.str;
         default = "roon-bridge";
-        description = ''
+        description = lib.mdDoc ''
           Group to run the Roon Bridge as.
         '';
       };
diff --git a/nixos/modules/services/audio/roon-server.nix b/nixos/modules/services/audio/roon-server.nix
index de1f61c8e73..4764ee3e598 100644
--- a/nixos/modules/services/audio/roon-server.nix
+++ b/nixos/modules/services/audio/roon-server.nix
@@ -8,25 +8,25 @@ let
 in {
   options = {
     services.roon-server = {
-      enable = mkEnableOption "Roon Server";
+      enable = mkEnableOption (lib.mdDoc "Roon Server");
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for the server.
         '';
       };
       user = mkOption {
         type = types.str;
         default = "roon-server";
-        description = ''
+        description = lib.mdDoc ''
           User to run the Roon Server as.
         '';
       };
       group = mkOption {
         type = types.str;
         default = "roon-server";
-        description = ''
+        description = lib.mdDoc ''
           Group to run the Roon Server as.
         '';
       };
@@ -53,10 +53,12 @@ in {
     networking.firewall = mkIf cfg.openFirewall {
       allowedTCPPortRanges = [
         { from = 9100; to = 9200; }
-        { from = 9330; to = 9332; }
+        { from = 9330; to = 9339; }
+        { from = 30000; to = 30010; }
       ];
       allowedUDPPorts = [ 9003 ];
       extraCommands = ''
+        ## IGMP / Broadcast ##
         iptables -A INPUT -s 224.0.0.0/4 -j ACCEPT
         iptables -A INPUT -d 224.0.0.0/4 -j ACCEPT
         iptables -A INPUT -s 240.0.0.0/5 -j ACCEPT
diff --git a/nixos/modules/services/audio/slimserver.nix b/nixos/modules/services/audio/slimserver.nix
index ecd26528499..9fbc68b7136 100644
--- a/nixos/modules/services/audio/slimserver.nix
+++ b/nixos/modules/services/audio/slimserver.nix
@@ -14,7 +14,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable slimserver.
         '';
       };
@@ -23,13 +23,13 @@ in {
         type = types.package;
         default = pkgs.slimserver;
         defaultText = literalExpression "pkgs.slimserver";
-        description = "Slimserver package to use.";
+        description = lib.mdDoc "Slimserver package to use.";
       };
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/slimserver";
-        description = ''
+        description = lib.mdDoc ''
           The directory where slimserver stores its state, tag cache,
           playlists etc.
         '';
diff --git a/nixos/modules/services/audio/snapserver.nix b/nixos/modules/services/audio/snapserver.nix
index 6d5ce98df89..fdc1f605bb3 100644
--- a/nixos/modules/services/audio/snapserver.nix
+++ b/nixos/modules/services/audio/snapserver.nix
@@ -1,4 +1,4 @@
-{ config, lib, pkgs, ... }:
+{ config, options, lib, pkgs, ... }:
 
 with lib;
 
@@ -12,7 +12,7 @@ let
   sampleFormat = mkOption {
     type = with types; nullOr str;
     default = null;
-    description = ''
+    description = lib.mdDoc ''
       Default sample format.
     '';
     example = "48000:16:2";
@@ -21,7 +21,7 @@ let
   codec = mkOption {
     type = with types; nullOr str;
     default = null;
-    description = ''
+    description = lib.mdDoc ''
       Default audio compression method.
     '';
     example = "flac";
@@ -77,7 +77,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable snapserver.
         '';
       };
@@ -86,7 +86,7 @@ in {
         type = types.str;
         default = "::";
         example = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           The address where snapclients can connect.
         '';
       };
@@ -94,15 +94,17 @@ in {
       port = mkOption {
         type = types.port;
         default = 1704;
-        description = ''
+        description = lib.mdDoc ''
           The port that snapclients can connect to.
         '';
       };
 
       openFirewall = mkOption {
         type = types.bool;
+        # Make the behavior consistent with other services. Set the default to
+        # false and remove the accompanying warning after NixOS 22.05 is released.
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to automatically open the specified ports in the firewall.
         '';
       };
@@ -113,7 +115,7 @@ in {
       streamBuffer = mkOption {
         type = with types; nullOr int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Stream read (input) buffer in ms.
         '';
         example = 20;
@@ -122,7 +124,7 @@ in {
       buffer = mkOption {
         type = with types; nullOr int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Network buffer in ms.
         '';
         example = 1000;
@@ -131,7 +133,7 @@ in {
       sendToMuted = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Send audio to muted clients.
         '';
       };
@@ -139,7 +141,7 @@ in {
       tcp.enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the JSON-RPC via TCP.
         '';
       };
@@ -148,7 +150,7 @@ in {
         type = types.str;
         default = "::";
         example = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           The address where the TCP JSON-RPC listens on.
         '';
       };
@@ -156,7 +158,7 @@ in {
       tcp.port = mkOption {
         type = types.port;
         default = 1705;
-        description = ''
+        description = lib.mdDoc ''
           The port where the TCP JSON-RPC listens on.
         '';
       };
@@ -164,7 +166,7 @@ in {
       http.enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the JSON-RPC via HTTP.
         '';
       };
@@ -173,7 +175,7 @@ in {
         type = types.str;
         default = "::";
         example = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           The address where the HTTP JSON-RPC listens on.
         '';
       };
@@ -181,7 +183,7 @@ in {
       http.port = mkOption {
         type = types.port;
         default = 1780;
-        description = ''
+        description = lib.mdDoc ''
           The port where the HTTP JSON-RPC listens on.
         '';
       };
@@ -189,7 +191,7 @@ in {
       http.docRoot = mkOption {
         type = with types; nullOr path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to serve from the HTTP servers root.
         '';
       };
@@ -199,12 +201,12 @@ in {
           options = {
             location = mkOption {
               type = types.oneOf [ types.path types.str ];
-              description = ''
-                For type <literal>pipe</literal> or <literal>file</literal>, the path to the pipe or file.
-                For type <literal>librespot</literal>, <literal>airplay</literal> or <literal>process</literal>, the path to the corresponding binary.
-                For type <literal>tcp</literal>, the <literal>host:port</literal> address to connect to or listen on.
-                For type <literal>meta</literal>, a list of stream names in the form <literal>/one/two/...</literal>. Don't forget the leading slash.
-                For type <literal>alsa</literal>, use an empty string.
+              description = lib.mdDoc ''
+                For type `pipe` or `file`, the path to the pipe or file.
+                For type `librespot`, `airplay` or `process`, the path to the corresponding binary.
+                For type `tcp`, the `host:port` address to connect to or listen on.
+                For type `meta`, a list of stream names in the form `/one/two/...`. Don't forget the leading slash.
+                For type `alsa`, use an empty string.
               '';
               example = literalExpression ''
                 "/path/to/pipe"
@@ -216,14 +218,14 @@ in {
             type = mkOption {
               type = types.enum [ "pipe" "librespot" "airplay" "file" "process" "tcp" "alsa" "spotify" "meta" ];
               default = "pipe";
-              description = ''
+              description = lib.mdDoc ''
                 The type of input stream.
               '';
             };
             query = mkOption {
               type = attrsOf str;
               default = {};
-              description = ''
+              description = lib.mdDoc ''
                 Key-value pairs that convey additional parameters about a stream.
               '';
               example = literalExpression ''
@@ -251,7 +253,7 @@ in {
           };
         });
         default = { default = {}; };
-        description = ''
+        description = lib.mdDoc ''
           The definition for an input source.
         '';
         example = literalExpression ''
@@ -273,10 +275,16 @@ in {
 
   config = mkIf cfg.enable {
 
-    # https://github.com/badaix/snapcast/blob/98ac8b2fb7305084376607b59173ce4097c620d8/server/streamreader/stream_manager.cpp#L85
-    warnings = filter (w: w != "") (mapAttrsToList (k: v: if v.type == "spotify" then ''
-      services.snapserver.streams.${k}.type = "spotify" is deprecated, use services.snapserver.streams.${k}.type = "librespot" instead.
-    '' else "") cfg.streams);
+    warnings =
+      # https://github.com/badaix/snapcast/blob/98ac8b2fb7305084376607b59173ce4097c620d8/server/streamreader/stream_manager.cpp#L85
+      filter (w: w != "") (mapAttrsToList (k: v: if v.type == "spotify" then ''
+        services.snapserver.streams.${k}.type = "spotify" is deprecated, use services.snapserver.streams.${k}.type = "librespot" instead.
+      '' else "") cfg.streams)
+      # Remove this warning after NixOS 22.05 is released.
+      ++ optional (options.services.snapserver.openFirewall.highestPrio >= (mkOptionDefault null).priority) ''
+        services.snapserver.openFirewall will no longer default to true starting with NixOS 22.11.
+        Enable it explicitly if you need to control Snapserver remotely.
+      '';
 
     systemd.services.snapserver = {
       after = [ "network.target" ];
@@ -304,8 +312,8 @@ in {
 
     networking.firewall.allowedTCPPorts =
       optionals cfg.openFirewall [ cfg.port ]
-      ++ optional cfg.tcp.enable cfg.tcp.port
-      ++ optional cfg.http.enable cfg.http.port;
+      ++ optional (cfg.openFirewall && cfg.tcp.enable) cfg.tcp.port
+      ++ optional (cfg.openFirewall && cfg.http.enable) cfg.http.port;
   };
 
   meta = {
diff --git a/nixos/modules/services/audio/spotifyd.nix b/nixos/modules/services/audio/spotifyd.nix
index 22848ed9800..975be5a87cb 100644
--- a/nixos/modules/services/audio/spotifyd.nix
+++ b/nixos/modules/services/audio/spotifyd.nix
@@ -17,14 +17,14 @@ in
 {
   options = {
     services.spotifyd = {
-      enable = mkEnableOption "spotifyd, a Spotify playing daemon";
+      enable = mkEnableOption (lib.mdDoc "spotifyd, a Spotify playing daemon");
 
       config = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           (Deprecated) Configuration for Spotifyd. For syntax and directives, see
-          <link xlink:href="https://github.com/Spotifyd/spotifyd#Configuration"/>.
+          <https://github.com/Spotifyd/spotifyd#Configuration>.
         '';
       };
 
@@ -32,9 +32,9 @@ in
         default = {};
         type = toml.type;
         example = { global.bitrate = 320; };
-        description = ''
+        description = lib.mdDoc ''
           Configuration for Spotifyd. For syntax and directives, see
-          <link xlink:href="https://github.com/Spotifyd/spotifyd#Configuration"/>.
+          <https://github.com/Spotifyd/spotifyd#Configuration>.
         '';
       };
     };
diff --git a/nixos/modules/services/audio/squeezelite.nix b/nixos/modules/services/audio/squeezelite.nix
index 36295e21c60..30dc12552f0 100644
--- a/nixos/modules/services/audio/squeezelite.nix
+++ b/nixos/modules/services/audio/squeezelite.nix
@@ -14,14 +14,14 @@ in
   ###### interface
 
   options.services.squeezelite = {
-    enable = mkEnableOption "Squeezelite, a software Squeezebox emulator";
+    enable = mkEnableOption (lib.mdDoc "Squeezelite, a software Squeezebox emulator");
 
-    pulseAudio = mkEnableOption "pulseaudio support";
+    pulseAudio = mkEnableOption (lib.mdDoc "pulseaudio support");
 
     extraArguments = mkOption {
       default = "";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Additional command line arguments to pass to Squeezelite.
       '';
     };
diff --git a/nixos/modules/services/audio/ympd.nix b/nixos/modules/services/audio/ympd.nix
index 84b72d14251..811b81030ef 100644
--- a/nixos/modules/services/audio/ympd.nix
+++ b/nixos/modules/services/audio/ympd.nix
@@ -12,12 +12,12 @@ in {
 
     services.ympd = {
 
-      enable = mkEnableOption "ympd, the MPD Web GUI";
+      enable = mkEnableOption (lib.mdDoc "ympd, the MPD Web GUI");
 
       webPort = mkOption {
         type = types.either types.str types.port; # string for backwards compat
         default = "8080";
-        description = "The port where ympd's web interface will be available.";
+        description = lib.mdDoc "The port where ympd's web interface will be available.";
         example = "ssl://8080:/path/to/ssl-private-key.pem";
       };
 
@@ -25,14 +25,14 @@ in {
         host = mkOption {
           type = types.str;
           default = "localhost";
-          description = "The host where MPD is listening.";
+          description = lib.mdDoc "The host where MPD is listening.";
         };
 
         port = mkOption {
-          type = types.int;
+          type = types.port;
           default = config.services.mpd.network.port;
           defaultText = literalExpression "config.services.mpd.network.port";
-          description = "The port where MPD is listening.";
+          description = lib.mdDoc "The port where MPD is listening.";
           example = 6600;
         };
       };
diff --git a/nixos/modules/services/backup/automysqlbackup.nix b/nixos/modules/services/backup/automysqlbackup.nix
index fd2764a40ad..d0237f196a8 100644
--- a/nixos/modules/services/backup/automysqlbackup.nix
+++ b/nixos/modules/services/backup/automysqlbackup.nix
@@ -30,12 +30,12 @@ in
   options = {
     services.automysqlbackup = {
 
-      enable = mkEnableOption "AutoMySQLBackup";
+      enable = mkEnableOption (lib.mdDoc "AutoMySQLBackup");
 
       calendar = mkOption {
         type = types.str;
         default = "01:15:00";
-        description = ''
+        description = lib.mdDoc ''
           Configured when to run the backup service systemd unit (DayOfWeek Year-Month-Day Hour:Minute:Second).
         '';
       };
@@ -43,9 +43,9 @@ in
       config = mkOption {
         type = with types; attrsOf (oneOf [ str int bool (listOf str) ]);
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           automysqlbackup configuration. Refer to
-          <filename>''${pkgs.automysqlbackup}/etc/automysqlbackup.conf</filename>
+          {file}`''${pkgs.automysqlbackup}/etc/automysqlbackup.conf`
           for details on supported values.
         '';
         example = literalExpression ''
@@ -112,7 +112,7 @@ in
 
     services.mysql.ensureUsers = optional (config.services.mysql.enable && cfg.config.mysql_dump_host == "localhost") {
       name = user;
-      ensurePermissions = { "*.*" = "SELECT, SHOW VIEW, TRIGGER, LOCK TABLES"; };
+      ensurePermissions = { "*.*" = "SELECT, SHOW VIEW, TRIGGER, LOCK TABLES, EVENT"; };
     };
 
   };
diff --git a/nixos/modules/services/backup/bacula.nix b/nixos/modules/services/backup/bacula.nix
index 59890204234..0acbf1b3eab 100644
--- a/nixos/modules/services/backup/bacula.nix
+++ b/nixos/modules/services/backup/bacula.nix
@@ -114,7 +114,7 @@ let
       password = mkOption {
         type = types.str;
         # TODO: required?
-        description = ''
+        description = lib.mdDoc ''
           Specifies the password that must be supplied for the default Bacula
           Console to be authorized. The same password must appear in the
           Director resource of the Console configuration file. For added
@@ -135,10 +135,10 @@ let
         type = types.enum [ "no" "yes" ];
         default = "no";
         example = "yes";
-        description = ''
-          If Monitor is set to <literal>no</literal>, this director will have
+        description = lib.mdDoc ''
+          If Monitor is set to `no`, this director will have
           full access to this Storage daemon. If Monitor is set to
-          <literal>yes</literal>, this director will only be able to fetch the
+          `yes`, this director will only be able to fetch the
           current status of this Storage daemon.
 
           Please note that if this director is being used by a Monitor, we
@@ -154,15 +154,15 @@ let
     options = {
       changerDevice = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The specified name-string must be the generic SCSI device name of the
           autochanger that corresponds to the normal read/write Archive Device
           specified in the Device resource. This generic SCSI device name
           should be specified if you have an autochanger or if you have a
           standard tape drive and want to use the Alert Command (see below).
           For example, on Linux systems, for an Archive Device name of
-          <literal>/dev/nst0</literal>, you would specify
-          <literal>/dev/sg0</literal> for the Changer Device name.  Depending
+          `/dev/nst0`, you would specify
+          `/dev/sg0` for the Changer Device name.  Depending
           on your exact configuration, and the number of autochangers or the
           type of autochanger, what you specify here can vary. This directive
           is optional. See the Using AutochangersAutochangersChapter chapter of
@@ -173,7 +173,7 @@ let
 
       changerCommand = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The name-string specifies an external program to be called that will
           automatically change volumes as required by Bacula. Normally, this
           directive will be specified only in the AutoChanger resource, which
@@ -181,7 +181,7 @@ let
           different Changer Command in each Device resource. Most frequently,
           you will specify the Bacula supplied mtx-changer script as follows:
 
-          <literal>"/path/mtx-changer %c %o %S %a %d"</literal>
+          `"/path/mtx-changer %c %o %S %a %d"`
 
           and you will install the mtx on your system (found in the depkgs
           release). An example of this command is in the default bacula-sd.conf
@@ -195,14 +195,14 @@ let
       };
 
       devices = mkOption {
-        description = "";
+        description = lib.mdDoc "";
         type = types.listOf types.str;
       };
 
       extraAutochangerConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be passed in Autochanger directive.
         '';
         example = ''
@@ -219,13 +219,13 @@ let
       archiveDevice = mkOption {
         # TODO: required?
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The specified name-string gives the system file name of the storage
           device managed by this storage daemon. This will usually be the
           device file name of a removable storage device (tape drive), for
-          example <literal>/dev/nst0</literal> or
-          <literal>/dev/rmt/0mbn</literal>. For a DVD-writer, it will be for
-          example <literal>/dev/hdc</literal>. It may also be a directory name
+          example `/dev/nst0` or
+          `/dev/rmt/0mbn`. For a DVD-writer, it will be for
+          example `/dev/hdc`. It may also be a directory name
           if you are archiving to disk storage. In this case, you must supply
           the full absolute path to the directory. When specifying a tape
           device, it is preferable that the "non-rewind" variant of the device
@@ -236,9 +236,9 @@ let
       mediaType = mkOption {
         # TODO: required?
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The specified name-string names the type of media supported by this
-          device, for example, <literal>DLT7000</literal>. Media type names are
+          device, for example, `DLT7000`. Media type names are
           arbitrary in that you set them to anything you want, but they must be
           known to the volume database to keep track of which storage daemons
           can read which volumes. In general, each different storage type
@@ -255,9 +255,9 @@ let
           Storage daemon, but it is with multiple Storage daemons, especially
           if they have incompatible media.
 
-          For example, if you specify a Media Type of <literal>DDS-4</literal>
+          For example, if you specify a Media Type of `DDS-4`
           then during the restore, Bacula will be able to choose any Storage
-          Daemon that handles <literal>DDS-4</literal>. If you have an
+          Daemon that handles `DDS-4`. If you have an
           autochanger, you might want to name the Media Type in a way that is
           unique to the autochanger, unless you wish to possibly use the
           Volumes in other drives. You should also ensure to have unique Media
@@ -274,7 +274,7 @@ let
       extraDeviceConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be passed in Device directive.
         '';
         example = ''
@@ -295,7 +295,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Bacula File Daemon.
         '';
       };
@@ -304,7 +304,7 @@ in {
         default = "${config.networking.hostName}-fd";
         defaultText = literalExpression ''"''${config.networking.hostName}-fd"'';
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The client name that must be used by the Director when connecting.
           Generally, it is a good idea to use a name related to the machine so
           that error messages can be easily identified if you have multiple
@@ -314,8 +314,8 @@ in {
 
       port = mkOption {
         default = 9102;
-        type = types.int;
-        description = ''
+        type = types.port;
+        description = lib.mdDoc ''
           This specifies the port number on which the Client listens for
           Director connections. It must agree with the FDPort specified in
           the Client resource of the Director's configuration file.
@@ -324,7 +324,7 @@ in {
 
       director = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           This option defines director resources in Bacula File Daemon.
         '';
         type = with types; attrsOf (submodule directorOptions);
@@ -333,7 +333,7 @@ in {
       extraClientConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be passed in Client directive.
         '';
         example = ''
@@ -345,7 +345,7 @@ in {
       extraMessagesConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be passed in Messages directive.
         '';
         example = ''
@@ -358,7 +358,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Bacula Storage Daemon.
         '';
       };
@@ -367,15 +367,15 @@ in {
         default = "${config.networking.hostName}-sd";
         defaultText = literalExpression ''"''${config.networking.hostName}-sd"'';
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the Name of the Storage daemon.
         '';
       };
 
       port = mkOption {
         default = 9103;
-        type = types.int;
-        description = ''
+        type = types.port;
+        description = lib.mdDoc ''
           Specifies port number on which the Storage daemon listens for
           Director connections.
         '';
@@ -383,7 +383,7 @@ in {
 
       director = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           This option defines Director resources in Bacula Storage Daemon.
         '';
         type = with types; attrsOf (submodule directorOptions);
@@ -391,7 +391,7 @@ in {
 
       device = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           This option defines Device resources in Bacula Storage Daemon.
         '';
         type = with types; attrsOf (submodule deviceOptions);
@@ -399,7 +399,7 @@ in {
 
       autochanger = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           This option defines Autochanger resources in Bacula Storage Daemon.
         '';
         type = with types; attrsOf (submodule autochangerOptions);
@@ -408,7 +408,7 @@ in {
       extraStorageConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be passed in Storage directive.
         '';
         example = ''
@@ -420,7 +420,7 @@ in {
       extraMessagesConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be passed in Messages directive.
         '';
         example = ''
@@ -434,7 +434,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Bacula Director Daemon.
         '';
       };
@@ -443,7 +443,7 @@ in {
         default = "${config.networking.hostName}-dir";
         defaultText = literalExpression ''"''${config.networking.hostName}-dir"'';
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The director name used by the system administrator. This directive is
           required.
         '';
@@ -451,8 +451,8 @@ in {
 
       port = mkOption {
         default = 9101;
-        type = types.int;
-        description = ''
+        type = types.port;
+        description = lib.mdDoc ''
           Specify the port (a positive integer) on which the Director daemon
           will listen for Bacula Console connections. This same port number
           must be specified in the Director resource of the Console
@@ -465,7 +465,7 @@ in {
       password = mkOption {
         # TODO: required?
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
            Specifies the password that must be supplied for a Director.
         '';
       };
@@ -473,7 +473,7 @@ in {
       extraMessagesConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be passed in Messages directive.
         '';
         example = ''
@@ -484,7 +484,7 @@ in {
       extraDirectorConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be passed in Director directive.
         '';
         example = ''
@@ -496,7 +496,7 @@ in {
       extraConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration for Bacula Director Daemon.
         '';
         example = ''
diff --git a/nixos/modules/services/backup/borgbackup.nix b/nixos/modules/services/backup/borgbackup.nix
index 4c9ddfe4674..7b29eb41e72 100644
--- a/nixos/modules/services/backup/borgbackup.nix
+++ b/nixos/modules/services/backup/borgbackup.nix
@@ -23,12 +23,10 @@ let
     on_exit()
     {
       exitStatus=$?
-      # Reset the EXIT handler, or else we're called again on 'exit' below
-      trap - EXIT
       ${cfg.postHook}
       exit $exitStatus
     }
-    trap 'on_exit' INT TERM QUIT EXIT
+    trap on_exit EXIT
 
     archiveName="${if cfg.archiveBaseName == null then "" else cfg.archiveBaseName + "-"}$(date ${cfg.dateFormat})"
     archiveSuffix="${optionalString cfg.appendFailedSuffix ".failed"}"
@@ -118,7 +116,7 @@ let
       original, name, set ? {}
     }:
     pkgs.runCommand "${name}-wrapper" {
-      buildInputs = [ pkgs.makeWrapper ];
+      nativeBuildInputs = [ pkgs.makeWrapper ];
     } (with lib; ''
       makeWrapper "${original}" "$out/bin/${name}" \
         ${concatStringsSep " \\\n " (mapAttrsToList (name: value: ''--set ${name} "${value}"'') set)}
@@ -219,7 +217,7 @@ in {
   ###### interface
 
   options.services.borgbackup.jobs = mkOption {
-    description = ''
+    description = lib.mdDoc ''
       Deduplicating backups using BorgBackup.
       Adding a job will cause a borg-job-NAME wrapper to be added
       to your system path, so that you can perform maintenance easily.
@@ -265,9 +263,9 @@ in {
           paths = mkOption {
             type = with types; nullOr (coercedTo str lib.singleton (listOf str));
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Path(s) to back up.
-              Mutually exclusive with <option>dumpCommand</option>.
+              Mutually exclusive with {option}`dumpCommand`.
             '';
             example = "/home/user";
           };
@@ -275,42 +273,42 @@ in {
           dumpCommand = mkOption {
             type = with types; nullOr path;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Backup the stdout of this program instead of filesystem paths.
-              Mutually exclusive with <option>paths</option>.
+              Mutually exclusive with {option}`paths`.
             '';
             example = "/path/to/createZFSsend.sh";
           };
 
           repo = mkOption {
             type = types.str;
-            description = "Remote or local repository to back up to.";
+            description = lib.mdDoc "Remote or local repository to back up to.";
             example = "user@machine:/path/to/repo";
           };
 
           removableDevice = mkOption {
             type = types.bool;
             default = false;
-            description = "Whether the repo (which must be local) is a removable device.";
+            description = lib.mdDoc "Whether the repo (which must be local) is a removable device.";
           };
 
           archiveBaseName = mkOption {
             type = types.nullOr (types.strMatching "[^/{}]+");
             default = "${globalConfig.networking.hostName}-${name}";
             defaultText = literalExpression ''"''${config.networking.hostName}-<name>"'';
-            description = ''
+            description = lib.mdDoc ''
               How to name the created archives. A timestamp, whose format is
-              determined by <option>dateFormat</option>, will be appended. The full
-              name can be modified at runtime (<literal>$archiveName</literal>).
-              Placeholders like <literal>{hostname}</literal> must not be used.
-              Use <literal>null</literal> for no base name.
+              determined by {option}`dateFormat`, will be appended. The full
+              name can be modified at runtime (`$archiveName`).
+              Placeholders like `{hostname}` must not be used.
+              Use `null` for no base name.
             '';
           };
 
           dateFormat = mkOption {
             type = types.str;
-            description = ''
-              Arguments passed to <command>date</command>
+            description = lib.mdDoc ''
+              Arguments passed to {command}`date`
               to create a timestamp suffix for the archive name.
             '';
             default = "+%Y-%m-%dT%H:%M:%S";
@@ -320,13 +318,12 @@ in {
           startAt = mkOption {
             type = with types; either str (listOf str);
             default = "daily";
-            description = ''
+            description = lib.mdDoc ''
               When or how often the backup should run.
               Must be in the format described in
-              <citerefentry><refentrytitle>systemd.time</refentrytitle>
-              <manvolnum>7</manvolnum></citerefentry>.
+              {manpage}`systemd.time(7)`.
               If you do not want the backup to start
-              automatically, use <literal>[ ]</literal>.
+              automatically, use `[ ]`.
               It will generate a systemd service borgbackup-job-NAME.
               You may trigger it manually via systemctl restart borgbackup-job-NAME.
             '';
@@ -336,10 +333,9 @@ in {
             default = false;
             type = types.bool;
             example = true;
-            description = ''
-              Set the <literal>persistentTimer</literal> option for the
-              <citerefentry><refentrytitle>systemd.timer</refentrytitle>
-              <manvolnum>5</manvolnum></citerefentry>
+            description = lib.mdDoc ''
+              Set the `persistentTimer` option for the
+              {manpage}`systemd.timer(5)`
               which triggers the backup immediately if the last trigger
               was missed (e.g. if the system was powered down).
             '';
@@ -347,19 +343,19 @@ in {
 
           user = mkOption {
             type = types.str;
-            description = ''
-              The user <command>borg</command> is run as.
+            description = lib.mdDoc ''
+              The user {command}`borg` is run as.
               User or group need read permission
-              for the specified <option>paths</option>.
+              for the specified {option}`paths`.
             '';
             default = "root";
           };
 
           group = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               The group borg is run as. User or group needs read permission
-              for the specified <option>paths</option>.
+              for the specified {option}`paths`.
             '';
             default = "root";
           };
@@ -371,20 +367,20 @@ in {
               "authenticated" "authenticated-blake2"
               "none"
             ];
-            description = ''
+            description = lib.mdDoc ''
               Encryption mode to use. Setting a mode
-              other than <literal>"none"</literal> requires
-              you to specify a <option>passCommand</option>
-              or a <option>passphrase</option>.
+              other than `"none"` requires
+              you to specify a {option}`passCommand`
+              or a {option}`passphrase`.
             '';
             example = "repokey-blake2";
           };
 
           encryption.passCommand = mkOption {
             type = with types; nullOr str;
-            description = ''
+            description = lib.mdDoc ''
               A command which prints the passphrase to stdout.
-              Mutually exclusive with <option>passphrase</option>.
+              Mutually exclusive with {option}`passphrase`.
             '';
             default = null;
             example = "cat /path/to/passphrase_file";
@@ -392,11 +388,11 @@ in {
 
           encryption.passphrase = mkOption {
             type = with types; nullOr str;
-            description = ''
+            description = lib.mdDoc ''
               The passphrase the backups are encrypted with.
-              Mutually exclusive with <option>passCommand</option>.
+              Mutually exclusive with {option}`passCommand`.
               If you do not want the passphrase to be stored in the
-              world-readable Nix store, use <option>passCommand</option>.
+              world-readable Nix store, use {option}`passCommand`.
             '';
             default = null;
           };
@@ -406,9 +402,9 @@ in {
             # compression mode must be given,
             # compression level is optional
             type = types.strMatching "none|(auto,)?(lz4|zstd|zlib|lzma)(,[[:digit:]]{1,2})?";
-            description = ''
+            description = lib.mdDoc ''
               Compression method to use. Refer to
-              <command>borg help compression</command>
+              {command}`borg help compression`
               for all available options.
             '';
             default = "lz4";
@@ -417,9 +413,9 @@ in {
 
           exclude = mkOption {
             type = with types; listOf str;
-            description = ''
+            description = lib.mdDoc ''
               Exclude paths matching any of the given patterns. See
-              <command>borg help patterns</command> for pattern syntax.
+              {command}`borg help patterns` for pattern syntax.
             '';
             default = [ ];
             example = [
@@ -430,9 +426,9 @@ in {
 
           readWritePaths = mkOption {
             type = with types; listOf path;
-            description = ''
+            description = lib.mdDoc ''
               By default, borg cannot write anywhere on the system but
-              <literal>$HOME/.config/borg</literal> and <literal>$HOME/.cache/borg</literal>.
+              `$HOME/.config/borg` and `$HOME/.cache/borg`.
               If, for example, your preHook script needs to dump files
               somewhere, put those directories here.
             '';
@@ -444,8 +440,8 @@ in {
 
           privateTmp = mkOption {
             type = types.bool;
-            description = ''
-              Set the <literal>PrivateTmp</literal> option for
+            description = lib.mdDoc ''
+              Set the `PrivateTmp` option for
               the systemd-service. Set to false if you need sockets
               or other files from global /tmp.
             '';
@@ -454,10 +450,10 @@ in {
 
           doInit = mkOption {
             type = types.bool;
-            description = ''
-              Run <command>borg init</command> if the
-              specified <option>repo</option> does not exist.
-              You should set this to <literal>false</literal>
+            description = lib.mdDoc ''
+              Run {command}`borg init` if the
+              specified {option}`repo` does not exist.
+              You should set this to `false`
               if the repository is located on an external drive
               that might not always be mounted.
             '';
@@ -466,10 +462,10 @@ in {
 
           appendFailedSuffix = mkOption {
             type = types.bool;
-            description = ''
-              Append a <literal>.failed</literal> suffix
+            description = lib.mdDoc ''
+              Append a `.failed` suffix
               to the archive name, which is only removed if
-              <command>borg create</command> has a zero exit status.
+              {command}`borg create` has a zero exit status.
             '';
             default = true;
           };
@@ -479,9 +475,9 @@ in {
             # means there is no limit of yearly archives to keep
             # The regex is for use with e.g. --keep-within 1y
             type = with types; attrsOf (either int (strMatching "[[:digit:]]+[Hdwmy]"));
-            description = ''
+            description = lib.mdDoc ''
               Prune a repository by deleting all archives not matching any of the
-              specified retention options. See <command>borg help prune</command>
+              specified retention options. See {command}`borg help prune`
               for the available options.
             '';
             default = { };
@@ -497,10 +493,10 @@ in {
 
           prune.prefix = mkOption {
             type = types.nullOr (types.str);
-            description = ''
+            description = lib.mdDoc ''
               Only consider archive names starting with this prefix for pruning.
               By default, only archives created by this job are considered.
-              Use <literal>""</literal> or <literal>null</literal> to consider all archives.
+              Use `""` or `null` to consider all archives.
             '';
             default = config.archiveBaseName;
             defaultText = literalExpression "archiveBaseName";
@@ -508,7 +504,7 @@ in {
 
           environment = mkOption {
             type = with types; attrsOf str;
-            description = ''
+            description = lib.mdDoc ''
               Environment variables passed to the backup script.
               You can for example specify which SSH key to use.
             '';
@@ -518,7 +514,7 @@ in {
 
           preHook = mkOption {
             type = types.lines;
-            description = ''
+            description = lib.mdDoc ''
               Shell commands to run before the backup.
               This can for example be used to mount file systems.
             '';
@@ -531,43 +527,43 @@ in {
 
           postInit = mkOption {
             type = types.lines;
-            description = ''
-              Shell commands to run after <command>borg init</command>.
+            description = lib.mdDoc ''
+              Shell commands to run after {command}`borg init`.
             '';
             default = "";
           };
 
           postCreate = mkOption {
             type = types.lines;
-            description = ''
-              Shell commands to run after <command>borg create</command>. The name
-              of the created archive is stored in <literal>$archiveName</literal>.
+            description = lib.mdDoc ''
+              Shell commands to run after {command}`borg create`. The name
+              of the created archive is stored in `$archiveName`.
             '';
             default = "";
           };
 
           postPrune = mkOption {
             type = types.lines;
-            description = ''
-              Shell commands to run after <command>borg prune</command>.
+            description = lib.mdDoc ''
+              Shell commands to run after {command}`borg prune`.
             '';
             default = "";
           };
 
           postHook = mkOption {
             type = types.lines;
-            description = ''
+            description = lib.mdDoc ''
               Shell commands to run just before exit. They are executed
               even if a previous command exits with a non-zero exit code.
-              The latter is available as <literal>$exitStatus</literal>.
+              The latter is available as `$exitStatus`.
             '';
             default = "";
           };
 
           extraArgs = mkOption {
             type = types.str;
-            description = ''
-              Additional arguments for all <command>borg</command> calls the
+            description = lib.mdDoc ''
+              Additional arguments for all {command}`borg` calls the
               service has. Handle with care.
             '';
             default = "";
@@ -576,9 +572,9 @@ in {
 
           extraInitArgs = mkOption {
             type = types.str;
-            description = ''
-              Additional arguments for <command>borg init</command>.
-              Can also be set at runtime using <literal>$extraInitArgs</literal>.
+            description = lib.mdDoc ''
+              Additional arguments for {command}`borg init`.
+              Can also be set at runtime using `$extraInitArgs`.
             '';
             default = "";
             example = "--append-only";
@@ -586,9 +582,9 @@ in {
 
           extraCreateArgs = mkOption {
             type = types.str;
-            description = ''
-              Additional arguments for <command>borg create</command>.
-              Can also be set at runtime using <literal>$extraCreateArgs</literal>.
+            description = lib.mdDoc ''
+              Additional arguments for {command}`borg create`.
+              Can also be set at runtime using `$extraCreateArgs`.
             '';
             default = "";
             example = "--stats --checkpoint-interval 600";
@@ -596,9 +592,9 @@ in {
 
           extraPruneArgs = mkOption {
             type = types.str;
-            description = ''
-              Additional arguments for <command>borg prune</command>.
-              Can also be set at runtime using <literal>$extraPruneArgs</literal>.
+            description = lib.mdDoc ''
+              Additional arguments for {command}`borg prune`.
+              Can also be set at runtime using `$extraPruneArgs`.
             '';
             default = "";
             example = "--save-space";
@@ -610,12 +606,12 @@ in {
   };
 
   options.services.borgbackup.repos = mkOption {
-    description = ''
+    description = lib.mdDoc ''
       Serve BorgBackup repositories to given public SSH keys,
       restricting their access to the repository only.
       See also the chapter about BorgBackup in the NixOS manual.
       Also, clients do not need to specify the absolute path when accessing the repository,
-      i.e. <literal>user@machine:.</literal> is enough. (Note colon and dot.)
+      i.e. `user@machine:.` is enough. (Note colon and dot.)
     '';
     default = { };
     type = types.attrsOf (types.submodule (
@@ -623,7 +619,7 @@ in {
         options = {
           path = mkOption {
             type = types.path;
-            description = ''
+            description = lib.mdDoc ''
               Where to store the backups. Note that the directory
               is created automatically, with correct permissions.
             '';
@@ -632,30 +628,30 @@ in {
 
           user = mkOption {
             type = types.str;
-            description = ''
-              The user <command>borg serve</command> is run as.
+            description = lib.mdDoc ''
+              The user {command}`borg serve` is run as.
               User or group needs write permission
-              for the specified <option>path</option>.
+              for the specified {option}`path`.
             '';
             default = "borg";
           };
 
           group = mkOption {
             type = types.str;
-            description = ''
-              The group <command>borg serve</command> is run as.
+            description = lib.mdDoc ''
+              The group {command}`borg serve` is run as.
               User or group needs write permission
-              for the specified <option>path</option>.
+              for the specified {option}`path`.
             '';
             default = "borg";
           };
 
           authorizedKeys = mkOption {
             type = with types; listOf str;
-            description = ''
+            description = lib.mdDoc ''
               Public SSH keys that are given full write access to this repository.
               You should use a different SSH key for each repository you write to, because
-              the specified keys are restricted to running <command>borg serve</command>
+              the specified keys are restricted to running {command}`borg serve`
               and can only access this single repository.
             '';
             default = [ ];
@@ -663,7 +659,7 @@ in {
 
           authorizedKeysAppendOnly = mkOption {
             type = with types; listOf str;
-            description = ''
+            description = lib.mdDoc ''
               Public SSH keys that can only be used to append new data (archives) to the repository.
               Note that archives can still be marked as deleted and are subsequently removed from disk
               upon accessing the repo with full write access, e.g. when pruning.
@@ -673,11 +669,11 @@ in {
 
           allowSubRepos = mkOption {
             type = types.bool;
-            description = ''
+            description = lib.mdDoc ''
               Allow clients to create repositories in subdirectories of the
-              specified <option>path</option>. These can be accessed using
-              <literal>user@machine:path/to/subrepo</literal>. Note that a
-              <option>quota</option> applies to repositories independently.
+              specified {option}`path`. These can be accessed using
+              `user@machine:path/to/subrepo`. Note that a
+              {option}`quota` applies to repositories independently.
               Therefore, if this is enabled, clients can create multiple
               repositories and upload an arbitrary amount of data.
             '';
@@ -687,9 +683,9 @@ in {
           quota = mkOption {
             # See the definition of parse_file_size() in src/borg/helpers/parseformat.py
             type = with types; nullOr (strMatching "[[:digit:].]+[KMGTP]?");
-            description = ''
+            description = lib.mdDoc ''
               Storage quota for the repository. This quota is ensured for all
-              sub-repositories if <option>allowSubRepos</option> is enabled
+              sub-repositories if {option}`allowSubRepos` is enabled
               but not for the overall storage space used.
             '';
             default = null;
diff --git a/nixos/modules/services/backup/borgmatic.nix b/nixos/modules/services/backup/borgmatic.nix
index 5e5c0bbeccc..73c4acda393 100644
--- a/nixos/modules/services/backup/borgmatic.nix
+++ b/nixos/modules/services/backup/borgmatic.nix
@@ -4,21 +4,22 @@ with lib;
 
 let
   cfg = config.services.borgmatic;
-  cfgfile = pkgs.writeText "config.yaml" (builtins.toJSON cfg.settings);
+  settingsFormat = pkgs.formats.yaml { };
+  cfgfile = settingsFormat.generate "config.yaml" cfg.settings;
 in {
   options.services.borgmatic = {
-    enable = mkEnableOption "borgmatic";
+    enable = mkEnableOption (lib.mdDoc "borgmatic");
 
     settings = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         See https://torsion.org/borgmatic/docs/reference/configuration/
       '';
       type = types.submodule {
-        freeformType = with lib.types; attrsOf anything;
+        freeformType = settingsFormat.type;
         options.location = {
           source_directories = mkOption {
             type = types.listOf types.str;
-            description = ''
+            description = lib.mdDoc ''
               List of source directories to backup (required). Globs and
               tildes are expanded.
             '';
@@ -26,7 +27,7 @@ in {
           };
           repositories = mkOption {
             type = types.listOf types.str;
-            description = ''
+            description = lib.mdDoc ''
               Paths to local or remote repositories (required). Tildes are
               expanded. Multiple repositories are backed up to in
               sequence. Borg placeholders can be used. See the output of
diff --git a/nixos/modules/services/backup/btrbk.nix b/nixos/modules/services/backup/btrbk.nix
index 0c00b934405..b6eb68cc43f 100644
--- a/nixos/modules/services/backup/btrbk.nix
+++ b/nixos/modules/services/backup/btrbk.nix
@@ -1,87 +1,112 @@
 { config, pkgs, lib, ... }:
 let
-  cfg = config.services.btrbk;
-  sshEnabled = cfg.sshAccess != [ ];
-  serviceEnabled = cfg.instances != { };
-  attr2Lines = attr:
+  inherit (lib)
+    concatLists
+    concatMap
+    concatMapStringsSep
+    concatStringsSep
+    filterAttrs
+    isAttrs
+    literalExpression
+    mapAttrs'
+    mapAttrsToList
+    mkIf
+    mkOption
+    optionalString
+    sort
+    types
+    ;
+
+  # The priority of an option or section.
+  # The configurations format are order-sensitive. Pairs are added as children of
+  # the last sections if possible, otherwise, they start a new section.
+  # We sort them in topological order:
+  # 1. Leaf pairs.
+  # 2. Sections that may contain (1).
+  # 3. Sections that may contain (1) or (2).
+  # 4. Etc.
+  prioOf = { name, value }:
+    if !isAttrs value then 0 # Leaf options.
+    else {
+      target = 1; # Contains: options.
+      subvolume = 2; # Contains: options, target.
+      volume = 3; # Contains: options, target, subvolume.
+    }.${name} or (throw "Unknow section '${name}'");
+
+  genConfig' = set: concatStringsSep "\n" (genConfig set);
+  genConfig = set:
     let
-      pairs = lib.attrsets.mapAttrsToList (name: value: { inherit name value; }) attr;
-      isSubsection = value:
-        if builtins.isAttrs value then true
-        else if builtins.isString value then false
-        else throw "invalid type in btrbk config ${builtins.typeOf value}";
-      sortedPairs = lib.lists.partition (x: isSubsection x.value) pairs;
+      pairs = mapAttrsToList (name: value: { inherit name value; }) set;
+      sortedPairs = sort (a: b: prioOf a < prioOf b) pairs;
     in
-    lib.flatten (
-      # non subsections go first
-      (
-        map (pair: [ "${pair.name} ${pair.value}" ]) sortedPairs.wrong
-      )
-      ++ # subsections go last
-      (
-        map
-          (
-            pair:
-            lib.mapAttrsToList
-              (
-                childname: value:
-                  [ "${pair.name} ${childname}" ] ++ (map (x: " " + x) (attr2Lines value))
-              )
-              pair.value
-          )
-          sortedPairs.right
-      )
-    )
-  ;
+      concatMap genPair sortedPairs;
+  genSection = sec: secName: value:
+    [ "${sec} ${secName}" ] ++ map (x: " " + x) (genConfig value);
+  genPair = { name, value }:
+    if !isAttrs value
+    then [ "${name} ${value}" ]
+    else concatLists (mapAttrsToList (genSection name) value);
+
   addDefaults = settings: { backend = "btrfs-progs-sudo"; } // settings;
-  mkConfigFile = settings: lib.concatStringsSep "\n" (attr2Lines (addDefaults settings));
-  mkTestedConfigFile = name: settings:
-    let
-      configFile = pkgs.writeText "btrbk-${name}.conf" (mkConfigFile settings);
-    in
-    pkgs.runCommand "btrbk-${name}-tested.conf" { } ''
-      mkdir foo
-      cp ${configFile} $out
-      if (set +o pipefail; ${pkgs.btrbk}/bin/btrbk -c $out ls foo 2>&1 | grep $out);
-      then
-      echo btrbk configuration is invalid
-      cat $out
-      exit 1
-      fi;
+
+  mkConfigFile = name: settings: pkgs.writeTextFile {
+    name = "btrbk-${name}.conf";
+    text = genConfig' (addDefaults settings);
+    checkPhase = ''
+      set +e
+      ${pkgs.btrbk}/bin/btrbk -c $out dryrun
+      # According to btrbk(1), exit status 2 means parse error
+      # for CLI options or the config file.
+      if [[ $? == 2 ]]; then
+        echo "Btrbk configuration is invalid:"
+        cat $out
+        exit 1
+      fi
+      set -e
     '';
+  };
+
+  cfg = config.services.btrbk;
+  sshEnabled = cfg.sshAccess != [ ];
+  serviceEnabled = cfg.instances != { };
 in
 {
+  meta.maintainers = with lib.maintainers; [ oxalica ];
+
   options = {
     services.btrbk = {
-      extraPackages = lib.mkOption {
-        description = "Extra packages for btrbk, like compression utilities for <literal>stream_compress</literal>";
-        type = lib.types.listOf lib.types.package;
+      extraPackages = mkOption {
+        description = lib.mdDoc "Extra packages for btrbk, like compression utilities for `stream_compress`";
+        type = types.listOf types.package;
         default = [ ];
-        example = lib.literalExpression "[ pkgs.xz ]";
+        example = literalExpression "[ pkgs.xz ]";
       };
-      niceness = lib.mkOption {
-        description = "Niceness for local instances of btrbk. Also applies to remote ones connecting via ssh when positive.";
-        type = lib.types.ints.between (-20) 19;
+      niceness = mkOption {
+        description = lib.mdDoc "Niceness for local instances of btrbk. Also applies to remote ones connecting via ssh when positive.";
+        type = types.ints.between (-20) 19;
         default = 10;
       };
-      ioSchedulingClass = lib.mkOption {
-        description = "IO scheduling class for btrbk (see ionice(1) for a quick description). Applies to local instances, and remote ones connecting by ssh if set to idle.";
-        type = lib.types.enum [ "idle" "best-effort" "realtime" ];
+      ioSchedulingClass = mkOption {
+        description = lib.mdDoc "IO scheduling class for btrbk (see ionice(1) for a quick description). Applies to local instances, and remote ones connecting by ssh if set to idle.";
+        type = types.enum [ "idle" "best-effort" "realtime" ];
         default = "best-effort";
       };
-      instances = lib.mkOption {
-        description = "Set of btrbk instances. The instance named <literal>btrbk</literal> is the default one.";
-        type = with lib.types;
+      instances = mkOption {
+        description = lib.mdDoc "Set of btrbk instances. The instance named `btrbk` is the default one.";
+        type = with types;
           attrsOf (
             submodule {
               options = {
-                onCalendar = lib.mkOption {
-                  type = lib.types.str;
+                onCalendar = mkOption {
+                  type = types.nullOr types.str;
                   default = "daily";
-                  description = "How often this btrbk instance is started. See systemd.time(7) for more information about the format.";
+                  description = lib.mdDoc ''
+                    How often this btrbk instance is started. See systemd.time(7) for more information about the format.
+                    Setting it to null disables the timer, thus this instance can only be started manually.
+                  '';
                 };
-                settings = lib.mkOption {
-                  type = let t = lib.types.attrsOf (lib.types.either lib.types.str (t // { description = "instances of this type recursively"; })); in t;
+                settings = mkOption {
+                  type = let t = types.attrsOf (types.either types.str (t // { description = "instances of this type recursively"; })); in t;
                   default = { };
                   example = {
                     snapshot_preserve_min = "2d";
@@ -96,26 +121,26 @@ in
                       };
                     };
                   };
-                  description = "configuration options for btrbk. Nested attrsets translate to subsections.";
+                  description = lib.mdDoc "configuration options for btrbk. Nested attrsets translate to subsections.";
                 };
               };
             }
           );
         default = { };
       };
-      sshAccess = lib.mkOption {
-        description = "SSH keys that should be able to make or push snapshots on this system remotely with btrbk";
-        type = with lib.types; listOf (
+      sshAccess = mkOption {
+        description = lib.mdDoc "SSH keys that should be able to make or push snapshots on this system remotely with btrbk";
+        type = with types; listOf (
           submodule {
             options = {
-              key = lib.mkOption {
+              key = mkOption {
                 type = str;
-                description = "SSH public key allowed to login as user <literal>btrbk</literal> to run remote backups.";
+                description = lib.mdDoc "SSH public key allowed to login as user `btrbk` to run remote backups.";
               };
-              roles = lib.mkOption {
+              roles = mkOption {
                 type = listOf (enum [ "info" "source" "target" "delete" "snapshot" "send" "receive" ]);
                 example = [ "source" "info" "send" ];
-                description = "What actions can be performed with this SSH key. See ssh_filter_btrbk(1) for details";
+                description = lib.mdDoc "What actions can be performed with this SSH key. See ssh_filter_btrbk(1) for details";
               };
             };
           }
@@ -125,7 +150,7 @@ in
     };
 
   };
-  config = lib.mkIf (sshEnabled || serviceEnabled) {
+  config = mkIf (sshEnabled || serviceEnabled) {
     environment.systemPackages = [ pkgs.btrbk ] ++ cfg.extraPackages;
     security.sudo.extraRules = [
       {
@@ -152,14 +177,14 @@ in
         (
           v:
           let
-            options = lib.concatMapStringsSep " " (x: "--" + x) v.roles;
+            options = concatMapStringsSep " " (x: "--" + x) v.roles;
             ioniceClass = {
               "idle" = 3;
               "best-effort" = 2;
               "realtime" = 1;
             }.${cfg.ioSchedulingClass};
           in
-          ''command="${pkgs.util-linux}/bin/ionice -t -c ${toString ioniceClass} ${lib.optionalString (cfg.niceness >= 1) "${pkgs.coreutils}/bin/nice -n ${toString cfg.niceness}"} ${pkgs.btrbk}/share/btrbk/scripts/ssh_filter_btrbk.sh --sudo ${options}" ${v.key}''
+          ''command="${pkgs.util-linux}/bin/ionice -t -c ${toString ioniceClass} ${optionalString (cfg.niceness >= 1) "${pkgs.coreutils}/bin/nice -n ${toString cfg.niceness}"} ${pkgs.btrbk}/share/btrbk/scripts/ssh_filter_btrbk.sh --sudo ${options}" ${v.key}''
         )
         cfg.sshAccess;
     };
@@ -169,15 +194,15 @@ in
       "d /var/lib/btrbk/.ssh 0700 btrbk btrbk"
       "f /var/lib/btrbk/.ssh/config 0700 btrbk btrbk - StrictHostKeyChecking=accept-new"
     ];
-    environment.etc = lib.mapAttrs'
+    environment.etc = mapAttrs'
       (
         name: instance: {
           name = "btrbk/${name}.conf";
-          value.source = mkTestedConfigFile name instance.settings;
+          value.source = mkConfigFile name instance.settings;
         }
       )
       cfg.instances;
-    systemd.services = lib.mapAttrs'
+    systemd.services = mapAttrs'
       (
         name: _: {
           name = "btrbk-${name}";
@@ -199,7 +224,7 @@ in
       )
       cfg.instances;
 
-    systemd.timers = lib.mapAttrs'
+    systemd.timers = mapAttrs'
       (
         name: instance: {
           name = "btrbk-${name}";
@@ -214,7 +239,8 @@ in
           };
         }
       )
-      cfg.instances;
+      (filterAttrs (name: instance: instance.onCalendar != null)
+        cfg.instances);
   };
 
 }
diff --git a/nixos/modules/services/backup/duplicati.nix b/nixos/modules/services/backup/duplicati.nix
index 97864c44691..007396ebfc9 100644
--- a/nixos/modules/services/backup/duplicati.nix
+++ b/nixos/modules/services/backup/duplicati.nix
@@ -8,12 +8,12 @@ in
 {
   options = {
     services.duplicati = {
-      enable = mkEnableOption "Duplicati";
+      enable = mkEnableOption (lib.mdDoc "Duplicati");
 
       port = mkOption {
         default = 8200;
-        type = types.int;
-        description = ''
+        type = types.port;
+        description = lib.mdDoc ''
           Port serving the web interface
         '';
       };
@@ -21,21 +21,21 @@ in
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/duplicati";
-        description = ''
+        description = lib.mdDoc ''
           The directory where Duplicati stores its data files.
 
-          <note><para>
-            If left as the default value this directory will automatically be created
-            before the Duplicati server starts, otherwise you are responsible for ensuring
-            the directory exists with appropriate ownership and permissions.
-          </para></note>
+          ::: {.note}
+          If left as the default value this directory will automatically be created
+          before the Duplicati server starts, otherwise you are responsible for ensuring
+          the directory exists with appropriate ownership and permissions.
+          :::
         '';
       };
 
       interface = mkOption {
         default = "127.0.0.1";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Listening interface for the web UI
           Set it to "any" to listen on all available interfaces
         '';
@@ -44,7 +44,7 @@ in
       user = mkOption {
         default = "duplicati";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Duplicati runs as it's own user. It will only be able to backup world-readable files.
           Run as root with special care.
         '';
diff --git a/nixos/modules/services/backup/duplicity.nix b/nixos/modules/services/backup/duplicity.nix
index 6949fa8b995..05ec997ab66 100644
--- a/nixos/modules/services/backup/duplicity.nix
+++ b/nixos/modules/services/backup/duplicity.nix
@@ -13,12 +13,12 @@ let
 in
 {
   options.services.duplicity = {
-    enable = mkEnableOption "backups with duplicity";
+    enable = mkEnableOption (lib.mdDoc "backups with duplicity");
 
     root = mkOption {
       type = types.path;
       default = "/";
-      description = ''
+      description = lib.mdDoc ''
         Root directory to backup.
       '';
     };
@@ -27,56 +27,51 @@ in
       type = types.listOf types.str;
       default = [ ];
       example = [ "/home" ];
-      description = ''
+      description = lib.mdDoc ''
         List of paths to include into the backups. See the FILE SELECTION
-        section in <citerefentry><refentrytitle>duplicity</refentrytitle>
-        <manvolnum>1</manvolnum></citerefentry> for details on the syntax.
+        section in {manpage}`duplicity(1)` for details on the syntax.
       '';
     };
 
     exclude = mkOption {
       type = types.listOf types.str;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         List of paths to exclude from backups. See the FILE SELECTION section in
-        <citerefentry><refentrytitle>duplicity</refentrytitle>
-        <manvolnum>1</manvolnum></citerefentry> for details on the syntax.
+        {manpage}`duplicity(1)` for details on the syntax.
       '';
     };
 
     targetUrl = mkOption {
       type = types.str;
       example = "s3://host:port/prefix";
-      description = ''
+      description = lib.mdDoc ''
         Target url to backup to. See the URL FORMAT section in
-        <citerefentry><refentrytitle>duplicity</refentrytitle>
-        <manvolnum>1</manvolnum></citerefentry> for supported urls.
+        {manpage}`duplicity(1)` for supported urls.
       '';
     };
 
     secretFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Path of a file containing secrets (gpg passphrase, access key...) in
         the format of EnvironmentFile as described by
-        <citerefentry><refentrytitle>systemd.exec</refentrytitle>
-        <manvolnum>5</manvolnum></citerefentry>. For example:
-        <programlisting>
-        PASSPHRASE=<replaceable>...</replaceable>
-        AWS_ACCESS_KEY_ID=<replaceable>...</replaceable>
-        AWS_SECRET_ACCESS_KEY=<replaceable>...</replaceable>
-        </programlisting>
+        {manpage}`systemd.exec(5)`. For example:
+        ```
+        PASSPHRASE=«...»
+        AWS_ACCESS_KEY_ID=«...»
+        AWS_SECRET_ACCESS_KEY=«...»
+        ```
       '';
     };
 
     frequency = mkOption {
       type = types.nullOr types.str;
       default = "daily";
-      description = ''
+      description = lib.mdDoc ''
         Run duplicity with the given frequency (see
-        <citerefentry><refentrytitle>systemd.time</refentrytitle>
-        <manvolnum>7</manvolnum></citerefentry> for the format).
+        {manpage}`systemd.time(7)` for the format).
         If null, do not run automatically.
       '';
     };
@@ -85,10 +80,9 @@ in
       type = types.listOf types.str;
       default = [ ];
       example = [ "--backend-retry-delay" "100" ];
-      description = ''
+      description = lib.mdDoc ''
         Extra command-line flags passed to duplicity. See
-        <citerefentry><refentrytitle>duplicity</refentrytitle>
-        <manvolnum>1</manvolnum></citerefentry>.
+        {manpage}`duplicity(1)`.
       '';
     };
 
@@ -96,10 +90,10 @@ in
       type = types.str;
       default = "never";
       example = "1M";
-      description = ''
-        If <literal>"never"</literal> (the default) always do incremental
+      description = lib.mdDoc ''
+        If `"never"` (the default) always do incremental
         backups (the first backup will be a full backup, of course).  If
-        <literal>"always"</literal> always do full backups.  Otherwise, this
+        `"always"` always do full backups.  Otherwise, this
         must be a string representing a duration. Full backups will be made
         when the latest full backup is older than this duration. If this is not
         the case, an incremental backup is performed.
@@ -111,7 +105,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "6M";
-        description = ''
+        description = lib.mdDoc ''
           If non-null, delete all backup sets older than the given time.  Old backup sets
           will not be deleted if backup sets newer than time depend on them.
         '';
@@ -120,7 +114,7 @@ in
         type = types.nullOr types.int;
         default = null;
         example = 2;
-        description = ''
+        description = lib.mdDoc ''
           If non-null, delete all backups sets that are older than the count:th last full
           backup (in other words, keep the last count full backups and
           associated incremental sets).
@@ -130,7 +124,7 @@ in
         type = types.nullOr types.int;
         default = null;
         example = 1;
-        description = ''
+        description = lib.mdDoc ''
           If non-null, delete incremental sets of all backups sets that are
           older than the count:th last full backup (in other words, keep only
           old full backups and not their increments).
diff --git a/nixos/modules/services/backup/mysql-backup.nix b/nixos/modules/services/backup/mysql-backup.nix
index c40a0b5abc4..289291c6bd2 100644
--- a/nixos/modules/services/backup/mysql-backup.nix
+++ b/nixos/modules/services/backup/mysql-backup.nix
@@ -37,12 +37,12 @@ in
 
     services.mysqlBackup = {
 
-      enable = mkEnableOption "MySQL backups";
+      enable = mkEnableOption (lib.mdDoc "MySQL backups");
 
       calendar = mkOption {
         type = types.str;
         default = "01:15:00";
-        description = ''
+        description = lib.mdDoc ''
           Configured when to run the backup service systemd unit (DayOfWeek Year-Month-Day Hour:Minute:Second).
         '';
       };
@@ -50,7 +50,7 @@ in
       user = mkOption {
         type = types.str;
         default = defaultUser;
-        description = ''
+        description = lib.mdDoc ''
           User to be used to perform backup.
         '';
       };
@@ -58,7 +58,7 @@ in
       databases = mkOption {
         default = [];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           List of database names to dump.
         '';
       };
@@ -66,7 +66,7 @@ in
       location = mkOption {
         type = types.path;
         default = "/var/backup/mysql";
-        description = ''
+        description = lib.mdDoc ''
           Location to put the gzipped MySQL database dumps.
         '';
       };
@@ -74,7 +74,7 @@ in
       singleTransaction = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to create database dump in a single transaction
         '';
       };
diff --git a/nixos/modules/services/backup/postgresql-backup.nix b/nixos/modules/services/backup/postgresql-backup.nix
index 562458eb457..d3c6f3104fc 100644
--- a/nixos/modules/services/backup/postgresql-backup.nix
+++ b/nixos/modules/services/backup/postgresql-backup.nix
@@ -17,8 +17,8 @@ let
 
       compressCmd = getAttr cfg.compression {
         "none" = "cat";
-        "gzip" = "${pkgs.gzip}/bin/gzip -c";
-        "zstd" = "${pkgs.zstd}/bin/zstd -c";
+        "gzip" = "${pkgs.gzip}/bin/gzip -c -${toString cfg.compressionLevel}";
+        "zstd" = "${pkgs.zstd}/bin/zstd -c -${toString cfg.compressionLevel}";
       };
 
       mkSqlPath = prefix: suffix: "${cfg.location}/${db}${prefix}.sql${suffix}";
@@ -71,13 +71,13 @@ in {
 
   options = {
     services.postgresqlBackup = {
-      enable = mkEnableOption "PostgreSQL dumps";
+      enable = mkEnableOption (lib.mdDoc "PostgreSQL dumps");
 
       startAt = mkOption {
         default = "*-*-* 01:15:00";
         type = with types; either (listOf str) str;
-        description = ''
-          This option defines (see <literal>systemd.time</literal> for format) when the
+        description = lib.mdDoc ''
+          This option defines (see `systemd.time` for format) when the
           databases should be dumped.
           The default is to update at 01:15 (at night) every day.
         '';
@@ -87,10 +87,10 @@ in {
         default = cfg.databases == [];
         defaultText = literalExpression "services.postgresqlBackup.databases == []";
         type = lib.types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Backup all databases using pg_dumpall.
           This option is mutual exclusive to
-          <literal>services.postgresqlBackup.databases</literal>.
+          `services.postgresqlBackup.databases`.
           The resulting backup dump will have the name all.sql.gz.
           This option is the default if no databases are specified.
         '';
@@ -99,7 +99,7 @@ in {
       databases = mkOption {
         default = [];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           List of database names to dump.
         '';
       };
@@ -107,7 +107,7 @@ in {
       location = mkOption {
         default = "/var/backup/postgresql";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path of directory where the PostgreSQL database dumps will be placed.
         '';
       };
@@ -115,9 +115,9 @@ in {
       pgdumpOptions = mkOption {
         type = types.separatedString " ";
         default = "-C";
-        description = ''
+        description = lib.mdDoc ''
           Command line options for pg_dump. This options is not used
-          if <literal>config.services.postgresqlBackup.backupAll</literal> is enabled.
+          if `config.services.postgresqlBackup.backupAll` is enabled.
           Note that config.services.postgresqlBackup.backupAll is also active,
           when no databases where specified.
         '';
@@ -126,20 +126,37 @@ in {
       compression = mkOption {
         type = types.enum ["none" "gzip" "zstd"];
         default = "gzip";
-        description = ''
+        description = lib.mdDoc ''
           The type of compression to use on the generated database dump.
         '';
       };
+
+      compressionLevel = mkOption {
+        type = types.ints.between 1 19;
+        default = 6;
+        description = lib.mdDoc ''
+          The compression level used when compression is enabled.
+          gzip accepts levels 1 to 9. zstd accepts levels 1 to 19.
+        '';
+      };
     };
 
   };
 
   config = mkMerge [
     {
-      assertions = [{
-        assertion = cfg.backupAll -> cfg.databases == [];
-        message = "config.services.postgresqlBackup.backupAll cannot be used together with config.services.postgresqlBackup.databases";
-      }];
+      assertions = [
+        {
+          assertion = cfg.backupAll -> cfg.databases == [];
+          message = "config.services.postgresqlBackup.backupAll cannot be used together with config.services.postgresqlBackup.databases";
+        }
+        {
+          assertion = cfg.compression == "none" ||
+            (cfg.compression == "gzip" && cfg.compressionLevel >= 1 && cfg.compressionLevel <= 9) ||
+            (cfg.compression == "zstd" && cfg.compressionLevel >= 1 && cfg.compressionLevel <= 19);
+          message = "config.services.postgresqlBackup.compressionLevel must be set between 1 and 9 for gzip and 1 and 19 for zstd";
+        }
+      ];
     }
     (mkIf cfg.enable {
       systemd.tmpfiles.rules = [
diff --git a/nixos/modules/services/backup/postgresql-wal-receiver.nix b/nixos/modules/services/backup/postgresql-wal-receiver.nix
index 32643adfdae..01fd57f5c50 100644
--- a/nixos/modules/services/backup/postgresql-wal-receiver.nix
+++ b/nixos/modules/services/backup/postgresql-wal-receiver.nix
@@ -8,7 +8,7 @@ let
       postgresqlPackage = mkOption {
         type = types.package;
         example = literalExpression "pkgs.postgresql_11";
-        description = ''
+        description = lib.mdDoc ''
           PostgreSQL package to use.
         '';
       };
@@ -16,7 +16,7 @@ let
       directory = mkOption {
         type = types.path;
         example = literalExpression "/mnt/pg_wal/main/";
-        description = ''
+        description = lib.mdDoc ''
           Directory to write the output to.
         '';
       };
@@ -24,7 +24,7 @@ let
       statusInterval = mkOption {
         type = types.int;
         default = 10;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the number of seconds between status packets sent back to the server.
           This allows for easier monitoring of the progress from server.
           A value of zero disables the periodic status updates completely,
@@ -36,27 +36,27 @@ let
         type = types.str;
         default = "";
         example = "some_slot_name";
-        description = ''
-          Require <command>pg_receivewal</command> to use an existing replication slot (see
-          <link xlink:href="https://www.postgresql.org/docs/current/warm-standby.html#STREAMING-REPLICATION-SLOTS">Section 26.2.6 of the PostgreSQL manual</link>).
-          When this option is used, <command>pg_receivewal</command> will report a flush position to the server,
+        description = lib.mdDoc ''
+          Require {command}`pg_receivewal` to use an existing replication slot (see
+          [Section 26.2.6 of the PostgreSQL manual](https://www.postgresql.org/docs/current/warm-standby.html#STREAMING-REPLICATION-SLOTS)).
+          When this option is used, {command}`pg_receivewal` will report a flush position to the server,
           indicating when each segment has been synchronized to disk so that the server can remove that segment if it is not otherwise needed.
 
-          When the replication client of <command>pg_receivewal</command> is configured on the server as a synchronous standby,
+          When the replication client of {command}`pg_receivewal` is configured on the server as a synchronous standby,
           then using a replication slot will report the flush position to the server, but only when a WAL file is closed.
           Therefore, that configuration will cause transactions on the primary to wait for a long time and effectively not work satisfactorily.
-          The option <option>synchronous</option> must be specified in addition to make this work correctly.
+          The option {option}`synchronous` must be specified in addition to make this work correctly.
         '';
       };
 
       synchronous = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Flush the WAL data to disk immediately after it has been received.
-          Also send a status packet back to the server immediately after flushing, regardless of <option>statusInterval</option>.
+          Also send a status packet back to the server immediately after flushing, regardless of {option}`statusInterval`.
 
-          This option should be specified if the replication client of <command>pg_receivewal</command> is configured on the server as a synchronous standby,
+          This option should be specified if the replication client of {command}`pg_receivewal` is configured on the server as a synchronous standby,
           to ensure that timely feedback is sent to the server.
         '';
       };
@@ -64,10 +64,10 @@ let
       compress = mkOption {
         type = types.ints.between 0 9;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Enables gzip compression of write-ahead logs, and specifies the compression level
-          (<literal>0</literal> through <literal>9</literal>, <literal>0</literal> being no compression and <literal>9</literal> being best compression).
-          The suffix <literal>.gz</literal> will automatically be added to all filenames.
+          (`0` through `9`, `0` being no compression and `9` being best compression).
+          The suffix `.gz` will automatically be added to all filenames.
 
           This option requires PostgreSQL >= 10.
         '';
@@ -76,11 +76,11 @@ let
       connection = mkOption {
         type = types.str;
         example = "postgresql://user@somehost";
-        description = ''
+        description = lib.mdDoc ''
           Specifies parameters used to connect to the server, as a connection string.
-          See <link xlink:href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING">Section 34.1.1 of the PostgreSQL manual</link> for more information.
+          See [Section 34.1.1 of the PostgreSQL manual](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) for more information.
 
-          Because <command>pg_receivewal</command> doesn't connect to any particular database in the cluster,
+          Because {command}`pg_receivewal` doesn't connect to any particular database in the cluster,
           database name in the connection string will be ignored.
         '';
       };
@@ -93,8 +93,8 @@ let
             "--no-sync"
           ]
         '';
-        description = ''
-          A list of extra arguments to pass to the <command>pg_receivewal</command> command.
+        description = lib.mdDoc ''
+          A list of extra arguments to pass to the {command}`pg_receivewal` command.
         '';
       };
 
@@ -107,9 +107,9 @@ let
             PGSSLMODE = "require";
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Environment variables passed to the service.
-          Usable parameters are listed in <link xlink:href="https://www.postgresql.org/docs/current/libpq-envars.html">Section 34.14 of the PostgreSQL manual</link>.
+          Usable parameters are listed in [Section 34.14 of the PostgreSQL manual](https://www.postgresql.org/docs/current/libpq-envars.html).
         '';
       };
     };
@@ -131,10 +131,10 @@ in {
             };
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           PostgreSQL WAL receivers.
-          Stream write-ahead logs from a PostgreSQL server using <command>pg_receivewal</command> (formerly <command>pg_receivexlog</command>).
-          See <link xlink:href="https://www.postgresql.org/docs/current/app-pgreceivewal.html">the man page</link> for more information.
+          Stream write-ahead logs from a PostgreSQL server using {command}`pg_receivewal` (formerly {command}`pg_receivexlog`).
+          See [the man page](https://www.postgresql.org/docs/current/app-pgreceivewal.html) for more information.
         '';
       };
     };
diff --git a/nixos/modules/services/backup/restic-rest-server.nix b/nixos/modules/services/backup/restic-rest-server.nix
index 4717119f178..37a6150c99d 100644
--- a/nixos/modules/services/backup/restic-rest-server.nix
+++ b/nixos/modules/services/backup/restic-rest-server.nix
@@ -9,25 +9,25 @@ in
   meta.maintainers = [ maintainers.bachp ];
 
   options.services.restic.server = {
-    enable = mkEnableOption "Restic REST Server";
+    enable = mkEnableOption (lib.mdDoc "Restic REST Server");
 
     listenAddress = mkOption {
       default = ":8000";
       example = "127.0.0.1:8080";
       type = types.str;
-      description = "Listen on a specific IP address and port.";
+      description = lib.mdDoc "Listen on a specific IP address and port.";
     };
 
     dataDir = mkOption {
       default = "/var/lib/restic";
       type = types.path;
-      description = "The directory for storing the restic repository.";
+      description = lib.mdDoc "The directory for storing the restic repository.";
     };
 
     appendOnly = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Enable append only mode.
         This mode allows creation of new backups but prevents deletion and modification of existing backups.
         This can be useful when backing up systems that have a potential of being hacked.
@@ -37,7 +37,7 @@ in
     privateRepos = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Enable private repos.
         Grants access only when a subdirectory with the same name as the user is specified in the repository URL.
       '';
@@ -46,13 +46,13 @@ in
     prometheus = mkOption {
       default = false;
       type = types.bool;
-      description = "Enable Prometheus metrics at /metrics.";
+      description = lib.mdDoc "Enable Prometheus metrics at /metrics.";
     };
 
     extraFlags = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Extra commandline options to pass to Restic REST server.
       '';
     };
@@ -61,7 +61,7 @@ in
       default = pkgs.restic-rest-server;
       defaultText = literalExpression "pkgs.restic-rest-server";
       type = types.package;
-      description = "Restic REST server package to use.";
+      description = lib.mdDoc "Restic REST server package to use.";
     };
   };
 
diff --git a/nixos/modules/services/backup/restic.nix b/nixos/modules/services/backup/restic.nix
index 8ff8e31864b..869ed5d9976 100644
--- a/nixos/modules/services/backup/restic.nix
+++ b/nixos/modules/services/backup/restic.nix
@@ -8,14 +8,14 @@ let
 in
 {
   options.services.restic.backups = mkOption {
-    description = ''
+    description = lib.mdDoc ''
       Periodic backups to create with Restic.
     '';
     type = types.attrsOf (types.submodule ({ config, name, ... }: {
       options = {
         passwordFile = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             Read the repository password from a file.
           '';
           example = "/etc/nixos/restic-password";
@@ -26,7 +26,7 @@ in
           # added on 2021-08-28, s3CredentialsFile should
           # be removed in the future (+ remember the warning)
           default = config.s3CredentialsFile;
-          description = ''
+          description = lib.mdDoc ''
             file containing the credentials to access the repository, in the
             format of an EnvironmentFile as described by systemd.exec(5)
           '';
@@ -35,7 +35,7 @@ in
         s3CredentialsFile = mkOption {
           type = with types; nullOr str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             file containing the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
             for an S3-hosted repository, in the format of an EnvironmentFile
             as described by systemd.exec(5)
@@ -45,13 +45,13 @@ in
         rcloneOptions = mkOption {
           type = with types; nullOr (attrsOf (oneOf [ str bool ]));
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Options to pass to rclone to control its behavior.
-            See <link xlink:href="https://rclone.org/docs/#options"/> for
+            See <https://rclone.org/docs/#options> for
             available options. When specifying option names, strip the
-            leading <literal>--</literal>. To set a flag such as
-            <literal>--drive-use-trash</literal>, which does not take a value,
-            set the value to the Boolean <literal>true</literal>.
+            leading `--`. To set a flag such as
+            `--drive-use-trash`, which does not take a value,
+            set the value to the Boolean `true`.
           '';
           example = {
             bwlimit = "10M";
@@ -62,16 +62,16 @@ in
         rcloneConfig = mkOption {
           type = with types; nullOr (attrsOf (oneOf [ str bool ]));
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Configuration for the rclone remote being used for backup.
             See the remote's specific options under rclone's docs at
-            <link xlink:href="https://rclone.org/docs/"/>. When specifying
+            <https://rclone.org/docs/>. When specifying
             option names, use the "config" name specified in the docs.
-            For example, to set <literal>--b2-hard-delete</literal> for a B2
-            remote, use <literal>hard_delete = true</literal> in the
+            For example, to set `--b2-hard-delete` for a B2
+            remote, use `hard_delete = true` in the
             attribute set.
             Warning: Secrets set in here will be world-readable in the Nix
-            store! Consider using the <literal>rcloneConfigFile</literal>
+            store! Consider using the `rcloneConfigFile`
             option instead to specify secret values separately. Note that
             options set here will override those set in the config file.
           '';
@@ -86,27 +86,36 @@ in
         rcloneConfigFile = mkOption {
           type = with types; nullOr path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Path to the file containing rclone configuration. This file
             must contain configuration for the remote specified in this backup
             set and also must be readable by root. Options set in
-            <literal>rcloneConfig</literal> will override those set in this
+            `rcloneConfig` will override those set in this
             file.
           '';
         };
 
         repository = mkOption {
-          type = types.str;
-          description = ''
+          type = with types; nullOr str;
+          default = null;
+          description = lib.mdDoc ''
             repository to backup to.
           '';
           example = "sftp:backup@192.168.1.100:/backups/${name}";
         };
 
+        repositoryFile = mkOption {
+          type = with types; nullOr path;
+          default = null;
+          description = lib.mdDoc ''
+            Path to the file containing the repository location to backup to.
+          '';
+        };
+
         paths = mkOption {
           type = types.nullOr (types.listOf types.str);
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Which paths to backup.  If null or an empty array, no
             backup command will be run.  This can be used to create a
             prune-only job.
@@ -122,7 +131,7 @@ in
           default = {
             OnCalendar = "daily";
           };
-          description = ''
+          description = lib.mdDoc ''
             When to run the backup. See man systemd.timer for details.
           '';
           example = {
@@ -134,7 +143,7 @@ in
         user = mkOption {
           type = types.str;
           default = "root";
-          description = ''
+          description = lib.mdDoc ''
             As which user the backup should run.
           '';
           example = "postgresql";
@@ -142,8 +151,8 @@ in
 
         extraBackupArgs = mkOption {
           type = types.listOf types.str;
-          default = [];
-          description = ''
+          default = [ ];
+          description = lib.mdDoc ''
             Extra arguments passed to restic backup.
           '';
           example = [
@@ -153,8 +162,8 @@ in
 
         extraOptions = mkOption {
           type = types.listOf types.str;
-          default = [];
-          description = ''
+          default = [ ];
+          description = lib.mdDoc ''
             Extra extended options to be passed to the restic --option flag.
           '';
           example = [
@@ -165,19 +174,19 @@ in
         initialize = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Create the repository if it doesn't exist.
           '';
         };
 
         pruneOpts = mkOption {
           type = types.listOf types.str;
-          default = [];
-          description = ''
-            A list of options (--keep-* et al.) for 'restic forget
+          default = [ ];
+          description = lib.mdDoc ''
+            A list of options (--keep-\* et al.) for 'restic forget
             --prune', to automatically prune old snapshots.  The
             'forget' command is run *after* the 'backup' command, so
-            keep that in mind when constructing the --keep-* options.
+            keep that in mind when constructing the --keep-\* options.
           '';
           example = [
             "--keep-daily 7"
@@ -187,19 +196,56 @@ in
           ];
         };
 
+        checkOpts = mkOption {
+          type = types.listOf types.str;
+          default = [ ];
+          description = lib.mdDoc ''
+            A list of options for 'restic check', which is run after
+            pruning.
+          '';
+          example = [
+            "--with-cache"
+          ];
+        };
+
         dynamicFilesFrom = mkOption {
           type = with types; nullOr str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             A script that produces a list of files to back up.  The
             results of this command are given to the '--files-from'
             option.
           '';
           example = "find /home/matt/git -type d -name .git";
         };
+
+        backupPrepareCommand = mkOption {
+          type = with types; nullOr str;
+          default = null;
+          description = lib.mdDoc ''
+            A script that must run before starting the backup process.
+          '';
+        };
+
+        backupCleanupCommand = mkOption {
+          type = with types; nullOr str;
+          default = null;
+          description = lib.mdDoc ''
+            A script that must run after finishing the backup process.
+          '';
+        };
+
+        package = mkOption {
+          type = types.package;
+          default = pkgs.restic;
+          defaultText = literalExpression "pkgs.restic";
+          description = lib.mdDoc ''
+            Restic package to use.
+          '';
+        };
       };
     }));
-    default = {};
+    default = { };
     example = {
       localbackup = {
         paths = [ "/home" ];
@@ -225,66 +271,85 @@ in
   config = {
     warnings = mapAttrsToList (n: v: "services.restic.backups.${n}.s3CredentialsFile is deprecated, please use services.restic.backups.${n}.environmentFile instead.") (filterAttrs (n: v: v.s3CredentialsFile != null) config.services.restic.backups);
     systemd.services =
-      mapAttrs' (name: backup:
-        let
-          extraOptions = concatMapStrings (arg: " -o ${arg}") backup.extraOptions;
-          resticCmd = "${pkgs.restic}/bin/restic${extraOptions}";
-          filesFromTmpFile = "/run/restic-backups-${name}/includes";
-          backupPaths = if (backup.dynamicFilesFrom == null)
-                        then if (backup.paths != null) then concatStringsSep " " backup.paths else ""
-                        else "--files-from ${filesFromTmpFile}";
-          pruneCmd = optionals (builtins.length backup.pruneOpts > 0) [
-            ( resticCmd + " forget --prune " + (concatStringsSep " " backup.pruneOpts) )
-            ( resticCmd + " check" )
-          ];
-          # Helper functions for rclone remotes
-          rcloneRemoteName = builtins.elemAt (splitString ":" backup.repository) 1;
-          rcloneAttrToOpt = v: "RCLONE_" + toUpper (builtins.replaceStrings [ "-" ] [ "_" ] v);
-          rcloneAttrToConf = v: "RCLONE_CONFIG_" + toUpper (rcloneRemoteName + "_" + v);
-          toRcloneVal = v: if lib.isBool v then lib.boolToString v else v;
-        in nameValuePair "restic-backups-${name}" ({
-          environment = {
-            RESTIC_PASSWORD_FILE = backup.passwordFile;
-            RESTIC_REPOSITORY = backup.repository;
-          } // optionalAttrs (backup.rcloneOptions != null) (mapAttrs' (name: value:
-            nameValuePair (rcloneAttrToOpt name) (toRcloneVal value)
-          ) backup.rcloneOptions) // optionalAttrs (backup.rcloneConfigFile != null) {
-            RCLONE_CONFIG = backup.rcloneConfigFile;
-          } // optionalAttrs (backup.rcloneConfig != null) (mapAttrs' (name: value:
-            nameValuePair (rcloneAttrToConf name) (toRcloneVal value)
-          ) backup.rcloneConfig);
-          path = [ pkgs.openssh ];
-          restartIfChanged = false;
-          serviceConfig = {
-            Type = "oneshot";
-            ExecStart = (optionals (backupPaths != "") [ "${resticCmd} backup --cache-dir=%C/restic-backups-${name} ${concatStringsSep " " backup.extraBackupArgs} ${backupPaths}" ])
-                        ++ pruneCmd;
-            User = backup.user;
-            RuntimeDirectory = "restic-backups-${name}";
-            CacheDirectory = "restic-backups-${name}";
-            CacheDirectoryMode = "0700";
-          } // optionalAttrs (backup.environmentFile != null) {
-            EnvironmentFile = backup.environmentFile;
-          };
-        } // optionalAttrs (backup.initialize || backup.dynamicFilesFrom != null) {
-          preStart = ''
-            ${optionalString (backup.initialize) ''
-              ${resticCmd} snapshots || ${resticCmd} init
-            ''}
-            ${optionalString (backup.dynamicFilesFrom != null) ''
-              ${pkgs.writeScript "dynamicFilesFromScript" backup.dynamicFilesFrom} > ${filesFromTmpFile}
-            ''}
-          '';
-        } // optionalAttrs (backup.dynamicFilesFrom != null) {
-          postStart = ''
-            rm ${filesFromTmpFile}
-          '';
-        })
-      ) config.services.restic.backups;
+      mapAttrs'
+        (name: backup:
+          let
+            extraOptions = concatMapStrings (arg: " -o ${arg}") backup.extraOptions;
+            resticCmd = "${backup.package}/bin/restic${extraOptions}";
+            filesFromTmpFile = "/run/restic-backups-${name}/includes";
+            backupPaths =
+              if (backup.dynamicFilesFrom == null)
+              then if (backup.paths != null) then concatStringsSep " " backup.paths else ""
+              else "--files-from ${filesFromTmpFile}";
+            pruneCmd = optionals (builtins.length backup.pruneOpts > 0) [
+              (resticCmd + " forget --prune --cache-dir=%C/restic-backups-${name} " + (concatStringsSep " " backup.pruneOpts))
+              (resticCmd + " check --cache-dir=%C/restic-backups-${name} " + (concatStringsSep " " backup.checkOpts))
+            ];
+            # Helper functions for rclone remotes
+            rcloneRemoteName = builtins.elemAt (splitString ":" backup.repository) 1;
+            rcloneAttrToOpt = v: "RCLONE_" + toUpper (builtins.replaceStrings [ "-" ] [ "_" ] v);
+            rcloneAttrToConf = v: "RCLONE_CONFIG_" + toUpper (rcloneRemoteName + "_" + v);
+            toRcloneVal = v: if lib.isBool v then lib.boolToString v else v;
+          in
+          nameValuePair "restic-backups-${name}" ({
+            environment = {
+              RESTIC_PASSWORD_FILE = backup.passwordFile;
+              RESTIC_REPOSITORY = backup.repository;
+              RESTIC_REPOSITORY_FILE = backup.repositoryFile;
+            } // optionalAttrs (backup.rcloneOptions != null) (mapAttrs'
+              (name: value:
+                nameValuePair (rcloneAttrToOpt name) (toRcloneVal value)
+              )
+              backup.rcloneOptions) // optionalAttrs (backup.rcloneConfigFile != null) {
+              RCLONE_CONFIG = backup.rcloneConfigFile;
+            } // optionalAttrs (backup.rcloneConfig != null) (mapAttrs'
+              (name: value:
+                nameValuePair (rcloneAttrToConf name) (toRcloneVal value)
+              )
+              backup.rcloneConfig);
+            path = [ pkgs.openssh ];
+            restartIfChanged = false;
+            serviceConfig = {
+              Type = "oneshot";
+              ExecStart = (optionals (backupPaths != "") [ "${resticCmd} backup --cache-dir=%C/restic-backups-${name} ${concatStringsSep " " backup.extraBackupArgs} ${backupPaths}" ])
+                ++ pruneCmd;
+              User = backup.user;
+              RuntimeDirectory = "restic-backups-${name}";
+              CacheDirectory = "restic-backups-${name}";
+              CacheDirectoryMode = "0700";
+            } // optionalAttrs (backup.environmentFile != null) {
+              EnvironmentFile = backup.environmentFile;
+            };
+          } // optionalAttrs (backup.initialize || backup.dynamicFilesFrom != null || backup.backupPrepareCommand != null) {
+            preStart = ''
+              ${optionalString (backup.backupPrepareCommand != null) ''
+                ${pkgs.writeScript "backupPrepareCommand" backup.backupPrepareCommand}
+              ''}
+              ${optionalString (backup.initialize) ''
+                ${resticCmd} snapshots || ${resticCmd} init
+              ''}
+              ${optionalString (backup.dynamicFilesFrom != null) ''
+                ${pkgs.writeScript "dynamicFilesFromScript" backup.dynamicFilesFrom} > ${filesFromTmpFile}
+              ''}
+            '';
+          } // optionalAttrs (backup.dynamicFilesFrom != null || backup.backupCleanupCommand != null) {
+            postStop = ''
+              ${optionalString (backup.backupCleanupCommand != null) ''
+                ${pkgs.writeScript "backupCleanupCommand" backup.backupCleanupCommand}
+              ''}
+              ${optionalString (backup.dynamicFilesFrom != null) ''
+                rm ${filesFromTmpFile}
+              ''}
+            '';
+          })
+        )
+        config.services.restic.backups;
     systemd.timers =
-      mapAttrs' (name: backup: nameValuePair "restic-backups-${name}" {
-        wantedBy = [ "timers.target" ];
-        timerConfig = backup.timerConfig;
-      }) config.services.restic.backups;
+      mapAttrs'
+        (name: backup: nameValuePair "restic-backups-${name}" {
+          wantedBy = [ "timers.target" ];
+          timerConfig = backup.timerConfig;
+        })
+        config.services.restic.backups;
   };
 }
diff --git a/nixos/modules/services/backup/rsnapshot.nix b/nixos/modules/services/backup/rsnapshot.nix
index 6635a51ec2c..0b9bb60af0e 100644
--- a/nixos/modules/services/backup/rsnapshot.nix
+++ b/nixos/modules/services/backup/rsnapshot.nix
@@ -22,9 +22,9 @@ in
 {
   options = {
     services.rsnapshot = {
-      enable = mkEnableOption "rsnapshot backups";
+      enable = mkEnableOption (lib.mdDoc "rsnapshot backups");
       enableManualRsnapshot = mkOption {
-        description = "Whether to enable manual usage of the rsnapshot command with this module.";
+        description = lib.mdDoc "Whether to enable manual usage of the rsnapshot command with this module.";
         default = true;
         type = types.bool;
       };
@@ -37,7 +37,7 @@ in
           backup	/home/	localhost/
         '';
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           rsnapshot configuration option in addition to the defaults from
           rsnapshot and this module.
 
@@ -53,7 +53,7 @@ in
         default = {};
         example = { hourly = "0 * * * *"; daily = "50 21 * * *"; };
         type = types.attrsOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Periodicity at which intervals should be run by cron.
           Note that the intervals also have to exist in configuration
           as retain options.
diff --git a/nixos/modules/services/backup/sanoid.nix b/nixos/modules/services/backup/sanoid.nix
index 5eb031b2e9f..a51708170fb 100644
--- a/nixos/modules/services/backup/sanoid.nix
+++ b/nixos/modules/services/backup/sanoid.nix
@@ -12,37 +12,37 @@ let
 
   commonOptions = {
     hourly = mkOption {
-      description = "Number of hourly snapshots.";
+      description = lib.mdDoc "Number of hourly snapshots.";
       type = with types; nullOr ints.unsigned;
       default = null;
     };
 
     daily = mkOption {
-      description = "Number of daily snapshots.";
+      description = lib.mdDoc "Number of daily snapshots.";
       type = with types; nullOr ints.unsigned;
       default = null;
     };
 
     monthly = mkOption {
-      description = "Number of monthly snapshots.";
+      description = lib.mdDoc "Number of monthly snapshots.";
       type = with types; nullOr ints.unsigned;
       default = null;
     };
 
     yearly = mkOption {
-      description = "Number of yearly snapshots.";
+      description = lib.mdDoc "Number of yearly snapshots.";
       type = with types; nullOr ints.unsigned;
       default = null;
     };
 
     autoprune = mkOption {
-      description = "Whether to automatically prune old snapshots.";
+      description = lib.mdDoc "Whether to automatically prune old snapshots.";
       type = with types; nullOr bool;
       default = null;
     };
 
     autosnap = mkOption {
-      description = "Whether to automatically take snapshots.";
+      description = lib.mdDoc "Whether to automatically take snapshots.";
       type = with types; nullOr bool;
       default = null;
     };
@@ -50,7 +50,7 @@ let
 
   datasetOptions = rec {
     use_template = mkOption {
-      description = "Names of the templates to use for this dataset.";
+      description = lib.mdDoc "Names of the templates to use for this dataset.";
       type = types.listOf (types.str // {
         check = (types.enum (attrNames cfg.templates)).check;
         description = "configured template name";
@@ -60,9 +60,9 @@ let
     useTemplate = use_template;
 
     recursive = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Whether to recursively snapshot dataset children.
-        You can also set this to <literal>"zfs"</literal> to handle datasets
+        You can also set this to `"zfs"` to handle datasets
         recursively in an atomic way without the possibility to
         override settings for child datasets.
       '';
@@ -71,7 +71,7 @@ let
     };
 
     process_children_only = mkOption {
-      description = "Whether to only snapshot child datasets if recursing.";
+      description = lib.mdDoc "Whether to only snapshot child datasets if recursing.";
       type = types.bool;
       default = false;
     };
@@ -112,18 +112,17 @@ in
   # Interface
 
   options.services.sanoid = {
-    enable = mkEnableOption "Sanoid ZFS snapshotting service";
+    enable = mkEnableOption (lib.mdDoc "Sanoid ZFS snapshotting service");
 
     interval = mkOption {
       type = types.str;
       default = "hourly";
       example = "daily";
-      description = ''
+      description = lib.mdDoc ''
         Run sanoid at this interval. The default is to run hourly.
 
         The format is described in
-        <citerefentry><refentrytitle>systemd.time</refentrytitle>
-        <manvolnum>7</manvolnum></citerefentry>.
+        {manpage}`systemd.time(7)`.
       '';
     };
 
@@ -131,11 +130,11 @@ in
       type = types.attrsOf (types.submodule ({ config, options, ... }: {
         freeformType = datasetSettingsType;
         options = commonOptions // datasetOptions;
-        config.use_template = mkAliasDefinitions (mkDefault options.useTemplate or { });
-        config.process_children_only = mkAliasDefinitions (mkDefault options.processChildrenOnly or { });
+        config.use_template = modules.mkAliasAndWrapDefsWithPriority id (options.useTemplate or { });
+        config.process_children_only = modules.mkAliasAndWrapDefsWithPriority id (options.processChildrenOnly or { });
       }));
       default = { };
-      description = "Datasets to snapshot.";
+      description = lib.mdDoc "Datasets to snapshot.";
     };
 
     templates = mkOption {
@@ -144,14 +143,14 @@ in
         options = commonOptions;
       });
       default = { };
-      description = "Templates for datasets.";
+      description = lib.mdDoc "Templates for datasets.";
     };
 
     settings = mkOption {
       type = types.attrsOf datasetSettingsType;
-      description = ''
+      description = lib.mdDoc ''
         Free-form settings written directly to the config file. See
-        <link xlink:href="https://github.com/jimsalterjrs/sanoid/blob/master/sanoid.defaults.conf"/>
+        <https://github.com/jimsalterjrs/sanoid/blob/master/sanoid.defaults.conf>
         for allowed values.
       '';
     };
@@ -160,9 +159,9 @@ in
       type = types.listOf types.str;
       default = [ ];
       example = [ "--verbose" "--readonly" "--debug" ];
-      description = ''
+      description = lib.mdDoc ''
         Extra arguments to pass to sanoid. See
-        <link xlink:href="https://github.com/jimsalterjrs/sanoid/#sanoid-command-line-options"/>
+        <https://github.com/jimsalterjrs/sanoid/#sanoid-command-line-options>
         for allowed options.
       '';
     };
diff --git a/nixos/modules/services/backup/syncoid.nix b/nixos/modules/services/backup/syncoid.nix
index 4df10f5ee02..6188f109463 100644
--- a/nixos/modules/services/backup/syncoid.nix
+++ b/nixos/modules/services/backup/syncoid.nix
@@ -16,11 +16,11 @@ let
     lib.concatMapStrings (s: if lib.isList s then "-" else s)
       (builtins.split "[^a-zA-Z0-9_.\\-]+" name);
 
-  # Function to build "zfs allow" commands for the filesystems we've
-  # delegated permissions to. It also checks if the target dataset
-  # exists before delegating permissions, if it doesn't exist we
-  # delegate it to the parent dataset. This should solve the case of
-  # provisoning new datasets.
+  # Function to build "zfs allow" commands for the filesystems we've delegated
+  # permissions to. It also checks if the target dataset exists before
+  # delegating permissions, if it doesn't exist we delegate it to the parent
+  # dataset (if it exists). This should solve the case of provisoning new
+  # datasets.
   buildAllowCommand = permissions: dataset: (
     "-+${pkgs.writeShellScript "zfs-allow-${dataset}" ''
       # Here we explicitly use the booted system to guarantee the stable API needed by ZFS
@@ -38,15 +38,17 @@ let
           (concatStringsSep "," permissions)
           dataset
         ]}
-      else
-        ${lib.escapeShellArgs [
-          "/run/booted-system/sw/bin/zfs"
-          "allow"
-          cfg.user
-          (concatStringsSep "," permissions)
-          # Remove the last part of the path
-          (builtins.dirOf dataset)
-        ]}
+      ${lib.optionalString ((builtins.dirOf dataset) != ".") ''
+        else
+          ${lib.escapeShellArgs [
+            "/run/booted-system/sw/bin/zfs"
+            "allow"
+            cfg.user
+            (concatStringsSep "," permissions)
+            # Remove the last part of the path
+            (builtins.dirOf dataset)
+          ]}
+      ''}
       fi
     ''}"
   );
@@ -67,14 +69,14 @@ let
         (concatStringsSep "," permissions)
         dataset
       ]}
-      ${lib.escapeShellArgs [
+      ${lib.optionalString ((builtins.dirOf dataset) != ".") (lib.escapeShellArgs [
         "/run/booted-system/sw/bin/zfs"
         "unallow"
         cfg.user
         (concatStringsSep "," permissions)
         # Remove the last part of the path
         (builtins.dirOf dataset)
-      ]}
+      ])}
     ''}"
   );
 in
@@ -83,18 +85,17 @@ in
   # Interface
 
   options.services.syncoid = {
-    enable = mkEnableOption "Syncoid ZFS synchronization service";
+    enable = mkEnableOption (lib.mdDoc "Syncoid ZFS synchronization service");
 
     interval = mkOption {
       type = types.str;
       default = "hourly";
       example = "*-*-* *:15:00";
-      description = ''
+      description = lib.mdDoc ''
         Run syncoid at this interval. The default is to run hourly.
 
         The format is described in
-        <citerefentry><refentrytitle>systemd.time</refentrytitle>
-        <manvolnum>7</manvolnum></citerefentry>.
+        {manpage}`systemd.time(7)`.
       '';
     };
 
@@ -102,7 +103,7 @@ in
       type = types.str;
       default = "syncoid";
       example = "backup";
-      description = ''
+      description = lib.mdDoc ''
         The user for the service. ZFS privilege delegation will be
         automatically configured for any local pools used by syncoid if this
         option is set to a user other than root. The user will be given the
@@ -116,7 +117,7 @@ in
       type = types.str;
       default = "syncoid";
       example = "backup";
-      description = "The group for the service.";
+      description = lib.mdDoc "The group for the service.";
     };
 
     sshKey = mkOption {
@@ -124,7 +125,7 @@ in
       # Prevent key from being copied to store
       apply = mapNullable toString;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         SSH private key file to use to login to the remote system. Can be
         overridden in individual commands.
       '';
@@ -134,10 +135,10 @@ in
       type = types.listOf types.str;
       # Permissions snapshot and destroy are in case --no-sync-snap is not used
       default = [ "bookmark" "hold" "send" "snapshot" "destroy" ];
-      description = ''
-        Permissions granted for the <option>services.syncoid.user</option> user
+      description = lib.mdDoc ''
+        Permissions granted for the {option}`services.syncoid.user` user
         for local source datasets. See
-        <link xlink:href="https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html"/>
+        <https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html>
         for available permissions.
       '';
     };
@@ -146,13 +147,13 @@ in
       type = types.listOf types.str;
       default = [ "change-key" "compression" "create" "mount" "mountpoint" "receive" "rollback" ];
       example = [ "create" "mount" "receive" "rollback" ];
-      description = ''
-        Permissions granted for the <option>services.syncoid.user</option> user
+      description = lib.mdDoc ''
+        Permissions granted for the {option}`services.syncoid.user` user
         for local target datasets. See
-        <link xlink:href="https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html"/>
+        <https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html>
         for available permissions.
-        Make sure to include the <literal>change-key</literal> permission if you send raw encrypted datasets,
-        the <literal>compression</literal> permission if you send raw compressed datasets, and so on.
+        Make sure to include the `change-key` permission if you send raw encrypted datasets,
+        the `compression` permission if you send raw compressed datasets, and so on.
         For remote target datasets you'll have to set your remote user permissions by yourself.
       '';
     };
@@ -161,10 +162,10 @@ in
       type = types.listOf types.str;
       default = [ ];
       example = [ "--no-sync-snap" ];
-      description = ''
+      description = lib.mdDoc ''
         Arguments to add to every syncoid command, unless disabled for that
         command. See
-        <link xlink:href="https://github.com/jimsalterjrs/sanoid/#syncoid-command-line-options"/>
+        <https://github.com/jimsalterjrs/sanoid/#syncoid-command-line-options>
         for available options.
       '';
     };
@@ -172,7 +173,7 @@ in
     service = mkOption {
       type = types.attrs;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Systemd configuration common to all syncoid services.
       '';
     };
@@ -183,7 +184,7 @@ in
           source = mkOption {
             type = types.str;
             example = "pool/dataset";
-            description = ''
+            description = lib.mdDoc ''
               Source ZFS dataset. Can be either local or remote. Defaults to
               the attribute name.
             '';
@@ -192,45 +193,45 @@ in
           target = mkOption {
             type = types.str;
             example = "user@server:pool/dataset";
-            description = ''
+            description = lib.mdDoc ''
               Target ZFS dataset. Can be either local
-              (<replaceable>pool/dataset</replaceable>) or remote
-              (<replaceable>user@server:pool/dataset</replaceable>).
+              («pool/dataset») or remote
+              («user@server:pool/dataset»).
             '';
           };
 
-          recursive = mkEnableOption ''the transfer of child datasets'';
+          recursive = mkEnableOption (lib.mdDoc ''the transfer of child datasets'');
 
           sshKey = mkOption {
             type = types.nullOr types.path;
             # Prevent key from being copied to store
             apply = mapNullable toString;
-            description = ''
+            description = lib.mdDoc ''
               SSH private key file to use to login to the remote system.
-              Defaults to <option>services.syncoid.sshKey</option> option.
+              Defaults to {option}`services.syncoid.sshKey` option.
             '';
           };
 
           localSourceAllow = mkOption {
             type = types.listOf types.str;
-            description = ''
-              Permissions granted for the <option>services.syncoid.user</option> user
+            description = lib.mdDoc ''
+              Permissions granted for the {option}`services.syncoid.user` user
               for local source datasets. See
-              <link xlink:href="https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html"/>
+              <https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html>
               for available permissions.
-              Defaults to <option>services.syncoid.localSourceAllow</option> option.
+              Defaults to {option}`services.syncoid.localSourceAllow` option.
             '';
           };
 
           localTargetAllow = mkOption {
             type = types.listOf types.str;
-            description = ''
-              Permissions granted for the <option>services.syncoid.user</option> user
+            description = lib.mdDoc ''
+              Permissions granted for the {option}`services.syncoid.user` user
               for local target datasets. See
-              <link xlink:href="https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html"/>
+              <https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html>
               for available permissions.
-              Make sure to include the <literal>change-key</literal> permission if you send raw encrypted datasets,
-              the <literal>compression</literal> permission if you send raw compressed datasets, and so on.
+              Make sure to include the `change-key` permission if you send raw encrypted datasets,
+              the `compression` permission if you send raw compressed datasets, and so on.
               For remote target datasets you'll have to set your remote user permissions by yourself.
             '';
           };
@@ -239,7 +240,7 @@ in
             type = types.separatedString " ";
             default = "";
             example = "Lc e";
-            description = ''
+            description = lib.mdDoc ''
               Advanced options to pass to zfs send. Options are specified
               without their leading dashes and separated by spaces.
             '';
@@ -249,7 +250,7 @@ in
             type = types.separatedString " ";
             default = "";
             example = "ux recordsize o compression=lz4";
-            description = ''
+            description = lib.mdDoc ''
               Advanced options to pass to zfs recv. Options are specified
               without their leading dashes and separated by spaces.
             '';
@@ -258,7 +259,7 @@ in
           useCommonArgs = mkOption {
             type = types.bool;
             default = true;
-            description = ''
+            description = lib.mdDoc ''
               Whether to add the configured common arguments to this command.
             '';
           };
@@ -266,7 +267,7 @@ in
           service = mkOption {
             type = types.attrs;
             default = { };
-            description = ''
+            description = lib.mdDoc ''
               Systemd configuration specific to this syncoid service.
             '';
           };
@@ -275,7 +276,7 @@ in
             type = types.listOf types.str;
             default = [ ];
             example = [ "--sshport 2222" ];
-            description = "Extra syncoid arguments for this command.";
+            description = lib.mdDoc "Extra syncoid arguments for this command.";
           };
         };
         config = {
@@ -291,7 +292,7 @@ in
           "pool/test".target = "root@target:pool/test";
         }
       '';
-      description = "Syncoid commands to run.";
+      description = lib.mdDoc "Syncoid commands to run.";
     };
   };
 
diff --git a/nixos/modules/services/backup/tarsnap.nix b/nixos/modules/services/backup/tarsnap.nix
index 9b5fd90012e..b34aa3ff50d 100644
--- a/nixos/modules/services/backup/tarsnap.nix
+++ b/nixos/modules/services/backup/tarsnap.nix
@@ -30,15 +30,15 @@ in
 
   options = {
     services.tarsnap = {
-      enable = mkEnableOption "periodic tarsnap backups";
+      enable = mkEnableOption (lib.mdDoc "periodic tarsnap backups");
 
       keyfile = mkOption {
         type = types.str;
         default = "/root/tarsnap.key";
-        description = ''
+        description = lib.mdDoc ''
           The keyfile which associates this machine with your tarsnap
           account.
-          Create the keyfile with <command>tarsnap-keygen</command>.
+          Create the keyfile with {command}`tarsnap-keygen`.
 
           Note that each individual archive (specified below) may also have its
           own individual keyfile specified. Tarsnap does not allow multiple
@@ -47,11 +47,11 @@ in
           archives specified, you should either spread out your backups to be
           far apart, or specify a separate key for each archive. By default
           every archive defaults to using
-          <literal>"/root/tarsnap.key"</literal>.
+          `"/root/tarsnap.key"`.
 
           It's recommended for backups that you generate a key for every archive
-          using <literal>tarsnap-keygen(1)</literal>, and then generate a
-          write-only tarsnap key using <literal>tarsnap-keymgmt(1)</literal>,
+          using `tarsnap-keygen(1)`, and then generate a
+          write-only tarsnap key using `tarsnap-keymgmt(1)`,
           and keep your master key(s) for a particular machine off-site.
 
           The keyfile name should be given as a string and not a path, to
@@ -67,18 +67,18 @@ in
                 type = types.str;
                 default = gcfg.keyfile;
                 defaultText = literalExpression "config.${opt.keyfile}";
-                description = ''
+                description = lib.mdDoc ''
                   Set a specific keyfile for this archive. This defaults to
-                  <literal>"/root/tarsnap.key"</literal> if left unspecified.
+                  `"/root/tarsnap.key"` if left unspecified.
 
                   Use this option if you want to run multiple backups
                   concurrently - each archive must have a unique key. You can
                   generate a write-only key derived from your master key (which
-                  is recommended) using <literal>tarsnap-keymgmt(1)</literal>.
+                  is recommended) using `tarsnap-keymgmt(1)`.
 
                   Note: every archive must have an individual master key. You
                   must generate multiple keys with
-                  <literal>tarsnap-keygen(1)</literal>, and then generate write
+                  `tarsnap-keygen(1)`, and then generate write
                   only keys from those.
 
                   The keyfile name should be given as a string and not a path, to
@@ -92,47 +92,47 @@ in
                 defaultText = literalExpression ''
                   "/var/cache/tarsnap/''${utils.escapeSystemdPath config.${options.keyfile}}"
                 '';
-                description = ''
+                description = lib.mdDoc ''
                   The cache allows tarsnap to identify previously stored data
                   blocks, reducing archival time and bandwidth usage.
 
                   Should the cache become desynchronized or corrupted, tarsnap
                   will refuse to run until you manually rebuild the cache with
-                  <command>tarsnap --fsck</command>.
+                  {command}`tarsnap --fsck`.
 
-                  Set to <literal>null</literal> to disable caching.
+                  Set to `null` to disable caching.
                 '';
               };
 
               nodump = mkOption {
                 type = types.bool;
                 default = true;
-                description = ''
-                  Exclude files with the <literal>nodump</literal> flag.
+                description = lib.mdDoc ''
+                  Exclude files with the `nodump` flag.
                 '';
               };
 
               printStats = mkOption {
                 type = types.bool;
                 default = true;
-                description = ''
+                description = lib.mdDoc ''
                   Print global archive statistics upon completion.
                   The output is available via
-                  <command>systemctl status tarsnap-archive-name</command>.
+                  {command}`systemctl status tarsnap-archive-name`.
                 '';
               };
 
               checkpointBytes = mkOption {
                 type = types.nullOr types.str;
                 default = "1GB";
-                description = ''
-                  Create a checkpoint every <literal>checkpointBytes</literal>
+                description = lib.mdDoc ''
+                  Create a checkpoint every `checkpointBytes`
                   of uploaded data (optionally specified using an SI prefix).
 
                   1GB is the minimum value. A higher value is recommended,
                   as checkpointing is expensive.
 
-                  Set to <literal>null</literal> to disable checkpointing.
+                  Set to `null` to disable checkpointing.
                 '';
               };
 
@@ -140,19 +140,18 @@ in
                 type = types.str;
                 default = "01:15";
                 example = "hourly";
-                description = ''
+                description = lib.mdDoc ''
                   Create archive at this interval.
 
                   The format is described in
-                  <citerefentry><refentrytitle>systemd.time</refentrytitle>
-                  <manvolnum>7</manvolnum></citerefentry>.
+                  {manpage}`systemd.time(7)`.
                 '';
               };
 
               aggressiveNetworking = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Upload data over multiple TCP connections, potentially
                   increasing tarsnap's bandwidth utilisation at the cost
                   of slowing down all other network traffic. Not
@@ -164,13 +163,13 @@ in
               directories = mkOption {
                 type = types.listOf types.path;
                 default = [];
-                description = "List of filesystem paths to archive.";
+                description = lib.mdDoc "List of filesystem paths to archive.";
               };
 
               excludes = mkOption {
                 type = types.listOf types.str;
                 default = [];
-                description = ''
+                description = lib.mdDoc ''
                   Exclude files and directories matching these patterns.
                 '';
               };
@@ -178,7 +177,7 @@ in
               includes = mkOption {
                 type = types.listOf types.str;
                 default = [];
-                description = ''
+                description = lib.mdDoc ''
                   Include only files and directories matching these
                   patterns (the empty list includes everything).
 
@@ -189,7 +188,7 @@ in
               lowmem = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Reduce memory consumption by not caching small files.
                   Possibly beneficial if the average file size is smaller
                   than 1 MB and the number of files is lower than the
@@ -200,9 +199,9 @@ in
               verylowmem = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Reduce memory consumption by a factor of 2 beyond what
-                  <literal>lowmem</literal> does, at the cost of significantly
+                  `lowmem` does, at the cost of significantly
                   slowing down the archiving process.
                 '';
               };
@@ -210,7 +209,7 @@ in
               maxbw = mkOption {
                 type = types.nullOr types.int;
                 default = null;
-                description = ''
+                description = lib.mdDoc ''
                   Abort archival if upstream bandwidth usage in bytes
                   exceeds this threshold.
                 '';
@@ -220,7 +219,7 @@ in
                 type = types.nullOr types.int;
                 default = null;
                 example = literalExpression "25 * 1000";
-                description = ''
+                description = lib.mdDoc ''
                   Upload bandwidth rate limit in bytes.
                 '';
               };
@@ -229,7 +228,7 @@ in
                 type = types.nullOr types.int;
                 default = null;
                 example = literalExpression "50 * 1000";
-                description = ''
+                description = lib.mdDoc ''
                   Download bandwidth rate limit in bytes.
                 '';
               };
@@ -237,21 +236,21 @@ in
               verbose = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Whether to produce verbose logging output.
                 '';
               };
               explicitSymlinks = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Whether to follow symlinks specified as archives.
                 '';
               };
               followSymlinks = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Whether to follow all symlinks in archive trees.
                 '';
               };
@@ -274,17 +273,17 @@ in
           }
         '';
 
-        description = ''
+        description = lib.mdDoc ''
           Tarsnap archive configurations. Each attribute names an archive
           to be created at a given time interval, according to the options
           associated with it. When uploading to the tarsnap server,
           archive names are suffixed by a 1 second resolution timestamp,
-          with the format <literal>%Y%m%d%H%M%S</literal>.
+          with the format `%Y%m%d%H%M%S`.
 
           For each member of the set is created a timer which triggers the
-          instanced <literal>tarsnap-archive-name</literal> service unit. You may use
-          <command>systemctl start tarsnap-archive-name</command> to
-          manually trigger creation of <literal>archive-name</literal> at
+          instanced `tarsnap-archive-name` service unit. You may use
+          {command}`systemctl start tarsnap-archive-name` to
+          manually trigger creation of `archive-name` at
           any time.
         '';
       };
diff --git a/nixos/modules/services/backup/tsm.nix b/nixos/modules/services/backup/tsm.nix
index 4e690ac6ecd..c4de0b16d47 100644
--- a/nixos/modules/services/backup/tsm.nix
+++ b/nixos/modules/services/backup/tsm.nix
@@ -8,48 +8,48 @@ let
   inherit (lib.types) nonEmptyStr nullOr;
 
   options.services.tsmBackup = {
-    enable = mkEnableOption ''
+    enable = mkEnableOption (lib.mdDoc ''
       automatic backups with the
       IBM Spectrum Protect (Tivoli Storage Manager, TSM) client.
       This also enables
-      <option>programs.tsmClient.enable</option>
-    '';
+      {option}`programs.tsmClient.enable`
+    '');
     command = mkOption {
       type = nonEmptyStr;
       default = "backup";
       example = "incr";
-      description = ''
+      description = lib.mdDoc ''
         The actual command passed to the
-        <literal>dsmc</literal> executable to start the backup.
+        `dsmc` executable to start the backup.
       '';
     };
     servername = mkOption {
       type = nonEmptyStr;
       example = "mainTsmServer";
-      description = ''
+      description = lib.mdDoc ''
         Create a systemd system service
-        <literal>tsm-backup.service</literal> that starts
+        `tsm-backup.service` that starts
         a backup based on the given servername's stanza.
         Note that this server's
-        <option>passwdDir</option> will default to
-        <filename>/var/lib/tsm-backup/password</filename>
+        {option}`passwdDir` will default to
+        {file}`/var/lib/tsm-backup/password`
         (but may be overridden);
         also, the service will use
-        <filename>/var/lib/tsm-backup</filename> as
-        <literal>HOME</literal> when calling
-        <literal>dsmc</literal>.
+        {file}`/var/lib/tsm-backup` as
+        `HOME` when calling
+        `dsmc`.
       '';
     };
     autoTime = mkOption {
       type = nullOr nonEmptyStr;
       default = null;
       example = "12:00";
-      description = ''
+      description = lib.mdDoc ''
         The backup service will be invoked
         automatically at the given date/time,
         which must be in the format described in
-        <citerefentry><refentrytitle>systemd.time</refentrytitle><manvolnum>5</manvolnum></citerefentry>.
-        The default <literal>null</literal>
+        {manpage}`systemd.time(5)`.
+        The default `null`
         disables automatic backups.
       '';
     };
diff --git a/nixos/modules/services/backup/zfs-replication.nix b/nixos/modules/services/backup/zfs-replication.nix
index 6d75774c78f..f0267c47364 100644
--- a/nixos/modules/services/backup/zfs-replication.nix
+++ b/nixos/modules/services/backup/zfs-replication.nix
@@ -9,46 +9,46 @@ let
 in {
   options = {
     services.zfs.autoReplication = {
-      enable = mkEnableOption "ZFS snapshot replication.";
+      enable = mkEnableOption (lib.mdDoc "ZFS snapshot replication.");
 
       followDelete = mkOption {
-        description = "Remove remote snapshots that don't have a local correspondant.";
+        description = lib.mdDoc "Remove remote snapshots that don't have a local correspondant.";
         default = true;
         type = types.bool;
       };
 
       host = mkOption {
-        description = "Remote host where snapshots should be sent. <literal>lz4</literal> is expected to be installed on this host.";
+        description = lib.mdDoc "Remote host where snapshots should be sent. `lz4` is expected to be installed on this host.";
         example = "example.com";
         type = types.str;
       };
 
       identityFilePath = mkOption {
-        description = "Path to SSH key used to login to host.";
+        description = lib.mdDoc "Path to SSH key used to login to host.";
         example = "/home/username/.ssh/id_rsa";
         type = types.path;
       };
 
       localFilesystem = mkOption {
-        description = "Local ZFS fileystem from which snapshots should be sent.  Defaults to the attribute name.";
+        description = lib.mdDoc "Local ZFS fileystem from which snapshots should be sent.  Defaults to the attribute name.";
         example = "pool/file/path";
         type = types.str;
       };
 
       remoteFilesystem = mkOption {
-        description = "Remote ZFS filesystem where snapshots should be sent.";
+        description = lib.mdDoc "Remote ZFS filesystem where snapshots should be sent.";
         example = "pool/file/path";
         type = types.str;
       };
 
       recursive = mkOption {
-        description = "Recursively discover snapshots to send.";
+        description = lib.mdDoc "Recursively discover snapshots to send.";
         default = true;
         type = types.bool;
       };
 
       username = mkOption {
-        description = "Username used by SSH to login to remote host.";
+        description = lib.mdDoc "Username used by SSH to login to remote host.";
         example = "username";
         type = types.str;
       };
diff --git a/nixos/modules/services/backup/znapzend.nix b/nixos/modules/services/backup/znapzend.nix
index 09e60177c39..f8d741e3ad9 100644
--- a/nixos/modules/services/backup/znapzend.nix
+++ b/nixos/modules/services/backup/znapzend.nix
@@ -12,19 +12,19 @@ let
       backups. It consists of a series of retention periodes to interval
       associations:
 
-      <literal>
+      ```
         retA=>intA,retB=>intB,...
-      </literal>
+      ```
 
       Both intervals and retention periods are expressed in standard units
       of time or multiples of them. You can use both the full name or a
       shortcut according to the following listing:
 
-      <literal>
+      ```
         second|sec|s, minute|min, hour|h, day|d, week|w, month|mon|m, year|y
-      </literal>
+      ```
 
-      See <citerefentry><refentrytitle>znapzendzetup</refentrytitle><manvolnum>1</manvolnum></citerefentry> for more info.
+      See {manpage}`znapzendzetup(1)` for more info.
   '';
   planExample = "1h=>10min,1d=>1h,1w=>1d,1m=>1w,1y=>1m";
 
@@ -52,26 +52,26 @@ let
 
       label = mkOption {
         type = str;
-        description = "Label for this destination. Defaults to the attribute name.";
+        description = lib.mdDoc "Label for this destination. Defaults to the attribute name.";
       };
 
       plan = mkOption {
         type = str;
-        description = planDescription;
+        description = lib.mdDoc planDescription;
         example = planExample;
       };
 
       dataset = mkOption {
         type = str;
-        description = "Dataset name to send snapshots to.";
+        description = lib.mdDoc "Dataset name to send snapshots to.";
         example = "tank/main";
       };
 
       host = mkOption {
         type = nullOr str;
-        description = ''
+        description = lib.mdDoc ''
           Host to use for the destination dataset. Can be prefixed with
-          <literal>user@</literal> to specify the ssh user.
+          `user@` to specify the ssh user.
         '';
         default = null;
         example = "john@example.com";
@@ -79,11 +79,11 @@ let
 
       presend = mkOption {
         type = nullOr str;
-        description = ''
+        description = lib.mdDoc ''
           Command to run before sending the snapshot to the destination.
-          Intended to run a remote script via <command>ssh</command> on the
+          Intended to run a remote script via {command}`ssh` on the
           destination, e.g. to bring up a backup disk or server or to put a
-          zpool online/offline. See also <option>postsend</option>.
+          zpool online/offline. See also {option}`postsend`.
         '';
         default = null;
         example = "ssh root@bserv zpool import -Nf tank";
@@ -91,11 +91,11 @@ let
 
       postsend = mkOption {
         type = nullOr str;
-        description = ''
+        description = lib.mdDoc ''
           Command to run after sending the snapshot to the destination.
-          Intended to run a remote script via <command>ssh</command> on the
+          Intended to run a remote script via {command}`ssh` on the
           destination, e.g. to bring up a backup disk or server or to put a
-          zpool online/offline. See also <option>presend</option>.
+          zpool online/offline. See also {option}`presend`.
         '';
         default = null;
         example = "ssh root@bserv zpool export tank";
@@ -115,32 +115,32 @@ let
 
       enable = mkOption {
         type = bool;
-        description = "Whether to enable this source.";
+        description = lib.mdDoc "Whether to enable this source.";
         default = true;
       };
 
       recursive = mkOption {
         type = bool;
-        description = "Whether to do recursive snapshots.";
+        description = lib.mdDoc "Whether to do recursive snapshots.";
         default = false;
       };
 
       mbuffer = {
         enable = mkOption {
           type = bool;
-          description = "Whether to use <command>mbuffer</command>.";
+          description = lib.mdDoc "Whether to use {command}`mbuffer`.";
           default = false;
         };
 
         port = mkOption {
           type = nullOr ints.u16;
-          description = ''
-              Port to use for <command>mbuffer</command>.
+          description = lib.mdDoc ''
+              Port to use for {command}`mbuffer`.
 
-              If this is null, it will run <command>mbuffer</command> through
+              If this is null, it will run {command}`mbuffer` through
               ssh.
 
-              If this is not null, it will run <command>mbuffer</command>
+              If this is not null, it will run {command}`mbuffer`
               directly through TCP, which is not encrypted but faster. In that
               case the given port needs to be open on the destination host.
           '';
@@ -149,8 +149,8 @@ let
 
         size = mkOption {
           type = mbufferSizeType;
-          description = ''
-            The size for <command>mbuffer</command>.
+          description = lib.mdDoc ''
+            The size for {command}`mbuffer`.
             Supports the units b, k, M, G.
           '';
           default = "1G";
@@ -160,10 +160,10 @@ let
 
       presnap = mkOption {
         type = nullOr str;
-        description = ''
+        description = lib.mdDoc ''
           Command to run before snapshots are taken on the source dataset,
           e.g. for database locking/flushing. See also
-          <option>postsnap</option>.
+          {option}`postsnap`.
         '';
         default = null;
         example = literalExpression ''
@@ -173,9 +173,9 @@ let
 
       postsnap = mkOption {
         type = nullOr str;
-        description = ''
+        description = lib.mdDoc ''
           Command to run after snapshots are taken on the source dataset,
-          e.g. for database unlocking. See also <option>presnap</option>.
+          e.g. for database unlocking. See also {option}`presnap`.
         '';
         default = null;
         example = literalExpression ''
@@ -185,13 +185,13 @@ let
 
       timestampFormat = mkOption {
         type = timestampType;
-        description = ''
+        description = lib.mdDoc ''
           The timestamp format to use for constructing snapshot names.
-          The syntax is <literal>strftime</literal>-like. The string must
-          consist of the mandatory <literal>%Y %m %d %H %M %S</literal>.
-          Optionally  <literal>- _ . :</literal>  characters as well as any
+          The syntax is `strftime`-like. The string must
+          consist of the mandatory `%Y %m %d %H %M %S`.
+          Optionally  `- _ . :`  characters as well as any
           alphanumeric character are allowed. If suffixed by a
-          <literal>Z</literal>, times will be in UTC.
+          `Z`, times will be in UTC.
         '';
         default = "%Y-%m-%d-%H%M%S";
         example = "znapzend-%m.%d.%Y-%H%M%SZ";
@@ -199,7 +199,7 @@ let
 
       sendDelay = mkOption {
         type = int;
-        description = ''
+        description = lib.mdDoc ''
           Specify delay (in seconds) before sending snaps to the destination.
           May be useful if you want to control sending time.
         '';
@@ -209,19 +209,19 @@ let
 
       plan = mkOption {
         type = str;
-        description = planDescription;
+        description = lib.mdDoc planDescription;
         example = planExample;
       };
 
       dataset = mkOption {
         type = str;
-        description = "The dataset to use for this source.";
+        description = lib.mdDoc "The dataset to use for this source.";
         example = "tank/home";
       };
 
       destinations = mkOption {
         type = attrsOf (destType config);
-        description = "Additional destinations.";
+        description = lib.mdDoc "Additional destinations.";
         default = {};
         example = literalExpression ''
           {
@@ -294,13 +294,13 @@ in
 {
   options = {
     services.znapzend = {
-      enable = mkEnableOption "ZnapZend ZFS backup daemon";
+      enable = mkEnableOption (lib.mdDoc "ZnapZend ZFS backup daemon");
 
       logLevel = mkOption {
         default = "debug";
         example = "warning";
         type = enum ["debug" "info" "warning" "err" "alert"];
-        description = ''
+        description = lib.mdDoc ''
           The log level when logging to file. Any of debug, info, warning, err,
           alert. Default in daemonized form is debug.
         '';
@@ -310,26 +310,26 @@ in
         type = str;
         default = "syslog::daemon";
         example = "/var/log/znapzend.log";
-        description = ''
-          Where to log to (syslog::&lt;facility&gt; or &lt;filepath&gt;).
+        description = lib.mdDoc ''
+          Where to log to (syslog::\<facility\> or \<filepath\>).
         '';
       };
 
       noDestroy = mkOption {
         type = bool;
         default = false;
-        description = "Does all changes to the filesystem except destroy.";
+        description = lib.mdDoc "Does all changes to the filesystem except destroy.";
       };
 
       autoCreation = mkOption {
         type = bool;
         default = false;
-        description = "Automatically create the destination dataset if it does not exist.";
+        description = lib.mdDoc "Automatically create the destination dataset if it does not exist.";
       };
 
       zetup = mkOption {
         type = attrsOf srcType;
-        description = "Znapzend configuration.";
+        description = lib.mdDoc "Znapzend configuration.";
         default = {};
         example = literalExpression ''
           {
@@ -350,7 +350,7 @@ in
 
       pure = mkOption {
         type = bool;
-        description = ''
+        description = lib.mdDoc ''
           Do not persist any stateful znapzend setups. If this option is
           enabled, your previously set znapzend setups will be cleared and only
           the ones defined with this module will be applied.
@@ -358,62 +358,62 @@ in
         default = false;
       };
 
-      features.oracleMode = mkEnableOption ''
+      features.oracleMode = mkEnableOption (lib.mdDoc ''
         Destroy snapshots one by one instead of using one long argument list.
         If source and destination are out of sync for a long time, you may have
         so many snapshots to destroy that the argument gets is too long and the
         command fails.
-      '';
-      features.recvu = mkEnableOption ''
-        recvu feature which uses <literal>-u</literal> on the receiving end to keep the destination
+      '');
+      features.recvu = mkEnableOption (lib.mdDoc ''
+        recvu feature which uses `-u` on the receiving end to keep the destination
         filesystem unmounted.
-      '';
-      features.compressed = mkEnableOption ''
-        compressed feature which adds the options <literal>-Lce</literal> to
-        the <command>zfs send</command> command. When this is enabled, make
+      '');
+      features.compressed = mkEnableOption (lib.mdDoc ''
+        compressed feature which adds the options `-Lce` to
+        the {command}`zfs send` command. When this is enabled, make
         sure that both the sending and receiving pool have the same relevant
-        features enabled. Using <literal>-c</literal> will skip unneccessary
-        decompress-compress stages, <literal>-L</literal> is for large block
+        features enabled. Using `-c` will skip unneccessary
+        decompress-compress stages, `-L` is for large block
         support and -e is for embedded data support. see
-        <citerefentry><refentrytitle>znapzend</refentrytitle><manvolnum>1</manvolnum></citerefentry>
-        and <citerefentry><refentrytitle>zfs</refentrytitle><manvolnum>8</manvolnum></citerefentry>
+        {manpage}`znapzend(1)`
+        and {manpage}`zfs(8)`
         for more info.
-      '';
-      features.sendRaw = mkEnableOption ''
-        sendRaw feature which adds the options <literal>-w</literal> to the
-        <command>zfs send</command> command. For encrypted source datasets this
+      '');
+      features.sendRaw = mkEnableOption (lib.mdDoc ''
+        sendRaw feature which adds the options `-w` to the
+        {command}`zfs send` command. For encrypted source datasets this
         instructs zfs not to decrypt before sending which results in a remote
         backup that can't be read without the encryption key/passphrase, useful
         when the remote isn't fully trusted or not physically secure. This
         option must be used consistently, raw incrementals cannot be based on
         non-raw snapshots and vice versa.
-      '';
-      features.skipIntermediates = mkEnableOption ''
+      '');
+      features.skipIntermediates = mkEnableOption (lib.mdDoc ''
         Enable the skipIntermediates feature to send a single increment
         between latest common snapshot and the newly made one. It may skip
         several source snaps if the destination was offline for some time, and
         it should skip snapshots not managed by znapzend. Normally for online
         destinations, the new snapshot is sent as soon as it is created on the
         source, so there are no automatic increments to skip.
-      '';
-      features.lowmemRecurse = mkEnableOption ''
+      '');
+      features.lowmemRecurse = mkEnableOption (lib.mdDoc ''
         use lowmemRecurse on systems where you have too many datasets, so a
         recursive listing of attributes to find backup plans exhausts the
-        memory available to <command>znapzend</command>: instead, go the slower
+        memory available to {command}`znapzend`: instead, go the slower
         way to first list all impacted dataset names, and then query their
         configs one by one.
-      '';
-      features.zfsGetType = mkEnableOption ''
-        use zfsGetType if your <command>zfs get</command> supports a
-        <literal>-t</literal> argument for filtering by dataset type at all AND
+      '');
+      features.zfsGetType = mkEnableOption (lib.mdDoc ''
+        use zfsGetType if your {command}`zfs get` supports a
+        `-t` argument for filtering by dataset type at all AND
         lists properties for snapshots by default when recursing, so that there
         is too much data to process while searching for backup plans.
         If these two conditions apply to your system, the time needed for a
-        <literal>--recursive</literal> search for backup plans can literally
+        `--recursive` search for backup plans can literally
         differ by hundreds of times (depending on the amount of snapshots in
         that dataset tree... and a decent backup plan will ensure you have a lot
         of those), so you would benefit from requesting this feature.
-      '';
+      '');
     };
   };
 
diff --git a/nixos/modules/services/backup/zrepl.nix b/nixos/modules/services/backup/zrepl.nix
index 4356479b663..1d3afa3eda0 100644
--- a/nixos/modules/services/backup/zrepl.nix
+++ b/nixos/modules/services/backup/zrepl.nix
@@ -11,13 +11,19 @@ in
 
   options = {
     services.zrepl = {
-      enable = mkEnableOption "zrepl";
+      enable = mkEnableOption (lib.mdDoc "zrepl");
+
+      package = mkOption {
+        type = types.package;
+        default = pkgs.zrepl;
+        defaultText = literalExpression "pkgs.zrepl";
+        description = lib.mdDoc "Which package to use for zrepl";
+      };
 
       settings = mkOption {
         default = { };
-        description = ''
-          Configuration for zrepl. See <link
-          xlink:href="https://zrepl.github.io/configuration.html"/>
+        description = lib.mdDoc ''
+          Configuration for zrepl. See <https://zrepl.github.io/configuration.html>
           for more information.
         '';
         type = types.submodule {
@@ -30,14 +36,17 @@ in
   ### Implementation ###
 
   config = mkIf cfg.enable {
-    environment.systemPackages = [ pkgs.zrepl ];
+    environment.systemPackages = [ cfg.package ];
 
     # zrepl looks for its config in this location by default. This
     # allows the use of e.g. `zrepl signal wakeup <job>` without having
     # to specify the storepath of the config.
     environment.etc."zrepl/zrepl.yml".source = configFile;
 
-    systemd.packages = [ pkgs.zrepl ];
+    systemd.packages = [ cfg.package ];
+
+    # Note that pkgs.zrepl copies and adapts the upstream systemd unit, and
+    # the fields defined here only override certain fields from that unit.
     systemd.services.zrepl = {
       requires = [ "local-fs.target" ];
       wantedBy = [ "zfs.target" ];
diff --git a/nixos/modules/services/blockchain/ethereum/erigon.nix b/nixos/modules/services/blockchain/ethereum/erigon.nix
new file mode 100644
index 00000000000..8ebe0fcaff5
--- /dev/null
+++ b/nixos/modules/services/blockchain/ethereum/erigon.nix
@@ -0,0 +1,120 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let
+
+  cfg = config.services.erigon;
+
+  settingsFormat = pkgs.formats.toml { };
+  configFile = settingsFormat.generate "config.toml" cfg.settings;
+in {
+
+  options = {
+    services.erigon = {
+      enable = mkEnableOption (lib.mdDoc "Ethereum implementation on the efficiency frontier");
+
+      extraArgs = mkOption {
+        type = types.listOf types.str;
+        description = lib.mdDoc "Additional arguments passed to Erigon";
+        default = [ ];
+      };
+
+      secretJwtPath = mkOption {
+        type = types.path;
+        description = lib.mdDoc ''
+          Path to the secret jwt used for the http api authentication.
+        '';
+        default = "";
+        example = "config.age.secrets.ERIGON_JWT.path";
+      };
+
+      settings = mkOption {
+        description = lib.mdDoc ''
+          Configuration for Erigon
+          Refer to <https://github.com/ledgerwatch/erigon#usage> for details on supported values.
+        '';
+
+        type = settingsFormat.type;
+
+        example = {
+          datadir = "/var/lib/erigon";
+          chain = "mainnet";
+          http = true;
+          "http.port" = 8545;
+          "http.api" = ["eth" "debug" "net" "trace" "web3" "erigon"];
+          ws = true;
+          port = 30303;
+          "authrpc.port" = 8551;
+          "torrent.port" = 42069;
+          "private.api.addr" = "localhost:9090";
+          "log.console.verbosity" = 3; # info
+        };
+
+        defaultText = literalExpression ''
+          {
+            datadir = "/var/lib/erigon";
+            chain = "mainnet";
+            http = true;
+            "http.port" = 8545;
+            "http.api" = ["eth" "debug" "net" "trace" "web3" "erigon"];
+            ws = true;
+            port = 30303;
+            "authrpc.port" = 8551;
+            "torrent.port" = 42069;
+            "private.api.addr" = "localhost:9090";
+            "log.console.verbosity" = 3; # info
+          }
+        '';
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    # Default values are the same as in the binary, they are just written here for convenience.
+    services.erigon.settings = {
+      datadir = mkDefault "/var/lib/erigon";
+      chain = mkDefault "mainnet";
+      http = mkDefault true;
+      "http.port" = mkDefault 8545;
+      "http.api" = mkDefault ["eth" "debug" "net" "trace" "web3" "erigon"];
+      ws = mkDefault true;
+      port = mkDefault 30303;
+      "authrpc.port" = mkDefault 8551;
+      "torrent.port" = mkDefault 42069;
+      "private.api.addr" = mkDefault "localhost:9090";
+      "log.console.verbosity" = mkDefault 3; # info
+    };
+
+    systemd.services.erigon = {
+      description = "Erigon ethereum implemenntation";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+
+      serviceConfig = {
+        LoadCredential = "ERIGON_JWT:${cfg.secretJwtPath}";
+        ExecStart = "${pkgs.erigon}/bin/erigon --config ${configFile} --authrpc.jwtsecret=%d/ERIGON_JWT ${lib.escapeShellArgs cfg.extraArgs}";
+        DynamicUser = true;
+        Restart = "on-failure";
+        StateDirectory = "erigon";
+        CapabilityBoundingSet = "";
+        NoNewPrivileges = true;
+        PrivateTmp = true;
+        ProtectHome = true;
+        ProtectClock = true;
+        ProtectProc = "noaccess";
+        ProcSubset = "pid";
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectControlGroups = true;
+        ProtectHostname = true;
+        RestrictSUIDSGID = true;
+        RestrictRealtime = true;
+        RestrictNamespaces = true;
+        LockPersonality = true;
+        RemoveIPC = true;
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/blockchain/ethereum/geth.nix b/nixos/modules/services/blockchain/ethereum/geth.nix
index bf2cf1edd4d..eca308dc366 100644
--- a/nixos/modules/services/blockchain/ethereum/geth.nix
+++ b/nixos/modules/services/blockchain/ethereum/geth.nix
@@ -9,100 +9,129 @@ let
 
     options = {
 
-      enable = lib.mkEnableOption "Go Ethereum Node";
+      enable = lib.mkEnableOption (lib.mdDoc "Go Ethereum Node");
 
       port = mkOption {
         type = types.port;
         default = 30303;
-        description = "Port number Go Ethereum will be listening on, both TCP and UDP.";
+        description = lib.mdDoc "Port number Go Ethereum will be listening on, both TCP and UDP.";
       };
 
       http = {
-        enable = lib.mkEnableOption "Go Ethereum HTTP API";
+        enable = lib.mkEnableOption (lib.mdDoc "Go Ethereum HTTP API");
         address = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "Listen address of Go Ethereum HTTP API.";
+          description = lib.mdDoc "Listen address of Go Ethereum HTTP API.";
         };
 
         port = mkOption {
           type = types.port;
           default = 8545;
-          description = "Port number of Go Ethereum HTTP API.";
+          description = lib.mdDoc "Port number of Go Ethereum HTTP API.";
         };
 
         apis = mkOption {
           type = types.nullOr (types.listOf types.str);
           default = null;
-          description = "APIs to enable over WebSocket";
+          description = lib.mdDoc "APIs to enable over WebSocket";
           example = ["net" "eth"];
         };
       };
 
       websocket = {
-        enable = lib.mkEnableOption "Go Ethereum WebSocket API";
+        enable = lib.mkEnableOption (lib.mdDoc "Go Ethereum WebSocket API");
         address = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "Listen address of Go Ethereum WebSocket API.";
+          description = lib.mdDoc "Listen address of Go Ethereum WebSocket API.";
         };
 
         port = mkOption {
           type = types.port;
           default = 8546;
-          description = "Port number of Go Ethereum WebSocket API.";
+          description = lib.mdDoc "Port number of Go Ethereum WebSocket API.";
         };
 
         apis = mkOption {
           type = types.nullOr (types.listOf types.str);
           default = null;
-          description = "APIs to enable over WebSocket";
+          description = lib.mdDoc "APIs to enable over WebSocket";
           example = ["net" "eth"];
         };
       };
 
+      authrpc = {
+        enable = lib.mkEnableOption (lib.mdDoc "Go Ethereum Auth RPC API");
+        address = mkOption {
+          type = types.str;
+          default = "127.0.0.1";
+          description = lib.mdDoc "Listen address of Go Ethereum Auth RPC API.";
+        };
+
+        port = mkOption {
+          type = types.port;
+          default = 8551;
+          description = lib.mdDoc "Port number of Go Ethereum Auth RPC API.";
+        };
+
+        vhosts = mkOption {
+          type = types.nullOr (types.listOf types.str);
+          default = ["localhost"];
+          description = lib.mdDoc "List of virtual hostnames from which to accept requests.";
+          example = ["localhost" "geth.example.org"];
+        };
+
+        jwtsecret = mkOption {
+          type = types.str;
+          default = "";
+          description = lib.mdDoc "Path to a JWT secret for authenticated RPC endpoint.";
+          example = "/var/run/geth/jwtsecret";
+        };
+      };
+
       metrics = {
-        enable = lib.mkEnableOption "Go Ethereum prometheus metrics";
+        enable = lib.mkEnableOption (lib.mdDoc "Go Ethereum prometheus metrics");
         address = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "Listen address of Go Ethereum metrics service.";
+          description = lib.mdDoc "Listen address of Go Ethereum metrics service.";
         };
 
         port = mkOption {
           type = types.port;
           default = 6060;
-          description = "Port number of Go Ethereum metrics service.";
+          description = lib.mdDoc "Port number of Go Ethereum metrics service.";
         };
       };
 
       network = mkOption {
         type = types.nullOr (types.enum [ "goerli" "rinkeby" "yolov2" "ropsten" ]);
         default = null;
-        description = "The network to connect to. Mainnet (null) is the default ethereum network.";
+        description = lib.mdDoc "The network to connect to. Mainnet (null) is the default ethereum network.";
       };
 
       syncmode = mkOption {
         type = types.enum [ "snap" "fast" "full" "light" ];
         default = "snap";
-        description = "Blockchain sync mode.";
+        description = lib.mdDoc "Blockchain sync mode.";
       };
 
       gcmode = mkOption {
         type = types.enum [ "full" "archive" ];
         default = "full";
-        description = "Blockchain garbage collection mode.";
+        description = lib.mdDoc "Blockchain garbage collection mode.";
       };
 
       maxpeers = mkOption {
         type = types.int;
         default = 50;
-        description = "Maximum peers to connect to.";
+        description = lib.mdDoc "Maximum peers to connect to.";
       };
 
       extraArgs = mkOption {
         type = types.listOf types.str;
-        description = "Additional arguments passed to Go Ethereum.";
+        description = lib.mdDoc "Additional arguments passed to Go Ethereum.";
         default = [];
       };
 
@@ -110,7 +139,7 @@ let
         default = pkgs.go-ethereum.geth;
         defaultText = literalExpression "pkgs.go-ethereum.geth";
         type = types.package;
-        description = "Package to use as Go Ethereum node.";
+        description = lib.mdDoc "Package to use as Go Ethereum node.";
       };
     };
   };
@@ -124,7 +153,7 @@ in
     services.geth = mkOption {
       type = types.attrsOf (types.submodule gethOpts);
       default = {};
-      description = "Specification of one or more geth instances.";
+      description = lib.mdDoc "Specification of one or more geth instances.";
     };
   };
 
@@ -136,7 +165,10 @@ in
       cfg.package
     ]) eachGeth);
 
-    systemd.services = mapAttrs' (gethName: cfg: (
+    systemd.services = mapAttrs' (gethName: cfg: let
+      stateDir = "goethereum/${gethName}/${if (cfg.network == null) then "mainnet" else cfg.network}";
+      dataDir = "/var/lib/${stateDir}";
+    in (
       nameValuePair "geth-${gethName}" (mkIf cfg.enable {
       description = "Go Ethereum node (${gethName})";
       wantedBy = [ "multi-user.target" ];
@@ -145,7 +177,7 @@ in
       serviceConfig = {
         DynamicUser = true;
         Restart = "always";
-        StateDirectory = "goethereum/${gethName}/${if (cfg.network == null) then "mainnet" else cfg.network}";
+        StateDirectory = stateDir;
 
         # Hardening measures
         PrivateTmp = "true";
@@ -169,8 +201,10 @@ in
           ${if cfg.websocket.enable then ''--ws --ws.addr ${cfg.websocket.address} --ws.port ${toString cfg.websocket.port}'' else ""} \
           ${optionalString (cfg.websocket.apis != null) ''--ws.api ${lib.concatStringsSep "," cfg.websocket.apis}''} \
           ${optionalString cfg.metrics.enable ''--metrics --metrics.addr ${cfg.metrics.address} --metrics.port ${toString cfg.metrics.port}''} \
+          --authrpc.addr ${cfg.authrpc.address} --authrpc.port ${toString cfg.authrpc.port} --authrpc.vhosts ${lib.concatStringsSep "," cfg.authrpc.vhosts} \
+          ${if (cfg.authrpc.jwtsecret != "") then ''--authrpc.jwtsecret ${cfg.authrpc.jwtsecret}'' else ''--authrpc.jwtsecret ${dataDir}/geth/jwtsecret''} \
           ${lib.escapeShellArgs cfg.extraArgs} \
-          --datadir /var/lib/goethereum/${gethName}/${if (cfg.network == null) then "mainnet" else cfg.network}
+          --datadir ${dataDir}
       '';
     }))) eachGeth;
 
diff --git a/nixos/modules/services/blockchain/ethereum/lighthouse.nix b/nixos/modules/services/blockchain/ethereum/lighthouse.nix
new file mode 100644
index 00000000000..20a4ead689c
--- /dev/null
+++ b/nixos/modules/services/blockchain/ethereum/lighthouse.nix
@@ -0,0 +1,315 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let
+
+  cfg = config.services.lighthouse;
+in {
+
+  options = {
+    services.lighthouse = {
+      beacon = mkOption {
+        description = lib.mdDoc "Beacon node";
+        default = {};
+        type = types.submodule {
+          options = {
+            enable = lib.mkEnableOption (lib.mdDoc "Lightouse Beacon node");
+
+            dataDir = mkOption {
+              type = types.str;
+              default = "/var/lib/lighthouse-beacon";
+              description = lib.mdDoc ''
+                Directory where data will be stored. Each chain will be stored under it's own specific subdirectory.
+              '';
+            };
+
+            address = mkOption {
+              type = types.str;
+              default = "0.0.0.0";
+              description = lib.mdDoc ''
+                Listen address of Beacon node.
+              '';
+            };
+
+            port = mkOption {
+              type = types.port;
+              default = 9000;
+              description = lib.mdDoc ''
+                Port number the Beacon node will be listening on.
+              '';
+            };
+
+            openFirewall = mkOption {
+              type = types.bool;
+              default = false;
+              description = lib.mdDoc ''
+                Open the port in the firewall
+              '';
+            };
+
+            disableDepositContractSync = mkOption {
+              type = types.bool;
+              default = false;
+              description = lib.mdDoc ''
+                Explictly disables syncing of deposit logs from the execution node.
+                This overrides any previous option that depends on it.
+                Useful if you intend to run a non-validating beacon node.
+              '';
+            };
+
+            execution = {
+              address = mkOption {
+                type = types.str;
+                default = "127.0.0.1";
+                description = lib.mdDoc ''
+                  Listen address for the execution layer.
+                '';
+              };
+
+              port = mkOption {
+                type = types.port;
+                default = 8551;
+                description = lib.mdDoc ''
+                  Port number the Beacon node will be listening on for the execution layer.
+                '';
+              };
+
+              jwtPath = mkOption {
+                type = types.str;
+                default = "";
+                description = lib.mdDoc ''
+                  Path for the jwt secret required to connect to the execution layer.
+                '';
+              };
+            };
+
+            http = {
+              enable = lib.mkEnableOption (lib.mdDoc "Beacon node http api");
+              port = mkOption {
+                type = types.port;
+                default = 5052;
+                description = lib.mdDoc ''
+                  Port number of Beacon node RPC service.
+                '';
+              };
+
+              address = mkOption {
+                type = types.str;
+                default = "127.0.0.1";
+                description = lib.mdDoc ''
+                  Listen address of Beacon node RPC service.
+                '';
+              };
+            };
+
+            metrics = {
+              enable = lib.mkEnableOption (lib.mdDoc "Beacon node prometheus metrics");
+              address = mkOption {
+                type = types.str;
+                default = "127.0.0.1";
+                description = lib.mdDoc ''
+                  Listen address of Beacon node metrics service.
+                '';
+              };
+
+              port = mkOption {
+                type = types.port;
+                default = 5054;
+                description = lib.mdDoc ''
+                  Port number of Beacon node metrics service.
+                '';
+              };
+            };
+
+            extraArgs = mkOption {
+              type = types.str;
+              description = lib.mdDoc ''
+                Additional arguments passed to the lighthouse beacon command.
+              '';
+              default = "";
+              example = "";
+            };
+          };
+        };
+      };
+
+      validator = mkOption {
+        description = lib.mdDoc "Validator node";
+        default = {};
+        type = types.submodule {
+          options = {
+            enable = mkOption {
+              type = types.bool;
+              default = false;
+              description = lib.mdDoc "Enable Lightouse Validator node.";
+            };
+
+            dataDir = mkOption {
+              type = types.str;
+              default = "/var/lib/lighthouse-validator";
+              description = lib.mdDoc ''
+                Directory where data will be stored. Each chain will be stored under it's own specific subdirectory.
+              '';
+            };
+
+            beaconNodes = mkOption {
+              type = types.listOf types.str;
+              default = ["http://localhost:5052"];
+              description = lib.mdDoc ''
+                Beacon nodes to connect to.
+              '';
+            };
+
+            metrics = {
+              enable = lib.mkEnableOption (lib.mdDoc "Validator node prometheus metrics");
+              address = mkOption {
+                type = types.str;
+                default = "127.0.0.1";
+                description = lib.mdDoc ''
+                  Listen address of Validator node metrics service.
+                '';
+              };
+
+              port = mkOption {
+                type = types.port;
+                default = 5056;
+                description = lib.mdDoc ''
+                  Port number of Validator node metrics service.
+                '';
+              };
+            };
+
+            extraArgs = mkOption {
+              type = types.str;
+              description = lib.mdDoc ''
+                Additional arguments passed to the lighthouse validator command.
+              '';
+              default = "";
+              example = "";
+            };
+          };
+        };
+      };
+
+      network = mkOption {
+        type = types.enum [ "mainnet" "prater" "goerli" "gnosis" "kiln" "ropsten" "sepolia" ];
+        default = "mainnet";
+        description = lib.mdDoc ''
+          The network to connect to. Mainnet is the default ethereum network.
+        '';
+      };
+
+      extraArgs = mkOption {
+        type = types.str;
+        description = lib.mdDoc ''
+          Additional arguments passed to every lighthouse command.
+        '';
+        default = "";
+        example = "";
+      };
+    };
+  };
+
+  config = mkIf (cfg.beacon.enable || cfg.validator.enable) {
+
+    environment.systemPackages = [ pkgs.lighthouse ] ;
+
+    networking.firewall = mkIf cfg.beacon.enable {
+      allowedTCPPorts = mkIf cfg.beacon.openFirewall [ cfg.beacon.port ];
+      allowedUDPPorts = mkIf cfg.beacon.openFirewall [ cfg.beacon.port ];
+    };
+
+
+    systemd.services.lighthouse-beacon = mkIf cfg.beacon.enable {
+      description = "Lighthouse beacon node (connect to P2P nodes and verify blocks)";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+
+      script = ''
+        # make sure the chain data directory is created on first run
+        mkdir -p ${cfg.beacon.dataDir}/${cfg.network}
+
+        ${pkgs.lighthouse}/bin/lighthouse beacon_node \
+          --disable-upnp \
+          ${lib.optionalString cfg.beacon.disableDepositContractSync "--disable-deposit-contract-sync"} \
+          --port ${toString cfg.beacon.port} \
+          --listen-address ${cfg.beacon.address} \
+          --network ${cfg.network} \
+          --datadir ${cfg.beacon.dataDir}/${cfg.network} \
+          --execution-endpoint http://${cfg.beacon.execution.address}:${toString cfg.beacon.execution.port} \
+          --execution-jwt ''${CREDENTIALS_DIRECTORY}/LIGHTHOUSE_JWT \
+          ${lib.optionalString cfg.beacon.http.enable '' --http --http-address ${cfg.beacon.http.address} --http-port ${toString cfg.beacon.http.port}''} \
+          ${lib.optionalString cfg.beacon.metrics.enable '' --metrics --metrics-address ${cfg.beacon.metrics.address} --metrics-port ${toString cfg.beacon.metrics.port}''} \
+          ${cfg.extraArgs} ${cfg.beacon.extraArgs}
+      '';
+      serviceConfig = {
+        LoadCredential = "LIGHTHOUSE_JWT:${cfg.beacon.execution.jwtPath}";
+        DynamicUser = true;
+        Restart = "on-failure";
+        StateDirectory = "lighthouse-beacon";
+        ReadWritePaths = [ cfg.beacon.dataDir ];
+        NoNewPrivileges = true;
+        PrivateTmp = true;
+        ProtectHome = true;
+        ProtectClock = true;
+        ProtectProc = "noaccess";
+        ProcSubset = "pid";
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectControlGroups = true;
+        ProtectHostname = true;
+        RestrictSUIDSGID = true;
+        RestrictRealtime = true;
+        RestrictNamespaces = true;
+        LockPersonality = true;
+        RemoveIPC = true;
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
+      };
+    };
+
+    systemd.services.lighthouse-validator = mkIf cfg.validator.enable {
+      description = "Lighthouse validtor node (manages validators, using data obtained from the beacon node via a HTTP API)";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+
+      script = ''
+        # make sure the chain data directory is created on first run
+        mkdir -p ${cfg.validator.dataDir}/${cfg.network}
+
+        ${pkgs.lighthouse}/bin/lighthouse validator_client \
+          --network ${cfg.network} \
+          --beacon-nodes ${lib.concatStringsSep "," cfg.validator.beaconNodes} \
+          --datadir ${cfg.validator.dataDir}/${cfg.network}
+          ${optionalString cfg.validator.metrics.enable ''--metrics --metrics-address ${cfg.validator.metrics.address} --metrics-port ${toString cfg.validator.metrics.port}''} \
+          ${cfg.extraArgs} ${cfg.validator.extraArgs}
+      '';
+
+      serviceConfig = {
+        Restart = "on-failure";
+        StateDirectory = "lighthouse-validator";
+        ReadWritePaths = [ cfg.validator.dataDir ];
+        CapabilityBoundingSet = "";
+        DynamicUser = true;
+        NoNewPrivileges = true;
+        PrivateTmp = true;
+        ProtectHome = true;
+        ProtectClock = true;
+        ProtectProc = "noaccess";
+        ProcSubset = "pid";
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectControlGroups = true;
+        ProtectHostname = true;
+        RestrictSUIDSGID = true;
+        RestrictRealtime = true;
+        RestrictNamespaces = true;
+        LockPersonality = true;
+        RemoveIPC = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/cluster/corosync/default.nix b/nixos/modules/services/cluster/corosync/default.nix
index b4144917fee..7ef17c46b81 100644
--- a/nixos/modules/services/cluster/corosync/default.nix
+++ b/nixos/modules/services/cluster/corosync/default.nix
@@ -7,43 +7,43 @@ in
 {
   # interface
   options.services.corosync = {
-    enable = mkEnableOption "corosync";
+    enable = mkEnableOption (lib.mdDoc "corosync");
 
     package = mkOption {
       type = types.package;
       default = pkgs.corosync;
       defaultText = literalExpression "pkgs.corosync";
-      description = "Package that should be used for corosync.";
+      description = lib.mdDoc "Package that should be used for corosync.";
     };
 
     clusterName = mkOption {
       type = types.str;
       default = "nixcluster";
-      description = "Name of the corosync cluster.";
+      description = lib.mdDoc "Name of the corosync cluster.";
     };
 
     extraOptions = mkOption {
       type = with types; listOf str;
       default = [];
-      description = "Additional options with which to start corosync.";
+      description = lib.mdDoc "Additional options with which to start corosync.";
     };
 
     nodelist = mkOption {
-      description = "Corosync nodelist: all cluster members.";
+      description = lib.mdDoc "Corosync nodelist: all cluster members.";
       default = [];
       type = with types; listOf (submodule {
         options = {
           nodeid = mkOption {
             type = int;
-            description = "Node ID number";
+            description = lib.mdDoc "Node ID number";
           };
           name = mkOption {
             type = str;
-            description = "Node name";
+            description = lib.mdDoc "Node name";
           };
           ring_addrs = mkOption {
             type = listOf str;
-            description = "List of addresses, one for each ring.";
+            description = lib.mdDoc "List of addresses, one for each ring.";
           };
         };
       });
diff --git a/nixos/modules/services/cluster/hadoop/conf.nix b/nixos/modules/services/cluster/hadoop/conf.nix
index e3c26a0d550..388eaafcc36 100644
--- a/nixos/modules/services/cluster/hadoop/conf.nix
+++ b/nixos/modules/services/cluster/hadoop/conf.nix
@@ -33,6 +33,7 @@ pkgs.runCommand "hadoop-conf" {} (with cfg; ''
   mkdir -p $out/
   cp ${siteXml "core-site.xml" (coreSite // coreSiteInternal)}/* $out/
   cp ${siteXml "hdfs-site.xml" (hdfsSiteDefault // hdfsSite // hdfsSiteInternal)}/* $out/
+  cp ${siteXml "hbase-site.xml" (hbaseSiteDefault // hbaseSite // hbaseSiteInternal)}/* $out/
   cp ${siteXml "mapred-site.xml" (mapredSiteDefault // mapredSite)}/* $out/
   cp ${siteXml "yarn-site.xml" (yarnSiteDefault // yarnSite // yarnSiteInternal)}/* $out/
   cp ${siteXml "httpfs-site.xml" httpfsSite}/* $out/
@@ -40,5 +41,5 @@ pkgs.runCommand "hadoop-conf" {} (with cfg; ''
   cp ${pkgs.writeTextDir "hadoop-user-functions.sh" userFunctions}/* $out/
   cp ${pkgs.writeTextDir "hadoop-env.sh" hadoopEnv}/* $out/
   cp ${log4jProperties} $out/log4j.properties
-  ${lib.concatMapStringsSep "\n" (dir: "cp -r ${dir}/* $out/") extraConfDirs}
+  ${lib.concatMapStringsSep "\n" (dir: "cp -f -r ${dir}/* $out/") extraConfDirs}
 '')
diff --git a/nixos/modules/services/cluster/hadoop/default.nix b/nixos/modules/services/cluster/hadoop/default.nix
index a4fdea81037..72bf25c2114 100644
--- a/nixos/modules/services/cluster/hadoop/default.nix
+++ b/nixos/modules/services/cluster/hadoop/default.nix
@@ -5,7 +5,7 @@ let
 in
 with lib;
 {
-  imports = [ ./yarn.nix ./hdfs.nix ];
+  imports = [ ./yarn.nix ./hdfs.nix ./hbase.nix ];
 
   options.services.hadoop = {
     coreSite = mkOption {
@@ -16,16 +16,16 @@ with lib;
           "fs.defaultFS" = "hdfs://localhost";
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Hadoop core-site.xml definition
-        <link xlink:href="https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/core-default.xml"/>
+        <https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/core-default.xml>
       '';
     };
     coreSiteInternal = mkOption {
       default = {};
       type = types.attrsOf types.anything;
       internal = true;
-      description = ''
+      description = lib.mdDoc ''
         Internal option to add configs to core-site.xml based on module options
       '';
     };
@@ -38,7 +38,7 @@ with lib;
         "dfs.namenode.http-bind-host" = "0.0.0.0";
       };
       type = types.attrsOf types.anything;
-      description = ''
+      description = lib.mdDoc ''
         Default options for hdfs-site.xml
       '';
     };
@@ -50,16 +50,16 @@ with lib;
           "dfs.nameservices" = "namenode1";
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Additional options and overrides for hdfs-site.xml
-        <link xlink:href="https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml"/>
+        <https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml>
       '';
     };
     hdfsSiteInternal = mkOption {
       default = {};
       type = types.attrsOf types.anything;
       internal = true;
-      description = ''
+      description = lib.mdDoc ''
         Internal option to add configs to hdfs-site.xml based on module options
       '';
     };
@@ -80,7 +80,7 @@ with lib;
         }
       '';
       type = types.attrsOf types.anything;
-      description = ''
+      description = lib.mdDoc ''
         Default options for mapred-site.xml
       '';
     };
@@ -92,9 +92,9 @@ with lib;
           "mapreduce.map.java.opts" = "-Xmx900m -XX:+UseParallelGC";
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Additional options and overrides for mapred-site.xml
-        <link xlink:href="https://hadoop.apache.org/docs/current/hadoop-mapreduce-client/hadoop-mapreduce-client-core/mapred-default.xml"/>
+        <https://hadoop.apache.org/docs/current/hadoop-mapreduce-client/hadoop-mapreduce-client-core/mapred-default.xml>
       '';
     };
 
@@ -113,7 +113,7 @@ with lib;
         "yarn.resourcemanager.scheduler.class" = "org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler";
       };
       type = types.attrsOf types.anything;
-      description = ''
+      description = lib.mdDoc ''
         Default options for yarn-site.xml
       '';
     };
@@ -125,16 +125,16 @@ with lib;
           "yarn.resourcemanager.hostname" = "''${config.networking.hostName}";
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Additional options and overrides for yarn-site.xml
-        <link xlink:href="https://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-common/yarn-default.xml"/>
+        <https://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-common/yarn-default.xml>
       '';
     };
     yarnSiteInternal = mkOption {
       default = {};
       type = types.attrsOf types.anything;
       internal = true;
-      description = ''
+      description = lib.mdDoc ''
         Internal option to add configs to yarn-site.xml based on module options
       '';
     };
@@ -147,9 +147,9 @@ with lib;
           "hadoop.http.max.threads" = 500;
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Hadoop httpfs-site.xml definition
-        <link xlink:href="https://hadoop.apache.org/docs/current/hadoop-hdfs-httpfs/httpfs-default.html"/>
+        <https://hadoop.apache.org/docs/current/hadoop-hdfs-httpfs/httpfs-default.html>
       '';
     };
 
@@ -162,7 +162,7 @@ with lib;
       example = literalExpression ''
         "''${pkgs.hadoop}/lib/''${pkgs.hadoop.untarDir}/etc/hadoop/log4j.properties";
       '';
-      description = "log4j.properties file added to HADOOP_CONF_DIR";
+      description = lib.mdDoc "log4j.properties file added to HADOOP_CONF_DIR";
     };
 
     containerExecutorCfg = mkOption {
@@ -179,9 +179,9 @@ with lib;
           "feature.terminal.enabled" = 0;
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Yarn container-executor.cfg definition
-        <link xlink:href="https://hadoop.apache.org/docs/r2.7.2/hadoop-yarn/hadoop-yarn-site/SecureContainer.html"/>
+        <https://hadoop.apache.org/docs/r2.7.2/hadoop-yarn/hadoop-yarn-site/SecureContainer.html>
       '';
     };
 
@@ -194,16 +194,16 @@ with lib;
           ./extraYARNConfs
         ]
       '';
-      description = "Directories containing additional config files to be added to HADOOP_CONF_DIR";
+      description = lib.mdDoc "Directories containing additional config files to be added to HADOOP_CONF_DIR";
     };
 
-    gatewayRole.enable = mkEnableOption "gateway role for deploying hadoop configs";
+    gatewayRole.enable = mkEnableOption (lib.mdDoc "gateway role for deploying hadoop configs");
 
     package = mkOption {
       type = types.package;
       default = pkgs.hadoop;
       defaultText = literalExpression "pkgs.hadoop";
-      description = "";
+      description = lib.mdDoc "";
     };
   };
 
diff --git a/nixos/modules/services/cluster/hadoop/hbase.nix b/nixos/modules/services/cluster/hadoop/hbase.nix
new file mode 100644
index 00000000000..97951ebfe33
--- /dev/null
+++ b/nixos/modules/services/cluster/hadoop/hbase.nix
@@ -0,0 +1,196 @@
+{ config, lib, pkgs, ...}:
+
+with lib;
+let
+  cfg = config.services.hadoop;
+  hadoopConf = "${import ./conf.nix { inherit cfg pkgs lib; }}/";
+  mkIfNotNull = x: mkIf (x != null) x;
+in
+{
+  options.services.hadoop = {
+
+    gatewayRole.enableHbaseCli = mkEnableOption (lib.mdDoc "HBase CLI tools");
+
+    hbaseSiteDefault = mkOption {
+      default = {
+        "hbase.regionserver.ipc.address" = "0.0.0.0";
+        "hbase.master.ipc.address" = "0.0.0.0";
+        "hbase.master.info.bindAddress" = "0.0.0.0";
+        "hbase.regionserver.info.bindAddress" = "0.0.0.0";
+
+        "hbase.cluster.distributed" = "true";
+      };
+      type = types.attrsOf types.anything;
+      description = lib.mdDoc ''
+        Default options for hbase-site.xml
+      '';
+    };
+    hbaseSite = mkOption {
+      default = {};
+      type = with types; attrsOf anything;
+      example = literalExpression ''
+      '';
+      description = lib.mdDoc ''
+        Additional options and overrides for hbase-site.xml
+        <https://github.com/apache/hbase/blob/rel/2.4.11/hbase-common/src/main/resources/hbase-default.xml>
+      '';
+    };
+    hbaseSiteInternal = mkOption {
+      default = {};
+      type = with types; attrsOf anything;
+      internal = true;
+      description = lib.mdDoc ''
+        Internal option to add configs to hbase-site.xml based on module options
+      '';
+    };
+
+    hbase = {
+
+      package = mkOption {
+        type = types.package;
+        default = pkgs.hbase;
+        defaultText = literalExpression "pkgs.hbase";
+        description = lib.mdDoc "HBase package";
+      };
+
+      rootdir = mkOption {
+        description = lib.mdDoc ''
+          This option will set "hbase.rootdir" in hbase-site.xml and determine
+          the directory shared by region servers and into which HBase persists.
+          The URL should be 'fully-qualified' to include the filesystem scheme.
+          If a core-site.xml is provided, the FS scheme defaults to the value
+          of "fs.defaultFS".
+
+          Filesystems other than HDFS (like S3, QFS, Swift) are also supported.
+        '';
+        type = types.str;
+        example = "hdfs://nameservice1/hbase";
+        default = "/hbase";
+      };
+      zookeeperQuorum = mkOption {
+        description = lib.mdDoc ''
+          This option will set "hbase.zookeeper.quorum" in hbase-site.xml.
+          Comma separated list of servers in the ZooKeeper ensemble.
+        '';
+        type = with types; nullOr commas;
+        example = "zk1.internal,zk2.internal,zk3.internal";
+        default = null;
+      };
+      master = {
+        enable = mkEnableOption (lib.mdDoc "HBase Master");
+        initHDFS = mkEnableOption (lib.mdDoc "initialization of the hbase directory on HDFS");
+
+        openFirewall = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc ''
+            Open firewall ports for HBase master.
+          '';
+        };
+      };
+      regionServer = {
+        enable = mkEnableOption (lib.mdDoc "HBase RegionServer");
+
+        overrideHosts = mkOption {
+          type = types.bool;
+          default = true;
+          description = lib.mdDoc ''
+            Remove /etc/hosts entries for "127.0.0.2" and "::1" defined in nixos/modules/config/networking.nix
+            Regionservers must be able to resolve their hostnames to their IP addresses, through PTR records
+            or /etc/hosts entries.
+
+          '';
+        };
+
+        openFirewall = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc ''
+            Open firewall ports for HBase master.
+          '';
+        };
+      };
+    };
+  };
+
+  config = mkMerge [
+    (mkIf cfg.hbase.master.enable {
+      services.hadoop.gatewayRole = {
+        enable = true;
+        enableHbaseCli = mkDefault true;
+      };
+
+      systemd.services.hbase-master = {
+        description = "HBase master";
+        wantedBy = [ "multi-user.target" ];
+
+        preStart = mkIf cfg.hbase.master.initHDFS ''
+          HADOOP_USER_NAME=hdfs ${cfg.package}/bin/hdfs --config ${hadoopConf} dfsadmin -safemode wait
+          HADOOP_USER_NAME=hdfs ${cfg.package}/bin/hdfs --config ${hadoopConf} dfs -mkdir -p ${cfg.hbase.rootdir}
+          HADOOP_USER_NAME=hdfs ${cfg.package}/bin/hdfs --config ${hadoopConf} dfs -chown hbase ${cfg.hbase.rootdir}
+        '';
+
+        serviceConfig = {
+          User = "hbase";
+          SyslogIdentifier = "hbase-master";
+          ExecStart = "${cfg.hbase.package}/bin/hbase --config ${hadoopConf} " +
+                      "master start";
+          Restart = "always";
+        };
+      };
+
+      services.hadoop.hbaseSiteInternal."hbase.rootdir" = cfg.hbase.rootdir;
+
+      networking.firewall.allowedTCPPorts = mkIf cfg.hbase.master.openFirewall [
+        16000 16010
+      ];
+
+    })
+
+    (mkIf cfg.hbase.regionServer.enable {
+      services.hadoop.gatewayRole = {
+        enable = true;
+        enableHbaseCli = mkDefault true;
+      };
+
+      systemd.services.hbase-regionserver = {
+        description = "HBase RegionServer";
+        wantedBy = [ "multi-user.target" ];
+        serviceConfig = {
+          User = "hbase";
+          SyslogIdentifier = "hbase-regionserver";
+          ExecStart = "${cfg.hbase.package}/bin/hbase --config /etc/hadoop-conf/ " +
+                      "regionserver start";
+          Restart = "always";
+        };
+      };
+
+      services.hadoop.hbaseSiteInternal."hbase.rootdir" = cfg.hbase.rootdir;
+
+      networking = {
+        firewall.allowedTCPPorts = mkIf cfg.hbase.regionServer.openFirewall [
+          16020 16030
+        ];
+        hosts = mkIf cfg.hbase.regionServer.overrideHosts {
+          "127.0.0.2" = mkForce [ ];
+          "::1" = mkForce [ ];
+        };
+      };
+    })
+
+    (mkIf cfg.gatewayRole.enable {
+
+      environment.systemPackages = mkIf cfg.gatewayRole.enableHbaseCli [ cfg.hbase.package ];
+
+      services.hadoop.hbaseSiteInternal = with cfg.hbase; {
+        "hbase.zookeeper.quorum" = mkIfNotNull zookeeperQuorum;
+      };
+
+      users.users.hbase = {
+        description = "Hadoop HBase user";
+        group = "hadoop";
+        isSystemUser = true;
+      };
+    })
+  ];
+}
diff --git a/nixos/modules/services/cluster/hadoop/hdfs.nix b/nixos/modules/services/cluster/hadoop/hdfs.nix
index 325a002ad32..4a49bd0ddd4 100644
--- a/nixos/modules/services/cluster/hadoop/hdfs.nix
+++ b/nixos/modules/services/cluster/hadoop/hdfs.nix
@@ -8,10 +8,10 @@ let
 
   # Generator for HDFS service options
   hadoopServiceOption = { serviceName, firewallOption ? true, extraOpts ? null }: {
-    enable = mkEnableOption serviceName;
+    enable = mkEnableOption (lib.mdDoc serviceName);
     restartIfChanged = mkOption {
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Automatically restart the service on config change.
         This can be set to false to defer restarts on clusters running critical applications.
         Please consider the security implications of inadvertently running an older version,
@@ -22,7 +22,7 @@ let
     extraFlags = mkOption{
       type = with types; listOf str;
       default = [];
-      description = "Extra command line flags to pass to ${serviceName}";
+      description = lib.mdDoc "Extra command line flags to pass to ${serviceName}";
       example = [
         "-Dcom.sun.management.jmxremote"
         "-Dcom.sun.management.jmxremote.port=8010"
@@ -31,13 +31,13 @@ let
     extraEnv = mkOption{
       type = with types; attrsOf str;
       default = {};
-      description = "Extra environment variables for ${serviceName}";
+      description = lib.mdDoc "Extra environment variables for ${serviceName}";
     };
   } // (optionalAttrs firewallOption {
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = "Open firewall ports for ${serviceName}.";
+      description = lib.mdDoc "Open firewall ports for ${serviceName}.";
     };
   }) // (optionalAttrs (extraOpts != null) extraOpts);
 
@@ -83,12 +83,12 @@ in
       formatOnInit = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Format HDFS namenode on first start. This is useful for quickly spinning up
           ephemeral HDFS clusters with a single namenode.
           For HA clusters, initialization involves multiple steps across multiple nodes.
           Follow this guide to initialize an HA cluster manually:
-          <link xlink:href="https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HDFSHighAvailabilityWithQJM.html"/>
+          <https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HDFSHighAvailabilityWithQJM.html>
         '';
       };
     };
@@ -96,19 +96,19 @@ in
     datanode = hadoopServiceOption { serviceName = "HDFS DataNode"; } // {
       dataDirs = mkOption {
         default = null;
-        description = "Tier and path definitions for datanode storage.";
+        description = lib.mdDoc "Tier and path definitions for datanode storage.";
         type = with types; nullOr (listOf (submodule {
           options = {
             type = mkOption {
               type = enum [ "SSD" "DISK" "ARCHIVE" "RAM_DISK" ];
-              description = ''
+              description = lib.mdDoc ''
                 Storage types ([SSD]/[DISK]/[ARCHIVE]/[RAM_DISK]) for HDFS storage policies.
               '';
             };
             path = mkOption {
               type = path;
               example = [ "/var/lib/hadoop/hdfs/dn" ];
-              description = "Determines where on the local filesystem a data node should store its blocks.";
+              description = lib.mdDoc "Determines where on the local filesystem a data node should store its blocks.";
             };
           };
         }));
@@ -126,7 +126,7 @@ in
       tempPath = mkOption {
         type = types.path;
         default = "/tmp/hadoop/httpfs";
-        description = "HTTPFS_TEMP path used by HTTPFS";
+        description = lib.mdDoc "HTTPFS_TEMP path used by HTTPFS";
       };
     };
 
@@ -158,8 +158,8 @@ in
         50010 # datanode.address
         50020 # datanode.ipc.address
       ];
-      extraConfig.services.hadoop.hdfsSiteInternal."dfs.datanode.data.dir" = let d = cfg.hdfs.datanode.dataDirs; in
-        if (d!= null) then (concatMapStringsSep "," (x: "["+x.type+"]file://"+x.path) cfg.hdfs.datanode.dataDirs) else d;
+      extraConfig.services.hadoop.hdfsSiteInternal."dfs.datanode.data.dir" = mkIf (cfg.hdfs.datanode.dataDirs!= null)
+        (concatMapStringsSep "," (x: "["+x.type+"]file://"+x.path) cfg.hdfs.datanode.dataDirs);
     })
 
     (hadoopServiceConfig {
diff --git a/nixos/modules/services/cluster/hadoop/yarn.nix b/nixos/modules/services/cluster/hadoop/yarn.nix
index 74e16bdec68..26077f35fdd 100644
--- a/nixos/modules/services/cluster/hadoop/yarn.nix
+++ b/nixos/modules/services/cluster/hadoop/yarn.nix
@@ -5,7 +5,7 @@ let
   hadoopConf = "${import ./conf.nix { inherit cfg pkgs lib; }}/";
   restartIfChanged  = mkOption {
     type = types.bool;
-    description = ''
+    description = lib.mdDoc ''
       Automatically restart the service on config change.
       This can be set to false to defer restarts on clusters running critical applications.
       Please consider the security implications of inadvertently running an older version,
@@ -16,7 +16,7 @@ let
   extraFlags = mkOption{
     type = with types; listOf str;
     default = [];
-    description = "Extra command line flags to pass to the service";
+    description = lib.mdDoc "Extra command line flags to pass to the service";
     example = [
       "-Dcom.sun.management.jmxremote"
       "-Dcom.sun.management.jmxremote.port=8010"
@@ -25,45 +25,45 @@ let
   extraEnv = mkOption{
     type = with types; attrsOf str;
     default = {};
-    description = "Extra environment variables";
+    description = lib.mdDoc "Extra environment variables";
   };
 in
 {
   options.services.hadoop.yarn = {
     resourcemanager = {
-      enable = mkEnableOption "Hadoop YARN ResourceManager";
+      enable = mkEnableOption (lib.mdDoc "Hadoop YARN ResourceManager");
       inherit restartIfChanged extraFlags extraEnv;
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open firewall ports for resourcemanager
         '';
       };
     };
     nodemanager = {
-      enable = mkEnableOption "Hadoop YARN NodeManager";
+      enable = mkEnableOption (lib.mdDoc "Hadoop YARN NodeManager");
       inherit restartIfChanged extraFlags extraEnv;
 
       resource = {
         cpuVCores = mkOption {
-          description = "Number of vcores that can be allocated for containers.";
+          description = lib.mdDoc "Number of vcores that can be allocated for containers.";
           type = with types; nullOr ints.positive;
           default = null;
         };
         maximumAllocationVCores = mkOption {
-          description = "The maximum virtual CPU cores any container can be allocated.";
+          description = lib.mdDoc "The maximum virtual CPU cores any container can be allocated.";
           type = with types; nullOr ints.positive;
           default = null;
         };
         memoryMB = mkOption {
-          description = "Amount of physical memory, in MB, that can be allocated for containers.";
+          description = lib.mdDoc "Amount of physical memory, in MB, that can be allocated for containers.";
           type = with types; nullOr ints.positive;
           default = null;
         };
         maximumAllocationMB = mkOption {
-          description = "The maximum physical memory any container can be allocated.";
+          description = lib.mdDoc "The maximum physical memory any container can be allocated.";
           type = with types; nullOr ints.positive;
           default = null;
         };
@@ -72,13 +72,13 @@ in
       useCGroups = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Use cgroups to enforce resource limits on containers
         '';
       };
 
       localDir = mkOption {
-        description = "List of directories to store localized files in.";
+        description = lib.mdDoc "List of directories to store localized files in.";
         type = with types; nullOr (listOf path);
         example = [ "/var/lib/hadoop/yarn/nm" ];
         default = null;
@@ -87,14 +87,14 @@ in
       addBinBash = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Add /bin/bash. This is needed by the linux container executor's launch script.
         '';
       };
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open firewall ports for nodemanager.
           Because containers can listen on any ephemeral port, TCP ports 1024–65535 will be opened.
         '';
@@ -178,18 +178,18 @@ in
 
       services.hadoop.gatewayRole.enable = true;
 
-      services.hadoop.yarnSiteInternal = with cfg.yarn.nodemanager; {
-        "yarn.nodemanager.local-dirs" = localDir;
+      services.hadoop.yarnSiteInternal = with cfg.yarn.nodemanager; mkMerge [ ({
+        "yarn.nodemanager.local-dirs" = mkIf (localDir!= null) (concatStringsSep "," localDir);
         "yarn.scheduler.maximum-allocation-vcores" = resource.maximumAllocationVCores;
         "yarn.scheduler.maximum-allocation-mb" = resource.maximumAllocationMB;
         "yarn.nodemanager.resource.cpu-vcores" = resource.cpuVCores;
         "yarn.nodemanager.resource.memory-mb" = resource.memoryMB;
-      } // mkIf useCGroups {
+      }) (mkIf useCGroups {
         "yarn.nodemanager.linux-container-executor.cgroups.hierarchy" = "/hadoop-yarn";
         "yarn.nodemanager.linux-container-executor.resources-handler.class" = "org.apache.hadoop.yarn.server.nodemanager.util.CgroupsLCEResourcesHandler";
         "yarn.nodemanager.linux-container-executor.cgroups.mount" = "true";
         "yarn.nodemanager.linux-container-executor.cgroups.mount-path" = "/run/wrappers/yarn-nodemanager/cgroup";
-      };
+      })];
 
       networking.firewall.allowedTCPPortRanges = [
         (mkIf (cfg.yarn.nodemanager.openFirewall) {from = 1024; to = 65535;})
diff --git a/nixos/modules/services/cluster/k3s/default.nix b/nixos/modules/services/cluster/k3s/default.nix
index 3a36cfa3f37..693f388de14 100644
--- a/nixos/modules/services/cluster/k3s/default.nix
+++ b/nixos/modules/services/cluster/k3s/default.nix
@@ -3,23 +3,39 @@
 with lib;
 let
   cfg = config.services.k3s;
+  removeOption = config: instruction:
+    lib.mkRemovedOptionModule ([ "services" "k3s" ] ++ config) instruction;
 in
 {
+  imports = [
+    (removeOption [ "docker" ] "k3s docker option is no longer supported.")
+  ];
+
   # interface
   options.services.k3s = {
-    enable = mkEnableOption "k3s";
+    enable = mkEnableOption (lib.mdDoc "k3s");
 
     package = mkOption {
       type = types.package;
       default = pkgs.k3s;
       defaultText = literalExpression "pkgs.k3s";
-      description = "Package that should be used for k3s";
+      description = lib.mdDoc "Package that should be used for k3s";
     };
 
     role = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Whether k3s should run as a server or agent.
-        Note that the server, by default, also runs as an agent.
+
+        If it's a server:
+
+        - By default it also runs workloads as an agent.
+        - Starts by default as a standalone server using an embedded sqlite datastore.
+        - Configure `clusterInit = true` to switch over to embedded etcd datastore and enable HA mode.
+        - Configure `serverAddr` to join an already-initialized HA cluster.
+
+        If it's an agent:
+
+        - `serverAddr` is required.
       '';
       default = "server";
       type = types.enum [ "server" "agent" ];
@@ -27,15 +43,44 @@ in
 
     serverAddr = mkOption {
       type = types.str;
-      description = "The k3s server to connect to. This option only makes sense for an agent.";
+      description = lib.mdDoc ''
+        The k3s server to connect to.
+
+        Servers and agents need to communicate each other. Read
+        [the networking docs](https://rancher.com/docs/k3s/latest/en/installation/installation-requirements/#networking)
+        to know how to configure the firewall.
+      '';
       example = "https://10.0.0.10:6443";
       default = "";
     };
 
+    clusterInit = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Initialize HA cluster using an embedded etcd datastore.
+
+        If this option is `false` and `role` is `server`
+
+        On a server that was using the default embedded sqlite backend,
+        enabling this option will migrate to an embedded etcd DB.
+
+        If an HA cluster using the embedded etcd datastore was already initialized,
+        this option has no effect.
+
+        This option only makes sense in a server that is not connecting to another server.
+
+        If you are configuring an HA cluster with an embedded etcd,
+        the 1st server must have `clusterInit = true`
+        and other servers must connect to it using `serverAddr`.
+      '';
+    };
+
     token = mkOption {
       type = types.str;
-      description = ''
-        The k3s token to use when connecting to the server. This option only makes sense for an agent.
+      description = lib.mdDoc ''
+        The k3s token to use when connecting to a server.
+
         WARNING: This option will expose store your token unencrypted world-readable in the nix store.
         If this is undesired use the tokenFile option instead.
       '';
@@ -44,18 +89,12 @@ in
 
     tokenFile = mkOption {
       type = types.nullOr types.path;
-      description = "File path containing k3s token to use when connecting to the server. This option only makes sense for an agent.";
+      description = lib.mdDoc "File path containing k3s token to use when connecting to the server.";
       default = null;
     };
 
-    docker = mkOption {
-      type = types.bool;
-      default = false;
-      description = "Use docker to run containers rather than the built-in containerd.";
-    };
-
     extraFlags = mkOption {
-      description = "Extra flags to pass to the k3s command.";
+      description = lib.mdDoc "Extra flags to pass to the k3s command.";
       type = types.str;
       default = "";
       example = "--no-deploy traefik --cluster-cidr 10.24.0.0/16";
@@ -64,13 +103,13 @@ in
     disableAgent = mkOption {
       type = types.bool;
       default = false;
-      description = "Only run the server. This option only makes sense for a server.";
+      description = lib.mdDoc "Only run the server. This option only makes sense for a server.";
     };
 
     configPath = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = "File path containing the k3s YAML config. This is useful when the config is generated (for example on boot).";
+      description = lib.mdDoc "File path containing the k3s YAML config. This is useful when the config is generated (for example on boot).";
     };
   };
 
@@ -86,16 +125,21 @@ in
         assertion = cfg.role == "agent" -> cfg.configPath != null || cfg.tokenFile != null || cfg.token != "";
         message = "token or tokenFile or configPath (with 'token' or 'token-file' keys) should be set if role is 'agent'";
       }
+      {
+        assertion = cfg.role == "agent" -> !cfg.disableAgent;
+        message = "disableAgent must be false if role is 'agent'";
+      }
+      {
+        assertion = cfg.role == "agent" -> !cfg.clusterInit;
+        message = "clusterInit must be false if role is 'agent'";
+      }
     ];
 
-    virtualisation.docker = mkIf cfg.docker {
-      enable = mkDefault true;
-    };
     environment.systemPackages = [ config.services.k3s.package ];
 
     systemd.services.k3s = {
       description = "k3s service";
-      after = [ "network.service" "firewall.service" ] ++ (optional cfg.docker "docker.service");
+      after = [ "network.service" "firewall.service" ];
       wants = [ "network.service" "firewall.service" ];
       wantedBy = [ "multi-user.target" ];
       path = optional config.boot.zfs.enabled config.boot.zfs.package;
@@ -113,8 +157,8 @@ in
         ExecStart = concatStringsSep " \\\n " (
           [
             "${cfg.package}/bin/k3s ${cfg.role}"
-          ] ++ (optional cfg.docker "--docker")
-          ++ (optional (cfg.docker && config.systemd.enableUnifiedCgroupHierarchy) "--kubelet-arg=cgroup-driver=systemd")
+          ]
+          ++ (optional cfg.clusterInit "--cluster-init")
           ++ (optional cfg.disableAgent "--disable-agent")
           ++ (optional (cfg.serverAddr != "") "--server ${cfg.serverAddr}")
           ++ (optional (cfg.token != "") "--token ${cfg.token}")
diff --git a/nixos/modules/services/cluster/kubernetes/addon-manager.nix b/nixos/modules/services/cluster/kubernetes/addon-manager.nix
index b677d900ff5..d6b3428908b 100644
--- a/nixos/modules/services/cluster/kubernetes/addon-manager.nix
+++ b/nixos/modules/services/cluster/kubernetes/addon-manager.nix
@@ -21,7 +21,7 @@ in
   options.services.kubernetes.addonManager = with lib.types; {
 
     bootstrapAddons = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Bootstrap addons are like regular addons, but they are applied with cluster-admin rigths.
         They are applied at addon-manager startup only.
       '';
@@ -43,7 +43,7 @@ in
     };
 
     addons = mkOption {
-      description = "Kubernetes addons (any kind of Kubernetes resource can be an addon).";
+      description = lib.mdDoc "Kubernetes addons (any kind of Kubernetes resource can be an addon).";
       default = { };
       type = attrsOf (either attrs (listOf attrs));
       example = literalExpression ''
@@ -62,7 +62,7 @@ in
       '';
     };
 
-    enable = mkEnableOption "Kubernetes addon manager.";
+    enable = mkEnableOption (lib.mdDoc "Kubernetes addon manager.");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/cluster/kubernetes/addons/dns.nix b/nixos/modules/services/cluster/kubernetes/addons/dns.nix
index 7bd4991f43f..3d41b5f0085 100644
--- a/nixos/modules/services/cluster/kubernetes/addons/dns.nix
+++ b/nixos/modules/services/cluster/kubernetes/addons/dns.nix
@@ -12,10 +12,10 @@ let
   };
 in {
   options.services.kubernetes.addons.dns = {
-    enable = mkEnableOption "kubernetes dns addon";
+    enable = mkEnableOption (lib.mdDoc "kubernetes dns addon");
 
     clusterIp = mkOption {
-      description = "Dns addon clusterIP";
+      description = lib.mdDoc "Dns addon clusterIP";
 
       # this default is also what kubernetes users
       default = (
@@ -23,39 +23,39 @@ in {
           take 3 (splitString "." config.services.kubernetes.apiserver.serviceClusterIpRange
         ))
       ) + ".254";
-      defaultText = literalDocBook ''
-        The <literal>x.y.z.254</literal> IP of
-        <literal>config.${options.services.kubernetes.apiserver.serviceClusterIpRange}</literal>.
+      defaultText = literalMD ''
+        The `x.y.z.254` IP of
+        `config.${options.services.kubernetes.apiserver.serviceClusterIpRange}`.
       '';
       type = types.str;
     };
 
     clusterDomain = mkOption {
-      description = "Dns cluster domain";
+      description = lib.mdDoc "Dns cluster domain";
       default = "cluster.local";
       type = types.str;
     };
 
     replicas = mkOption {
-      description = "Number of DNS pod replicas to deploy in the cluster.";
+      description = lib.mdDoc "Number of DNS pod replicas to deploy in the cluster.";
       default = 2;
       type = types.int;
     };
 
     reconcileMode = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Controls the addon manager reconciliation mode for the DNS addon.
 
         Setting reconcile mode to EnsureExists makes it possible to tailor DNS behavior by editing the coredns ConfigMap.
 
-        See: <link xlink:href="https://github.com/kubernetes/kubernetes/blob/master/cluster/addons/addon-manager/README.md"/>.
+        See: <https://github.com/kubernetes/kubernetes/blob/master/cluster/addons/addon-manager/README.md>.
       '';
       default = "Reconcile";
       type = types.enum [ "Reconcile" "EnsureExists" ];
     };
 
     coredns = mkOption {
-      description = "Docker image to seed for the CoreDNS container.";
+      description = lib.mdDoc "Docker image to seed for the CoreDNS container.";
       type = types.attrs;
       default = {
         imageName = "coredns/coredns";
@@ -66,10 +66,10 @@ in {
     };
 
     corefile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Custom coredns corefile configuration.
 
-        See: <link xlink:href="https://coredns.io/manual/toc/#configuration"/>.
+        See: <https://coredns.io/manual/toc/#configuration>.
       '';
       type = types.str;
       default = ''
diff --git a/nixos/modules/services/cluster/kubernetes/apiserver.nix b/nixos/modules/services/cluster/kubernetes/apiserver.nix
index a192e93badc..d5ec1e5e6d2 100644
--- a/nixos/modules/services/cluster/kubernetes/apiserver.nix
+++ b/nixos/modules/services/cluster/kubernetes/apiserver.nix
@@ -18,7 +18,8 @@ in
   imports = [
     (mkRenamedOptionModule [ "services" "kubernetes" "apiserver" "admissionControl" ] [ "services" "kubernetes" "apiserver" "enableAdmissionPlugins" ])
     (mkRenamedOptionModule [ "services" "kubernetes" "apiserver" "address" ] ["services" "kubernetes" "apiserver" "bindAddress"])
-    (mkRenamedOptionModule [ "services" "kubernetes" "apiserver" "port" ] ["services" "kubernetes" "apiserver" "insecurePort"])
+    (mkRemovedOptionModule [ "services" "kubernetes" "apiserver" "insecureBindAddress" ] "")
+    (mkRemovedOptionModule [ "services" "kubernetes" "apiserver" "insecurePort" ] "")
     (mkRemovedOptionModule [ "services" "kubernetes" "apiserver" "publicAddress" ] "")
     (mkRenamedOptionModule [ "services" "kubernetes" "etcd" "servers" ] [ "services" "kubernetes" "apiserver" "etcd" "servers" ])
     (mkRenamedOptionModule [ "services" "kubernetes" "etcd" "keyFile" ] [ "services" "kubernetes" "apiserver" "etcd" "keyFile" ])
@@ -30,7 +31,7 @@ in
   options.services.kubernetes.apiserver = with lib.types; {
 
     advertiseAddress = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver IP address on which to advertise the apiserver
         to members of the cluster. This address must be reachable by the rest
         of the cluster.
@@ -40,40 +41,40 @@ in
     };
 
     allowPrivileged = mkOption {
-      description = "Whether to allow privileged containers on Kubernetes.";
+      description = lib.mdDoc "Whether to allow privileged containers on Kubernetes.";
       default = false;
       type = bool;
     };
 
     authorizationMode = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver authorization mode (AlwaysAllow/AlwaysDeny/ABAC/Webhook/RBAC/Node). See
-        <link xlink:href="https://kubernetes.io/docs/reference/access-authn-authz/authorization/"/>
+        <https://kubernetes.io/docs/reference/access-authn-authz/authorization/>
       '';
       default = ["RBAC" "Node"]; # Enabling RBAC by default, although kubernetes default is AllowAllow
       type = listOf (enum ["AlwaysAllow" "AlwaysDeny" "ABAC" "Webhook" "RBAC" "Node"]);
     };
 
     authorizationPolicy = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver authorization policy file. See
-        <link xlink:href="https://kubernetes.io/docs/reference/access-authn-authz/authorization/"/>
+        <https://kubernetes.io/docs/reference/access-authn-authz/authorization/>
       '';
       default = [];
       type = listOf attrs;
     };
 
     basicAuthFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver basic authentication file. See
-        <link xlink:href="https://kubernetes.io/docs/reference/access-authn-authz/authentication"/>
+        <https://kubernetes.io/docs/reference/access-authn-authz/authentication>
       '';
       default = null;
       type = nullOr path;
     };
 
     bindAddress = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The IP address on which to listen for the --secure-port port.
         The associated interface(s) must be reachable by the rest
         of the cluster, and by CLI/web clients.
@@ -83,27 +84,27 @@ in
     };
 
     clientCaFile = mkOption {
-      description = "Kubernetes apiserver CA file for client auth.";
+      description = lib.mdDoc "Kubernetes apiserver CA file for client auth.";
       default = top.caFile;
       defaultText = literalExpression "config.${otop.caFile}";
       type = nullOr path;
     };
 
     disableAdmissionPlugins = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes admission control plugins to disable. See
-        <link xlink:href="https://kubernetes.io/docs/admin/admission-controllers/"/>
+        <https://kubernetes.io/docs/admin/admission-controllers/>
       '';
       default = [];
       type = listOf str;
     };
 
-    enable = mkEnableOption "Kubernetes apiserver";
+    enable = mkEnableOption (lib.mdDoc "Kubernetes apiserver");
 
     enableAdmissionPlugins = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes admission control plugins to enable. See
-        <link xlink:href="https://kubernetes.io/docs/admin/admission-controllers/"/>
+        <https://kubernetes.io/docs/admin/admission-controllers/>
       '';
       default = [
         "NamespaceLifecycle" "LimitRanger" "ServiceAccount"
@@ -120,25 +121,25 @@ in
 
     etcd = {
       servers = mkOption {
-        description = "List of etcd servers.";
+        description = lib.mdDoc "List of etcd servers.";
         default = ["http://127.0.0.1:2379"];
         type = types.listOf types.str;
       };
 
       keyFile = mkOption {
-        description = "Etcd key file.";
+        description = lib.mdDoc "Etcd key file.";
         default = null;
         type = types.nullOr types.path;
       };
 
       certFile = mkOption {
-        description = "Etcd cert file.";
+        description = lib.mdDoc "Etcd cert file.";
         default = null;
         type = types.nullOr types.path;
       };
 
       caFile = mkOption {
-        description = "Etcd ca file.";
+        description = lib.mdDoc "Etcd ca file.";
         default = top.caFile;
         defaultText = literalExpression "config.${otop.caFile}";
         type = types.nullOr types.path;
@@ -146,77 +147,65 @@ in
     };
 
     extraOpts = mkOption {
-      description = "Kubernetes apiserver extra command line options.";
+      description = lib.mdDoc "Kubernetes apiserver extra command line options.";
       default = "";
       type = separatedString " ";
     };
 
     extraSANs = mkOption {
-      description = "Extra x509 Subject Alternative Names to be added to the kubernetes apiserver tls cert.";
+      description = lib.mdDoc "Extra x509 Subject Alternative Names to be added to the kubernetes apiserver tls cert.";
       default = [];
       type = listOf str;
     };
 
     featureGates = mkOption {
-      description = "List set of feature gates";
+      description = lib.mdDoc "List set of feature gates";
       default = top.featureGates;
       defaultText = literalExpression "config.${otop.featureGates}";
       type = listOf str;
     };
 
-    insecureBindAddress = mkOption {
-      description = "The IP address on which to serve the --insecure-port.";
-      default = "127.0.0.1";
-      type = str;
-    };
-
-    insecurePort = mkOption {
-      description = "Kubernetes apiserver insecure listening port. (0 = disabled)";
-      default = 0;
-      type = int;
-    };
-
     kubeletClientCaFile = mkOption {
-      description = "Path to a cert file for connecting to kubelet.";
+      description = lib.mdDoc "Path to a cert file for connecting to kubelet.";
       default = top.caFile;
       defaultText = literalExpression "config.${otop.caFile}";
       type = nullOr path;
     };
 
     kubeletClientCertFile = mkOption {
-      description = "Client certificate to use for connections to kubelet.";
+      description = lib.mdDoc "Client certificate to use for connections to kubelet.";
       default = null;
       type = nullOr path;
     };
 
     kubeletClientKeyFile = mkOption {
-      description = "Key to use for connections to kubelet.";
+      description = lib.mdDoc "Key to use for connections to kubelet.";
       default = null;
       type = nullOr path;
     };
 
     preferredAddressTypes = mkOption {
-      description = "List of the preferred NodeAddressTypes to use for kubelet connections.";
+      description = lib.mdDoc "List of the preferred NodeAddressTypes to use for kubelet connections.";
       type = nullOr str;
       default = null;
     };
 
     proxyClientCertFile = mkOption {
-      description = "Client certificate to use for connections to proxy.";
+      description = lib.mdDoc "Client certificate to use for connections to proxy.";
       default = null;
       type = nullOr path;
     };
 
     proxyClientKeyFile = mkOption {
-      description = "Key to use for connections to proxy.";
+      description = lib.mdDoc "Key to use for connections to proxy.";
       default = null;
       type = nullOr path;
     };
 
     runtimeConfig = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Api runtime configuration. See
-        <link xlink:href="https://kubernetes.io/docs/tasks/administer-cluster/cluster-management/"/>
+        <https://kubernetes.io/docs/tasks/administer-cluster/cluster-management/>
       '';
       default = "authentication.k8s.io/v1beta1=true";
       example = "api/all=false,api/v1=true";
@@ -224,7 +213,7 @@ in
     };
 
     storageBackend = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver storage backend.
       '';
       default = "etcd3";
@@ -232,13 +221,13 @@ in
     };
 
     securePort = mkOption {
-      description = "Kubernetes apiserver secure port.";
+      description = lib.mdDoc "Kubernetes apiserver secure port.";
       default = 6443;
       type = int;
     };
 
     apiAudiences = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver ServiceAccount issuer.
       '';
       default = "api,https://kubernetes.default.svc";
@@ -246,7 +235,7 @@ in
     };
 
     serviceAccountIssuer = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver ServiceAccount issuer.
       '';
       default = "https://kubernetes.default.svc";
@@ -254,7 +243,7 @@ in
     };
 
     serviceAccountSigningKeyFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Path to the file that contains the current private key of the service
         account token issuer. The issuer will sign issued ID tokens with this
         private key.
@@ -263,7 +252,7 @@ in
     };
 
     serviceAccountKeyFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         File containing PEM-encoded x509 RSA or ECDSA private or public keys,
         used to verify ServiceAccount tokens. The specified file can contain
         multiple keys, and the flag can be specified multiple times with
@@ -274,7 +263,7 @@ in
     };
 
     serviceClusterIpRange = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         A CIDR notation IP range from which to assign service cluster IPs.
         This must not overlap with any IP ranges assigned to nodes for pods.
       '';
@@ -283,39 +272,39 @@ in
     };
 
     tlsCertFile = mkOption {
-      description = "Kubernetes apiserver certificate file.";
+      description = lib.mdDoc "Kubernetes apiserver certificate file.";
       default = null;
       type = nullOr path;
     };
 
     tlsKeyFile = mkOption {
-      description = "Kubernetes apiserver private key file.";
+      description = lib.mdDoc "Kubernetes apiserver private key file.";
       default = null;
       type = nullOr path;
     };
 
     tokenAuthFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver token authentication file. See
-        <link xlink:href="https://kubernetes.io/docs/reference/access-authn-authz/authentication"/>
+        <https://kubernetes.io/docs/reference/access-authn-authz/authentication>
       '';
       default = null;
       type = nullOr path;
     };
 
     verbosity = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Optional glog verbosity level for logging statements. See
-        <link xlink:href="https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md"/>
+        <https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md>
       '';
       default = null;
       type = nullOr int;
     };
 
     webhookConfig = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes apiserver Webhook config file. It uses the kubeconfig file format.
-        See <link xlink:href="https://kubernetes.io/docs/reference/access-authn-authz/webhook/"/>
+        See <https://kubernetes.io/docs/reference/access-authn-authz/webhook/>
       '';
       default = null;
       type = nullOr path;
@@ -376,8 +365,6 @@ in
                 "--proxy-client-cert-file=${cfg.proxyClientCertFile}"} \
               ${optionalString (cfg.proxyClientKeyFile != null)
                 "--proxy-client-key-file=${cfg.proxyClientKeyFile}"} \
-              --insecure-bind-address=${cfg.insecureBindAddress} \
-              --insecure-port=${toString cfg.insecurePort} \
               ${optionalString (cfg.runtimeConfig != "")
                 "--runtime-config=${cfg.runtimeConfig}"} \
               --secure-port=${toString cfg.securePort} \
diff --git a/nixos/modules/services/cluster/kubernetes/controller-manager.nix b/nixos/modules/services/cluster/kubernetes/controller-manager.nix
index 7c317e94dee..18c82fc2359 100644
--- a/nixos/modules/services/cluster/kubernetes/controller-manager.nix
+++ b/nixos/modules/services/cluster/kubernetes/controller-manager.nix
@@ -10,62 +10,56 @@ in
 {
   imports = [
     (mkRenamedOptionModule [ "services" "kubernetes" "controllerManager" "address" ] ["services" "kubernetes" "controllerManager" "bindAddress"])
-    (mkRenamedOptionModule [ "services" "kubernetes" "controllerManager" "port" ] ["services" "kubernetes" "controllerManager" "insecurePort"])
+    (mkRemovedOptionModule [ "services" "kubernetes" "controllerManager" "insecurePort" ] "")
   ];
 
   ###### interface
   options.services.kubernetes.controllerManager = with lib.types; {
 
     allocateNodeCIDRs = mkOption {
-      description = "Whether to automatically allocate CIDR ranges for cluster nodes.";
+      description = lib.mdDoc "Whether to automatically allocate CIDR ranges for cluster nodes.";
       default = true;
       type = bool;
     };
 
     bindAddress = mkOption {
-      description = "Kubernetes controller manager listening address.";
+      description = lib.mdDoc "Kubernetes controller manager listening address.";
       default = "127.0.0.1";
       type = str;
     };
 
     clusterCidr = mkOption {
-      description = "Kubernetes CIDR Range for Pods in cluster.";
+      description = lib.mdDoc "Kubernetes CIDR Range for Pods in cluster.";
       default = top.clusterCidr;
       defaultText = literalExpression "config.${otop.clusterCidr}";
       type = str;
     };
 
-    enable = mkEnableOption "Kubernetes controller manager";
+    enable = mkEnableOption (lib.mdDoc "Kubernetes controller manager");
 
     extraOpts = mkOption {
-      description = "Kubernetes controller manager extra command line options.";
+      description = lib.mdDoc "Kubernetes controller manager extra command line options.";
       default = "";
       type = separatedString " ";
     };
 
     featureGates = mkOption {
-      description = "List set of feature gates";
+      description = lib.mdDoc "List set of feature gates";
       default = top.featureGates;
       defaultText = literalExpression "config.${otop.featureGates}";
       type = listOf str;
     };
 
-    insecurePort = mkOption {
-      description = "Kubernetes controller manager insecure listening port.";
-      default = 0;
-      type = int;
-    };
-
     kubeconfig = top.lib.mkKubeConfigOptions "Kubernetes controller manager";
 
     leaderElect = mkOption {
-      description = "Whether to start leader election before executing main loop.";
+      description = lib.mdDoc "Whether to start leader election before executing main loop.";
       type = bool;
       default = true;
     };
 
     rootCaFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes controller manager certificate authority file included in
         service account's token secret.
       '';
@@ -75,13 +69,13 @@ in
     };
 
     securePort = mkOption {
-      description = "Kubernetes controller manager secure listening port.";
+      description = lib.mdDoc "Kubernetes controller manager secure listening port.";
       default = 10252;
       type = int;
     };
 
     serviceAccountKeyFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes controller manager PEM-encoded private RSA key file used to
         sign service account tokens
       '';
@@ -90,21 +84,21 @@ in
     };
 
     tlsCertFile = mkOption {
-      description = "Kubernetes controller-manager certificate file.";
+      description = lib.mdDoc "Kubernetes controller-manager certificate file.";
       default = null;
       type = nullOr path;
     };
 
     tlsKeyFile = mkOption {
-      description = "Kubernetes controller-manager private key file.";
+      description = lib.mdDoc "Kubernetes controller-manager private key file.";
       default = null;
       type = nullOr path;
     };
 
     verbosity = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Optional glog verbosity level for logging statements. See
-        <link xlink:href="https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md"/>
+        <https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md>
       '';
       default = null;
       type = nullOr int;
@@ -133,7 +127,6 @@ in
           --leader-elect=${boolToString cfg.leaderElect} \
           ${optionalString (cfg.rootCaFile!=null)
             "--root-ca-file=${cfg.rootCaFile}"} \
-          --port=${toString cfg.insecurePort} \
           --secure-port=${toString cfg.securePort} \
           ${optionalString (cfg.serviceAccountKeyFile!=null)
             "--service-account-private-key-file=${cfg.serviceAccountKeyFile}"} \
diff --git a/nixos/modules/services/cluster/kubernetes/default.nix b/nixos/modules/services/cluster/kubernetes/default.nix
index 35ec99d83c8..f5374fc7194 100644
--- a/nixos/modules/services/cluster/kubernetes/default.nix
+++ b/nixos/modules/services/cluster/kubernetes/default.nix
@@ -77,25 +77,25 @@ let
 
   mkKubeConfigOptions = prefix: {
     server = mkOption {
-      description = "${prefix} kube-apiserver server address.";
+      description = lib.mdDoc "${prefix} kube-apiserver server address.";
       type = types.str;
     };
 
     caFile = mkOption {
-      description = "${prefix} certificate authority file used to connect to kube-apiserver.";
+      description = lib.mdDoc "${prefix} certificate authority file used to connect to kube-apiserver.";
       type = types.nullOr types.path;
       default = cfg.caFile;
       defaultText = literalExpression "config.${opt.caFile}";
     };
 
     certFile = mkOption {
-      description = "${prefix} client certificate file used to connect to kube-apiserver.";
+      description = lib.mdDoc "${prefix} client certificate file used to connect to kube-apiserver.";
       type = types.nullOr types.path;
       default = null;
     };
 
     keyFile = mkOption {
-      description = "${prefix} client key file used to connect to kube-apiserver.";
+      description = lib.mdDoc "${prefix} client key file used to connect to kube-apiserver.";
       type = types.nullOr types.path;
       default = null;
     };
@@ -111,7 +111,7 @@ in {
 
   options.services.kubernetes = {
     roles = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kubernetes role that this machine should take.
 
         Master role will enable etcd, apiserver, scheduler, controller manager
@@ -123,7 +123,7 @@ in {
     };
 
     package = mkOption {
-      description = "Kubernetes package to use.";
+      description = lib.mdDoc "Kubernetes package to use.";
       type = types.package;
       default = pkgs.kubernetes;
       defaultText = literalExpression "pkgs.kubernetes";
@@ -132,7 +132,7 @@ in {
     kubeconfig = mkKubeConfigOptions "Default kubeconfig";
 
     apiserverAddress = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Clusterwide accessible address for the kubernetes apiserver,
         including protocol and optional port.
       '';
@@ -141,49 +141,49 @@ in {
     };
 
     caFile = mkOption {
-      description = "Default kubernetes certificate authority";
+      description = lib.mdDoc "Default kubernetes certificate authority";
       type = types.nullOr types.path;
       default = null;
     };
 
     dataDir = mkOption {
-      description = "Kubernetes root directory for managing kubelet files.";
+      description = lib.mdDoc "Kubernetes root directory for managing kubelet files.";
       default = "/var/lib/kubernetes";
       type = types.path;
     };
 
     easyCerts = mkOption {
-      description = "Automatically setup x509 certificates and keys for the entire cluster.";
+      description = lib.mdDoc "Automatically setup x509 certificates and keys for the entire cluster.";
       default = false;
       type = types.bool;
     };
 
     featureGates = mkOption {
-      description = "List set of feature gates.";
+      description = lib.mdDoc "List set of feature gates.";
       default = [];
       type = types.listOf types.str;
     };
 
     masterAddress = mkOption {
-      description = "Clusterwide available network address or hostname for the kubernetes master server.";
+      description = lib.mdDoc "Clusterwide available network address or hostname for the kubernetes master server.";
       example = "master.example.com";
       type = types.str;
     };
 
     path = mkOption {
-      description = "Packages added to the services' PATH environment variable. Both the bin and sbin subdirectories of each package are added.";
+      description = lib.mdDoc "Packages added to the services' PATH environment variable. Both the bin and sbin subdirectories of each package are added.";
       type = types.listOf types.package;
       default = [];
     };
 
     clusterCidr = mkOption {
-      description = "Kubernetes controller manager and proxy CIDR Range for Pods in cluster.";
+      description = lib.mdDoc "Kubernetes controller manager and proxy CIDR Range for Pods in cluster.";
       default = "10.1.0.0/16";
       type = types.nullOr types.str;
     };
 
     lib = mkOption {
-      description = "Common functions for the kubernetes modules.";
+      description = lib.mdDoc "Common functions for the kubernetes modules.";
       default = {
         inherit mkCert;
         inherit mkKubeConfig;
@@ -193,7 +193,7 @@ in {
     };
 
     secretsPath = mkOption {
-      description = "Default location for kubernetes secrets. Not a store location.";
+      description = lib.mdDoc "Default location for kubernetes secrets. Not a store location.";
       type = types.path;
       default = cfg.dataDir + "/secrets";
       defaultText = literalExpression ''
diff --git a/nixos/modules/services/cluster/kubernetes/flannel.nix b/nixos/modules/services/cluster/kubernetes/flannel.nix
index cb81eaaf016..53003287fc9 100644
--- a/nixos/modules/services/cluster/kubernetes/flannel.nix
+++ b/nixos/modules/services/cluster/kubernetes/flannel.nix
@@ -12,7 +12,7 @@ in
 {
   ###### interface
   options.services.kubernetes.flannel = {
-    enable = mkEnableOption "enable flannel networking";
+    enable = mkEnableOption (lib.mdDoc "flannel networking");
   };
 
   ###### implementation
@@ -26,7 +26,6 @@ in
     };
 
     services.kubernetes.kubelet = {
-      networkPlugin = mkDefault "cni";
       cni.config = mkDefault [{
         name = "mynet";
         type = "flannel";
diff --git a/nixos/modules/services/cluster/kubernetes/kubelet.nix b/nixos/modules/services/cluster/kubernetes/kubelet.nix
index af3a5062feb..0898fee9bdb 100644
--- a/nixos/modules/services/cluster/kubernetes/kubelet.nix
+++ b/nixos/modules/services/cluster/kubernetes/kubelet.nix
@@ -23,7 +23,11 @@ let
   infraContainer = pkgs.dockerTools.buildImage {
     name = "pause";
     tag = "latest";
-    contents = top.package.pause;
+    copyToRoot = pkgs.buildEnv {
+      name = "image-root";
+      pathsToLink = [ "/bin" ];
+      paths = [ top.package.pause ];
+    };
     config.Cmd = ["/bin/pause"];
   };
 
@@ -34,17 +38,17 @@ let
   taintOptions = with lib.types; { name, ... }: {
     options = {
       key = mkOption {
-        description = "Key of taint.";
+        description = lib.mdDoc "Key of taint.";
         default = name;
-        defaultText = literalDocBook "Name of this submodule.";
+        defaultText = literalMD "Name of this submodule.";
         type = str;
       };
       value = mkOption {
-        description = "Value of taint.";
+        description = lib.mdDoc "Value of taint.";
         type = str;
       };
       effect = mkOption {
-        description = "Effect of taint.";
+        description = lib.mdDoc "Effect of taint.";
         example = "NoSchedule";
         type = enum ["NoSchedule" "PreferNoSchedule" "NoExecute"];
       };
@@ -58,32 +62,33 @@ in
     (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "applyManifests" ] "")
     (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "cadvisorPort" ] "")
     (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "allowPrivileged" ] "")
+    (mkRemovedOptionModule [ "services" "kubernetes" "kubelet" "networkPlugin" ] "")
   ];
 
   ###### interface
   options.services.kubernetes.kubelet = with lib.types; {
 
     address = mkOption {
-      description = "Kubernetes kubelet info server listening address.";
+      description = lib.mdDoc "Kubernetes kubelet info server listening address.";
       default = "0.0.0.0";
       type = str;
     };
 
     clusterDns = mkOption {
-      description = "Use alternative DNS.";
+      description = lib.mdDoc "Use alternative DNS.";
       default = "10.1.0.1";
       type = str;
     };
 
     clusterDomain = mkOption {
-      description = "Use alternative domain.";
+      description = lib.mdDoc "Use alternative domain.";
       default = config.services.kubernetes.addons.dns.clusterDomain;
       defaultText = literalExpression "config.${options.services.kubernetes.addons.dns.clusterDomain}";
       type = str;
     };
 
     clientCaFile = mkOption {
-      description = "Kubernetes apiserver CA file for client authentication.";
+      description = lib.mdDoc "Kubernetes apiserver CA file for client authentication.";
       default = top.caFile;
       defaultText = literalExpression "config.${otop.caFile}";
       type = nullOr path;
@@ -91,13 +96,13 @@ in
 
     cni = {
       packages = mkOption {
-        description = "List of network plugin packages to install.";
+        description = lib.mdDoc "List of network plugin packages to install.";
         type = listOf package;
         default = [];
       };
 
       config = mkOption {
-        description = "Kubernetes CNI configuration.";
+        description = lib.mdDoc "Kubernetes CNI configuration.";
         type = listOf attrs;
         default = [];
         example = literalExpression ''
@@ -123,34 +128,34 @@ in
       };
 
       configDir = mkOption {
-        description = "Path to Kubernetes CNI configuration directory.";
+        description = lib.mdDoc "Path to Kubernetes CNI configuration directory.";
         type = nullOr path;
         default = null;
       };
     };
 
     containerRuntime = mkOption {
-      description = "Which container runtime type to use";
+      description = lib.mdDoc "Which container runtime type to use";
       type = enum ["docker" "remote"];
       default = "remote";
     };
 
     containerRuntimeEndpoint = mkOption {
-      description = "Endpoint at which to find the container runtime api interface/socket";
+      description = lib.mdDoc "Endpoint at which to find the container runtime api interface/socket";
       type = str;
       default = "unix:///run/containerd/containerd.sock";
     };
 
-    enable = mkEnableOption "Kubernetes kubelet.";
+    enable = mkEnableOption (lib.mdDoc "Kubernetes kubelet.");
 
     extraOpts = mkOption {
-      description = "Kubernetes kubelet extra command line options.";
+      description = lib.mdDoc "Kubernetes kubelet extra command line options.";
       default = "";
       type = separatedString " ";
     };
 
     featureGates = mkOption {
-      description = "List set of feature gates";
+      description = lib.mdDoc "List set of feature gates";
       default = top.featureGates;
       defaultText = literalExpression "config.${otop.featureGates}";
       type = listOf str;
@@ -158,91 +163,84 @@ in
 
     healthz = {
       bind = mkOption {
-        description = "Kubernetes kubelet healthz listening address.";
+        description = lib.mdDoc "Kubernetes kubelet healthz listening address.";
         default = "127.0.0.1";
         type = str;
       };
 
       port = mkOption {
-        description = "Kubernetes kubelet healthz port.";
+        description = lib.mdDoc "Kubernetes kubelet healthz port.";
         default = 10248;
         type = int;
       };
     };
 
     hostname = mkOption {
-      description = "Kubernetes kubelet hostname override.";
-      default = config.networking.hostName;
-      defaultText = literalExpression "config.networking.hostName";
+      description = lib.mdDoc "Kubernetes kubelet hostname override.";
+      defaultText = literalExpression "config.networking.fqdnOrHostName";
       type = str;
     };
 
     kubeconfig = top.lib.mkKubeConfigOptions "Kubelet";
 
     manifests = mkOption {
-      description = "List of manifests to bootstrap with kubelet (only pods can be created as manifest entry)";
+      description = lib.mdDoc "List of manifests to bootstrap with kubelet (only pods can be created as manifest entry)";
       type = attrsOf attrs;
       default = {};
     };
 
-    networkPlugin = mkOption {
-      description = "Network plugin to use by Kubernetes.";
-      type = nullOr (enum ["cni" "kubenet"]);
-      default = "kubenet";
-    };
-
     nodeIp = mkOption {
-      description = "IP address of the node. If set, kubelet will use this IP address for the node.";
+      description = lib.mdDoc "IP address of the node. If set, kubelet will use this IP address for the node.";
       default = null;
       type = nullOr str;
     };
 
     registerNode = mkOption {
-      description = "Whether to auto register kubelet with API server.";
+      description = lib.mdDoc "Whether to auto register kubelet with API server.";
       default = true;
       type = bool;
     };
 
     port = mkOption {
-      description = "Kubernetes kubelet info server listening port.";
+      description = lib.mdDoc "Kubernetes kubelet info server listening port.";
       default = 10250;
       type = int;
     };
 
     seedDockerImages = mkOption {
-      description = "List of docker images to preload on system";
+      description = lib.mdDoc "List of docker images to preload on system";
       default = [];
       type = listOf package;
     };
 
     taints = mkOption {
-      description = "Node taints (https://kubernetes.io/docs/concepts/configuration/assign-pod-node/).";
+      description = lib.mdDoc "Node taints (https://kubernetes.io/docs/concepts/configuration/assign-pod-node/).";
       default = {};
       type = attrsOf (submodule [ taintOptions ]);
     };
 
     tlsCertFile = mkOption {
-      description = "File containing x509 Certificate for HTTPS.";
+      description = lib.mdDoc "File containing x509 Certificate for HTTPS.";
       default = null;
       type = nullOr path;
     };
 
     tlsKeyFile = mkOption {
-      description = "File containing x509 private key matching tlsCertFile.";
+      description = lib.mdDoc "File containing x509 private key matching tlsCertFile.";
       default = null;
       type = nullOr path;
     };
 
     unschedulable = mkOption {
-      description = "Whether to set node taint to unschedulable=true as it is the case of node that has only master role.";
+      description = lib.mdDoc "Whether to set node taint to unschedulable=true as it is the case of node that has only master role.";
       default = false;
       type = bool;
     };
 
     verbosity = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Optional glog verbosity level for logging statements. See
-        <link xlink:href="https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md"/>
+        <https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md>
       '';
       default = null;
       type = nullOr int;
@@ -311,7 +309,6 @@ in
               "--cluster-dns=${cfg.clusterDns}"} \
             ${optionalString (cfg.clusterDomain != "")
               "--cluster-domain=${cfg.clusterDomain}"} \
-            --cni-conf-dir=${cniConfig} \
             ${optionalString (cfg.featureGates != [])
               "--feature-gates=${concatMapStringsSep "," (feature: "${feature}=true") cfg.featureGates}"} \
             --hairpin-mode=hairpin-veth \
@@ -319,8 +316,6 @@ in
             --healthz-port=${toString cfg.healthz.port} \
             --hostname-override=${cfg.hostname} \
             --kubeconfig=${kubeconfig} \
-            ${optionalString (cfg.networkPlugin != null)
-              "--network-plugin=${cfg.networkPlugin}"} \
             ${optionalString (cfg.nodeIp != null)
               "--node-ip=${cfg.nodeIp}"} \
             --pod-infra-container-image=pause \
@@ -353,8 +348,8 @@ in
 
       boot.kernelModules = ["br_netfilter" "overlay"];
 
-      services.kubernetes.kubelet.hostname = with config.networking;
-        mkDefault (hostName + optionalString (domain != null) ".${domain}");
+      services.kubernetes.kubelet.hostname =
+        mkDefault config.networking.fqdnOrHostName;
 
       services.kubernetes.pki.certs = with top.lib; {
         kubelet = mkCert {
diff --git a/nixos/modules/services/cluster/kubernetes/pki.nix b/nixos/modules/services/cluster/kubernetes/pki.nix
index 7d9198d20e8..d68267883e4 100644
--- a/nixos/modules/services/cluster/kubernetes/pki.nix
+++ b/nixos/modules/services/cluster/kubernetes/pki.nix
@@ -41,16 +41,16 @@ in
   ###### interface
   options.services.kubernetes.pki = with lib.types; {
 
-    enable = mkEnableOption "easyCert issuer service";
+    enable = mkEnableOption (lib.mdDoc "easyCert issuer service");
 
     certs = mkOption {
-      description = "List of certificate specs to feed to cert generator.";
+      description = lib.mdDoc "List of certificate specs to feed to cert generator.";
       default = {};
       type = attrs;
     };
 
     genCfsslCACert = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Whether to automatically generate cfssl CA certificate and key,
         if they don't exist.
       '';
@@ -59,7 +59,7 @@ in
     };
 
     genCfsslAPICerts = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Whether to automatically generate cfssl API webserver TLS cert and key,
         if they don't exist.
       '';
@@ -68,7 +68,7 @@ in
     };
 
     cfsslAPIExtraSANs = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Extra x509 Subject Alternative Names to be added to the cfssl API webserver TLS cert.
       '';
       default = [];
@@ -77,7 +77,7 @@ in
     };
 
     genCfsslAPIToken = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Whether to automatically generate cfssl API-token secret,
         if they doesn't exist.
       '';
@@ -86,13 +86,13 @@ in
     };
 
     pkiTrustOnBootstrap = mkOption {
-      description = "Whether to always trust remote cfssl server upon initial PKI bootstrap.";
+      description = lib.mdDoc "Whether to always trust remote cfssl server upon initial PKI bootstrap.";
       default = true;
       type = bool;
     };
 
     caCertPathPrefix = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Path-prefrix for the CA-certificate to be used for cfssl signing.
         Suffixes ".pem" and "-key.pem" will be automatically appended for
         the public and private keys respectively.
@@ -103,7 +103,7 @@ in
     };
 
     caSpec = mkOption {
-      description = "Certificate specification for the auto-generated CAcert.";
+      description = lib.mdDoc "Certificate specification for the auto-generated CAcert.";
       default = {
         CN = "kubernetes-cluster-ca";
         O = "NixOS";
@@ -114,9 +114,9 @@ in
     };
 
     etcClusterAdminKubeconfig = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Symlink a kubeconfig with cluster-admin privileges to environment path
-        (/etc/&lt;path&gt;).
+        (/etc/\<path\>).
       '';
       default = null;
       type = nullOr str;
@@ -266,7 +266,7 @@ in
           in
           ''
             export KUBECONFIG=${clusterAdminKubeconfig}
-            ${kubernetes}/bin/kubectl apply -f ${concatStringsSep " \\\n -f " files}
+            ${top.package}/bin/kubectl apply -f ${concatStringsSep " \\\n -f " files}
           '';
         })]);
 
diff --git a/nixos/modules/services/cluster/kubernetes/proxy.nix b/nixos/modules/services/cluster/kubernetes/proxy.nix
index 0fd98d1c157..015784f7e31 100644
--- a/nixos/modules/services/cluster/kubernetes/proxy.nix
+++ b/nixos/modules/services/cluster/kubernetes/proxy.nix
@@ -16,28 +16,28 @@ in
   options.services.kubernetes.proxy = with lib.types; {
 
     bindAddress = mkOption {
-      description = "Kubernetes proxy listening address.";
+      description = lib.mdDoc "Kubernetes proxy listening address.";
       default = "0.0.0.0";
       type = str;
     };
 
-    enable = mkEnableOption "Kubernetes proxy";
+    enable = mkEnableOption (lib.mdDoc "Kubernetes proxy");
 
     extraOpts = mkOption {
-      description = "Kubernetes proxy extra command line options.";
+      description = lib.mdDoc "Kubernetes proxy extra command line options.";
       default = "";
       type = separatedString " ";
     };
 
     featureGates = mkOption {
-      description = "List set of feature gates";
+      description = lib.mdDoc "List set of feature gates";
       default = top.featureGates;
       defaultText = literalExpression "config.${otop.featureGates}";
       type = listOf str;
     };
 
     hostname = mkOption {
-      description = "Kubernetes proxy hostname override.";
+      description = lib.mdDoc "Kubernetes proxy hostname override.";
       default = config.networking.hostName;
       defaultText = literalExpression "config.networking.hostName";
       type = str;
@@ -46,9 +46,9 @@ in
     kubeconfig = top.lib.mkKubeConfigOptions "Kubernetes proxy";
 
     verbosity = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Optional glog verbosity level for logging statements. See
-        <link xlink:href="https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md"/>
+        <https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md>
       '';
       default = null;
       type = nullOr int;
diff --git a/nixos/modules/services/cluster/kubernetes/scheduler.nix b/nixos/modules/services/cluster/kubernetes/scheduler.nix
index 2d95528a6ea..2eada43eb4e 100644
--- a/nixos/modules/services/cluster/kubernetes/scheduler.nix
+++ b/nixos/modules/services/cluster/kubernetes/scheduler.nix
@@ -12,21 +12,21 @@ in
   options.services.kubernetes.scheduler = with lib.types; {
 
     address = mkOption {
-      description = "Kubernetes scheduler listening address.";
+      description = lib.mdDoc "Kubernetes scheduler listening address.";
       default = "127.0.0.1";
       type = str;
     };
 
-    enable = mkEnableOption "Kubernetes scheduler";
+    enable = mkEnableOption (lib.mdDoc "Kubernetes scheduler");
 
     extraOpts = mkOption {
-      description = "Kubernetes scheduler extra command line options.";
+      description = lib.mdDoc "Kubernetes scheduler extra command line options.";
       default = "";
       type = separatedString " ";
     };
 
     featureGates = mkOption {
-      description = "List set of feature gates";
+      description = lib.mdDoc "List set of feature gates";
       default = top.featureGates;
       defaultText = literalExpression "config.${otop.featureGates}";
       type = listOf str;
@@ -35,21 +35,21 @@ in
     kubeconfig = top.lib.mkKubeConfigOptions "Kubernetes scheduler";
 
     leaderElect = mkOption {
-      description = "Whether to start leader election before executing main loop.";
+      description = lib.mdDoc "Whether to start leader election before executing main loop.";
       type = bool;
       default = true;
     };
 
     port = mkOption {
-      description = "Kubernetes scheduler listening port.";
+      description = lib.mdDoc "Kubernetes scheduler listening port.";
       default = 10251;
       type = int;
     };
 
     verbosity = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Optional glog verbosity level for logging statements. See
-        <link xlink:href="https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md"/>
+        <https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md>
       '';
       default = null;
       type = nullOr int;
diff --git a/nixos/modules/services/cluster/pacemaker/default.nix b/nixos/modules/services/cluster/pacemaker/default.nix
index 7eeadffcc58..0f37f4b754f 100644
--- a/nixos/modules/services/cluster/pacemaker/default.nix
+++ b/nixos/modules/services/cluster/pacemaker/default.nix
@@ -7,13 +7,13 @@ in
 {
   # interface
   options.services.pacemaker = {
-    enable = mkEnableOption "pacemaker";
+    enable = mkEnableOption (lib.mdDoc "pacemaker");
 
     package = mkOption {
       type = types.package;
       default = pkgs.pacemaker;
       defaultText = literalExpression "pkgs.pacemaker";
-      description = "Package that should be used for pacemaker.";
+      description = lib.mdDoc "Package that should be used for pacemaker.";
     };
   };
 
diff --git a/nixos/modules/services/cluster/patroni/default.nix b/nixos/modules/services/cluster/patroni/default.nix
new file mode 100644
index 00000000000..83b372f5949
--- /dev/null
+++ b/nixos/modules/services/cluster/patroni/default.nix
@@ -0,0 +1,268 @@
+{ config, lib, pkgs, ... }:
+with lib;
+let
+  cfg = config.services.patroni;
+  defaultUser = "patroni";
+  defaultGroup = "patroni";
+  format = pkgs.formats.yaml { };
+
+  #boto doesn't support python 3.10 yet
+  patroni = pkgs.patroni.override { pythonPackages = pkgs.python39Packages; };
+
+  configFileName = "patroni-${cfg.scope}-${cfg.name}.yaml";
+  configFile = format.generate configFileName cfg.settings;
+in
+{
+  options.services.patroni = {
+
+    enable = mkEnableOption (lib.mdDoc "Patroni");
+
+    postgresqlPackage = mkOption {
+      type = types.package;
+      example = literalExpression "pkgs.postgresql_14";
+      description = mdDoc ''
+        PostgreSQL package to use.
+        Plugins can be enabled like this `pkgs.postgresql_14.withPackages (p: [ p.pg_safeupdate p.postgis ])`.
+      '';
+    };
+
+    postgresqlDataDir = mkOption {
+      type = types.path;
+      defaultText = literalExpression ''"/var/lib/postgresql/''${config.services.patroni.postgresqlPackage.psqlSchema}"'';
+      example = "/var/lib/postgresql/14";
+      default = "/var/lib/postgresql/${cfg.postgresqlPackage.psqlSchema}";
+      description = mdDoc ''
+        The data directory for PostgreSQL. If left as the default value
+        this directory will automatically be created before the PostgreSQL server starts, otherwise
+        the sysadmin is responsible for ensuring the directory exists with appropriate ownership
+        and permissions.
+      '';
+    };
+
+    postgresqlPort = mkOption {
+      type = types.port;
+      default = 5432;
+      description = mdDoc ''
+        The port on which PostgreSQL listens.
+      '';
+    };
+
+    user = mkOption {
+      type = types.str;
+      default = defaultUser;
+      example = "postgres";
+      description = mdDoc ''
+        The user for the service. If left as the default value this user will automatically be created,
+        otherwise the sysadmin is responsible for ensuring the user exists.
+      '';
+    };
+
+    group = mkOption {
+      type = types.str;
+      default = defaultGroup;
+      example = "postgres";
+      description = mdDoc ''
+        The group for the service. If left as the default value this group will automatically be created,
+        otherwise the sysadmin is responsible for ensuring the group exists.
+      '';
+    };
+
+    dataDir = mkOption {
+      type = types.path;
+      default = "/var/lib/patroni";
+      description = mdDoc ''
+        Folder where Patroni data will be written, used by Raft as well if enabled.
+      '';
+    };
+
+    scope = mkOption {
+      type = types.str;
+      example = "cluster1";
+      description = mdDoc ''
+        Cluster name.
+      '';
+    };
+
+    name = mkOption {
+      type = types.str;
+      example = "node1";
+      description = mdDoc ''
+        The name of the host. Must be unique for the cluster.
+      '';
+    };
+
+    namespace = mkOption {
+      type = types.str;
+      default = "/service";
+      description = mdDoc ''
+        Path within the configuration store where Patroni will keep information about the cluster.
+      '';
+    };
+
+    nodeIp = mkOption {
+      type = types.str;
+      example = "192.168.1.1";
+      description = mdDoc ''
+        IP address of this node.
+      '';
+    };
+
+    otherNodesIps = mkOption {
+      type = types.listOf types.string;
+      example = [ "192.168.1.2" "192.168.1.3" ];
+      description = mdDoc ''
+        IP addresses of the other nodes.
+      '';
+    };
+
+    restApiPort = mkOption {
+      type = types.port;
+      default = 8008;
+      description = mdDoc ''
+        The port on Patroni's REST api listens.
+      '';
+    };
+
+    raft = mkOption {
+      type = types.bool;
+      default = false;
+      description = mdDoc ''
+        This will configure Patroni to use its own RAFT implementation instead of using a dedicated DCS.
+      '';
+    };
+
+    raftPort = mkOption {
+      type = types.port;
+      default = 5010;
+      description = mdDoc ''
+        The port on which RAFT listens.
+      '';
+    };
+
+    softwareWatchdog = mkOption {
+      type = types.bool;
+      default = false;
+      description = mdDoc ''
+        This will configure Patroni to use the software watchdog built into the Linux kernel
+        as described in the [documentation](https://patroni.readthedocs.io/en/latest/watchdog.html#setting-up-software-watchdog-on-linux).
+      '';
+    };
+
+    settings = mkOption {
+      type = format.type;
+      default = { };
+      description = mdDoc ''
+        The primary patroni configuration. See the [documentation](https://patroni.readthedocs.io/en/latest/SETTINGS.html)
+        for possible values.
+        Secrets should be passed in by using the `environmentFiles` option.
+      '';
+    };
+
+    environmentFiles = mkOption {
+      type = with types; attrsOf (nullOr (oneOf [ str path package ]));
+      default = { };
+      example = {
+        PATRONI_REPLICATION_PASSWORD = "/secret/file";
+        PATRONI_SUPERUSER_PASSWORD = "/secret/file";
+      };
+      description = mdDoc "Environment variables made available to Patroni as files content, useful for providing secrets from files.";
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    services.patroni.settings = {
+      scope = cfg.scope;
+      name = cfg.name;
+      namespace = cfg.namespace;
+
+      restapi = {
+        listen = "${cfg.nodeIp}:${toString cfg.restApiPort}";
+        connect_address = "${cfg.nodeIp}:${toString cfg.restApiPort}";
+      };
+
+      raft = mkIf cfg.raft {
+        data_dir = "${cfg.dataDir}/raft";
+        self_addr = "${cfg.nodeIp}:5010";
+        partner_addrs = map (ip: ip + ":5010") cfg.otherNodesIps;
+      };
+
+      postgresql = {
+        listen = "${cfg.nodeIp}:${toString cfg.postgresqlPort}";
+        connect_address = "${cfg.nodeIp}:${toString cfg.postgresqlPort}";
+        data_dir = cfg.postgresqlDataDir;
+        bin_dir = "${cfg.postgresqlPackage}/bin";
+        pgpass = "${cfg.dataDir}/pgpass";
+      };
+
+      watchdog = mkIf cfg.softwareWatchdog {
+        mode = "required";
+        device = "/dev/watchdog";
+        safety_margin = 5;
+      };
+    };
+
+
+    users = {
+      users = mkIf (cfg.user == defaultUser) {
+        patroni = {
+          group = cfg.group;
+          isSystemUser = true;
+        };
+      };
+      groups = mkIf (cfg.group == defaultGroup) {
+        patroni = { };
+      };
+    };
+
+    systemd.services = {
+      patroni = {
+        description = "Runners to orchestrate a high-availability PostgreSQL";
+
+        wantedBy = [ "multi-user.target" ];
+        after = [ "network.target" ];
+
+        script = ''
+          ${concatStringsSep "\n" (attrValues (mapAttrs (name: path: ''export ${name}="$(< ${escapeShellArg path})"'') cfg.environmentFiles))}
+          exec ${patroni}/bin/patroni ${configFile}
+        '';
+
+        serviceConfig = mkMerge [
+          {
+            User = cfg.user;
+            Group = cfg.group;
+            Type = "simple";
+            Restart = "on-failure";
+            TimeoutSec = 30;
+            ExecReload = "${pkgs.coreutils}/bin/kill -s HUP $MAINPID";
+            KillMode = "process";
+          }
+          (mkIf (cfg.postgresqlDataDir == "/var/lib/postgresql/${cfg.postgresqlPackage.psqlSchema}" && cfg.dataDir == "/var/lib/patroni") {
+            StateDirectory = "patroni patroni/raft postgresql postgresql/${cfg.postgresqlPackage.psqlSchema}";
+            StateDirectoryMode = "0750";
+          })
+        ];
+      };
+    };
+
+    boot.kernelModules = mkIf cfg.softwareWatchdog [ "softdog" ];
+
+    services.udev.extraRules = mkIf cfg.softwareWatchdog ''
+      KERNEL=="watchdog", OWNER="${cfg.user}", GROUP="${cfg.group}", MODE="0600"
+    '';
+
+    environment.systemPackages = [
+      patroni
+      cfg.postgresqlPackage
+      (mkIf cfg.raft pkgs.python310Packages.pysyncobj)
+    ];
+
+    environment.etc."${configFileName}".source = configFile;
+
+    environment.sessionVariables = {
+      PATRONICTL_CONFIG_FILE = "/etc/${configFileName}";
+    };
+  };
+
+  meta.maintainers = [ maintainers.phfroidmont ];
+}
diff --git a/nixos/modules/services/cluster/spark/default.nix b/nixos/modules/services/cluster/spark/default.nix
index e6b44e130a3..bf39c553733 100644
--- a/nixos/modules/services/cluster/spark/default.nix
+++ b/nixos/modules/services/cluster/spark/default.nix
@@ -7,16 +7,16 @@ with lib;
   options = {
     services.spark = {
       master = {
-        enable = mkEnableOption "Spark master service";
+        enable = mkEnableOption (lib.mdDoc "Spark master service");
         bind = mkOption {
           type = types.str;
-          description = "Address the spark master binds to.";
+          description = lib.mdDoc "Address the spark master binds to.";
           default = "127.0.0.1";
           example = "0.0.0.0";
         };
         restartIfChanged  = mkOption {
           type = types.bool;
-          description = ''
+          description = lib.mdDoc ''
             Automatically restart master service on config change.
             This can be set to false to defer restarts on clusters running critical applications.
             Please consider the security implications of inadvertently running an older version,
@@ -26,7 +26,7 @@ with lib;
         };
         extraEnvironment = mkOption {
           type = types.attrsOf types.str;
-          description = "Extra environment variables to pass to spark master. See spark-standalone documentation.";
+          description = lib.mdDoc "Extra environment variables to pass to spark master. See spark-standalone documentation.";
           default = {};
           example = {
             SPARK_MASTER_WEBUI_PORT = 8181;
@@ -35,20 +35,20 @@ with lib;
         };
       };
       worker = {
-        enable = mkEnableOption "Spark worker service";
+        enable = mkEnableOption (lib.mdDoc "Spark worker service");
         workDir = mkOption {
           type = types.path;
-          description = "Spark worker work dir.";
+          description = lib.mdDoc "Spark worker work dir.";
           default = "/var/lib/spark";
         };
         master = mkOption {
           type = types.str;
-          description = "Address of the spark master.";
+          description = lib.mdDoc "Address of the spark master.";
           default = "127.0.0.1:7077";
         };
         restartIfChanged  = mkOption {
           type = types.bool;
-          description = ''
+          description = lib.mdDoc ''
             Automatically restart worker service on config change.
             This can be set to false to defer restarts on clusters running critical applications.
             Please consider the security implications of inadvertently running an older version,
@@ -58,7 +58,7 @@ with lib;
         };
         extraEnvironment = mkOption {
           type = types.attrsOf types.str;
-          description = "Extra environment variables to pass to spark worker.";
+          description = lib.mdDoc "Extra environment variables to pass to spark worker.";
           default = {};
           example = {
             SPARK_WORKER_CORES = 5;
@@ -68,18 +68,18 @@ with lib;
       };
       confDir = mkOption {
         type = types.path;
-        description = "Spark configuration directory. Spark will use the configuration files (spark-defaults.conf, spark-env.sh, log4j.properties, etc) from this directory.";
+        description = lib.mdDoc "Spark configuration directory. Spark will use the configuration files (spark-defaults.conf, spark-env.sh, log4j.properties, etc) from this directory.";
         default = "${cfg.package}/lib/${cfg.package.untarDir}/conf";
         defaultText = literalExpression ''"''${package}/lib/''${package.untarDir}/conf"'';
       };
       logDir = mkOption {
         type = types.path;
-        description = "Spark log directory.";
+        description = lib.mdDoc "Spark log directory.";
         default = "/var/log/spark";
       };
       package = mkOption {
         type = types.package;
-        description = "Spark package.";
+        description = lib.mdDoc "Spark package.";
         default = pkgs.spark;
         defaultText = literalExpression "pkgs.spark";
         example = literalExpression ''pkgs.spark.overrideAttrs (super: rec {
diff --git a/nixos/modules/services/computing/boinc/client.nix b/nixos/modules/services/computing/boinc/client.nix
index 52249455fd4..5fb715f4d77 100644
--- a/nixos/modules/services/computing/boinc/client.nix
+++ b/nixos/modules/services/computing/boinc/client.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the BOINC distributed computing client. If this
           option is set to true, the boinc_client daemon will be run as a
           background service. The boinccmd command can be used to control the
@@ -31,7 +31,7 @@ in
         type = types.package;
         default = pkgs.boinc;
         defaultText = literalExpression "pkgs.boinc";
-        description = ''
+        description = lib.mdDoc ''
           Which BOINC package to use.
         '';
       };
@@ -39,7 +39,7 @@ in
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/boinc";
-        description = ''
+        description = lib.mdDoc ''
           The directory in which to store BOINC's configuration and data files.
         '';
       };
@@ -47,13 +47,13 @@ in
       allowRemoteGuiRpc = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If set to true, any remote host can connect to and control this BOINC
           client (subject to password authentication). If instead set to false,
-          only the hosts listed in <varname>dataDir</varname>/remote_hosts.cfg will be allowed to
+          only the hosts listed in {var}`dataDir`/remote_hosts.cfg will be allowed to
           connect.
 
-          See also: <link xlink:href="http://boinc.berkeley.edu/wiki/Controlling_BOINC_remotely#Remote_access"/>
+          See also: <http://boinc.berkeley.edu/wiki/Controlling_BOINC_remotely#Remote_access>
         '';
       };
 
@@ -61,36 +61,23 @@ in
         type = types.listOf types.package;
         default = [];
         example = literalExpression "[ pkgs.virtualbox ]";
-        description = ''
+        description = lib.mdDoc ''
           Additional packages to make available in the environment in which
           BOINC will run. Common choices are:
-          <variablelist>
-            <varlistentry>
-              <term><varname>pkgs.virtualbox</varname></term>
-              <listitem><para>
-                The VirtualBox virtual machine framework. Required by some BOINC
-                projects, such as ATLAS@home.
-              </para></listitem>
-            </varlistentry>
-            <varlistentry>
-              <term><varname>pkgs.ocl-icd</varname></term>
-              <listitem><para>
-                OpenCL infrastructure library. Required by BOINC projects that
-                use OpenCL, in addition to a device-specific OpenCL driver.
-              </para></listitem>
-            </varlistentry>
-            <varlistentry>
-              <term><varname>pkgs.linuxPackages.nvidia_x11</varname></term>
-              <listitem><para>
-                Provides CUDA libraries. Required by BOINC projects that use
-                CUDA. Note that this requires an NVIDIA graphics device to be
-                present on the system.
-              </para><para>
-                Also provides OpenCL drivers for NVIDIA GPUs;
-                <varname>pkgs.ocl-icd</varname> is also needed in this case.
-              </para></listitem>
-            </varlistentry>
-          </variablelist>
+
+          - {var}`pkgs.virtualbox`:
+            The VirtualBox virtual machine framework. Required by some BOINC
+            projects, such as ATLAS@home.
+          - {var}`pkgs.ocl-icd`:
+            OpenCL infrastructure library. Required by BOINC projects that
+            use OpenCL, in addition to a device-specific OpenCL driver.
+          - {var}`pkgs.linuxPackages.nvidia_x11`:
+            Provides CUDA libraries. Required by BOINC projects that use
+            CUDA. Note that this requires an NVIDIA graphics device to be
+            present on the system.
+
+            Also provides OpenCL drivers for NVIDIA GPUs;
+            {var}`pkgs.ocl-icd` is also needed in this case.
         '';
       };
     };
diff --git a/nixos/modules/services/computing/foldingathome/client.nix b/nixos/modules/services/computing/foldingathome/client.nix
index aa9d0a5218f..1229e5ac987 100644
--- a/nixos/modules/services/computing/foldingathome/client.nix
+++ b/nixos/modules/services/computing/foldingathome/client.nix
@@ -18,13 +18,13 @@ in
     '')
   ];
   options.services.foldingathome = {
-    enable = mkEnableOption "Enable the Folding@home client";
+    enable = mkEnableOption (lib.mdDoc "Folding@home client");
 
     package = mkOption {
       type = types.package;
       default = pkgs.fahclient;
       defaultText = literalExpression "pkgs.fahclient";
-      description = ''
+      description = lib.mdDoc ''
         Which Folding@home client to use.
       '';
     };
@@ -32,7 +32,7 @@ in
     user = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The user associated with the reported computation results. This will
         be used in the ranking statistics.
       '';
@@ -41,7 +41,7 @@ in
     team = mkOption {
       type = types.int;
       default = 236565;
-      description = ''
+      description = lib.mdDoc ''
         The team ID associated with the reported computation results. This
         will be used in the ranking statistics.
 
@@ -52,7 +52,7 @@ in
     daemonNiceLevel = mkOption {
       type = types.ints.between (-20) 19;
       default = 0;
-      description = ''
+      description = lib.mdDoc ''
         Daemon process priority for FAHClient.
         0 is the default Unix process priority, 19 is the lowest.
       '';
@@ -61,9 +61,9 @@ in
     extraArgs = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Extra startup options for the FAHClient. Run
-        <literal>FAHClient --help</literal> to find all the available options.
+        `FAHClient --help` to find all the available options.
       '';
     };
   };
diff --git a/nixos/modules/services/computing/slurm/slurm.nix b/nixos/modules/services/computing/slurm/slurm.nix
index 8cbe54c6060..0c80e79d4b7 100644
--- a/nixos/modules/services/computing/slurm/slurm.nix
+++ b/nixos/modules/services/computing/slurm/slurm.nix
@@ -66,25 +66,25 @@ in
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable the slurm control daemon.
             Note that the standard authentication method is "munge".
             The "munge" service needs to be provided with a password file in order for
-            slurm to work properly (see <literal>services.munge.password</literal>).
+            slurm to work properly (see `services.munge.password`).
           '';
         };
       };
 
       dbdserver = {
-        enable = mkEnableOption "SlurmDBD service";
+        enable = mkEnableOption (lib.mdDoc "SlurmDBD service");
 
         dbdHost = mkOption {
           type = types.str;
           default = config.networking.hostName;
           defaultText = literalExpression "config.networking.hostName";
-          description = ''
-            Hostname of the machine where <literal>slurmdbd</literal>
-            is running (i.e. name returned by <literal>hostname -s</literal>).
+          description = lib.mdDoc ''
+            Hostname of the machine where `slurmdbd`
+            is running (i.e. name returned by `hostname -s`).
           '';
         };
 
@@ -92,7 +92,7 @@ in
           type = types.str;
           default = cfg.user;
           defaultText = literalExpression "config.${opt.user}";
-          description = ''
+          description = lib.mdDoc ''
             Database user name.
           '';
         };
@@ -100,34 +100,33 @@ in
         storagePassFile = mkOption {
           type = with types; nullOr str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Path to file with database password. The content of this will be used to
-            create the password for the <literal>StoragePass</literal> option.
+            create the password for the `StoragePass` option.
           '';
         };
 
         extraConfig = mkOption {
           type = types.lines;
           default = "";
-          description = ''
-            Extra configuration for <literal>slurmdbd.conf</literal> See also:
-            <citerefentry><refentrytitle>slurmdbd.conf</refentrytitle>
-            <manvolnum>8</manvolnum></citerefentry>.
+          description = lib.mdDoc ''
+            Extra configuration for `slurmdbd.conf` See also:
+            {manpage}`slurmdbd.conf(8)`.
           '';
         };
       };
 
       client = {
-        enable = mkEnableOption "slurm client daemon";
+        enable = mkEnableOption (lib.mdDoc "slurm client daemon");
       };
 
       enableStools = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to provide a slurm.conf file.
           Enable this option if you do not run a slurm daemon on this host
-          (i.e. <literal>server.enable</literal> and <literal>client.enable</literal> are <literal>false</literal>)
+          (i.e. `server.enable` and `client.enable` are `false`)
           but you still want to run slurm commands from this host.
         '';
       };
@@ -137,7 +136,7 @@ in
         default = pkgs.slurm.override { enableX11 = ! cfg.enableSrunX11; };
         defaultText = literalExpression "pkgs.slurm";
         example = literalExpression "pkgs.slurm-full";
-        description = ''
+        description = lib.mdDoc ''
           The package to use for slurm binaries.
         '';
       };
@@ -146,7 +145,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = null;
-        description = ''
+        description = lib.mdDoc ''
           The short hostname of the machine where SLURM control functions are
           executed (i.e. the name returned by the command "hostname -s", use "tux001"
           rather than "tux001.my.com").
@@ -158,7 +157,7 @@ in
         default = cfg.controlMachine;
         defaultText = literalExpression "config.${opt.controlMachine}";
         example = null;
-        description = ''
+        description = lib.mdDoc ''
           Name that ControlMachine should be referred to in establishing a
           communications path.
         '';
@@ -168,7 +167,7 @@ in
         type = types.str;
         default = "default";
         example = "myCluster";
-        description = ''
+        description = lib.mdDoc ''
           Necessary to distinguish accounting records in a multi-cluster environment.
         '';
       };
@@ -177,7 +176,7 @@ in
         type = types.listOf types.str;
         default = [];
         example = literalExpression ''[ "linux[1-32] CPUs=1 State=UNKNOWN" ];'';
-        description = ''
+        description = lib.mdDoc ''
           Name that SLURM uses to refer to a node (or base partition for BlueGene
           systems). Typically this would be the string that "/bin/hostname -s"
           returns. Note that now you have to write node's parameters after the name.
@@ -188,7 +187,7 @@ in
         type = types.listOf types.str;
         default = [];
         example = literalExpression ''[ "debug Nodes=linux[1-32] Default=YES MaxTime=INFINITE State=UP" ];'';
-        description = ''
+        description = lib.mdDoc ''
           Name by which the partition may be referenced. Note that now you have
           to write the partition's parameters after the name.
         '';
@@ -197,17 +196,17 @@ in
       enableSrunX11 = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           If enabled srun will accept the option "--x11" to allow for X11 forwarding
           from within an interactive session or a batch job. This activates the
           slurm-spank-x11 module. Note that this option also enables
-          <option>services.openssh.forwardX11</option> on the client.
+          {option}`services.openssh.forwardX11` on the client.
 
           This option requires slurm to be compiled without native X11 support.
           The default behavior is to re-compile the slurm package with native X11
           support disabled if this option is set to true.
 
-          To use the native X11 support add <literal>PrologFlags=X11</literal> in <option>extraConfig</option>.
+          To use the native X11 support add `PrologFlags=X11` in {option}`extraConfig`.
           Note that this method will only work RSA SSH host keys.
         '';
       };
@@ -215,7 +214,7 @@ in
       procTrackType = mkOption {
         type = types.str;
         default = "proctrack/linuxproc";
-        description = ''
+        description = lib.mdDoc ''
           Plugin to be used for process tracking on a job step basis.
           The slurmd daemon uses this mechanism to identify all processes
           which are children of processes it spawns for a user job step.
@@ -225,7 +224,7 @@ in
       stateSaveLocation = mkOption {
         type = types.str;
         default = "/var/spool/slurmctld";
-        description = ''
+        description = lib.mdDoc ''
           Directory into which the Slurm controller, slurmctld, saves its state.
         '';
       };
@@ -233,7 +232,7 @@ in
       user = mkOption {
         type = types.str;
         default = defaultUser;
-        description = ''
+        description = lib.mdDoc ''
           Set this option when you want to run the slurmctld daemon
           as something else than the default slurm user "slurm".
           Note that the UID of this user needs to be the same
@@ -244,7 +243,7 @@ in
       extraConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration options that will be added verbatim at
           the end of the slurm configuration file.
         '';
@@ -253,28 +252,28 @@ in
       extraPlugstackConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
-          Extra configuration that will be added to the end of <literal>plugstack.conf</literal>.
+        description = lib.mdDoc ''
+          Extra configuration that will be added to the end of `plugstack.conf`.
         '';
       };
 
       extraCgroupConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
-          Extra configuration for <literal>cgroup.conf</literal>. This file is
-          used when <literal>procTrackType=proctrack/cgroup</literal>.
+        description = lib.mdDoc ''
+          Extra configuration for `cgroup.conf`. This file is
+          used when `procTrackType=proctrack/cgroup`.
         '';
       };
 
       extraConfigPaths = mkOption {
         type = with types; listOf path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Slurm expects config files for plugins in the same path
-          as <literal>slurm.conf</literal>. Add extra nix store
+          as `slurm.conf`. Add extra nix store
           paths that should be merged into same directory as
-          <literal>slurm.conf</literal>.
+          `slurm.conf`.
         '';
       };
 
@@ -282,11 +281,11 @@ in
         type = types.path;
         internal = true;
         default = etcSlurm;
-        defaultText = literalDocBook ''
+        defaultText = literalMD ''
           Directory created from generated config files and
-          <literal>config.${opt.extraConfigPaths}</literal>.
+          `config.${opt.extraConfigPaths}`.
         '';
-        description = ''
+        description = lib.mdDoc ''
           Path to directory with slurm config files. This option is set by default from the
           Slurm module and is meant to make the Slurm config file available to other modules.
         '';
@@ -361,8 +360,13 @@ in
         ++ lib.optional cfg.enableSrunX11 slurm-spank-x11;
 
       wantedBy = [ "multi-user.target" ];
-      after = [ "systemd-tmpfiles-clean.service" ];
-      requires = [ "network.target" ];
+      after = [
+        "systemd-tmpfiles-clean.service"
+        "munge.service"
+        "network-online.target"
+        "remote-fs.target"
+      ];
+      wants = [ "network-online.target" ];
 
       serviceConfig = {
         Type = "forking";
@@ -371,6 +375,7 @@ in
         PIDFile = "/run/slurmd.pid";
         ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
         LimitMEMLOCK = "infinity";
+        Delegate="Yes";
       };
     };
 
diff --git a/nixos/modules/services/computing/torque/mom.nix b/nixos/modules/services/computing/torque/mom.nix
index 6747bd4b0d5..5dd41429bf8 100644
--- a/nixos/modules/services/computing/torque/mom.nix
+++ b/nixos/modules/services/computing/torque/mom.nix
@@ -17,11 +17,11 @@ in
   options = {
 
     services.torque.mom = {
-      enable = mkEnableOption "torque computing node";
+      enable = mkEnableOption (lib.mdDoc "torque computing node");
 
       serverNode = mkOption {
         type = types.str;
-        description = "Hostname running pbs server.";
+        description = lib.mdDoc "Hostname running pbs server.";
       };
 
     };
diff --git a/nixos/modules/services/computing/torque/server.nix b/nixos/modules/services/computing/torque/server.nix
index 8d923fc04d4..02f20fb37c1 100644
--- a/nixos/modules/services/computing/torque/server.nix
+++ b/nixos/modules/services/computing/torque/server.nix
@@ -11,7 +11,7 @@ in
 
     services.torque.server = {
 
-      enable = mkEnableOption "torque server";
+      enable = mkEnableOption (lib.mdDoc "torque server");
 
     };
 
diff --git a/nixos/modules/services/continuous-integration/buildbot/master.nix b/nixos/modules/services/continuous-integration/buildbot/master.nix
index 80c6c6abfd0..d00e0ba3956 100644
--- a/nixos/modules/services/continuous-integration/buildbot/master.nix
+++ b/nixos/modules/services/continuous-integration/buildbot/master.nix
@@ -10,7 +10,7 @@ let
 
   python = cfg.package.pythonModule;
 
-  escapeStr = s: escape ["'"] s;
+  escapeStr = escape [ "'" ];
 
   defaultMasterCfg = pkgs.writeText "master.cfg" ''
     from buildbot.plugins import *
@@ -61,7 +61,7 @@ in {
 
       factorySteps = mkOption {
         type = types.listOf types.str;
-        description = "Factory Steps";
+        description = lib.mdDoc "Factory Steps";
         default = [];
         example = [
           "steps.Git(repourl='https://github.com/buildbot/pyflakes.git', mode='incremental')"
@@ -71,7 +71,7 @@ in {
 
       changeSource = mkOption {
         type = types.listOf types.str;
-        description = "List of Change Sources.";
+        description = lib.mdDoc "List of Change Sources.";
         default = [];
         example = [
           "changes.GitPoller('https://github.com/buildbot/pyflakes.git', workdir='gitpoller-workdir', branch='master', pollinterval=300)"
@@ -81,26 +81,26 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the Buildbot continuous integration server.";
+        description = lib.mdDoc "Whether to enable the Buildbot continuous integration server.";
       };
 
       extraConfig = mkOption {
         type = types.str;
-        description = "Extra configuration to append to master.cfg";
+        description = lib.mdDoc "Extra configuration to append to master.cfg";
         default = "c['buildbotNetUsageData'] = None";
       };
 
       masterCfg = mkOption {
         type = types.path;
-        description = "Optionally pass master.cfg path. Other options in this configuration will be ignored.";
+        description = lib.mdDoc "Optionally pass master.cfg path. Other options in this configuration will be ignored.";
         default = defaultMasterCfg;
-        defaultText = literalDocBook ''generated configuration file'';
+        defaultText = literalMD ''generated configuration file'';
         example = "/etc/nixos/buildbot/master.cfg";
       };
 
       schedulers = mkOption {
         type = types.listOf types.str;
-        description = "List of Schedulers.";
+        description = lib.mdDoc "List of Schedulers.";
         default = [
           "schedulers.SingleBranchScheduler(name='all', change_filter=util.ChangeFilter(branch='master'), treeStableTimer=None, builderNames=['runtests'])"
           "schedulers.ForceScheduler(name='force',builderNames=['runtests'])"
@@ -109,7 +109,7 @@ in {
 
       builders = mkOption {
         type = types.listOf types.str;
-        description = "List of Builders.";
+        description = lib.mdDoc "List of Builders.";
         default = [
           "util.BuilderConfig(name='runtests',workernames=['example-worker'],factory=factory)"
         ];
@@ -117,52 +117,52 @@ in {
 
       workers = mkOption {
         type = types.listOf types.str;
-        description = "List of Workers.";
+        description = lib.mdDoc "List of Workers.";
         default = [ "worker.Worker('example-worker', 'pass')" ];
       };
 
       reporters = mkOption {
         default = [];
         type = types.listOf types.str;
-        description = "List of reporter objects used to present build status to various users.";
+        description = lib.mdDoc "List of reporter objects used to present build status to various users.";
       };
 
       user = mkOption {
         default = "buildbot";
         type = types.str;
-        description = "User the buildbot server should execute under.";
+        description = lib.mdDoc "User the buildbot server should execute under.";
       };
 
       group = mkOption {
         default = "buildbot";
         type = types.str;
-        description = "Primary group of buildbot user.";
+        description = lib.mdDoc "Primary group of buildbot user.";
       };
 
       extraGroups = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "List of extra groups that the buildbot user should be a part of.";
+        description = lib.mdDoc "List of extra groups that the buildbot user should be a part of.";
       };
 
       home = mkOption {
         default = "/home/buildbot";
         type = types.path;
-        description = "Buildbot home directory.";
+        description = lib.mdDoc "Buildbot home directory.";
       };
 
       buildbotDir = mkOption {
         default = "${cfg.home}/master";
         defaultText = literalExpression ''"''${config.${opt.home}}/master"'';
         type = types.path;
-        description = "Specifies the Buildbot directory.";
+        description = lib.mdDoc "Specifies the Buildbot directory.";
       };
 
       pbPort = mkOption {
         default = 9989;
         type = types.either types.str types.int;
         example = "'tcp:9990:interface=127.0.0.1'";
-        description = ''
+        description = lib.mdDoc ''
           The buildmaster will listen on a TCP port of your choosing
           for connections from workers.
           It can also use this port for connections from remote Change Sources,
@@ -170,51 +170,51 @@ in {
           This port should be visible to the outside world, and you’ll need to tell
           your worker admins about your choice.
           If put in (single) quotes, this can also be used as a connection string,
-          as defined in the <link xlink:href="https://twistedmatrix.com/documents/current/core/howto/endpoints.html">ConnectionStrings guide</link>.
+          as defined in the [ConnectionStrings guide](https://twistedmatrix.com/documents/current/core/howto/endpoints.html).
         '';
       };
 
       listenAddress = mkOption {
         default = "0.0.0.0";
         type = types.str;
-        description = "Specifies the bind address on which the buildbot HTTP interface listens.";
+        description = lib.mdDoc "Specifies the bind address on which the buildbot HTTP interface listens.";
       };
 
       buildbotUrl = mkOption {
         default = "http://localhost:8010/";
         type = types.str;
-        description = "Specifies the Buildbot URL.";
+        description = lib.mdDoc "Specifies the Buildbot URL.";
       };
 
       title = mkOption {
         default = "Buildbot";
         type = types.str;
-        description = "Specifies the Buildbot Title.";
+        description = lib.mdDoc "Specifies the Buildbot Title.";
       };
 
       titleUrl = mkOption {
         default = "Buildbot";
         type = types.str;
-        description = "Specifies the Buildbot TitleURL.";
+        description = lib.mdDoc "Specifies the Buildbot TitleURL.";
       };
 
       dbUrl = mkOption {
         default = "sqlite:///state.sqlite";
         type = types.str;
-        description = "Specifies the database connection string.";
+        description = lib.mdDoc "Specifies the database connection string.";
       };
 
       port = mkOption {
         default = 8010;
         type = types.int;
-        description = "Specifies port number on which the buildbot HTTP interface listens.";
+        description = lib.mdDoc "Specifies port number on which the buildbot HTTP interface listens.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.python3Packages.buildbot-full;
         defaultText = literalExpression "pkgs.python3Packages.buildbot-full";
-        description = "Package to use for buildbot.";
+        description = lib.mdDoc "Package to use for buildbot.";
         example = literalExpression "pkgs.python3Packages.buildbot";
       };
 
@@ -222,14 +222,14 @@ in {
         default = [ pkgs.git ];
         defaultText = literalExpression "[ pkgs.git ]";
         type = types.listOf types.package;
-        description = "Packages to add to PATH for the buildbot process.";
+        description = lib.mdDoc "Packages to add to PATH for the buildbot process.";
       };
 
       pythonPackages = mkOption {
         type = types.functionTo (types.listOf types.package);
         default = pythonPackages: with pythonPackages; [ ];
         defaultText = literalExpression "pythonPackages: with pythonPackages; [ ]";
-        description = "Packages to add the to the PYTHONPATH of the buildbot process.";
+        description = lib.mdDoc "Packages to add the to the PYTHONPATH of the buildbot process.";
         example = literalExpression "pythonPackages: with pythonPackages; [ requests ]";
       };
     };
@@ -245,9 +245,7 @@ in {
         description = "Buildbot User.";
         isNormalUser = true;
         createHome = true;
-        home = cfg.home;
-        group = cfg.group;
-        extraGroups = cfg.extraGroups;
+        inherit (cfg) home group extraGroups;
         useDefaultShell = true;
       };
     };
diff --git a/nixos/modules/services/continuous-integration/buildbot/worker.nix b/nixos/modules/services/continuous-integration/buildbot/worker.nix
index 1d7f53bb655..52c41c4a758 100644
--- a/nixos/modules/services/continuous-integration/buildbot/worker.nix
+++ b/nixos/modules/services/continuous-integration/buildbot/worker.nix
@@ -49,89 +49,89 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the Buildbot Worker.";
+        description = lib.mdDoc "Whether to enable the Buildbot Worker.";
       };
 
       user = mkOption {
         default = "bbworker";
         type = types.str;
-        description = "User the buildbot Worker should execute under.";
+        description = lib.mdDoc "User the buildbot Worker should execute under.";
       };
 
       group = mkOption {
         default = "bbworker";
         type = types.str;
-        description = "Primary group of buildbot Worker user.";
+        description = lib.mdDoc "Primary group of buildbot Worker user.";
       };
 
       extraGroups = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "List of extra groups that the Buildbot Worker user should be a part of.";
+        description = lib.mdDoc "List of extra groups that the Buildbot Worker user should be a part of.";
       };
 
       home = mkOption {
         default = "/home/bbworker";
         type = types.path;
-        description = "Buildbot home directory.";
+        description = lib.mdDoc "Buildbot home directory.";
       };
 
       buildbotDir = mkOption {
         default = "${cfg.home}/worker";
         defaultText = literalExpression ''"''${config.${opt.home}}/worker"'';
         type = types.path;
-        description = "Specifies the Buildbot directory.";
+        description = lib.mdDoc "Specifies the Buildbot directory.";
       };
 
       workerUser = mkOption {
         default = "example-worker";
         type = types.str;
-        description = "Specifies the Buildbot Worker user.";
+        description = lib.mdDoc "Specifies the Buildbot Worker user.";
       };
 
       workerPass = mkOption {
         default = "pass";
         type = types.str;
-        description = "Specifies the Buildbot Worker password.";
+        description = lib.mdDoc "Specifies the Buildbot Worker password.";
       };
 
       workerPassFile = mkOption {
         type = types.path;
-        description = "File used to store the Buildbot Worker password";
+        description = lib.mdDoc "File used to store the Buildbot Worker password";
       };
 
       hostMessage = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = "Description of this worker";
+        description = lib.mdDoc "Description of this worker";
       };
 
       adminMessage = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = "Name of the administrator of this worker";
+        description = lib.mdDoc "Name of the administrator of this worker";
       };
 
       masterUrl = mkOption {
         default = "localhost:9989";
         type = types.str;
-        description = "Specifies the Buildbot Worker connection string.";
+        description = lib.mdDoc "Specifies the Buildbot Worker connection string.";
       };
 
       keepalive = mkOption {
         default = 600;
         type = types.int;
-        description = "
+        description = lib.mdDoc ''
           This is a number that indicates how frequently keepalive messages should be sent
           from the worker to the buildmaster, expressed in seconds.
-        ";
+        '';
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.python3Packages.buildbot-worker;
         defaultText = literalExpression "pkgs.python3Packages.buildbot-worker";
-        description = "Package to use for buildbot worker.";
+        description = lib.mdDoc "Package to use for buildbot worker.";
         example = literalExpression "pkgs.python2Packages.buildbot-worker";
       };
 
@@ -139,7 +139,7 @@ in {
         default = with pkgs; [ git ];
         defaultText = literalExpression "[ pkgs.git ]";
         type = types.listOf types.package;
-        description = "Packages to add to PATH for the buildbot process.";
+        description = lib.mdDoc "Packages to add to PATH for the buildbot process.";
       };
     };
   };
diff --git a/nixos/modules/services/continuous-integration/buildkite-agents.nix b/nixos/modules/services/continuous-integration/buildkite-agents.nix
index 1872567c9f1..7c8f77580ff 100644
--- a/nixos/modules/services/continuous-integration/buildkite-agents.nix
+++ b/nixos/modules/services/continuous-integration/buildkite-agents.nix
@@ -9,7 +9,7 @@ let
     inherit name;
     value = mkOption {
       default = null;
-      inherit description;
+      description = lib.mdDoc description;
       type = types.nullOr types.lines;
     } // (if example == null then {} else { inherit example; });
   };
@@ -34,32 +34,32 @@ let
       enable = mkOption {
         default = true;
         type = types.bool;
-        description = "Whether to enable this buildkite agent";
+        description = lib.mdDoc "Whether to enable this buildkite agent";
       };
 
       package = mkOption {
         default = pkgs.buildkite-agent;
         defaultText = literalExpression "pkgs.buildkite-agent";
-        description = "Which buildkite-agent derivation to use";
+        description = lib.mdDoc "Which buildkite-agent derivation to use";
         type = types.package;
       };
 
       dataDir = mkOption {
         default = "/var/lib/buildkite-agent-${name}";
-        description = "The workdir for the agent";
+        description = lib.mdDoc "The workdir for the agent";
         type = types.str;
       };
 
       runtimePackages = mkOption {
         default = [ pkgs.bash pkgs.gnutar pkgs.gzip pkgs.git pkgs.nix ];
         defaultText = literalExpression "[ pkgs.bash pkgs.gnutar pkgs.gzip pkgs.git pkgs.nix ]";
-        description = "Add programs to the buildkite-agent environment";
+        description = lib.mdDoc "Add programs to the buildkite-agent environment";
         type = types.listOf types.package;
       };
 
       tokenPath = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The token from your Buildkite "Agents" page.
 
           A run-time path to the token file, which is supposed to be provisioned
@@ -70,7 +70,7 @@ let
       name = mkOption {
         type = types.str;
         default = "%hostname-${name}-%n";
-        description = ''
+        description = lib.mdDoc ''
           The name of the agent as seen in the buildkite dashboard.
         '';
       };
@@ -79,7 +79,7 @@ let
         type = types.attrsOf (types.either types.str (types.listOf types.str));
         default = {};
         example = { queue = "default"; docker = "true"; ruby2 ="true"; };
-        description = ''
+        description = lib.mdDoc ''
           Tags for the agent.
         '';
       };
@@ -88,7 +88,7 @@ let
         type = types.lines;
         default = "";
         example = "debug=true";
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to the configuration file.
         '';
       };
@@ -100,7 +100,7 @@ let
         ## don't end up in the Nix store.
         apply = final: if final == null then null else toString final;
 
-        description = ''
+        description = lib.mdDoc ''
           OpenSSH private key
 
           A run-time path to the key file, which is supposed to be provisioned
@@ -168,10 +168,10 @@ let
       hooksPath = mkOption {
         type = types.path;
         default = hooksDir config;
-        defaultText = literalDocBook "generated from <option>services.buildkite-agents.&lt;name&gt;.hooks</option>";
-        description = ''
+        defaultText = literalMD "generated from {option}`services.buildkite-agents.<name>.hooks`";
+        description = lib.mdDoc ''
           Path to the directory storing the hooks.
-          Consider using <option>services.buildkite-agents.&lt;name&gt;.hooks.&lt;name&gt;</option>
+          Consider using {option}`services.buildkite-agents.<name>.hooks.<name>`
           instead.
         '';
       };
@@ -180,7 +180,7 @@ let
         type = types.str;
         default = "${pkgs.bash}/bin/bash -e -c";
         defaultText = literalExpression ''"''${pkgs.bash}/bin/bash -e -c"'';
-        description = ''
+        description = lib.mdDoc ''
           Command that buildkite-agent 3 will execute when it spawns a shell.
         '';
       };
@@ -193,7 +193,7 @@ in
   options.services.buildkite-agents = mkOption {
     type = types.attrsOf (types.submodule buildkiteOptions);
     default = {};
-    description = ''
+    description = lib.mdDoc ''
       Attribute set of buildkite agents.
       The attribute key is combined with the hostname and a unique integer to
       create the final agent name. This can be overridden by setting the `name`
diff --git a/nixos/modules/services/continuous-integration/github-runner.nix b/nixos/modules/services/continuous-integration/github-runner.nix
index a7645e1f56e..24d02c931a4 100644
--- a/nixos/modules/services/continuous-integration/github-runner.nix
+++ b/nixos/modules/services/continuous-integration/github-runner.nix
@@ -1,310 +1,23 @@
-{ config, pkgs, lib, ... }:
+{ config
+, pkgs
+, lib
+, ...
+}@args:
+
 with lib;
+
 let
   cfg = config.services.github-runner;
-  svcName = "github-runner";
-  systemdDir = "${svcName}/${cfg.name}";
-  # %t: Runtime directory root (usually /run); see systemd.unit(5)
-  runtimeDir = "%t/${systemdDir}";
-  # %S: State directory root (usually /var/lib); see systemd.unit(5)
-  stateDir = "%S/${systemdDir}";
-  # %L: Log directory root (usually /var/log); see systemd.unit(5)
-  logsDir = "%L/${systemdDir}";
-  # Name of file stored in service state directory
-  currentConfigTokenFilename = ".current-token";
 in
-{
-  options.services.github-runner = {
-    enable = mkOption {
-      default = false;
-      example = true;
-      description = ''
-        Whether to enable GitHub Actions runner.
-
-        Note: GitHub recommends using self-hosted runners with private repositories only. Learn more here:
-        <link xlink:href="https://docs.github.com/en/actions/hosting-your-own-runners/about-self-hosted-runners"
-        >About self-hosted runners</link>.
-      '';
-      type = lib.types.bool;
-    };
-
-    url = mkOption {
-      type = types.str;
-      description = ''
-        Repository to add the runner to.
-
-        Changing this option triggers a new runner registration.
-
-        IMPORTANT: If your token is org-wide (not per repository), you need to
-        provide a github org link, not a single repository, so do it like this
-        <literal>https://github.com/nixos</literal>, not like this
-        <literal>https://github.com/nixos/nixpkgs</literal>.
-        Otherwise, you are going to get a <literal>404 NotFound</literal>
-        from <literal>POST https://api.github.com/actions/runner-registration</literal>
-        in the configure script.
-      '';
-      example = "https://github.com/nixos/nixpkgs";
-    };
-
-    tokenFile = mkOption {
-      type = types.path;
-      description = ''
-        The full path to a file which contains the runner registration token.
-        The file should contain exactly one line with the token without any newline.
-        The token can be used to re-register a runner of the same name but is time-limited.
-
-        Changing this option or the file's content triggers a new runner registration.
-      '';
-      example = "/run/secrets/github-runner/nixos.token";
-    };
-
-    name = mkOption {
-      # Same pattern as for `networking.hostName`
-      type = types.strMatching "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$";
-      description = ''
-        Name of the runner to configure. Defaults to the hostname.
-
-        Changing this option triggers a new runner registration.
-      '';
-      example = "nixos";
-      default = config.networking.hostName;
-      defaultText = literalExpression "config.networking.hostName";
-    };
 
-    runnerGroup = mkOption {
-      type = types.nullOr types.str;
-      description = ''
-        Name of the runner group to add this runner to (defaults to the default runner group).
-
-        Changing this option triggers a new runner registration.
-      '';
-      default = null;
-    };
-
-    extraLabels = mkOption {
-      type = types.listOf types.str;
-      description = ''
-        Extra labels in addition to the default (<literal>["self-hosted", "Linux", "X64"]</literal>).
-
-        Changing this option triggers a new runner registration.
-      '';
-      example = literalExpression ''[ "nixos" ]'';
-      default = [ ];
-    };
-
-    replace = mkOption {
-      type = types.bool;
-      description = ''
-        Replace any existing runner with the same name.
-
-        Without this flag, registering a new runner with the same name fails.
-      '';
-      default = false;
-    };
-
-    extraPackages = mkOption {
-      type = types.listOf types.package;
-      description = ''
-        Extra packages to add to <literal>PATH</literal> of the service to make them available to workflows.
-      '';
-      default = [ ];
-    };
-
-    package = mkOption {
-      type = types.package;
-      description = ''
-        Which github-runner derivation to use.
-      '';
-      default = pkgs.github-runner;
-      defaultText = literalExpression "pkgs.github-runner";
-    };
-  };
+{
+  options.services.github-runner = import ./github-runner/options.nix (args // {
+    # Users don't need to specify options.services.github-runner.name; it will default
+    # to the hostname.
+    includeNameDefault = true;
+  });
 
   config = mkIf cfg.enable {
-    warnings = optionals (isStorePath cfg.tokenFile) [
-      ''
-        `services.github-runner.tokenFile` points to the Nix store and, therefore, is world-readable.
-        Consider using a path outside of the Nix store to keep the token private.
-      ''
-    ];
-
-    systemd.services.${svcName} = {
-      description = "GitHub Actions runner";
-
-      wantedBy = [ "multi-user.target" ];
-      wants = [ "network-online.target" ];
-      after = [ "network.target" "network-online.target" ];
-
-      environment = {
-        HOME = runtimeDir;
-        RUNNER_ROOT = runtimeDir;
-      };
-
-      path = (with pkgs; [
-        bash
-        coreutils
-        git
-        gnutar
-        gzip
-      ]) ++ [
-        config.nix.package
-      ] ++ cfg.extraPackages;
-
-      serviceConfig = rec {
-        ExecStart = "${cfg.package}/bin/runsvc.sh";
-
-        # Does the following, sequentially:
-        # - If the module configuration or the token has changed, purge the state directory,
-        #   and create the current and the new token file with the contents of the configured
-        #   token. While both files have the same content, only the later is accessible by
-        #   the service user.
-        # - Configure the runner using the new token file. When finished, delete it.
-        # - Set up the directory structure by creating the necessary symlinks.
-        ExecStartPre =
-          let
-            # Wrapper script which expects the full path of the state, runtime and logs
-            # directory as arguments. Overrides the respective systemd variables to provide
-            # unambiguous directory names. This becomes relevant, for example, if the
-            # caller overrides any of the StateDirectory=, RuntimeDirectory= or LogDirectory=
-            # to contain more than one directory. This causes systemd to set the respective
-            # environment variables with the path of all of the given directories, separated
-            # by a colon.
-            writeScript = name: lines: pkgs.writeShellScript "${svcName}-${name}.sh" ''
-              set -euo pipefail
-
-              STATE_DIRECTORY="$1"
-              RUNTIME_DIRECTORY="$2"
-              LOGS_DIRECTORY="$3"
-
-              ${lines}
-            '';
-            currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json";
-            runnerRegistrationConfig = getAttrs [ "name" "tokenFile" "url" "runnerGroup" "extraLabels" ] cfg;
-            newConfigPath = builtins.toFile "${svcName}-config.json" (builtins.toJSON runnerRegistrationConfig);
-            newConfigTokenFilename = ".new-token";
-            runnerCredFiles = [
-              ".credentials"
-              ".credentials_rsaparams"
-              ".runner"
-            ];
-            unconfigureRunner = writeScript "unconfigure" ''
-              differs=
-              # Set `differs = 1` if current and new runner config differ or if `currentConfigPath` does not exist
-              ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 || differs=1
-              # Also trigger a registration if the token content changed
-              ${pkgs.diffutils}/bin/diff -q \
-                "$STATE_DIRECTORY"/${currentConfigTokenFilename} \
-                ${escapeShellArg cfg.tokenFile} \
-                >/dev/null 2>&1 || differs=1
-
-              if [[ -n "$differs" ]]; then
-                echo "Config has changed, removing old runner state."
-                echo "The old runner will still appear in the GitHub Actions UI." \
-                  "You have to remove it manually."
-                find "$STATE_DIRECTORY/" -mindepth 1 -delete
-
-                # Copy the configured token file to the state dir and allow the service user to read the file
-                install --mode=666 ${escapeShellArg cfg.tokenFile} "$STATE_DIRECTORY/${newConfigTokenFilename}"
-                # Also copy current file to allow for a diff on the next start
-                install --mode=600 ${escapeShellArg cfg.tokenFile} "$STATE_DIRECTORY/${currentConfigTokenFilename}"
-              fi
-            '';
-            configureRunner = writeScript "configure" ''
-              if [[ -e "$STATE_DIRECTORY/${newConfigTokenFilename}" ]]; then
-                echo "Configuring GitHub Actions Runner"
-
-                token=$(< "$STATE_DIRECTORY"/${newConfigTokenFilename})
-                RUNNER_ROOT="$STATE_DIRECTORY" ${cfg.package}/bin/config.sh \
-                  --unattended \
-                  --disableupdate \
-                  --work "$RUNTIME_DIRECTORY" \
-                  --url ${escapeShellArg cfg.url} \
-                  --token "$token" \
-                  --labels ${escapeShellArg (concatStringsSep "," cfg.extraLabels)} \
-                  --name ${escapeShellArg cfg.name} \
-                  ${optionalString cfg.replace "--replace"} \
-                  ${optionalString (cfg.runnerGroup != null) "--runnergroup ${escapeShellArg cfg.runnerGroup}"}
-
-                # Move the automatically created _diag dir to the logs dir
-                mkdir -p  "$STATE_DIRECTORY/_diag"
-                cp    -r  "$STATE_DIRECTORY/_diag/." "$LOGS_DIRECTORY/"
-                rm    -rf "$STATE_DIRECTORY/_diag/"
-
-                # Cleanup token from config
-                rm "$STATE_DIRECTORY/${newConfigTokenFilename}"
-
-                # Symlink to new config
-                ln -s '${newConfigPath}' "${currentConfigPath}"
-              fi
-            '';
-            setupRuntimeDir = writeScript "setup-runtime-dirs" ''
-              # Link _diag dir
-              ln -s "$LOGS_DIRECTORY" "$RUNTIME_DIRECTORY/_diag"
-
-              # Link the runner credentials to the runtime dir
-              ln -s "$STATE_DIRECTORY"/{${lib.concatStringsSep "," runnerCredFiles}} "$RUNTIME_DIRECTORY/"
-            '';
-          in
-          map (x: "${x} ${escapeShellArgs [ stateDir runtimeDir logsDir ]}") [
-            "+${unconfigureRunner}" # runs as root
-            configureRunner
-            setupRuntimeDir
-          ];
-
-        # Contains _diag
-        LogsDirectory = [ systemdDir ];
-        # Default RUNNER_ROOT which contains ephemeral Runner data
-        RuntimeDirectory = [ systemdDir ];
-        # Home of persistent runner data, e.g., credentials
-        StateDirectory = [ systemdDir ];
-        StateDirectoryMode = "0700";
-        WorkingDirectory = runtimeDir;
-
-        InaccessiblePaths = [
-          # Token file path given in the configuration
-          cfg.tokenFile
-          # Token file in the state directory
-          "${stateDir}/${currentConfigTokenFilename}"
-        ];
-
-        # By default, use a dynamically allocated user
-        DynamicUser = true;
-
-        KillMode = "process";
-        KillSignal = "SIGTERM";
-
-        # Hardening (may overlap with DynamicUser=)
-        # The following options are only for optimizing:
-        # systemd-analyze security github-runner
-        AmbientCapabilities = "";
-        CapabilityBoundingSet = "";
-        # ProtectClock= adds DeviceAllow=char-rtc r
-        DeviceAllow = "";
-        LockPersonality = true;
-        NoNewPrivileges = true;
-        PrivateDevices = true;
-        PrivateMounts = true;
-        PrivateTmp = true;
-        PrivateUsers = true;
-        ProtectClock = true;
-        ProtectControlGroups = true;
-        ProtectHome = true;
-        ProtectHostname = true;
-        ProtectKernelLogs = true;
-        ProtectKernelModules = true;
-        ProtectKernelTunables = true;
-        ProtectSystem = "strict";
-        RemoveIPC = true;
-        RestrictNamespaces = true;
-        RestrictRealtime = true;
-        RestrictSUIDSGID = true;
-        UMask = "0066";
-
-        # Needs network access
-        PrivateNetwork = false;
-        # Cannot be true due to Node
-        MemoryDenyWriteExecute = false;
-      };
-    };
+    services.github-runners.${cfg.name} = cfg;
   };
 }
diff --git a/nixos/modules/services/continuous-integration/github-runner/options.nix b/nixos/modules/services/continuous-integration/github-runner/options.nix
new file mode 100644
index 00000000000..796b5a7f117
--- /dev/null
+++ b/nixos/modules/services/continuous-integration/github-runner/options.nix
@@ -0,0 +1,173 @@
+{ config
+, lib
+, pkgs
+, includeNameDefault
+, ...
+}:
+
+with lib;
+
+{
+  enable = mkOption {
+    default = false;
+    example = true;
+    description = lib.mdDoc ''
+      Whether to enable GitHub Actions runner.
+
+      Note: GitHub recommends using self-hosted runners with private repositories only. Learn more here:
+      [About self-hosted runners](https://docs.github.com/en/actions/hosting-your-own-runners/about-self-hosted-runners).
+    '';
+    type = lib.types.bool;
+  };
+
+  url = mkOption {
+    type = types.str;
+    description = lib.mdDoc ''
+      Repository to add the runner to.
+
+      Changing this option triggers a new runner registration.
+
+      IMPORTANT: If your token is org-wide (not per repository), you need to
+      provide a github org link, not a single repository, so do it like this
+      `https://github.com/nixos`, not like this
+      `https://github.com/nixos/nixpkgs`.
+      Otherwise, you are going to get a `404 NotFound`
+      from `POST https://api.github.com/actions/runner-registration`
+      in the configure script.
+    '';
+    example = "https://github.com/nixos/nixpkgs";
+  };
+
+  tokenFile = mkOption {
+    type = types.path;
+    description = lib.mdDoc ''
+      The full path to a file which contains either a runner registration token or a
+      (fine-grained) personal access token (PAT).
+      The file should contain exactly one line with the token without any newline.
+      If a registration token is given, it can be used to re-register a runner of the same
+      name but is time-limited. If the file contains a PAT, the service creates a new
+      registration token on startup as needed. Make sure the PAT has a scope of
+      `admin:org` for organization-wide registrations or a scope of
+      `repo` for a single repository. Fine-grained PATs need read and write permission
+      to the "Adminstration" resources.
+
+      Changing this option or the file's content triggers a new runner registration.
+    '';
+    example = "/run/secrets/github-runner/nixos.token";
+  };
+
+  name = let
+    # Same pattern as for `networking.hostName`
+    baseType = types.strMatching "^$|^[[:alnum:]]([[:alnum:]_-]{0,61}[[:alnum:]])?$";
+  in mkOption {
+    type = if includeNameDefault then baseType else types.nullOr baseType;
+    description = lib.mdDoc ''
+      Name of the runner to configure. Defaults to the hostname.
+
+      Changing this option triggers a new runner registration.
+    '';
+    example = "nixos";
+  } // (if includeNameDefault then {
+    default = config.networking.hostName;
+    defaultText = literalExpression "config.networking.hostName";
+  } else {
+    default = null;
+  });
+
+  runnerGroup = mkOption {
+    type = types.nullOr types.str;
+    description = lib.mdDoc ''
+      Name of the runner group to add this runner to (defaults to the default runner group).
+
+      Changing this option triggers a new runner registration.
+    '';
+    default = null;
+  };
+
+  extraLabels = mkOption {
+    type = types.listOf types.str;
+    description = lib.mdDoc ''
+      Extra labels in addition to the default (`["self-hosted", "Linux", "X64"]`).
+
+      Changing this option triggers a new runner registration.
+    '';
+    example = literalExpression ''[ "nixos" ]'';
+    default = [ ];
+  };
+
+  replace = mkOption {
+    type = types.bool;
+    description = lib.mdDoc ''
+      Replace any existing runner with the same name.
+
+      Without this flag, registering a new runner with the same name fails.
+    '';
+    default = false;
+  };
+
+  extraPackages = mkOption {
+    type = types.listOf types.package;
+    description = lib.mdDoc ''
+      Extra packages to add to `PATH` of the service to make them available to workflows.
+    '';
+    default = [ ];
+  };
+
+  extraEnvironment = mkOption {
+    type = types.attrs;
+    description = lib.mdDoc ''
+      Extra environment variables to set for the runner, as an attrset.
+    '';
+    example = {
+      GIT_CONFIG = "/path/to/git/config";
+    };
+    default = {};
+  };
+
+  serviceOverrides = mkOption {
+    type = types.attrs;
+    description = lib.mdDoc ''
+      Overrides for the systemd service. Can be used to adjust the sandboxing options.
+    '';
+    example = {
+      ProtectHome = false;
+    };
+    default = {};
+  };
+
+  package = mkOption {
+    type = types.package;
+    description = lib.mdDoc ''
+      Which github-runner derivation to use.
+    '';
+    default = pkgs.github-runner;
+    defaultText = literalExpression "pkgs.github-runner";
+  };
+
+  ephemeral = mkOption {
+    type = types.bool;
+    description = lib.mdDoc ''
+      If enabled, causes the following behavior:
+
+      - Passes the `--ephemeral` flag to the runner configuration script
+      - De-registers and stops the runner with GitHub after it has processed one job
+      - On stop, systemd wipes the runtime directory (this always happens, even without using the ephemeral option)
+      - Restarts the service after its successful exit
+      - On start, wipes the state directory and configures a new runner
+
+      You should only enable this option if `tokenFile` points to a file which contains a
+      personal access token (PAT). If you're using the option with a registration token, restarting the
+      service will fail as soon as the registration token expired.
+    '';
+    default = false;
+  };
+
+  user = mkOption {
+    type = types.nullOr types.str;
+    description = lib.mdDoc ''
+      User under which to run the service. If null, will use a systemd dynamic user.
+    '';
+    default = null;
+    defaultText = literalExpression "username";
+  };
+}
diff --git a/nixos/modules/services/continuous-integration/github-runner/service.nix b/nixos/modules/services/continuous-integration/github-runner/service.nix
new file mode 100644
index 00000000000..cd81631582f
--- /dev/null
+++ b/nixos/modules/services/continuous-integration/github-runner/service.nix
@@ -0,0 +1,257 @@
+{ config
+, lib
+, pkgs
+
+, cfg ? config.services.github-runner
+, svcName
+
+, systemdDir ? "${svcName}/${cfg.name}"
+  # %t: Runtime directory root (usually /run); see systemd.unit(5)
+, runtimeDir ? "%t/${systemdDir}"
+  # %S: State directory root (usually /var/lib); see systemd.unit(5)
+, stateDir ? "%S/${systemdDir}"
+  # %L: Log directory root (usually /var/log); see systemd.unit(5)
+, logsDir ? "%L/${systemdDir}"
+  # Name of file stored in service state directory
+, currentConfigTokenFilename ? ".current-token"
+
+, ...
+}:
+
+with lib;
+
+{
+  description = "GitHub Actions runner";
+
+  wantedBy = [ "multi-user.target" ];
+  wants = [ "network-online.target" ];
+  after = [ "network.target" "network-online.target" ];
+
+  environment = {
+    HOME = runtimeDir;
+    RUNNER_ROOT = stateDir;
+  } // cfg.extraEnvironment;
+
+  path = (with pkgs; [
+    bash
+    coreutils
+    git
+    gnutar
+    gzip
+  ]) ++ [
+    config.nix.package
+  ] ++ cfg.extraPackages;
+
+  serviceConfig = rec {
+    ExecStart = "${cfg.package}/bin/Runner.Listener run --startuptype service";
+
+    # Does the following, sequentially:
+    # - If the module configuration or the token has changed, purge the state directory,
+    #   and create the current and the new token file with the contents of the configured
+    #   token. While both files have the same content, only the later is accessible by
+    #   the service user.
+    # - Configure the runner using the new token file. When finished, delete it.
+    # - Set up the directory structure by creating the necessary symlinks.
+    ExecStartPre =
+      let
+        # Wrapper script which expects the full path of the state, runtime and logs
+        # directory as arguments. Overrides the respective systemd variables to provide
+        # unambiguous directory names. This becomes relevant, for example, if the
+        # caller overrides any of the StateDirectory=, RuntimeDirectory= or LogDirectory=
+        # to contain more than one directory. This causes systemd to set the respective
+        # environment variables with the path of all of the given directories, separated
+        # by a colon.
+        writeScript = name: lines: pkgs.writeShellScript "${svcName}-${name}.sh" ''
+          set -euo pipefail
+
+          STATE_DIRECTORY="$1"
+          RUNTIME_DIRECTORY="$2"
+          LOGS_DIRECTORY="$3"
+
+          ${lines}
+        '';
+        runnerRegistrationConfig = getAttrs [ "name" "tokenFile" "url" "runnerGroup" "extraLabels" "ephemeral" ] cfg;
+        newConfigPath = builtins.toFile "${svcName}-config.json" (builtins.toJSON runnerRegistrationConfig);
+        currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json";
+        newConfigTokenPath= "$STATE_DIRECTORY/.new-token";
+        currentConfigTokenPath = "$STATE_DIRECTORY/${currentConfigTokenFilename}";
+
+        runnerCredFiles = [
+          ".credentials"
+          ".credentials_rsaparams"
+          ".runner"
+        ];
+        unconfigureRunner = writeScript "unconfigure" ''
+          copy_tokens() {
+            # Copy the configured token file to the state dir and allow the service user to read the file
+            install --mode=666 ${escapeShellArg cfg.tokenFile} "${newConfigTokenPath}"
+            # Also copy current file to allow for a diff on the next start
+            install --mode=600 ${escapeShellArg cfg.tokenFile} "${currentConfigTokenPath}"
+          }
+          clean_state() {
+            find "$STATE_DIRECTORY/" -mindepth 1 -delete
+            copy_tokens
+          }
+          diff_config() {
+            changed=0
+            # Check for module config changes
+            [[ -f "${currentConfigPath}" ]] \
+              && ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 \
+              || changed=1
+            # Also check the content of the token file
+            [[ -f "${currentConfigTokenPath}" ]] \
+              && ${pkgs.diffutils}/bin/diff -q "${currentConfigTokenPath}" ${escapeShellArg cfg.tokenFile} >/dev/null 2>&1 \
+              || changed=1
+            # If the config has changed, remove old state and copy tokens
+            if [[ "$changed" -eq 1 ]]; then
+              echo "Config has changed, removing old runner state."
+              echo "The old runner will still appear in the GitHub Actions UI." \
+                   "You have to remove it manually."
+              clean_state
+            fi
+          }
+          if [[ "${optionalString cfg.ephemeral "1"}" ]]; then
+            # In ephemeral mode, we always want to start with a clean state
+            clean_state
+          elif [[ "$(ls -A "$STATE_DIRECTORY")" ]]; then
+            # There are state files from a previous run; diff them to decide if we need a new registration
+            diff_config
+          else
+            # The state directory is entirely empty which indicates a first start
+            copy_tokens
+          fi        '';
+        configureRunner = writeScript "configure" ''
+          if [[ -e "${newConfigTokenPath}" ]]; then
+            echo "Configuring GitHub Actions Runner"
+            args=(
+              --unattended
+              --disableupdate
+              --work "$RUNTIME_DIRECTORY"
+              --url ${escapeShellArg cfg.url}
+              --labels ${escapeShellArg (concatStringsSep "," cfg.extraLabels)}
+              --name ${escapeShellArg cfg.name}
+              ${optionalString cfg.replace "--replace"}
+              ${optionalString (cfg.runnerGroup != null) "--runnergroup ${escapeShellArg cfg.runnerGroup}"}
+              ${optionalString cfg.ephemeral "--ephemeral"}
+            )
+            # If the token file contains a PAT (i.e., it starts with "ghp_" or "github_pat_"), we have to use the --pat option,
+            # if it is not a PAT, we assume it contains a registration token and use the --token option
+            token=$(<"${newConfigTokenPath}")
+            if [[ "$token" =~ ^ghp_* ]] || [[ "$token" =~ ^github_pat_* ]]; then
+              args+=(--pat "$token")
+            else
+              args+=(--token "$token")
+            fi
+            ${cfg.package}/bin/config.sh "''${args[@]}"
+            # Move the automatically created _diag dir to the logs dir
+            mkdir -p  "$STATE_DIRECTORY/_diag"
+            cp    -r  "$STATE_DIRECTORY/_diag/." "$LOGS_DIRECTORY/"
+            rm    -rf "$STATE_DIRECTORY/_diag/"
+            # Cleanup token from config
+            rm "${newConfigTokenPath}"
+            # Symlink to new config
+            ln -s '${newConfigPath}' "${currentConfigPath}"
+          fi
+        '';
+        setupRuntimeDir = writeScript "setup-runtime-dirs" ''
+          # Link _diag dir
+          ln -s "$LOGS_DIRECTORY" "$RUNTIME_DIRECTORY/_diag"
+
+          # Link the runner credentials to the runtime dir
+          ln -s "$STATE_DIRECTORY"/{${lib.concatStringsSep "," runnerCredFiles}} "$RUNTIME_DIRECTORY/"
+        '';
+      in
+        map (x: "${x} ${escapeShellArgs [ stateDir runtimeDir logsDir ]}") [
+          "+${unconfigureRunner}" # runs as root
+          configureRunner
+          setupRuntimeDir
+        ];
+
+    # If running in ephemeral mode, restart the service on-exit (i.e., successful de-registration of the runner)
+    # to trigger a fresh registration.
+    Restart = if cfg.ephemeral then "on-success" else "no";
+    # If the runner exits with `ReturnCode.RetryableError = 2`, always restart the service:
+    # https://github.com/actions/runner/blob/40ed7f8/src/Runner.Common/Constants.cs#L146
+    RestartForceExitStatus = [ 2 ];
+
+    # Contains _diag
+    LogsDirectory = [ systemdDir ];
+    # Default RUNNER_ROOT which contains ephemeral Runner data
+    RuntimeDirectory = [ systemdDir ];
+    # Home of persistent runner data, e.g., credentials
+    StateDirectory = [ systemdDir ];
+    StateDirectoryMode = "0700";
+    WorkingDirectory = runtimeDir;
+
+    InaccessiblePaths = [
+      # Token file path given in the configuration, if visible to the service
+      "-${cfg.tokenFile}"
+      # Token file in the state directory
+      "${stateDir}/${currentConfigTokenFilename}"
+    ];
+
+    KillSignal = "SIGINT";
+
+    # Hardening (may overlap with DynamicUser=)
+    # The following options are only for optimizing:
+    # systemd-analyze security github-runner
+    AmbientCapabilities = "";
+    CapabilityBoundingSet = "";
+    # ProtectClock= adds DeviceAllow=char-rtc r
+    DeviceAllow = "";
+    NoNewPrivileges = true;
+    PrivateDevices = true;
+    PrivateMounts = true;
+    PrivateTmp = true;
+    PrivateUsers = true;
+    ProtectClock = true;
+    ProtectControlGroups = true;
+    ProtectHome = true;
+    ProtectHostname = true;
+    ProtectKernelLogs = true;
+    ProtectKernelModules = true;
+    ProtectKernelTunables = true;
+    ProtectSystem = "strict";
+    RemoveIPC = true;
+    RestrictNamespaces = true;
+    RestrictRealtime = true;
+    RestrictSUIDSGID = true;
+    UMask = "0066";
+    ProtectProc = "invisible";
+    SystemCallFilter = [
+      "~@clock"
+      "~@cpu-emulation"
+      "~@module"
+      "~@mount"
+      "~@obsolete"
+      "~@raw-io"
+      "~@reboot"
+      "~capset"
+      "~setdomainname"
+      "~sethostname"
+    ];
+    RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" "AF_NETLINK" ];
+
+    # Needs network access
+    PrivateNetwork = false;
+    # Cannot be true due to Node
+    MemoryDenyWriteExecute = false;
+
+    # The more restrictive "pid" option makes `nix` commands in CI emit
+    # "GC Warning: Couldn't read /proc/stat"
+    # You may want to set this to "pid" if not using `nix` commands
+    ProcSubset = "all";
+    # Coverage programs for compiled code such as `cargo-tarpaulin` disable
+    # ASLR (address space layout randomization) which requires the
+    # `personality` syscall
+    # You may want to set this to `true` if not using coverage tooling on
+    # compiled code
+    LockPersonality = false;
+
+    # Note that this has some interactions with the User setting; so you may
+    # want to consult the systemd docs if using both.
+    DynamicUser = true;
+  } // (
+    lib.optionalAttrs (cfg.user != null) { User = cfg.user; }
+  ) // cfg.serviceOverrides;
+}
diff --git a/nixos/modules/services/continuous-integration/github-runners.nix b/nixos/modules/services/continuous-integration/github-runners.nix
new file mode 100644
index 00000000000..78b57f9c7a2
--- /dev/null
+++ b/nixos/modules/services/continuous-integration/github-runners.nix
@@ -0,0 +1,56 @@
+{ config
+, pkgs
+, lib
+, ...
+}@args:
+
+with lib;
+
+let
+  cfg = config.services.github-runners;
+
+in
+
+{
+  options.services.github-runners = mkOption {
+    default = {};
+    type = with types; attrsOf (submodule { options = import ./github-runner/options.nix (args // {
+      # services.github-runners.${name}.name doesn't have a default; it falls back to ${name} below.
+      includeNameDefault = false;
+    }); });
+    example = {
+      runner1 = {
+        enable = true;
+        url = "https://github.com/owner/repo";
+        name = "runner1";
+        tokenFile = "/secrets/token1";
+      };
+
+      runner2 = {
+        enable = true;
+        url = "https://github.com/owner/repo";
+        name = "runner2";
+        tokenFile = "/secrets/token2";
+      };
+    };
+    description = lib.mdDoc ''
+      Multiple GitHub Runners.
+    '';
+  };
+
+  config = {
+    systemd.services = flip mapAttrs' cfg (n: v:
+      let
+        svcName = "github-runner-${n}";
+      in
+        nameValuePair svcName
+        (import ./github-runner/service.nix (args // {
+          inherit svcName;
+          cfg = v // {
+            name = if v.name != null then v.name else n;
+          };
+          systemdDir = "github-runner/${n}";
+        }))
+    );
+  };
+}
diff --git a/nixos/modules/services/continuous-integration/gitlab-runner.nix b/nixos/modules/services/continuous-integration/gitlab-runner.nix
index dc58c634523..2050e04d55c 100644
--- a/nixos/modules/services/continuous-integration/gitlab-runner.nix
+++ b/nixos/modules/services/continuous-integration/gitlab-runner.nix
@@ -22,6 +22,14 @@ let
       export CONFIG_FILE=${configPath}
 
       mkdir -p $(dirname ${configPath})
+      touch ${configPath}
+
+      # update global options
+      remarshal --if toml --of json ${configPath} \
+        | jq -cM 'with_entries(select([.key] | inside(["runners"])))' \
+        | jq -scM '.[0] + .[1]' - <(echo ${escapeShellArg (toJSON cfg.settings)}) \
+        | remarshal --if json --of toml \
+        | sponge ${configPath}
 
       # remove no longer existing services
       gitlab-runner verify --delete
@@ -36,12 +44,12 @@ let
 
       # register new services
       ${concatStringsSep "\n" (mapAttrsToList (name: service: ''
-        if echo "$NEW_SERVICES" | grep -xq ${name}; then
+        if echo "$NEW_SERVICES" | grep -xq "${name}"; then
           bash -c ${escapeShellArg (concatStringsSep " \\\n " ([
             "set -a && source ${service.registrationConfigFile} &&"
             "gitlab-runner register"
             "--non-interactive"
-            "--name ${name}"
+            (if service.description != null then "--description \"${service.description}\"" else "--name '${name}'")
             "--executor ${service.executor}"
             "--limit ${toString service.limit}"
             "--request-concurrency ${toString service.requestConcurrency}"
@@ -91,22 +99,6 @@ let
           --name "$NAME" && sleep 1
       done
 
-      # update global options
-      remarshal --if toml --of json ${configPath} \
-        | jq -cM ${escapeShellArg (concatStringsSep " | " [
-            ".check_interval = ${toJSON cfg.checkInterval}"
-            ".concurrent = ${toJSON cfg.concurrent}"
-            ".sentry_dsn = ${toJSON cfg.sentryDSN}"
-            ".listen_address = ${toJSON cfg.prometheusListenAddress}"
-            ".session_server.listen_address = ${toJSON cfg.sessionServer.listenAddress}"
-            ".session_server.advertise_address = ${toJSON cfg.sessionServer.advertiseAddress}"
-            ".session_server.session_timeout = ${toJSON cfg.sessionServer.sessionTimeout}"
-            "del(.[] | nulls)"
-            "del(.session_server[] | nulls)"
-          ])} \
-        | remarshal --if json --of toml \
-        | sponge ${configPath}
-
       # make config file readable by service
       chown -R --reference=$HOME $(dirname ${configPath})
     '');
@@ -117,107 +109,37 @@ let
 in
 {
   options.services.gitlab-runner = {
-    enable = mkEnableOption "Gitlab Runner";
+    enable = mkEnableOption (lib.mdDoc "Gitlab Runner");
     configFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Configuration file for gitlab-runner.
 
-        <option>configFile</option> takes precedence over <option>services</option>.
-        <option>checkInterval</option> and <option>concurrent</option> will be ignored too.
+        {option}`configFile` takes precedence over {option}`services`.
+        {option}`checkInterval` and {option}`concurrent` will be ignored too.
 
-        This option is deprecated, please use <option>services</option> instead.
-        You can use <option>registrationConfigFile</option> and
-        <option>registrationFlags</option>
+        This option is deprecated, please use {option}`services` instead.
+        You can use {option}`registrationConfigFile` and
+        {option}`registrationFlags`
         for settings not covered by this module.
       '';
     };
-    checkInterval = mkOption {
-      type = types.int;
-      default = 0;
-      example = literalExpression "with lib; (length (attrNames config.services.gitlab-runner.services)) * 3";
-      description = ''
-        Defines the interval length, in seconds, between new jobs check.
-        The default value is 3;
-        if set to 0 or lower, the default value will be used.
-        See <link xlink:href="https://docs.gitlab.com/runner/configuration/advanced-configuration.html#how-check_interval-works">runner documentation</link> for more information.
-      '';
-    };
-    concurrent = mkOption {
-      type = types.int;
-      default = 1;
-      example = literalExpression "config.nix.settings.max-jobs";
-      description = ''
-        Limits how many jobs globally can be run concurrently.
-        The most upper limit of jobs using all defined runners.
-        0 does not mean unlimited.
-      '';
-    };
-    sentryDSN = mkOption {
-      type = types.nullOr types.str;
-      default = null;
-      example = "https://public:private@host:port/1";
-      description = ''
-        Data Source Name for tracking of all system level errors to Sentry.
-      '';
-    };
-    prometheusListenAddress = mkOption {
-      type = types.nullOr types.str;
-      default = null;
-      example = "localhost:8080";
-      description = ''
-        Address (&lt;host&gt;:&lt;port&gt;) on which the Prometheus metrics HTTP server
-        should be listening.
-      '';
-    };
-    sessionServer = mkOption {
+    settings = mkOption {
       type = types.submodule {
-        options = {
-          listenAddress = mkOption {
-            type = types.nullOr types.str;
-            default = null;
-            example = "0.0.0.0:8093";
-            description = ''
-              An internal URL to be used for the session server.
-            '';
-          };
-          advertiseAddress = mkOption {
-            type = types.nullOr types.str;
-            default = null;
-            example = "runner-host-name.tld:8093";
-            description = ''
-              The URL that the Runner will expose to GitLab to be used
-              to access the session server.
-              Fallbacks to <option>listenAddress</option> if not defined.
-            '';
-          };
-          sessionTimeout = mkOption {
-            type = types.int;
-            default = 1800;
-            description = ''
-              How long in seconds the session can stay active after
-              the job completes (which will block the job from finishing).
-            '';
-          };
-        };
+        freeformType = (pkgs.formats.json { }).type;
       };
       default = { };
-      example = literalExpression ''
-        {
-          listenAddress = "0.0.0.0:8093";
-        }
-      '';
-      description = ''
-        The session server allows the user to interact with jobs
-        that the Runner is responsible for. A good example of this is the
-        <link xlink:href="https://docs.gitlab.com/ee/ci/interactive_web_terminal/index.html">interactive web terminal</link>.
+      description = lib.mdDoc ''
+        Global gitlab-runner configuration. See
+        <https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-global-section>
+        for supported values.
       '';
     };
     gracefulTermination = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Finish all remaining jobs before stopping.
         If not set gitlab-runner will stop immediatly without waiting
         for jobs to finish, which will lead to failed builds.
@@ -227,7 +149,7 @@ in
       type = types.str;
       default = "infinity";
       example = "5min 20s";
-      description = ''
+      description = lib.mdDoc ''
         Time to wait until a graceful shutdown is turned into a forceful one.
       '';
     };
@@ -236,17 +158,17 @@ in
       default = pkgs.gitlab-runner;
       defaultText = literalExpression "pkgs.gitlab-runner";
       example = literalExpression "pkgs.gitlab-runner_1_11";
-      description = "Gitlab Runner package to use.";
+      description = lib.mdDoc "Gitlab Runner package to use.";
     };
     extraPackages = mkOption {
       type = types.listOf types.package;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         Extra packages to add to PATH for the gitlab-runner process.
       '';
     };
     services = mkOption {
-      description = "GitLab Runner services.";
+      description = lib.mdDoc "GitLab Runner services.";
       default = { };
       example = literalExpression ''
         {
@@ -328,17 +250,17 @@ in
         options = {
           registrationConfigFile = mkOption {
             type = types.path;
-            description = ''
+            description = lib.mdDoc ''
               Absolute path to a file with environment variables
               used for gitlab-runner registration.
               A list of all supported environment variables can be found in
-              <literal>gitlab-runner register --help</literal>.
+              `gitlab-runner register --help`.
 
               Ones that you probably want to set is
 
-              <literal>CI_SERVER_URL=&lt;CI server URL&gt;</literal>
+              `CI_SERVER_URL=<CI server URL>`
 
-              <literal>REGISTRATION_TOKEN=&lt;registration secret&gt;</literal>
+              `REGISTRATION_TOKEN=<registration secret>`
 
               WARNING: make sure to use quoted absolute path,
               or it is going to be copied to Nix Store.
@@ -348,10 +270,10 @@ in
             type = types.listOf types.str;
             default = [ ];
             example = [ "--docker-helper-image my/gitlab-runner-helper" ];
-            description = ''
+            description = lib.mdDoc ''
               Extra command-line flags passed to
-              <literal>gitlab-runner register</literal>.
-              Execute <literal>gitlab-runner register --help</literal>
+              `gitlab-runner register`.
+              Execute `gitlab-runner register --help`
               for a list of supported flags.
             '';
           };
@@ -359,25 +281,32 @@ in
             type = types.attrsOf types.str;
             default = { };
             example = { NAME = "value"; };
-            description = ''
+            description = lib.mdDoc ''
               Custom environment variables injected to build environment.
-              For secrets you can use <option>registrationConfigFile</option>
-              with <literal>RUNNER_ENV</literal> variable set.
+              For secrets you can use {option}`registrationConfigFile`
+              with `RUNNER_ENV` variable set.
+            '';
+          };
+          description = mkOption {
+            type = types.nullOr types.str;
+            default = null;
+            description = lib.mdDoc ''
+              Name/description of the runner.
             '';
           };
           executor = mkOption {
             type = types.str;
             default = "docker";
-            description = ''
+            description = lib.mdDoc ''
               Select executor, eg. shell, docker, etc.
-              See <link xlink:href="https://docs.gitlab.com/runner/executors/README.html">runner documentation</link> for more information.
+              See [runner documentation](https://docs.gitlab.com/runner/executors/README.html) for more information.
             '';
           };
           buildsDir = mkOption {
             type = types.nullOr types.path;
             default = null;
             example = "/var/lib/gitlab-runner/builds";
-            description = ''
+            description = lib.mdDoc ''
               Absolute path to a directory where builds will be stored
               in context of selected executor (Locally, Docker, SSH).
             '';
@@ -386,14 +315,14 @@ in
             type = types.nullOr types.str;
             default = null;
             example = "http://gitlab.example.local";
-            description = ''
+            description = lib.mdDoc ''
               Overwrite the URL for the GitLab instance. Used if the Runner can’t connect to GitLab on the URL GitLab exposes itself.
             '';
           };
           dockerImage = mkOption {
             type = types.nullOr types.str;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Docker image to be used.
             '';
           };
@@ -401,7 +330,7 @@ in
             type = types.listOf types.str;
             default = [ ];
             example = [ "/var/run/docker.sock:/var/run/docker.sock" ];
-            description = ''
+            description = lib.mdDoc ''
               Bind-mount a volume and create it
               if it doesn't exist prior to mounting.
             '';
@@ -409,14 +338,14 @@ in
           dockerDisableCache = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Disable all container caching.
             '';
           };
           dockerPrivileged = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Give extended privileges to container.
             '';
           };
@@ -424,7 +353,7 @@ in
             type = types.listOf types.str;
             default = [ ];
             example = [ "other-host:127.0.0.1" ];
-            description = ''
+            description = lib.mdDoc ''
               Add a custom host-to-IP mapping.
             '';
           };
@@ -432,7 +361,7 @@ in
             type = types.listOf types.str;
             default = [ ];
             example = [ "ruby:*" "python:*" "php:*" "my.registry.tld:5000/*:*" ];
-            description = ''
+            description = lib.mdDoc ''
               Whitelist allowed images.
             '';
           };
@@ -440,21 +369,21 @@ in
             type = types.listOf types.str;
             default = [ ];
             example = [ "postgres:9" "redis:*" "mysql:*" ];
-            description = ''
+            description = lib.mdDoc ''
               Whitelist allowed services.
             '';
           };
           preCloneScript = mkOption {
             type = types.nullOr types.path;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Runner-specific command script executed before code is pulled.
             '';
           };
           preBuildScript = mkOption {
             type = types.nullOr types.path;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Runner-specific command script executed after code is pulled,
               just before build executes.
             '';
@@ -462,7 +391,7 @@ in
           postBuildScript = mkOption {
             type = types.nullOr types.path;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Runner-specific command script executed after code is pulled
               and just after build executes.
             '';
@@ -470,22 +399,22 @@ in
           tagList = mkOption {
             type = types.listOf types.str;
             default = [ ];
-            description = ''
+            description = lib.mdDoc ''
               Tag list.
             '';
           };
           runUntagged = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Register to run untagged builds; defaults to
-              <literal>true</literal> when <option>tagList</option> is empty.
+              `true` when {option}`tagList` is empty.
             '';
           };
           limit = mkOption {
             type = types.int;
             default = 0;
-            description = ''
+            description = lib.mdDoc ''
               Limit how many jobs can be handled concurrently by this service.
               0 (default) simply means don't limit.
             '';
@@ -493,14 +422,14 @@ in
           requestConcurrency = mkOption {
             type = types.int;
             default = 0;
-            description = ''
+            description = lib.mdDoc ''
               Limit number of concurrent requests for new jobs from GitLab.
             '';
           };
           maximumTimeout = mkOption {
             type = types.int;
             default = 0;
-            description = ''
+            description = lib.mdDoc ''
               What is the maximum timeout (in seconds) that will be set for
               job when using this Runner. 0 (default) simply means don't limit.
             '';
@@ -508,7 +437,7 @@ in
           protected = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               When set to true Runner will only run on pipelines
               triggered on protected branches.
             '';
@@ -516,20 +445,57 @@ in
           debugTraceDisabled = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               When set to true Runner will disable the possibility of
-              using the <literal>CI_DEBUG_TRACE</literal> feature.
+              using the `CI_DEBUG_TRACE` feature.
             '';
           };
         };
       });
     };
+    clear-docker-cache = {
+      enable = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to periodically prune gitlab runner's Docker resources. If
+          enabled, a systemd timer will run {command}`clear-docker-cache` as
+          specified by the `dates` option.
+        '';
+      };
+
+      flags = mkOption {
+        type = types.listOf types.str;
+        default = [ ];
+        example = [ "prune" ];
+        description = lib.mdDoc ''
+          Any additional flags passed to {command}`clear-docker-cache`.
+        '';
+      };
+
+      dates = mkOption {
+        default = "weekly";
+        type = types.str;
+        description = lib.mdDoc ''
+          Specification (in the format described by
+          {manpage}`systemd.time(7)`) of the time at
+          which the prune will occur.
+        '';
+      };
+
+      package = mkOption {
+        default = config.virtualisation.docker.package;
+        defaultText = literalExpression "config.virtualisation.docker.package";
+        example = literalExpression "pkgs.docker";
+        description = lib.mdDoc "Docker package to use for clearing up docker cache.";
+      };
+    };
   };
   config = mkIf cfg.enable {
     warnings = (mapAttrsToList
       (n: v: "services.gitlab-runner.services.${n}.`registrationConfigFile` points to a file in Nix Store. You should use quoted absolute path to prevent this.")
-      (filterAttrs (n: v: isStorePath v.registrationConfigFile) cfg.services))
-    ++ optional (cfg.configFile != null) "services.gitlab-runner.`configFile` is deprecated, please use services.gitlab-runner.`services`.";
+      (filterAttrs (n: v: isStorePath v.registrationConfigFile) cfg.services));
+
     environment.systemPackages = [ cfg.package ];
     systemd.services.gitlab-runner = {
       description = "Gitlab Runner";
@@ -568,6 +534,22 @@ in
         KillMode = "process";
       };
     };
+    # Enable periodic clear-docker-cache script
+    systemd.services.gitlab-runner-clear-docker-cache = {
+      description = "Prune gitlab-runner docker resources";
+      restartIfChanged = false;
+      unitConfig.X-StopOnRemoval = false;
+
+      serviceConfig.Type = "oneshot";
+
+      path = [ cfg.clear-docker-cache.package pkgs.gawk ];
+
+      script = ''
+        ${pkgs.gitlab-runner}/bin/clear-docker-cache ${toString cfg.clear-docker-cache.flags}
+      '';
+
+      startAt = optional cfg.clear-docker-cache.enable cfg.clear-docker-cache.dates;
+    };
     # Enable docker if `docker` executor is used in any service
     virtualisation.docker.enable = mkIf (
       any (s: s.executor == "docker") (attrValues cfg.services)
@@ -577,5 +559,14 @@ in
     (mkRenamedOptionModule [ "services" "gitlab-runner" "packages" ] [ "services" "gitlab-runner" "extraPackages" ] )
     (mkRemovedOptionModule [ "services" "gitlab-runner" "configOptions" ] "Use services.gitlab-runner.services option instead" )
     (mkRemovedOptionModule [ "services" "gitlab-runner" "workDir" ] "You should move contents of workDir (if any) to /var/lib/gitlab-runner" )
+
+    (mkRenamedOptionModule [ "services" "gitlab-runner" "checkInterval" ] [ "services" "gitlab-runner" "settings" "check_interval" ] )
+    (mkRenamedOptionModule [ "services" "gitlab-runner" "concurrent" ] [ "services" "gitlab-runner" "settings" "concurrent" ] )
+    (mkRenamedOptionModule [ "services" "gitlab-runner" "sentryDSN" ] [ "services" "gitlab-runner" "settings" "sentry_dsn" ] )
+    (mkRenamedOptionModule [ "services" "gitlab-runner" "prometheusListenAddress" ] [ "services" "gitlab-runner" "settings" "listen_address" ] )
+
+    (mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "listenAddress" ] [ "services" "gitlab-runner" "settings" "session_server" "listen_address" ] )
+    (mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "advertiseAddress" ] [ "services" "gitlab-runner" "settings" "session_server" "advertise_address" ] )
+    (mkRenamedOptionModule [ "services" "gitlab-runner" "sessionServer" "sessionTimeout" ] [ "services" "gitlab-runner" "settings" "session_server" "session_timeout" ] )
   ];
 }
diff --git a/nixos/modules/services/continuous-integration/gocd-agent/default.nix b/nixos/modules/services/continuous-integration/gocd-agent/default.nix
index c63998c6736..c0d752443a1 100644
--- a/nixos/modules/services/continuous-integration/gocd-agent/default.nix
+++ b/nixos/modules/services/continuous-integration/gocd-agent/default.nix
@@ -8,12 +8,12 @@ let
 in {
   options = {
     services.gocd-agent = {
-      enable = mkEnableOption "gocd-agent";
+      enable = mkEnableOption (lib.mdDoc "gocd-agent");
 
       user = mkOption {
         default = "gocd-agent";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User the Go.CD agent should execute under.
         '';
       };
@@ -21,7 +21,7 @@ in {
       group = mkOption {
         default = "gocd-agent";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           If the default user "gocd-agent" is configured then this is the primary
           group of that user.
         '';
@@ -31,7 +31,7 @@ in {
         type = types.listOf types.str;
         default = [ ];
         example = [ "wheel" "docker" ];
-        description = ''
+        description = lib.mdDoc ''
           List of extra groups that the "gocd-agent" user should be a part of.
         '';
       };
@@ -40,7 +40,7 @@ in {
         default = [ pkgs.stdenv pkgs.jre pkgs.git config.programs.ssh.package pkgs.nix ];
         defaultText = literalExpression "[ pkgs.stdenv pkgs.jre pkgs.git config.programs.ssh.package pkgs.nix ]";
         type = types.listOf types.package;
-        description = ''
+        description = lib.mdDoc ''
           Packages to add to PATH for the Go.CD agent process.
         '';
       };
@@ -53,7 +53,7 @@ in {
           agent.auto.register.environments=QA,Performance
           agent.auto.register.hostname=Agent01
         '';
-        description = ''
+        description = lib.mdDoc ''
           Agent registration configuration.
         '';
       };
@@ -61,7 +61,7 @@ in {
       goServer = mkOption {
         default = "https://127.0.0.1:8154/go";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           URL of the GoCD Server to attach the Go.CD Agent to.
         '';
       };
@@ -69,7 +69,7 @@ in {
       workDir = mkOption {
         default = "/var/lib/go-agent";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the working directory in which the Go.CD agent java archive resides.
         '';
       };
@@ -77,7 +77,7 @@ in {
       initialJavaHeapSize = mkOption {
         default = "128m";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the initial java heap memory size for the Go.CD agent java process.
         '';
       };
@@ -85,7 +85,7 @@ in {
       maxJavaHeapMemory = mkOption {
         default = "256m";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the java maximum heap memory size for the Go.CD agent java process.
         '';
       };
@@ -108,7 +108,7 @@ in {
             "-Djava.security.egd=file:/dev/./urandom"
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Specifies startup command line arguments to pass to Go.CD agent
           java process.
         '';
@@ -127,7 +127,7 @@ in {
           "-XX:+PrintGCDetails"
           "-XX:+PrintGC"
         ];
-        description = ''
+        description = lib.mdDoc ''
           Specifies additional command line arguments to pass to Go.CD agent
           java process.  Example contains debug and gcLog arguments.
         '';
@@ -136,10 +136,10 @@ in {
       environment = mkOption {
         default = { };
         type = with types; attrsOf str;
-        description = ''
+        description = lib.mdDoc ''
           Additional environment variables to be passed to the Go.CD agent process.
           As a base environment, Go.CD agent receives NIX_PATH from
-          <option>environment.sessionVariables</option>, NIX_REMOTE is set to
+          {option}`environment.sessionVariables`, NIX_REMOTE is set to
           "daemon".
         '';
       };
diff --git a/nixos/modules/services/continuous-integration/gocd-server/default.nix b/nixos/modules/services/continuous-integration/gocd-server/default.nix
index 3540656f934..bf7fd529bfc 100644
--- a/nixos/modules/services/continuous-integration/gocd-server/default.nix
+++ b/nixos/modules/services/continuous-integration/gocd-server/default.nix
@@ -8,12 +8,12 @@ let
 in {
   options = {
     services.gocd-server = {
-      enable = mkEnableOption "gocd-server";
+      enable = mkEnableOption (lib.mdDoc "gocd-server");
 
       user = mkOption {
         default = "gocd-server";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User the Go.CD server should execute under.
         '';
       };
@@ -21,7 +21,7 @@ in {
       group = mkOption {
         default = "gocd-server";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           If the default user "gocd-server" is configured then this is the primary group of that user.
         '';
       };
@@ -30,7 +30,7 @@ in {
         default = [ ];
         type = types.listOf types.str;
         example = [ "wheel" "docker" ];
-        description = ''
+        description = lib.mdDoc ''
           List of extra groups that the "gocd-server" user should be a part of.
         '';
       };
@@ -39,15 +39,15 @@ in {
         default = "0.0.0.0";
         example = "localhost";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the bind address on which the Go.CD server HTTP interface listens.
         '';
       };
 
       port = mkOption {
         default = 8153;
-        type = types.int;
-        description = ''
+        type = types.port;
+        description = lib.mdDoc ''
           Specifies port number on which the Go.CD server HTTP interface listens.
         '';
       };
@@ -55,7 +55,7 @@ in {
       sslPort = mkOption {
         default = 8154;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Specifies port number on which the Go.CD server HTTPS interface listens.
         '';
       };
@@ -63,7 +63,7 @@ in {
       workDir = mkOption {
         default = "/var/lib/go-server";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the working directory in which the Go.CD server java archive resides.
         '';
       };
@@ -72,7 +72,7 @@ in {
         default = [ pkgs.stdenv pkgs.jre pkgs.git config.programs.ssh.package pkgs.nix ];
         defaultText = literalExpression "[ pkgs.stdenv pkgs.jre pkgs.git config.programs.ssh.package pkgs.nix ]";
         type = types.listOf types.package;
-        description = ''
+        description = lib.mdDoc ''
           Packages to add to PATH for the Go.CD server's process.
         '';
       };
@@ -80,7 +80,7 @@ in {
       initialJavaHeapSize = mkOption {
         default = "512m";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the initial java heap memory size for the Go.CD server's java process.
         '';
       };
@@ -88,7 +88,7 @@ in {
       maxJavaHeapMemory = mkOption {
         default = "1024m";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the java maximum heap memory size for the Go.CD server's java process.
         '';
       };
@@ -106,6 +106,8 @@ in {
           "-Dcruise.config.file=${cfg.workDir}/conf/cruise-config.xml"
           "-Dcruise.server.port=${toString cfg.port}"
           "-Dcruise.server.ssl.port=${toString cfg.sslPort}"
+          "--add-opens=java.base/java.lang=ALL-UNNAMED"
+          "--add-opens=java.base/java.util=ALL-UNNAMED"
         ];
         defaultText = literalExpression ''
           [
@@ -119,10 +121,12 @@ in {
             "-Dcruise.config.file=''${config.${opt.workDir}}/conf/cruise-config.xml"
             "-Dcruise.server.port=''${toString config.${opt.port}}"
             "-Dcruise.server.ssl.port=''${toString config.${opt.sslPort}}"
+            "--add-opens=java.base/java.lang=ALL-UNNAMED"
+            "--add-opens=java.base/java.util=ALL-UNNAMED"
           ]
         '';
 
-        description = ''
+        description = lib.mdDoc ''
           Specifies startup command line arguments to pass to Go.CD server
           java process.
         '';
@@ -141,7 +145,7 @@ in {
           "-XX:+PrintGCDetails"
           "-XX:+PrintGC"
         ];
-        description = ''
+        description = lib.mdDoc ''
           Specifies additional command line arguments to pass to Go.CD server's
           java process.  Example contains debug and gcLog arguments.
         '';
@@ -150,10 +154,10 @@ in {
       environment = mkOption {
         default = { };
         type = with types; attrsOf str;
-        description = ''
+        description = lib.mdDoc ''
           Additional environment variables to be passed to the gocd-server process.
           As a base environment, gocd-server receives NIX_PATH from
-          <option>environment.sessionVariables</option>, NIX_REMOTE is set to
+          {option}`environment.sessionVariables`, NIX_REMOTE is set to
           "daemon".
         '';
       };
@@ -199,7 +203,7 @@ in {
         ${pkgs.git}/bin/git config --global --add http.sslCAinfo /etc/ssl/certs/ca-certificates.crt
         ${pkgs.jre}/bin/java -server ${concatStringsSep " " cfg.startupOptions} \
                                ${concatStringsSep " " cfg.extraOptions}  \
-                              -jar ${pkgs.gocd-server}/go-server/go.jar
+                              -jar ${pkgs.gocd-server}/go-server/lib/go.jar
       '';
 
       serviceConfig = {
diff --git a/nixos/modules/services/continuous-integration/hail.nix b/nixos/modules/services/continuous-integration/hail.nix
index 4070a3425c4..76d7356e247 100644
--- a/nixos/modules/services/continuous-integration/hail.nix
+++ b/nixos/modules/services/continuous-integration/hail.nix
@@ -13,7 +13,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enables the Hail Auto Update Service. Hail can automatically deploy artifacts
         built by a Hydra Continous Integration server. A common use case is to provide
         continous deployment for single services or a full NixOS configuration.'';
@@ -21,22 +21,22 @@ in {
     profile = mkOption {
       type = types.str;
       default = "hail-profile";
-      description = "The name of the Nix profile used by Hail.";
+      description = lib.mdDoc "The name of the Nix profile used by Hail.";
     };
     hydraJobUri = mkOption {
       type = types.str;
-      description = "The URI of the Hydra Job.";
+      description = lib.mdDoc "The URI of the Hydra Job.";
     };
     netrc = mkOption {
       type = types.nullOr types.path;
-      description = "The netrc file to use when fetching data from Hydra.";
+      description = lib.mdDoc "The netrc file to use when fetching data from Hydra.";
       default = null;
     };
     package = mkOption {
       type = types.package;
       default = pkgs.haskellPackages.hail;
       defaultText = literalExpression "pkgs.haskellPackages.hail";
-      description = "Hail package to use.";
+      description = lib.mdDoc "Hail package to use.";
     };
   };
 
diff --git a/nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix b/nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix
index 80c88714bfc..663f3df775c 100644
--- a/nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix
+++ b/nixos/modules/services/continuous-integration/hercules-ci-agent/common.nix
@@ -10,7 +10,7 @@
 let
   inherit (lib)
     filterAttrs
-    literalDocBook
+    literalMD
     literalExpression
     mkIf
     mkOption
@@ -28,7 +28,7 @@ let
     freeformType = format.type;
     options = {
       apiBaseUrl = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           API base URL that the agent will connect to.
 
           When using Hercules CI Enterprise, set this to the URL where your
@@ -40,19 +40,19 @@ let
       baseDirectory = mkOption {
         type = types.path;
         default = "/var/lib/hercules-ci-agent";
-        description = ''
+        description = lib.mdDoc ''
           State directory (secrets, work directory, etc) for agent
         '';
       };
       concurrentTasks = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Number of tasks to perform simultaneously.
 
           A task is a single derivation build, an evaluation or an effect run.
-          At minimum, you need 2 concurrent tasks for <literal>x86_64-linux</literal>
+          At minimum, you need 2 concurrent tasks for `x86_64-linux`
           in your cluster, to allow for import from derivation.
 
-          <literal>concurrentTasks</literal> can be around the CPU core count or lower if memory is
+          `concurrentTasks` can be around the CPU core count or lower if memory is
           the bottleneck.
 
           The optimal value depends on the resource consumption characteristics of your workload,
@@ -66,7 +66,7 @@ let
         default = "auto";
       };
       labels = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           A key-value map of user data.
 
           This data will be available to organization members in the dashboard and API.
@@ -85,7 +85,7 @@ let
         '';
       };
       workDirectory = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The directory in which temporary subdirectories are created for task state. This includes sources for Nix evaluation.
         '';
         type = types.path;
@@ -93,25 +93,25 @@ let
         defaultText = literalExpression ''baseDirectory + "/work"'';
       };
       staticSecretsDirectory = mkOption {
-        description = ''
-          This is the default directory to look for statically configured secrets like <literal>cluster-join-token.key</literal>.
+        description = lib.mdDoc ''
+          This is the default directory to look for statically configured secrets like `cluster-join-token.key`.
 
-          See also <literal>clusterJoinTokenPath</literal> and <literal>binaryCachesPath</literal> for fine-grained configuration.
+          See also `clusterJoinTokenPath` and `binaryCachesPath` for fine-grained configuration.
         '';
         type = types.path;
         default = config.baseDirectory + "/secrets";
         defaultText = literalExpression ''baseDirectory + "/secrets"'';
       };
       clusterJoinTokenPath = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Location of the cluster-join-token.key file.
 
           You can retrieve the contents of the file when creating a new agent via
-          <link xlink:href="https://hercules-ci.com/dashboard">https://hercules-ci.com/dashboard</link>.
+          <https://hercules-ci.com/dashboard>.
 
           As this value is confidential, it should not be in the store, but
           installed using other means, such as agenix, NixOps
-          <literal>deployment.keys</literal>, or manual installation.
+          `deployment.keys`, or manual installation.
 
           The contents of the file are used for authentication between the agent and the API.
         '';
@@ -120,29 +120,28 @@ let
         defaultText = literalExpression ''staticSecretsDirectory + "/cluster-join-token.key"'';
       };
       binaryCachesPath = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Path to a JSON file containing binary cache secret keys.
 
           As these values are confidential, they should not be in the store, but
           copied over using other means, such as agenix, NixOps
-          <literal>deployment.keys</literal>, or manual installation.
+          `deployment.keys`, or manual installation.
 
-          The format is described on <link xlink:href="https://docs.hercules-ci.com/hercules-ci-agent/binary-caches-json/">https://docs.hercules-ci.com/hercules-ci-agent/binary-caches-json/</link>.
+          The format is described on <https://docs.hercules-ci.com/hercules-ci-agent/binary-caches-json/>.
         '';
         type = types.path;
         default = config.staticSecretsDirectory + "/binary-caches.json";
         defaultText = literalExpression ''staticSecretsDirectory + "/binary-caches.json"'';
       };
       secretsJsonPath = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Path to a JSON file containing secrets for effects.
 
           As these values are confidential, they should not be in the store, but
           copied over using other means, such as agenix, NixOps
-          <literal>deployment.keys</literal>, or manual installation.
-
-          The format is described on <link xlink:href="https://docs.hercules-ci.com/hercules-ci-agent/secrets-json/">https://docs.hercules-ci.com/hercules-ci-agent/secrets-json/</link>.
+          `deployment.keys`, or manual installation.
 
+          The format is described on <https://docs.hercules-ci.com/hercules-ci-agent/secrets-json/>.
         '';
         type = types.path;
         default = config.staticSecretsDirectory + "/secrets.json";
@@ -190,26 +189,26 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable to run Hercules CI Agent as a system service.
 
-        <link xlink:href="https://hercules-ci.com">Hercules CI</link> is a
+        [Hercules CI](https://hercules-ci.com) is a
         continuous integation service that is centered around Nix.
 
-        Support is available at <link xlink:href="mailto:help@hercules-ci.com">help@hercules-ci.com</link>.
+        Support is available at [help@hercules-ci.com](mailto:help@hercules-ci.com).
       '';
     };
     checkNix = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to make sure that the system's Nix (nix-daemon) is compatible.
 
         If you set this to false, please keep up with the change log.
       '';
     };
     package = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Package containing the bin/hercules-ci-agent executable.
       '';
       type = types.package;
@@ -217,12 +216,12 @@ in
       defaultText = literalExpression "pkgs.hercules-ci-agent";
     };
     settings = mkOption {
-      description = ''
-        These settings are written to the <literal>agent.toml</literal> file.
+      description = lib.mdDoc ''
+        These settings are written to the `agent.toml` file.
 
         Not all settings are listed as options, can be set nonetheless.
 
-        For the exhaustive list of settings, see <link xlink:href="https://docs.hercules-ci.com/hercules-ci/reference/agent-config/"/>.
+        For the exhaustive list of settings, see <https://docs.hercules-ci.com/hercules-ci/reference/agent-config/>.
       '';
       type = types.submoduleWith { modules = [ settingsModule ]; };
     };
@@ -236,8 +235,8 @@ in
     tomlFile = mkOption {
       type = types.path;
       internal = true;
-      defaultText = literalDocBook "generated <literal>hercules-ci-agent.toml</literal>";
-      description = ''
+      defaultText = literalMD "generated `hercules-ci-agent.toml`";
+      description = lib.mdDoc ''
         The fully assembled config file.
       '';
     };
diff --git a/nixos/modules/services/continuous-integration/hydra/default.nix b/nixos/modules/services/continuous-integration/hydra/default.nix
index cc5de97d6d1..564bcd37dec 100644
--- a/nixos/modules/services/continuous-integration/hydra/default.nix
+++ b/nixos/modules/services/continuous-integration/hydra/default.nix
@@ -42,7 +42,7 @@ let
     makeWrapperArgs = concatStringsSep " " (mapAttrsToList (key: value: "--set \"${key}\" \"${value}\"") hydraEnv);
   in pkgs.buildEnv rec {
     name = "hydra-env";
-    buildInputs = [ pkgs.makeWrapper ];
+    nativeBuildInputs = [ pkgs.makeWrapper ];
     paths = [ cfg.package ];
 
     postBuild = ''
@@ -78,7 +78,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run Hydra services.
         '';
       };
@@ -87,7 +87,7 @@ in
         type = types.str;
         default = localDB;
         example = "dbi:Pg:dbname=hydra;host=postgres.example.org;user=foo;";
-        description = ''
+        description = lib.mdDoc ''
           The DBI string for Hydra database connection.
 
           NOTE: Attempts to set `application_name` will be overridden by
@@ -99,14 +99,14 @@ in
 
       package = mkOption {
         type = types.package;
-        default = pkgs.hydra-unstable;
-        defaultText = literalExpression "pkgs.hydra-unstable";
-        description = "The Hydra package.";
+        default = pkgs.hydra_unstable;
+        defaultText = literalExpression "pkgs.hydra_unstable";
+        description = lib.mdDoc "The Hydra package.";
       };
 
       hydraURL = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The base URL for the Hydra webserver instance. Used for links in emails.
         '';
       };
@@ -115,16 +115,16 @@ in
         type = types.str;
         default = "*";
         example = "localhost";
-        description = ''
-          The hostname or address to listen on or <literal>*</literal> to listen
+        description = lib.mdDoc ''
+          The hostname or address to listen on or `*` to listen
           on all interfaces.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 3000;
-        description = ''
+        description = lib.mdDoc ''
           TCP port the web server should listen to.
         '';
       };
@@ -132,7 +132,7 @@ in
       minimumDiskFree = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Threshold of minimum disk space (GiB) to determine if the queue runner should run or not.
         '';
       };
@@ -140,14 +140,14 @@ in
       minimumDiskFreeEvaluator = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Threshold of minimum disk space (GiB) to determine if the evaluator should run or not.
         '';
       };
 
       notificationSender = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Sender email address used for email notifications.
         '';
       };
@@ -156,7 +156,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           Hostname of the SMTP server to use to send email.
         '';
       };
@@ -164,7 +164,7 @@ in
       tracker = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Piece of HTML that is included on all pages.
         '';
       };
@@ -172,7 +172,7 @@ in
       logo = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to a file containing the logo of your Hydra instance.
         '';
       };
@@ -180,24 +180,24 @@ in
       debugServer = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to run the server in debug mode.";
+        description = lib.mdDoc "Whether to run the server in debug mode.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
-        description = "Extra lines for the Hydra configuration.";
+        description = lib.mdDoc "Extra lines for the Hydra configuration.";
       };
 
       extraEnv = mkOption {
         type = types.attrsOf types.str;
         default = {};
-        description = "Extra environment variables for Hydra.";
+        description = lib.mdDoc "Extra environment variables for Hydra.";
       };
 
       gcRootsDir = mkOption {
         type = types.path;
         default = "/nix/var/nix/gcroots/hydra";
-        description = "Directory that holds Hydra garbage collector roots.";
+        description = lib.mdDoc "Directory that holds Hydra garbage collector roots.";
       };
 
       buildMachinesFiles = mkOption {
@@ -205,13 +205,13 @@ in
         default = optional (config.nix.buildMachines != []) "/etc/nix/machines";
         defaultText = literalExpression ''optional (config.nix.buildMachines != []) "/etc/nix/machines"'';
         example = [ "/etc/nix/machines" "/var/lib/hydra/provisioner/machines" ];
-        description = "List of files containing build machines.";
+        description = lib.mdDoc "List of files containing build machines.";
       };
 
       useSubstitutes = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use binary caches for downloading store paths. Note that
           binary substitutions trigger (a potentially large number of) additional
           HTTP requests that slow down the queue monitor thread significantly.
@@ -298,27 +298,32 @@ in
         environment = env // {
           HYDRA_DBI = "${env.HYDRA_DBI};application_name=hydra-init";
         };
+        path = [ pkgs.util-linux ];
         preStart = ''
           mkdir -p ${baseDir}
-          chown hydra.hydra ${baseDir}
+          chown hydra:hydra ${baseDir}
           chmod 0750 ${baseDir}
 
           ln -sf ${hydraConf} ${baseDir}/hydra.conf
 
           mkdir -m 0700 -p ${baseDir}/www
-          chown hydra-www.hydra ${baseDir}/www
+          chown hydra-www:hydra ${baseDir}/www
 
           mkdir -m 0700 -p ${baseDir}/queue-runner
           mkdir -m 0750 -p ${baseDir}/build-logs
-          chown hydra-queue-runner.hydra ${baseDir}/queue-runner ${baseDir}/build-logs
+          mkdir -m 0750 -p ${baseDir}/runcommand-logs
+          chown hydra-queue-runner.hydra \
+            ${baseDir}/queue-runner \
+            ${baseDir}/build-logs \
+            ${baseDir}/runcommand-logs
 
           ${optionalString haveLocalDB ''
             if ! [ -e ${baseDir}/.db-created ]; then
-              ${pkgs.sudo}/bin/sudo -u ${config.services.postgresql.superUser} ${config.services.postgresql.package}/bin/createuser hydra
-              ${pkgs.sudo}/bin/sudo -u ${config.services.postgresql.superUser} ${config.services.postgresql.package}/bin/createdb -O hydra hydra
+              runuser -u ${config.services.postgresql.superUser} ${config.services.postgresql.package}/bin/createuser hydra
+              runuser -u ${config.services.postgresql.superUser} ${config.services.postgresql.package}/bin/createdb -- -O hydra hydra
               touch ${baseDir}/.db-created
             fi
-            echo "create extension if not exists pg_trgm" | ${pkgs.sudo}/bin/sudo -u ${config.services.postgresql.superUser} -- ${config.services.postgresql.package}/bin/psql hydra
+            echo "create extension if not exists pg_trgm" | runuser -u ${config.services.postgresql.superUser} -- ${config.services.postgresql.package}/bin/psql hydra
           ''}
 
           if [ ! -e ${cfg.gcRootsDir} ]; then
@@ -338,7 +343,7 @@ in
             rmdir /nix/var/nix/gcroots/per-user/hydra-www/hydra-roots
           fi
 
-          chown hydra.hydra ${cfg.gcRootsDir}
+          chown hydra:hydra ${cfg.gcRootsDir}
           chmod 2775 ${cfg.gcRootsDir}
         '';
         serviceConfig.ExecStart = "${hydra-package}/bin/hydra-init";
diff --git a/nixos/modules/services/continuous-integration/jenkins/default.nix b/nixos/modules/services/continuous-integration/jenkins/default.nix
index d37dcb5519d..a9a587b41e8 100644
--- a/nixos/modules/services/continuous-integration/jenkins/default.nix
+++ b/nixos/modules/services/continuous-integration/jenkins/default.nix
@@ -9,7 +9,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the jenkins continuous integration server.
         '';
       };
@@ -17,7 +17,7 @@ in {
       user = mkOption {
         default = "jenkins";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User the jenkins server should execute under.
         '';
       };
@@ -25,7 +25,7 @@ in {
       group = mkOption {
         default = "jenkins";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           If the default user "jenkins" is configured then this is the primary
           group of that user.
         '';
@@ -35,7 +35,7 @@ in {
         type = types.listOf types.str;
         default = [ ];
         example = [ "wheel" "dialout" ];
-        description = ''
+        description = lib.mdDoc ''
           List of extra groups that the "jenkins" user should be a part of.
         '';
       };
@@ -43,7 +43,7 @@ in {
       home = mkOption {
         default = "/var/lib/jenkins";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The path to use as JENKINS_HOME. If the default user "jenkins" is configured then
           this is the home of the "jenkins" user.
         '';
@@ -53,7 +53,7 @@ in {
         default = "0.0.0.0";
         example = "localhost";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the bind address on which the jenkins HTTP interface listens.
           The default is the wildcard address.
         '';
@@ -62,7 +62,7 @@ in {
       port = mkOption {
         default = 8080;
         type = types.port;
-        description = ''
+        description = lib.mdDoc ''
           Specifies port number on which the jenkins HTTP interface listens.
           The default is 8080.
         '';
@@ -72,7 +72,7 @@ in {
         default = "";
         example = "/jenkins";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specifies a urlPrefix to use with jenkins.
           If the example /jenkins is given, the jenkins server will be
           accessible using localhost:8080/jenkins.
@@ -83,14 +83,14 @@ in {
         default = pkgs.jenkins;
         defaultText = literalExpression "pkgs.jenkins";
         type = types.package;
-        description = "Jenkins package to use.";
+        description = lib.mdDoc "Jenkins package to use.";
       };
 
       packages = mkOption {
-        default = [ pkgs.stdenv pkgs.git pkgs.jdk11 config.programs.ssh.package pkgs.nix ];
-        defaultText = literalExpression "[ pkgs.stdenv pkgs.git pkgs.jdk11 config.programs.ssh.package pkgs.nix ]";
+        default = [ pkgs.stdenv pkgs.git pkgs.jdk17 config.programs.ssh.package pkgs.nix ];
+        defaultText = literalExpression "[ pkgs.stdenv pkgs.git pkgs.jdk17 config.programs.ssh.package pkgs.nix ]";
         type = types.listOf types.package;
-        description = ''
+        description = lib.mdDoc ''
           Packages to add to PATH for the jenkins process.
         '';
       };
@@ -98,12 +98,12 @@ in {
       environment = mkOption {
         default = { };
         type = with types; attrsOf str;
-        description = ''
+        description = lib.mdDoc ''
           Additional environment variables to be passed to the jenkins process.
           As a base environment, jenkins receives NIX_PATH from
-          <option>environment.sessionVariables</option>, NIX_REMOTE is set to
+          {option}`environment.sessionVariables`, NIX_REMOTE is set to
           "daemon" and JENKINS_HOME is set to the value of
-          <option>services.jenkins.home</option>.
+          {option}`services.jenkins.home`.
           This option has precedence and can be used to override those
           mentioned variables.
         '';
@@ -112,13 +112,13 @@ in {
       plugins = mkOption {
         default = null;
         type = types.nullOr (types.attrsOf types.package);
-        description = ''
+        description = lib.mdDoc ''
           A set of plugins to activate. Note that this will completely
           remove and replace any previously installed plugins. If you
           have manually-installed plugins that you want to keep while
           using this module, set this option to
-          <literal>null</literal>. You can generate this set with a
-          tool such as <literal>jenkinsPlugins2nix</literal>.
+          `null`. You can generate this set with a
+          tool such as `jenkinsPlugins2nix`.
         '';
         example = literalExpression ''
           import path/to/jenkinsPlugins2nix-generated-plugins.nix { inherit (pkgs) fetchurl stdenv; }
@@ -129,7 +129,7 @@ in {
         type = types.listOf types.str;
         default = [ ];
         example = [ "--debug=9" ];
-        description = ''
+        description = lib.mdDoc ''
           Additional command line arguments to pass to Jenkins.
         '';
       };
@@ -138,7 +138,7 @@ in {
         type = types.listOf types.str;
         default = [ ];
         example = [ "-Xmx80m" ];
-        description = ''
+        description = lib.mdDoc ''
           Additional command line arguments to pass to the Java run time (as opposed to Jenkins).
         '';
       };
@@ -146,12 +146,12 @@ in {
       withCLI = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to make the CLI available.
 
           More info about the CLI available at
-          <link xlink:href="https://www.jenkins.io/doc/book/managing/cli">
-          https://www.jenkins.io/doc/book/managing/cli</link> .
+          [
+          https://www.jenkins.io/doc/book/managing/cli](https://www.jenkins.io/doc/book/managing/cli) .
         '';
       };
     };
@@ -228,7 +228,7 @@ in {
 
       # For reference: https://wiki.jenkins.io/display/JENKINS/JenkinsLinuxStartupScript
       script = ''
-        ${pkgs.jdk11}/bin/java ${concatStringsSep " " cfg.extraJavaOptions} -jar ${cfg.package}/webapps/jenkins.war --httpListenAddress=${cfg.listenAddress} \
+        ${pkgs.jdk17}/bin/java ${concatStringsSep " " cfg.extraJavaOptions} -jar ${cfg.package}/webapps/jenkins.war --httpListenAddress=${cfg.listenAddress} \
                                                   --httpPort=${toString cfg.port} \
                                                   --prefix=${cfg.prefix} \
                                                   -Djava.awt.headless=true \
diff --git a/nixos/modules/services/continuous-integration/jenkins/job-builder.nix b/nixos/modules/services/continuous-integration/jenkins/job-builder.nix
index 3ca1542c18f..3a1c6c1a371 100644
--- a/nixos/modules/services/continuous-integration/jenkins/job-builder.nix
+++ b/nixos/modules/services/continuous-integration/jenkins/job-builder.nix
@@ -12,7 +12,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether or not to enable the Jenkins Job Builder (JJB) service. It
           allows defining jobs for Jenkins in a declarative manner.
 
@@ -24,15 +24,15 @@ in {
           deleted.
 
           Please see the Jenkins Job Builder documentation for more info:
-          <link xlink:href="http://docs.openstack.org/infra/jenkins-job-builder/">
-          http://docs.openstack.org/infra/jenkins-job-builder/</link>
+          [
+          http://docs.openstack.org/infra/jenkins-job-builder/](http://docs.openstack.org/infra/jenkins-job-builder/)
         '';
       };
 
       accessUser = mkOption {
-        default = "";
+        default = "admin";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User id in Jenkins used to reload config.
         '';
       };
@@ -40,19 +40,20 @@ in {
       accessToken = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User token in Jenkins used to reload config.
           WARNING: This token will be world readable in the Nix store. To keep
-          it secret, use the <option>accessTokenFile</option> option instead.
+          it secret, use the {option}`accessTokenFile` option instead.
         '';
       };
 
       accessTokenFile = mkOption {
-        default = "";
+        default = "${config.services.jenkins.home}/secrets/initialAdminPassword";
+        defaultText = literalExpression ''"''${config.services.jenkins.home}/secrets/initialAdminPassword"'';
         type = types.str;
         example = "/run/keys/jenkins-job-builder-access-token";
-        description = ''
-          File containing the API token for the <option>accessUser</option>
+        description = lib.mdDoc ''
+          File containing the API token for the {option}`accessUser`
           user.
         '';
       };
@@ -66,7 +67,7 @@ in {
               builders:
                 - shell: echo 'Hello world!'
         '';
-        description = ''
+        description = lib.mdDoc ''
           Job descriptions for Jenkins Job Builder in YAML format.
         '';
       };
@@ -86,7 +87,7 @@ in {
             '''
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Job descriptions for Jenkins Job Builder in JSON format.
         '';
       };
@@ -104,7 +105,7 @@ in {
             }
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Job descriptions for Jenkins Job Builder in Nix format.
 
           This is a trivial wrapper around jsonJobs, using builtins.toJSON
@@ -156,12 +157,22 @@ in {
           reloadScript = ''
             echo "Asking Jenkins to reload config"
             curl_opts="--silent --fail --show-error"
-            access_token=${if cfg.accessTokenFile != ""
-                           then "$(cat '${cfg.accessTokenFile}')"
-                           else cfg.accessToken}
-            jenkins_url="http://${cfg.accessUser}:$access_token@${jenkinsCfg.listenAddress}:${toString jenkinsCfg.port}${jenkinsCfg.prefix}"
-            crumb=$(curl $curl_opts "$jenkins_url"'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')
-            curl $curl_opts -X POST -H "$crumb" "$jenkins_url"/reload
+            access_token_file=${if cfg.accessTokenFile != ""
+                           then cfg.accessTokenFile
+                           else "$RUNTIME_DIRECTORY/jenkins_access_token.txt"}
+            if [ "${cfg.accessToken}" != "" ]; then
+               (umask 0077; printf "${cfg.accessToken}" >"$access_token_file")
+            fi
+            jenkins_url="http://${jenkinsCfg.listenAddress}:${toString jenkinsCfg.port}${jenkinsCfg.prefix}"
+            auth_file="$RUNTIME_DIRECTORY/jenkins_auth_file.txt"
+            trap 'rm -f "$auth_file"' EXIT
+            (umask 0077; printf "${cfg.accessUser}:@password_placeholder@" >"$auth_file")
+            "${pkgs.replace-secret}/bin/replace-secret" "@password_placeholder@" "$access_token_file" "$auth_file"
+
+            if ! "${pkgs.jenkins}/bin/jenkins-cli" -s "$jenkins_url" -auth "@$auth_file" reload-configuration; then
+                echo "error: failed to reload configuration"
+                exit 1
+            fi
           '';
         in
           ''
@@ -233,6 +244,7 @@ in {
             done
           '' + (if cfg.accessUser != "" then reloadScript else "");
       serviceConfig = {
+        Type = "oneshot";
         User = jenkinsCfg.user;
         RuntimeDirectory = "jenkins-job-builder";
       };
diff --git a/nixos/modules/services/continuous-integration/jenkins/slave.nix b/nixos/modules/services/continuous-integration/jenkins/slave.nix
index 3c0e6f78e74..9b86917ab38 100644
--- a/nixos/modules/services/continuous-integration/jenkins/slave.nix
+++ b/nixos/modules/services/continuous-integration/jenkins/slave.nix
@@ -1,4 +1,4 @@
-{ config, lib, ... }:
+{ config, lib, pkgs, ... }:
 with lib;
 let
   cfg = config.services.jenkinsSlave;
@@ -14,7 +14,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If true the system will be configured to work as a jenkins slave.
           If the system is also configured to work as a jenkins master then this has no effect.
           In progress: Currently only assures the jenkins user is configured.
@@ -24,7 +24,7 @@ in {
       user = mkOption {
         default = "jenkins";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User the jenkins slave agent should execute under.
         '';
       };
@@ -32,7 +32,7 @@ in {
       group = mkOption {
         default = "jenkins";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           If the default slave agent user "jenkins" is configured then this is
           the primary group of that user.
         '';
@@ -41,11 +41,20 @@ in {
       home = mkOption {
         default = "/var/lib/jenkins";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The path to use as JENKINS_HOME. If the default user "jenkins" is configured then
           this is the home of the "jenkins" user.
         '';
       };
+
+      javaPackage = mkOption {
+        default = pkgs.jdk;
+        defaultText = literalExpression "pkgs.jdk";
+        description = lib.mdDoc ''
+          Java package to install.
+        '';
+        type = types.package;
+      };
     };
   };
 
@@ -64,5 +73,10 @@ in {
         uid = config.ids.uids.jenkins;
       };
     };
+
+    programs.java = {
+      enable = true;
+      package = cfg.javaPackage;
+    };
   };
 }
diff --git a/nixos/modules/services/databases/aerospike.nix b/nixos/modules/services/databases/aerospike.nix
index 8109762aea7..21df4cd0577 100644
--- a/nixos/modules/services/databases/aerospike.nix
+++ b/nixos/modules/services/databases/aerospike.nix
@@ -39,19 +39,19 @@ in
   options = {
 
     services.aerospike = {
-      enable = mkEnableOption "Aerospike server";
+      enable = mkEnableOption (lib.mdDoc "Aerospike server");
 
       package = mkOption {
         default = pkgs.aerospike;
         defaultText = literalExpression "pkgs.aerospike";
         type = types.package;
-        description = "Which Aerospike derivation to use";
+        description = lib.mdDoc "Which Aerospike derivation to use";
       };
 
       workDir = mkOption {
         type = types.str;
         default = "/var/lib/aerospike";
-        description = "Location where Aerospike stores its files";
+        description = lib.mdDoc "Location where Aerospike stores its files";
       };
 
       networkConfig = mkOption {
@@ -80,7 +80,7 @@ in
             port 3003
           }
         '';
-        description = "network section of configuration file";
+        description = lib.mdDoc "network section of configuration file";
       };
 
       extraConfig = mkOption {
@@ -94,7 +94,7 @@ in
             storage-engine memory
           }
         '';
-        description = "Extra configuration";
+        description = lib.mdDoc "Extra configuration";
       };
     };
 
diff --git a/nixos/modules/services/databases/cassandra.nix b/nixos/modules/services/databases/cassandra.nix
index b36cac35e7c..7556dbfc7b8 100644
--- a/nixos/modules/services/databases/cassandra.nix
+++ b/nixos/modules/services/databases/cassandra.nix
@@ -4,11 +4,12 @@ let
   inherit (lib)
     concatStringsSep
     flip
-    literalDocBook
+    literalMD
     literalExpression
     optionalAttrs
     optionals
     recursiveUpdate
+    mdDoc
     mkEnableOption
     mkIf
     mkOption
@@ -100,14 +101,14 @@ in
 {
   options.services.cassandra = {
 
-    enable = mkEnableOption ''
+    enable = mkEnableOption (lib.mdDoc ''
       Apache Cassandra – Scalable and highly available database.
-    '';
+    '');
 
     clusterName = mkOption {
       type = types.str;
       default = "Test Cluster";
-      description = ''
+      description = mdDoc ''
         The name of the cluster.
         This setting prevents nodes in one logical cluster from joining
         another. All nodes in a cluster must have the same value.
@@ -117,19 +118,19 @@ in
     user = mkOption {
       type = types.str;
       default = defaultUser;
-      description = "Run Apache Cassandra under this user.";
+      description = mdDoc "Run Apache Cassandra under this user.";
     };
 
     group = mkOption {
       type = types.str;
       default = defaultUser;
-      description = "Run Apache Cassandra under this group.";
+      description = mdDoc "Run Apache Cassandra under this group.";
     };
 
     homeDir = mkOption {
       type = types.path;
       default = "/var/lib/cassandra";
-      description = ''
+      description = mdDoc ''
         Home directory for Apache Cassandra.
       '';
     };
@@ -139,7 +140,7 @@ in
       default = pkgs.cassandra;
       defaultText = literalExpression "pkgs.cassandra";
       example = literalExpression "pkgs.cassandra_3_11";
-      description = ''
+      description = mdDoc ''
         The Apache Cassandra package to use.
       '';
     };
@@ -147,8 +148,8 @@ in
     jvmOpts = mkOption {
       type = types.listOf types.str;
       default = [ ];
-      description = ''
-        Populate the JVM_OPT environment variable.
+      description = mdDoc ''
+        Populate the `JVM_OPT` environment variable.
       '';
     };
 
@@ -156,20 +157,20 @@ in
       type = types.nullOr types.str;
       default = "127.0.0.1";
       example = null;
-      description = ''
+      description = mdDoc ''
         Address or interface to bind to and tell other Cassandra nodes
         to connect to. You _must_ change this if you want multiple
         nodes to be able to communicate!
 
-        Set listenAddress OR listenInterface, not both.
+        Set {option}`listenAddress` OR {option}`listenInterface`, not both.
 
         Leaving it blank leaves it up to
-        InetAddress.getLocalHost(). This will always do the Right
-        Thing _if_ the node is properly configured (hostname, name
+        `InetAddress.getLocalHost()`. This will always do the "Right
+        Thing" _if_ the node is properly configured (hostname, name
         resolution, etc), and the Right Thing is to use the address
         associated with the hostname (it might not be).
 
-        Setting listen_address to 0.0.0.0 is always wrong.
+        Setting {option}`listenAddress` to `0.0.0.0` is always wrong.
       '';
     };
 
@@ -177,8 +178,8 @@ in
       type = types.nullOr types.str;
       default = null;
       example = "eth1";
-      description = ''
-        Set listenAddress OR listenInterface, not both. Interfaces
+      description = mdDoc ''
+        Set `listenAddress` OR `listenInterface`, not both. Interfaces
         must correspond to a single address, IP aliasing is not
         supported.
       '';
@@ -188,18 +189,18 @@ in
       type = types.nullOr types.str;
       default = "127.0.0.1";
       example = null;
-      description = ''
+      description = mdDoc ''
         The address or interface to bind the native transport server to.
 
-        Set rpcAddress OR rpcInterface, not both.
+        Set {option}`rpcAddress` OR {option}`rpcInterface`, not both.
 
-        Leaving rpcAddress blank has the same effect as on
-        listenAddress (i.e. it will be based on the configured hostname
+        Leaving {option}`rpcAddress` blank has the same effect as on
+        {option}`listenAddress` (i.e. it will be based on the configured hostname
         of the node).
 
-        Note that unlike listenAddress, you can specify 0.0.0.0, but you
-        must also set extraConfig.broadcast_rpc_address to a value other
-        than 0.0.0.0.
+        Note that unlike {option}`listenAddress`, you can specify `"0.0.0.0"`, but you
+        must also set `extraConfig.broadcast_rpc_address` to a value other
+        than `"0.0.0.0"`.
 
         For security reasons, you should not expose this port to the
         internet. Firewall it if needed.
@@ -210,8 +211,8 @@ in
       type = types.nullOr types.str;
       default = null;
       example = "eth1";
-      description = ''
-        Set rpcAddress OR rpcInterface, not both. Interfaces must
+      description = mdDoc ''
+        Set {option}`rpcAddress` OR {option}`rpcInterface`, not both. Interfaces must
         correspond to a single address, IP aliasing is not supported.
       '';
     };
@@ -233,7 +234,7 @@ in
           <logger name="com.thinkaurelius.thrift" level="ERROR"/>
         </configuration>
       '';
-      description = ''
+      description = mdDoc ''
         XML logback configuration for cassandra
       '';
     };
@@ -241,24 +242,24 @@ in
     seedAddresses = mkOption {
       type = types.listOf types.str;
       default = [ "127.0.0.1" ];
-      description = ''
+      description = mdDoc ''
         The addresses of hosts designated as contact points in the cluster. A
         joining node contacts one of the nodes in the seeds list to learn the
         topology of the ring.
-        Set to 127.0.0.1 for a single node cluster.
+        Set to `[ "127.0.0.1" ]` for a single node cluster.
       '';
     };
 
     allowClients = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = mdDoc ''
         Enables or disables the native transport server (CQL binary protocol).
-        This server uses the same address as the <literal>rpcAddress</literal>,
-        but the port it uses is not <literal>rpc_port</literal> but
-        <literal>native_transport_port</literal>. See the official Cassandra
+        This server uses the same address as the {option}`rpcAddress`,
+        but the port it uses is not `rpc_port` but
+        `native_transport_port`. See the official Cassandra
         docs for more information on these variables and set them using
-        <literal>extraConfig</literal>.
+        {option}`extraConfig`.
       '';
     };
 
@@ -269,8 +270,8 @@ in
         {
           commitlog_sync_batch_window_in_ms = 3;
         };
-      description = ''
-        Extra options to be merged into cassandra.yaml as nix attribute set.
+      description = mdDoc ''
+        Extra options to be merged into {file}`cassandra.yaml` as nix attribute set.
       '';
     };
 
@@ -278,8 +279,8 @@ in
       type = types.lines;
       default = "";
       example = literalExpression ''"CLASSPATH=$CLASSPATH:''${extraJar}"'';
-      description = ''
-        Extra shell lines to be appended onto cassandra-env.sh.
+      description = mdDoc ''
+        Extra shell lines to be appended onto {file}`cassandra-env.sh`.
       '';
     };
 
@@ -287,13 +288,13 @@ in
       type = types.nullOr types.str;
       default = "3w";
       example = null;
-      description = ''
+      description = mdDoc ''
         Set the interval how often full repairs are run, i.e.
-        <literal>nodetool repair --full</literal> is executed. See
-        https://cassandra.apache.org/doc/latest/operating/repair.html
+        {command}`nodetool repair --full` is executed. See
+        <https://cassandra.apache.org/doc/latest/operating/repair.html>
         for more information.
 
-        Set to <literal>null</literal> to disable full repairs.
+        Set to `null` to disable full repairs.
       '';
     };
 
@@ -301,7 +302,7 @@ in
       type = types.listOf types.str;
       default = [ ];
       example = [ "--partitioner-range" ];
-      description = ''
+      description = mdDoc ''
         Options passed through to the full repair command.
       '';
     };
@@ -310,13 +311,13 @@ in
       type = types.nullOr types.str;
       default = "3d";
       example = null;
-      description = ''
+      description = mdDoc ''
         Set the interval how often incremental repairs are run, i.e.
-        <literal>nodetool repair</literal> is executed. See
-        https://cassandra.apache.org/doc/latest/operating/repair.html
+        {command}`nodetool repair` is executed. See
+        <https://cassandra.apache.org/doc/latest/operating/repair.html>
         for more information.
 
-        Set to <literal>null</literal> to disable incremental repairs.
+        Set to `null` to disable incremental repairs.
       '';
     };
 
@@ -324,7 +325,7 @@ in
       type = types.listOf types.str;
       default = [ ];
       example = [ "--partitioner-range" ];
-      description = ''
+      description = mdDoc ''
         Options passed through to the incremental repair command.
       '';
     };
@@ -333,15 +334,15 @@ in
       type = types.nullOr types.str;
       default = null;
       example = "4G";
-      description = ''
-        Must be left blank or set together with heapNewSize.
+      description = mdDoc ''
+        Must be left blank or set together with {option}`heapNewSize`.
         If left blank a sensible value for the available amount of RAM and CPU
         cores is calculated.
 
         Override to set the amount of memory to allocate to the JVM at
         start-up. For production use you may wish to adjust this for your
-        environment. MAX_HEAP_SIZE is the total amount of memory dedicated
-        to the Java heap. HEAP_NEWSIZE refers to the size of the young
+        environment. `MAX_HEAP_SIZE` is the total amount of memory dedicated
+        to the Java heap. `HEAP_NEWSIZE` refers to the size of the young
         generation.
 
         The main trade-off for the young generation is that the larger it
@@ -354,21 +355,21 @@ in
       type = types.nullOr types.str;
       default = null;
       example = "800M";
-      description = ''
-        Must be left blank or set together with heapNewSize.
+      description = mdDoc ''
+        Must be left blank or set together with {option}`heapNewSize`.
         If left blank a sensible value for the available amount of RAM and CPU
         cores is calculated.
 
         Override to set the amount of memory to allocate to the JVM at
         start-up. For production use you may wish to adjust this for your
-        environment. HEAP_NEWSIZE refers to the size of the young
+        environment. `HEAP_NEWSIZE` refers to the size of the young
         generation.
 
         The main trade-off for the young generation is that the larger it
         is, the longer GC pause times will be. The shorter it is, the more
         expensive GC will be (usually).
 
-        The example HEAP_NEWSIZE assumes a modern 8-core+ machine for decent pause
+        The example `HEAP_NEWSIZE` assumes a modern 8-core+ machine for decent pause
         times. If in doubt, and if you do not particularly want to tweak, go with
         100 MB per physical CPU core.
       '';
@@ -378,7 +379,7 @@ in
       type = types.nullOr types.int;
       default = null;
       example = 4;
-      description = ''
+      description = mdDoc ''
         Set this to control the amount of arenas per-thread in glibc.
       '';
     };
@@ -386,19 +387,19 @@ in
     remoteJmx = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = mdDoc ''
         Cassandra ships with JMX accessible *only* from localhost.
         To enable remote JMX connections set to true.
 
         Be sure to also enable authentication and/or TLS.
-        See: https://wiki.apache.org/cassandra/JmxSecurity
+        See: <https://wiki.apache.org/cassandra/JmxSecurity>
       '';
     };
 
     jmxPort = mkOption {
       type = types.int;
       default = 7199;
-      description = ''
+      description = mdDoc ''
         Specifies the default port over which Cassandra will be available for
         JMX connections.
         For security reasons, you should not expose this port to the internet.
@@ -408,11 +409,11 @@ in
 
     jmxRoles = mkOption {
       default = [ ];
-      description = ''
-        Roles that are allowed to access the JMX (e.g. nodetool)
-        BEWARE: The passwords will be stored world readable in the nix-store.
+      description = mdDoc ''
+        Roles that are allowed to access the JMX (e.g. {command}`nodetool`)
+        BEWARE: The passwords will be stored world readable in the nix store.
                 It's recommended to use your own protected file using
-                <literal>jmxRolesFile</literal>
+                {option}`jmxRolesFile`
 
         Doesn't work in versions older than 3.11 because they don't like that
         it's world readable.
@@ -421,11 +422,11 @@ in
         options = {
           username = mkOption {
             type = types.str;
-            description = "Username for JMX";
+            description = lib.mdDoc "Username for JMX";
           };
           password = mkOption {
             type = types.str;
-            description = "Password for JMX";
+            description = lib.mdDoc "Password for JMX";
           };
         };
       });
@@ -437,9 +438,9 @@ in
         if versionAtLeast cfg.package.version "3.11"
         then pkgs.writeText "jmx-roles-file" defaultJmxRolesFile
         else null;
-      defaultText = literalDocBook ''generated configuration file if version is at least 3.11, otherwise <literal>null</literal>'';
+      defaultText = literalMD ''generated configuration file if version is at least 3.11, otherwise `null`'';
       example = "/var/lib/cassandra/jmx.password";
-      description = ''
+      description = lib.mdDoc ''
         Specify your own jmx roles file.
 
         Make sure the permissions forbid "others" from reading the file if
diff --git a/nixos/modules/services/databases/clickhouse.nix b/nixos/modules/services/databases/clickhouse.nix
index 3a161d56107..96607d9a783 100644
--- a/nixos/modules/services/databases/clickhouse.nix
+++ b/nixos/modules/services/databases/clickhouse.nix
@@ -11,13 +11,13 @@ with lib;
 
     services.clickhouse = {
 
-      enable = mkEnableOption "ClickHouse database server";
+      enable = mkEnableOption (lib.mdDoc "ClickHouse database server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.clickhouse;
         defaultText = "pkgs.clickhouse";
-        description = ''
+        description = lib.mdDoc ''
           ClickHouse package to use.
         '';
       };
diff --git a/nixos/modules/services/databases/cockroachdb.nix b/nixos/modules/services/databases/cockroachdb.nix
index eb061af9262..26ccb030b3d 100644
--- a/nixos/modules/services/databases/cockroachdb.nix
+++ b/nixos/modules/services/databases/cockroachdb.nix
@@ -1,4 +1,4 @@
-{ config, lib, pkgs, ... }:
+{ config, lib, pkgs, utils, ... }:
 
 with lib;
 
@@ -6,52 +6,50 @@ let
   cfg = config.services.cockroachdb;
   crdb = cfg.package;
 
-  escape    = builtins.replaceStrings ["%"] ["%%"];
-  ifNotNull = v: s: optionalString (v != null) s;
-
-  startupCommand = lib.concatStringsSep " "
-    [ # Basic startup
-      "${crdb}/bin/cockroach start"
+  startupCommand = utils.escapeSystemdExecArgs
+    ([
+      # Basic startup
+      "${crdb}/bin/cockroach"
+      "start"
       "--logtostderr"
       "--store=/var/lib/cockroachdb"
-      (ifNotNull cfg.locality "--locality='${cfg.locality}'")
 
       # WebUI settings
-      "--http-addr='${cfg.http.address}:${toString cfg.http.port}'"
+      "--http-addr=${cfg.http.address}:${toString cfg.http.port}"
 
       # Cluster listen address
-      "--listen-addr='${cfg.listen.address}:${toString cfg.listen.port}'"
-
-      # Cluster configuration
-      (ifNotNull cfg.join "--join=${cfg.join}")
+      "--listen-addr=${cfg.listen.address}:${toString cfg.listen.port}"
 
-      # Cache and memory settings. Must be escaped.
-      "--cache='${escape cfg.cache}'"
-      "--max-sql-memory='${escape cfg.maxSqlMemory}'"
+      # Cache and memory settings.
+      "--cache=${cfg.cache}"
+      "--max-sql-memory=${cfg.maxSqlMemory}"
 
       # Certificate/security settings.
       (if cfg.insecure then "--insecure" else "--certs-dir=${cfg.certsDir}")
-    ];
-
-    addressOption = descr: defaultPort: {
-      address = mkOption {
-        type = types.str;
-        default = "localhost";
-        description = "Address to bind to for ${descr}";
-      };
+    ]
+    ++ lib.optional (cfg.join != null) "--join=${cfg.join}"
+    ++ lib.optional (cfg.locality != null) "--locality=${cfg.locality}"
+    ++ cfg.extraArgs);
+
+  addressOption = descr: defaultPort: {
+    address = mkOption {
+      type = types.str;
+      default = "localhost";
+      description = lib.mdDoc "Address to bind to for ${descr}";
+    };
 
-      port = mkOption {
-        type = types.port;
-        default = defaultPort;
-        description = "Port to bind to for ${descr}";
-      };
+    port = mkOption {
+      type = types.port;
+      default = defaultPort;
+      description = lib.mdDoc "Port to bind to for ${descr}";
     };
+  };
 in
 
 {
   options = {
     services.cockroachdb = {
-      enable = mkEnableOption "CockroachDB Server";
+      enable = mkEnableOption (lib.mdDoc "CockroachDB Server");
 
       listen = addressOption "intra-cluster communication" 26257;
 
@@ -60,7 +58,7 @@ in
       locality = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           An ordered, comma-separated list of key-value pairs that describe the
           topography of the machine. Topography might include country,
           datacenter or rack designations. Data is automatically replicated to
@@ -70,62 +68,62 @@ in
           like datacenter.  The tiers and order must be the same on all nodes.
           Including more tiers is better than including fewer. For example:
 
-          <literal>
+          ```
               country=us,region=us-west,datacenter=us-west-1b,rack=12
               country=ca,region=ca-east,datacenter=ca-east-2,rack=4
 
               planet=earth,province=manitoba,colo=secondary,power=3
-          </literal>
+          ```
         '';
       };
 
       join = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "The addresses for connecting the node to a cluster.";
+        description = lib.mdDoc "The addresses for connecting the node to a cluster.";
       };
 
       insecure = mkOption {
         type = types.bool;
         default = false;
-        description = "Run in insecure mode.";
+        description = lib.mdDoc "Run in insecure mode.";
       };
 
       certsDir = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "The path to the certificate directory.";
+        description = lib.mdDoc "The path to the certificate directory.";
       };
 
       user = mkOption {
         type = types.str;
         default = "cockroachdb";
-        description = "User account under which CockroachDB runs";
+        description = lib.mdDoc "User account under which CockroachDB runs";
       };
 
       group = mkOption {
         type = types.str;
         default = "cockroachdb";
-        description = "User account under which CockroachDB runs";
+        description = lib.mdDoc "User account under which CockroachDB runs";
       };
 
       openPorts = mkOption {
         type = types.bool;
         default = false;
-        description = "Open firewall ports for cluster communication by default";
+        description = lib.mdDoc "Open firewall ports for cluster communication by default";
       };
 
       cache = mkOption {
         type = types.str;
         default = "25%";
-        description = ''
+        description = lib.mdDoc ''
           The total size for caches.
 
           This can be a percentage, expressed with a fraction sign or as a
           decimal-point number, or any bytes-based unit. For example,
-          <literal>"25%"</literal>, <literal>"0.25"</literal> both represent
+          `"25%"`, `"0.25"` both represent
           25% of the available system memory. The values
-          <literal>"1000000000"</literal> and <literal>"1GB"</literal> both
+          `"1000000000"` and `"1GB"` both
           represent 1 gigabyte of memory.
 
         '';
@@ -134,15 +132,15 @@ in
       maxSqlMemory = mkOption {
         type = types.str;
         default = "25%";
-        description = ''
+        description = lib.mdDoc ''
           The maximum in-memory storage capacity available to store temporary
           data for SQL queries.
 
           This can be a percentage, expressed with a fraction sign or as a
           decimal-point number, or any bytes-based unit. For example,
-          <literal>"25%"</literal>, <literal>"0.25"</literal> both represent
+          `"25%"`, `"0.25"` both represent
           25% of the available system memory. The values
-          <literal>"1000000000"</literal> and <literal>"1GB"</literal> both
+          `"1000000000"` and `"1GB"` both
           represent 1 gigabyte of memory.
         '';
       };
@@ -151,7 +149,7 @@ in
         type = types.package;
         default = pkgs.cockroachdb;
         defaultText = literalExpression "pkgs.cockroachdb";
-        description = ''
+        description = lib.mdDoc ''
           The CockroachDB derivation to use for running the service.
 
           This would primarily be useful to enable Enterprise Edition features
@@ -159,6 +157,16 @@ in
           only contain open source features and open source code).
         '';
       };
+
+      extraArgs = mkOption {
+        type = types.listOf types.str;
+        default = [];
+        example = [ "--advertise-addr" "[fe80::f6f2:::]" ];
+        description = lib.mdDoc ''
+          Extra CLI arguments passed to {command}`cockroach start`.
+          For the full list of supported argumemnts, check <https://www.cockroachlabs.com/docs/stable/cockroach-start.html#flags>
+        '';
+      };
     };
   };
 
diff --git a/nixos/modules/services/databases/couchdb.nix b/nixos/modules/services/databases/couchdb.nix
index 742e605d224..cdf32654e66 100644
--- a/nixos/modules/services/databases/couchdb.nix
+++ b/nixos/modules/services/databases/couchdb.nix
@@ -34,19 +34,13 @@ in {
 
     services.couchdb = {
 
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Whether to run CouchDB Server.
-        '';
-      };
+      enable = mkEnableOption (lib.mdDoc "CouchDB Server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.couchdb3;
         defaultText = literalExpression "pkgs.couchdb3";
-        description = ''
+        description = lib.mdDoc ''
           CouchDB package to use.
         '';
       };
@@ -54,7 +48,7 @@ in {
       adminUser = mkOption {
         type = types.str;
         default = "admin";
-        description = ''
+        description = lib.mdDoc ''
           Couchdb (i.e. fauxton) account with permission for all dbs and
           tasks.
         '';
@@ -63,7 +57,7 @@ in {
       adminPass = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Couchdb (i.e. fauxton) account with permission for all dbs and
           tasks.
         '';
@@ -72,7 +66,7 @@ in {
       user = mkOption {
         type = types.str;
         default = "couchdb";
-        description = ''
+        description = lib.mdDoc ''
           User account under which couchdb runs.
         '';
       };
@@ -80,7 +74,7 @@ in {
       group = mkOption {
         type = types.str;
         default = "couchdb";
-        description = ''
+        description = lib.mdDoc ''
           Group account under which couchdb runs.
         '';
       };
@@ -90,7 +84,7 @@ in {
       databaseDir = mkOption {
         type = types.path;
         default = "/var/lib/couchdb";
-        description = ''
+        description = lib.mdDoc ''
           Specifies location of CouchDB database files (*.couch named). This
           location should be writable and readable for the user the CouchDB
           service runs as (couchdb by default).
@@ -100,7 +94,7 @@ in {
       uriFile = mkOption {
         type = types.path;
         default = "/run/couchdb/couchdb.uri";
-        description = ''
+        description = lib.mdDoc ''
           This file contains the full URI that can be used to access this
           instance of CouchDB. It is used to help discover the port CouchDB is
           running on (if it was set to 0 (e.g. automatically assigned any free
@@ -112,7 +106,7 @@ in {
       viewIndexDir = mkOption {
         type = types.path;
         default = "/var/lib/couchdb";
-        description = ''
+        description = lib.mdDoc ''
           Specifies location of CouchDB view index files. This location should
           be writable and readable for the user that runs the CouchDB service
           (couchdb by default).
@@ -122,15 +116,15 @@ in {
       bindAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = ''
+        description = lib.mdDoc ''
           Defines the IP address by which CouchDB will be accessible.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 5984;
-        description = ''
+        description = lib.mdDoc ''
           Defined the port number to listen.
         '';
       };
@@ -138,7 +132,7 @@ in {
       logFile = mkOption {
         type = types.path;
         default = "/var/log/couchdb.log";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the location of file for logging output.
         '';
       };
@@ -146,7 +140,7 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration. Overrides any other cofiguration.
         '';
       };
@@ -155,14 +149,14 @@ in {
         type = types.path;
         default = "${cfg.package}/etc/vm.args";
         defaultText = literalExpression ''"config.${opt.package}/etc/vm.args"'';
-        description = ''
+        description = lib.mdDoc ''
           vm.args configuration. Overrides Couchdb's Erlang VM parameters file.
         '';
       };
 
       configFile = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Configuration file for persisting runtime changes. File
           needs to be readable and writable from couchdb user/group.
         '';
@@ -193,6 +187,11 @@ in {
 
       preStart = ''
         touch ${cfg.configFile}
+        if ! test -e ${cfg.databaseDir}/.erlang.cookie; then
+          touch ${cfg.databaseDir}/.erlang.cookie
+          chmod 600 ${cfg.databaseDir}/.erlang.cookie
+          dd if=/dev/random bs=16 count=1 | base64 > ${cfg.databaseDir}/.erlang.cookie
+        fi
       '';
 
       environment = {
@@ -204,6 +203,7 @@ in {
         ERL_FLAGS= ''-couch_ini ${cfg.package}/etc/default.ini ${configFile} ${pkgs.writeText "couchdb-extra.ini" cfg.extraConfig} ${cfg.configFile}'';
         # 5. the vm.args file
         COUCHDB_ARGS_FILE=''${cfg.argsFile}'';
+        HOME =''${cfg.databaseDir}'';
       };
 
       serviceConfig = {
diff --git a/nixos/modules/services/databases/dgraph.nix b/nixos/modules/services/databases/dgraph.nix
new file mode 100644
index 00000000000..5726851a43f
--- /dev/null
+++ b/nixos/modules/services/databases/dgraph.nix
@@ -0,0 +1,148 @@
+{ config, pkgs, lib, ... }:
+
+with lib;
+
+let
+  cfg = config.services.dgraph;
+  settingsFormat = pkgs.formats.json {};
+  configFile = settingsFormat.generate "config.json" cfg.settings;
+  dgraphWithNode = pkgs.runCommand "dgraph" {
+    nativeBuildInputs = [ pkgs.makeWrapper ];
+  }
+  ''
+    mkdir -p $out/bin
+    makeWrapper ${cfg.package}/bin/dgraph $out/bin/dgraph \
+      --set PATH '${lib.makeBinPath [ pkgs.nodejs ]}:$PATH' \
+  '';
+  securityOptions = {
+      NoNewPrivileges = true;
+
+      AmbientCapabilities = "";
+      CapabilityBoundingSet = "";
+
+      DeviceAllow = "";
+
+      LockPersonality = true;
+
+      PrivateTmp = true;
+      PrivateDevices = true;
+      PrivateUsers = true;
+
+      ProtectClock = true;
+      ProtectControlGroups = true;
+      ProtectHostname = true;
+      ProtectKernelLogs = true;
+      ProtectKernelModules = true;
+      ProtectKernelTunables = true;
+
+      RemoveIPC = true;
+
+      RestrictNamespaces = true;
+      RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+      RestrictRealtime = true;
+      RestrictSUIDSGID = true;
+
+      SystemCallArchitectures = "native";
+      SystemCallErrorNumber = "EPERM";
+      SystemCallFilter = [
+        "@system-service"
+        "~@cpu-emulation" "~@debug" "~@keyring" "~@memlock" "~@obsolete" "~@privileged" "~@setuid"
+      ];
+  };
+in
+{
+  options = {
+    services.dgraph = {
+      enable = mkEnableOption (lib.mdDoc "Dgraph native GraphQL database with a graph backend");
+
+      package = lib.mkPackageOption pkgs "dgraph" { };
+
+      settings = mkOption {
+        type = settingsFormat.type;
+        default = {};
+        description = lib.mdDoc ''
+          Contents of the dgraph config. For more details see https://dgraph.io/docs/deploy/config
+        '';
+      };
+
+      alpha = {
+        host = mkOption {
+          type = types.str;
+          default = "localhost";
+          description = lib.mdDoc ''
+            The host which dgraph alpha will be run on.
+          '';
+        };
+        port = mkOption {
+          type = types.port;
+          default = 7080;
+          description = lib.mdDoc ''
+            The port which to run dgraph alpha on.
+          '';
+        };
+
+      };
+
+      zero = {
+        host = mkOption {
+          type = types.str;
+          default = "localhost";
+          description = lib.mdDoc ''
+            The host which dgraph zero will be run on.
+          '';
+        };
+        port = mkOption {
+          type = types.port;
+          default = 5080;
+          description = lib.mdDoc ''
+            The port which to run dgraph zero on.
+          '';
+        };
+      };
+
+    };
+  };
+
+  config = mkIf cfg.enable {
+    services.dgraph.settings = {
+      badger.compression = mkDefault "zstd:3";
+    };
+
+    systemd.services.dgraph-zero = {
+      description = "Dgraph native GraphQL database with a graph backend. Zero controls node clustering";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = {
+        StateDirectory = "dgraph-zero";
+        WorkingDirectory = "/var/lib/dgraph-zero";
+        DynamicUser = true;
+        ExecStart = "${cfg.package}/bin/dgraph zero --my ${cfg.zero.host}:${toString cfg.zero.port}";
+        Restart = "on-failure";
+      } // securityOptions;
+    };
+
+    systemd.services.dgraph-alpha = {
+      description = "Dgraph native GraphQL database with a graph backend. Alpha serves data";
+      after = [ "network.target" "dgraph-zero.service" ];
+      requires = [ "dgraph-zero.service" ];
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = {
+        StateDirectory = "dgraph-alpha";
+        WorkingDirectory = "/var/lib/dgraph-alpha";
+        DynamicUser = true;
+        ExecStart = "${dgraphWithNode}/bin/dgraph alpha --config ${configFile} --my ${cfg.alpha.host}:${toString cfg.alpha.port} --zero ${cfg.zero.host}:${toString cfg.zero.port}";
+        ExecStop = ''
+          ${pkgs.curl}/bin/curl --data "mutation { shutdown { response { message code } } }" \
+              --header 'Content-Type: application/graphql' \
+              -X POST \
+              http://localhost:8080/admin
+        '';
+        Restart = "on-failure";
+      } // securityOptions;
+    };
+  };
+
+  meta.maintainers = with lib.maintainers; [ happysalada ];
+}
diff --git a/nixos/modules/services/databases/dragonflydb.nix b/nixos/modules/services/databases/dragonflydb.nix
new file mode 100644
index 00000000000..46a0c188c3a
--- /dev/null
+++ b/nixos/modules/services/databases/dragonflydb.nix
@@ -0,0 +1,152 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.dragonflydb;
+  dragonflydb = pkgs.dragonflydb;
+
+  settings =
+    {
+      port = cfg.port;
+      dir = "/var/lib/dragonflydb";
+      keys_output_limit = cfg.keysOutputLimit;
+    } //
+    (lib.optionalAttrs (cfg.bind != null) { bind = cfg.bind; }) //
+    (lib.optionalAttrs (cfg.requirePass != null) { requirepass = cfg.requirePass; }) //
+    (lib.optionalAttrs (cfg.maxMemory != null) { maxmemory = cfg.maxMemory; }) //
+    (lib.optionalAttrs (cfg.memcachePort != null) { memcache_port = cfg.memcachePort; }) //
+    (lib.optionalAttrs (cfg.dbNum != null) { dbnum = cfg.dbNum; }) //
+    (lib.optionalAttrs (cfg.cacheMode != null) { cache_mode = cfg.cacheMode; });
+in
+{
+
+  ###### interface
+
+  options = {
+    services.dragonflydb = {
+      enable = mkEnableOption (lib.mdDoc "DragonflyDB");
+
+      user = mkOption {
+        type = types.str;
+        default = "dragonfly";
+        description = lib.mdDoc "The user to run DragonflyDB as";
+      };
+
+      port = mkOption {
+        type = types.port;
+        default = 6379;
+        description = lib.mdDoc "The TCP port to accept connections.";
+      };
+
+      bind = mkOption {
+        type = with types; nullOr str;
+        default = "127.0.0.1";
+        description = lib.mdDoc ''
+          The IP interface to bind to.
+          `null` means "all interfaces".
+        '';
+      };
+
+      requirePass = mkOption {
+        type = with types; nullOr str;
+        default = null;
+        description = lib.mdDoc "Password for database";
+        example = "letmein!";
+      };
+
+      maxMemory = mkOption {
+        type = with types; nullOr ints.unsigned;
+        default = null;
+        description = lib.mdDoc ''
+          The maximum amount of memory to use for storage (in bytes).
+          `null` means this will be automatically set.
+        '';
+      };
+
+      memcachePort = mkOption {
+        type = with types; nullOr port;
+        default = null;
+        description = lib.mdDoc ''
+          To enable memcached compatible API on this port.
+          `null` means disabled.
+        '';
+      };
+
+      keysOutputLimit = mkOption {
+        type = types.ints.unsigned;
+        default = 8192;
+        description = lib.mdDoc ''
+          Maximum number of returned keys in keys command.
+          `keys` is a dangerous command.
+          We truncate its result to avoid blowup in memory when fetching too many keys.
+        '';
+      };
+
+      dbNum = mkOption {
+        type = with types; nullOr ints.unsigned;
+        default = null;
+        description = lib.mdDoc "Maximum number of supported databases for `select`";
+      };
+
+      cacheMode = mkOption {
+        type = with types; nullOr bool;
+        default = null;
+        description = lib.mdDoc ''
+          Once this mode is on, Dragonfly will evict items least likely to be stumbled
+          upon in the future but only when it is near maxmemory limit.
+        '';
+      };
+    };
+  };
+
+  ###### implementation
+
+  config = mkIf config.services.dragonflydb.enable {
+
+    users.users = optionalAttrs (cfg.user == "dragonfly") {
+      dragonfly.description = "DragonflyDB server user";
+      dragonfly.isSystemUser = true;
+      dragonfly.group = "dragonfly";
+    };
+    users.groups = optionalAttrs (cfg.user == "dragonfly") { dragonfly = { }; };
+
+    environment.systemPackages = [ dragonflydb ];
+
+    systemd.services.dragonflydb = {
+      description = "DragonflyDB server";
+
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+
+      serviceConfig = {
+        ExecStart = "${dragonflydb}/bin/dragonfly --alsologtostderr ${builtins.concatStringsSep " " (attrsets.mapAttrsToList (n: v: "--${n} ${strings.escapeShellArg v}") settings)}";
+
+        User = cfg.user;
+
+        # Filesystem access
+        ReadWritePaths = [ settings.dir ];
+        StateDirectory = "dragonflydb";
+        StateDirectoryMode = "0700";
+        # Process Properties
+        LimitMEMLOCK = "infinity";
+        # Caps
+        CapabilityBoundingSet = "";
+        NoNewPrivileges = true;
+        # Sandboxing
+        ProtectSystem = "strict";
+        ProtectHome = true;
+        PrivateTmp = true;
+        PrivateDevices = true;
+        ProtectKernelTunables = true;
+        ProtectKernelModules = true;
+        ProtectControlGroups = true;
+        LockPersonality = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+        RestrictRealtime = true;
+        PrivateMounts = true;
+        MemoryDenyWriteExecute = true;
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/databases/firebird.nix b/nixos/modules/services/databases/firebird.nix
index 4e3130bea22..b2c4a5dd8f6 100644
--- a/nixos/modules/services/databases/firebird.nix
+++ b/nixos/modules/services/databases/firebird.nix
@@ -40,23 +40,23 @@ in
 
     services.firebird = {
 
-      enable = mkEnableOption "the Firebird super server";
+      enable = mkEnableOption (lib.mdDoc "the Firebird super server");
 
       package = mkOption {
         default = pkgs.firebird;
         defaultText = literalExpression "pkgs.firebird";
         type = types.package;
         example = literalExpression "pkgs.firebird_3";
-        description = ''
-          Which Firebird package to be installed: <code>pkgs.firebird_3</code>
-          For SuperServer use override: <code>pkgs.firebird_3.override { superServer = true; };</code>
+        description = lib.mdDoc ''
+          Which Firebird package to be installed: `pkgs.firebird_3`
+          For SuperServer use override: `pkgs.firebird_3.override { superServer = true; };`
         '';
       };
 
       port = mkOption {
         default = 3050;
         type = types.port;
-        description = ''
+        description = lib.mdDoc ''
           Port Firebird uses.
         '';
       };
@@ -64,7 +64,7 @@ in
       user = mkOption {
         default = "firebird";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User account under which firebird runs.
         '';
       };
@@ -72,7 +72,7 @@ in
       baseDir = mkOption {
         default = "/var/lib/firebird";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Location containing data/ and system/ directories.
           data/ stores the databases, system/ stores the password database security2.fdb.
         '';
diff --git a/nixos/modules/services/databases/foundationdb.nix b/nixos/modules/services/databases/foundationdb.nix
index e22127403e9..16d539b661e 100644
--- a/nixos/modules/services/databases/foundationdb.nix
+++ b/nixos/modules/services/databases/foundationdb.nix
@@ -62,11 +62,11 @@ in
 {
   options.services.foundationdb = {
 
-    enable = mkEnableOption "FoundationDB Server";
+    enable = mkEnableOption (lib.mdDoc "FoundationDB Server");
 
     package = mkOption {
       type        = types.package;
-      description = ''
+      description = lib.mdDoc ''
         The FoundationDB package to use for this server. This must be specified by the user
         in order to ensure migrations and upgrades are controlled appropriately.
       '';
@@ -75,19 +75,19 @@ in
     publicAddress = mkOption {
       type        = types.str;
       default     = "auto";
-      description = "Publicly visible IP address of the process. Port is determined by process ID";
+      description = lib.mdDoc "Publicly visible IP address of the process. Port is determined by process ID";
     };
 
     listenAddress = mkOption {
       type        = types.str;
       default     = "public";
-      description = "Publicly visible IP address of the process. Port is determined by process ID";
+      description = lib.mdDoc "Publicly visible IP address of the process. Port is determined by process ID";
     };
 
     listenPortStart = mkOption {
       type          = types.int;
       default       = 4500;
-      description   = ''
+      description   = lib.mdDoc ''
         Starting port number for database listening sockets. Every FDB process binds to a
         subsequent port, to this number reflects the start of the overall range. e.g. having
         8 server processes will use all ports between 4500 and 4507.
@@ -97,52 +97,52 @@ in
     openFirewall = mkOption {
       type        = types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         Open the firewall ports corresponding to FoundationDB processes and coordinators
-        using <option>config.networking.firewall.*</option>.
+        using {option}`config.networking.firewall.*`.
       '';
     };
 
     dataDir = mkOption {
       type        = types.path;
       default     = "/var/lib/foundationdb";
-      description = "Data directory. All cluster data will be put under here.";
+      description = lib.mdDoc "Data directory. All cluster data will be put under here.";
     };
 
     logDir = mkOption {
       type        = types.path;
       default     = "/var/log/foundationdb";
-      description = "Log directory.";
+      description = lib.mdDoc "Log directory.";
     };
 
     user = mkOption {
       type        = types.str;
       default     = "foundationdb";
-      description = "User account under which FoundationDB runs.";
+      description = lib.mdDoc "User account under which FoundationDB runs.";
     };
 
     group = mkOption {
       type        = types.str;
       default     = "foundationdb";
-      description = "Group account under which FoundationDB runs.";
+      description = lib.mdDoc "Group account under which FoundationDB runs.";
     };
 
     class = mkOption {
       type        = types.nullOr (types.enum [ "storage" "transaction" "stateless" ]);
       default     = null;
-      description = "Process class";
+      description = lib.mdDoc "Process class";
     };
 
     restartDelay = mkOption {
       type = types.int;
       default = 10;
-      description = "Number of seconds to wait before restarting servers.";
+      description = lib.mdDoc "Number of seconds to wait before restarting servers.";
     };
 
     logSize = mkOption {
       type        = types.str;
       default     = "10MiB";
-      description = ''
+      description = lib.mdDoc ''
         Roll over to a new log file after the current log file
         reaches the specified size.
       '';
@@ -151,7 +151,7 @@ in
     maxLogSize = mkOption {
       type        = types.str;
       default     = "100MiB";
-      description = ''
+      description = lib.mdDoc ''
         Delete the oldest log file when the total size of all log
         files exceeds the specified size. If set to 0, old log files
         will not be deleted.
@@ -161,33 +161,33 @@ in
     serverProcesses = mkOption {
       type = types.int;
       default = 1;
-      description = "Number of fdbserver processes to run.";
+      description = lib.mdDoc "Number of fdbserver processes to run.";
     };
 
     backupProcesses = mkOption {
       type = types.int;
       default = 1;
-      description = "Number of backup_agent processes to run for snapshots.";
+      description = lib.mdDoc "Number of backup_agent processes to run for snapshots.";
     };
 
     memory = mkOption {
       type        = types.str;
       default     = "8GiB";
-      description = ''
+      description = lib.mdDoc ''
         Maximum memory used by the process. The default value is
-        <literal>8GiB</literal>. When specified without a unit,
-        <literal>MiB</literal> is assumed. This parameter does not
+        `8GiB`. When specified without a unit,
+        `MiB` is assumed. This parameter does not
         change the memory allocation of the program. Rather, it sets
         a hard limit beyond which the process will kill itself and
-        be restarted. The default value of <literal>8GiB</literal>
+        be restarted. The default value of `8GiB`
         is double the intended memory usage in the default
         configuration (providing an emergency buffer to deal with
         memory leaks or similar problems). It is not recommended to
         decrease the value of this parameter below its default
         value. It may be increased if you wish to allocate a very
         large amount of storage engine memory or cache. In
-        particular, when the <literal>storageMemory</literal>
-        parameter is increased, the <literal>memory</literal>
+        particular, when the `storageMemory`
+        parameter is increased, the `memory`
         parameter should be increased by an equal amount.
       '';
     };
@@ -195,22 +195,22 @@ in
     storageMemory = mkOption {
       type        = types.str;
       default     = "1GiB";
-      description = ''
+      description = lib.mdDoc ''
         Maximum memory used for data storage. The default value is
-        <literal>1GiB</literal>. When specified without a unit,
-        <literal>MB</literal> is assumed. Clusters using the memory
+        `1GiB`. When specified without a unit,
+        `MB` is assumed. Clusters using the memory
         storage engine will be restricted to using this amount of
         memory per process for purposes of data storage. Memory
         overhead associated with storing the data is counted against
         this total. If you increase the
-        <literal>storageMemory</literal>, you should also increase
-        the <literal>memory</literal> parameter by the same amount.
+        `storageMemory`, you should also increase
+        the `memory` parameter by the same amount.
       '';
     };
 
     tls = mkOption {
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         FoundationDB Transport Security Layer (TLS) settings.
       '';
 
@@ -218,7 +218,7 @@ in
         options = {
           certificate = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               Path to the TLS certificate file. This certificate will
               be offered to, and may be verified by, clients.
             '';
@@ -226,13 +226,13 @@ in
 
           key = mkOption {
             type = types.str;
-            description = "Private key file for the certificate.";
+            description = lib.mdDoc "Private key file for the certificate.";
           };
 
           allowedPeers = mkOption {
             type = types.str;
             default = "Check.Valid=1,Check.Unexpired=1";
-            description = ''
+            description = lib.mdDoc ''
               "Peer verification string". This may be used to adjust which TLS
               client certificates a server will accept, as a form of user
               authorization; for example, it may only accept TLS clients who
@@ -253,7 +253,7 @@ in
         dataHall     = null;
       };
 
-      description = ''
+      description = lib.mdDoc ''
         FoundationDB locality settings.
       '';
 
@@ -262,7 +262,7 @@ in
           machineId = mkOption {
             default = null;
             type = types.nullOr types.str;
-            description = ''
+            description = lib.mdDoc ''
               Machine identifier key. All processes on a machine should share a
               unique id. By default, processes on a machine determine a unique id to share.
               This does not generally need to be set.
@@ -272,7 +272,7 @@ in
           zoneId = mkOption {
             default = null;
             type = types.nullOr types.str;
-            description = ''
+            description = lib.mdDoc ''
               Zone identifier key. Processes that share a zone id are
               considered non-unique for the purposes of data replication.
               If unset, defaults to machine id.
@@ -282,7 +282,7 @@ in
           datacenterId = mkOption {
             default = null;
             type = types.nullOr types.str;
-            description = ''
+            description = lib.mdDoc ''
               Data center identifier key. All processes physically located in a
               data center should share the id. If you are depending on data
               center based replication this must be set on all processes.
@@ -292,7 +292,7 @@ in
           dataHall = mkOption {
             default = null;
             type = types.nullOr types.str;
-            description = ''
+            description = lib.mdDoc ''
               Data hall identifier key. All processes physically located in a
               data hall should share the id. If you are depending on data
               hall based replication this must be set on all processes.
@@ -305,7 +305,7 @@ in
     extraReadWritePaths = mkOption {
       default = [ ];
       type = types.listOf types.path;
-      description = ''
+      description = lib.mdDoc ''
         An extra set of filesystem paths that FoundationDB can read to
         and write from. By default, FoundationDB runs under a heavily
         namespaced systemd environment without write access to most of
@@ -319,13 +319,13 @@ in
     pidfile = mkOption {
       type        = types.path;
       default     = "/run/foundationdb.pid";
-      description = "Path to pidfile for fdbmonitor.";
+      description = lib.mdDoc "Path to pidfile for fdbmonitor.";
     };
 
     traceFormat = mkOption {
       type = types.enum [ "xml" "json" ];
       default = "xml";
-      description = "Trace logging format.";
+      description = lib.mdDoc "Trace logging format.";
     };
   };
 
diff --git a/nixos/modules/services/databases/hbase.nix b/nixos/modules/services/databases/hbase-standalone.nix
index fe4f05eec64..1ee73ec8d1f 100644
--- a/nixos/modules/services/databases/hbase.nix
+++ b/nixos/modules/services/databases/hbase-standalone.nix
@@ -3,8 +3,8 @@
 with lib;
 
 let
-  cfg = config.services.hbase;
-  opt = options.services.hbase;
+  cfg = config.services.hbase-standalone;
+  opt = options.services.hbase-standalone;
 
   buildProperty = configAttr:
     (builtins.concatStringsSep "\n"
@@ -32,25 +32,25 @@ let
 
 in {
 
+  imports = [
+    (mkRenamedOptionModule [ "services" "hbase" ] [ "services" "hbase-standalone" ])
+  ];
+
   ###### interface
 
   options = {
+    services.hbase-standalone = {
 
-    services.hbase = {
-
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Whether to run HBase.
-        '';
-      };
+      enable = mkEnableOption (lib.mdDoc ''
+        HBase master in standalone mode with embedded regionserver and zookeper.
+        Do not use this configuration for production nor for evaluating HBase performance.
+      '');
 
       package = mkOption {
         type = types.package;
         default = pkgs.hbase;
         defaultText = literalExpression "pkgs.hbase";
-        description = ''
+        description = lib.mdDoc ''
           HBase package to use.
         '';
       };
@@ -59,7 +59,7 @@ in {
       user = mkOption {
         type = types.str;
         default = "hbase";
-        description = ''
+        description = lib.mdDoc ''
           User account under which HBase runs.
         '';
       };
@@ -67,7 +67,7 @@ in {
       group = mkOption {
         type = types.str;
         default = "hbase";
-        description = ''
+        description = lib.mdDoc ''
           Group account under which HBase runs.
         '';
       };
@@ -75,7 +75,7 @@ in {
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/hbase";
-        description = ''
+        description = lib.mdDoc ''
           Specifies location of HBase database files. This location should be
           writable and readable for the user the HBase service runs as
           (hbase by default).
@@ -85,7 +85,7 @@ in {
       logDir = mkOption {
         type = types.path;
         default = "/var/log/hbase";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the location of HBase log files.
         '';
       };
@@ -102,18 +102,17 @@ in {
             "hbase.zookeeper.property.dataDir" = "''${config.${opt.dataDir}}/zookeeper";
           }
         '';
-        description = ''
-          configurations in hbase-site.xml, see <link xlink:href="https://github.com/apache/hbase/blob/master/hbase-server/src/test/resources/hbase-site.xml"/> for details.
+        description = lib.mdDoc ''
+          configurations in hbase-site.xml, see <https://github.com/apache/hbase/blob/master/hbase-server/src/test/resources/hbase-site.xml> for details.
         '';
       };
 
     };
-
   };
 
   ###### implementation
 
-  config = mkIf config.services.hbase.enable {
+  config = mkIf cfg.enable {
 
     systemd.tmpfiles.rules = [
       "d '${cfg.dataDir}' - ${cfg.user} ${cfg.group} - -"
diff --git a/nixos/modules/services/databases/influxdb.nix b/nixos/modules/services/databases/influxdb.nix
index f7383b2023a..b3361d2014c 100644
--- a/nixos/modules/services/databases/influxdb.nix
+++ b/nixos/modules/services/databases/influxdb.nix
@@ -96,10 +96,8 @@ let
     };
   } cfg.extraConfig;
 
-  configFile = pkgs.runCommandLocal "config.toml" {
-    nativeBuildInputs = [ pkgs.remarshal ];
-  } ''
-    remarshal -if json -of toml \
+  configFile = pkgs.runCommandLocal "config.toml" { } ''
+    ${pkgs.buildPackages.remarshal}/bin/remarshal -if json -of toml \
       < ${pkgs.writeText "config.json" (builtins.toJSON configOptions)} \
       > $out
   '';
@@ -114,38 +112,38 @@ in
 
       enable = mkOption {
         default = false;
-        description = "Whether to enable the influxdb server";
+        description = lib.mdDoc "Whether to enable the influxdb server";
         type = types.bool;
       };
 
       package = mkOption {
         default = pkgs.influxdb;
         defaultText = literalExpression "pkgs.influxdb";
-        description = "Which influxdb derivation to use";
+        description = lib.mdDoc "Which influxdb derivation to use";
         type = types.package;
       };
 
       user = mkOption {
         default = "influxdb";
-        description = "User account under which influxdb runs";
+        description = lib.mdDoc "User account under which influxdb runs";
         type = types.str;
       };
 
       group = mkOption {
         default = "influxdb";
-        description = "Group under which influxdb runs";
+        description = lib.mdDoc "Group under which influxdb runs";
         type = types.str;
       };
 
       dataDir = mkOption {
         default = "/var/db/influxdb";
-        description = "Data directory for influxd data files.";
+        description = lib.mdDoc "Data directory for influxd data files.";
         type = types.path;
       };
 
       extraConfig = mkOption {
         default = {};
-        description = "Extra configuration options for influxdb";
+        description = lib.mdDoc "Extra configuration options for influxdb";
         type = types.attrs;
       };
     };
diff --git a/nixos/modules/services/databases/influxdb2.nix b/nixos/modules/services/databases/influxdb2.nix
index 340c515bbb4..e74de66ddc2 100644
--- a/nixos/modules/services/databases/influxdb2.nix
+++ b/nixos/modules/services/databases/influxdb2.nix
@@ -10,18 +10,18 @@ in
 {
   options = {
     services.influxdb2 = {
-      enable = mkEnableOption "the influxdb2 server";
+      enable = mkEnableOption (lib.mdDoc "the influxdb2 server");
 
       package = mkOption {
         default = pkgs.influxdb2-server;
         defaultText = literalExpression "pkgs.influxdb2";
-        description = "influxdb2 derivation to use.";
+        description = lib.mdDoc "influxdb2 derivation to use.";
         type = types.package;
       };
 
       settings = mkOption {
         default = { };
-        description = ''configuration options for influxdb2, see <link xlink:href="https://docs.influxdata.com/influxdb/v2.0/reference/config-options"/> for details.'';
+        description = lib.mdDoc ''configuration options for influxdb2, see <https://docs.influxdata.com/influxdb/v2.0/reference/config-options> for details.'';
         type = format.type;
       };
     };
@@ -40,6 +40,7 @@ in
       after = [ "network.target" ];
       environment = {
         INFLUXD_CONFIG_PATH = configFile;
+        ZONEINFO = "${pkgs.tzdata}/share/zoneinfo";
       };
       serviceConfig = {
         ExecStart = "${cfg.package}/bin/influxd --bolt-path \${STATE_DIRECTORY}/influxd.bolt --engine-path \${STATE_DIRECTORY}/engine";
diff --git a/nixos/modules/services/databases/memcached.nix b/nixos/modules/services/databases/memcached.nix
index 1c06937e2f3..542c80ab2e6 100644
--- a/nixos/modules/services/databases/memcached.nix
+++ b/nixos/modules/services/databases/memcached.nix
@@ -17,44 +17,44 @@ in
   options = {
 
     services.memcached = {
-      enable = mkEnableOption "Memcached";
+      enable = mkEnableOption (lib.mdDoc "Memcached");
 
       user = mkOption {
         type = types.str;
         default = "memcached";
-        description = "The user to run Memcached as";
+        description = lib.mdDoc "The user to run Memcached as";
       };
 
       listen = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "The IP address to bind to.";
+        description = lib.mdDoc "The IP address to bind to.";
       };
 
       port = mkOption {
         type = types.port;
         default = 11211;
-        description = "The port to bind to.";
+        description = lib.mdDoc "The port to bind to.";
       };
 
-      enableUnixSocket = mkEnableOption "unix socket at /run/memcached/memcached.sock";
+      enableUnixSocket = mkEnableOption (lib.mdDoc "unix socket at /run/memcached/memcached.sock");
 
       maxMemory = mkOption {
         type = types.ints.unsigned;
         default = 64;
-        description = "The maximum amount of memory to use for storage, in megabytes.";
+        description = lib.mdDoc "The maximum amount of memory to use for storage, in megabytes.";
       };
 
       maxConnections = mkOption {
         type = types.ints.unsigned;
         default = 1024;
-        description = "The maximum number of simultaneous connections.";
+        description = lib.mdDoc "The maximum number of simultaneous connections.";
       };
 
       extraOptions = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "A list of extra options that will be added as a suffix when running memcached.";
+        description = lib.mdDoc "A list of extra options that will be added as a suffix when running memcached.";
       };
     };
 
diff --git a/nixos/modules/services/databases/monetdb.nix b/nixos/modules/services/databases/monetdb.nix
index 52a2ef041f8..5573b530a91 100644
--- a/nixos/modules/services/databases/monetdb.nix
+++ b/nixos/modules/services/databases/monetdb.nix
@@ -12,44 +12,44 @@ in {
   options = {
     services.monetdb = {
 
-      enable = mkEnableOption "the MonetDB database server";
+      enable = mkEnableOption (lib.mdDoc "the MonetDB database server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.monetdb;
         defaultText = literalExpression "pkgs.monetdb";
-        description = "MonetDB package to use.";
+        description = lib.mdDoc "MonetDB package to use.";
       };
 
       user = mkOption {
         type = types.str;
         default = "monetdb";
-        description = "User account under which MonetDB runs.";
+        description = lib.mdDoc "User account under which MonetDB runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "monetdb";
-        description = "Group under which MonetDB runs.";
+        description = lib.mdDoc "Group under which MonetDB runs.";
       };
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/monetdb";
-        description = "Data directory for the dbfarm.";
+        description = lib.mdDoc "Data directory for the dbfarm.";
       };
 
       port = mkOption {
         type = types.ints.u16;
         default = 50000;
-        description = "Port to listen on.";
+        description = lib.mdDoc "Port to listen on.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
         example = "0.0.0.0";
-        description = "Address to listen on.";
+        description = lib.mdDoc "Address to listen on.";
       };
     };
   };
diff --git a/nixos/modules/services/databases/mongodb.nix b/nixos/modules/services/databases/mongodb.nix
index fccf85d482e..211133de63f 100644
--- a/nixos/modules/services/databases/mongodb.nix
+++ b/nixos/modules/services/databases/mongodb.nix
@@ -29,63 +29,63 @@ in
 
     services.mongodb = {
 
-      enable = mkEnableOption "the MongoDB server";
+      enable = mkEnableOption (lib.mdDoc "the MongoDB server");
 
       package = mkOption {
         default = pkgs.mongodb;
         defaultText = literalExpression "pkgs.mongodb";
         type = types.package;
-        description = "
+        description = lib.mdDoc ''
           Which MongoDB derivation to use.
-        ";
+        '';
       };
 
       user = mkOption {
         type = types.str;
         default = "mongodb";
-        description = "User account under which MongoDB runs";
+        description = lib.mdDoc "User account under which MongoDB runs";
       };
 
       bind_ip = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "IP to bind to";
+        description = lib.mdDoc "IP to bind to";
       };
 
       quiet = mkOption {
         type = types.bool;
         default = false;
-        description = "quieter output";
+        description = lib.mdDoc "quieter output";
       };
 
       enableAuth = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable client authentication. Creates a default superuser with username root!";
+        description = lib.mdDoc "Enable client authentication. Creates a default superuser with username root!";
       };
 
       initialRootPassword = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "Password for the root user if auth is enabled.";
+        description = lib.mdDoc "Password for the root user if auth is enabled.";
       };
 
       dbpath = mkOption {
         type = types.str;
         default = "/var/db/mongodb";
-        description = "Location where MongoDB stores its files";
+        description = lib.mdDoc "Location where MongoDB stores its files";
       };
 
       pidFile = mkOption {
         type = types.str;
         default = "/run/mongodb.pid";
-        description = "Location of MongoDB pid file";
+        description = lib.mdDoc "Location of MongoDB pid file";
       };
 
       replSetName = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           If this instance is part of a replica set, set its name here.
           Otherwise, leave empty to run as single node.
         '';
@@ -97,13 +97,13 @@ in
         example = ''
           storage.journal.enabled: false
         '';
-        description = "MongoDB extra configuration in YAML format";
+        description = lib.mdDoc "MongoDB extra configuration in YAML format";
       };
 
       initialScript = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A file containing MongoDB statements to execute on first startup.
         '';
       };
diff --git a/nixos/modules/services/databases/mysql.nix b/nixos/modules/services/databases/mysql.nix
index 625b31d081c..ec4524e9061 100644
--- a/nixos/modules/services/databases/mysql.nix
+++ b/nixos/modules/services/databases/mysql.nix
@@ -31,54 +31,54 @@ in
 
     services.mysql = {
 
-      enable = mkEnableOption "MySQL server";
+      enable = mkEnableOption (lib.mdDoc "MySQL server");
 
       package = mkOption {
         type = types.package;
         example = literalExpression "pkgs.mariadb";
-        description = "
+        description = lib.mdDoc ''
           Which MySQL derivation to use. MariaDB packages are supported too.
-        ";
+        '';
       };
 
       user = mkOption {
         type = types.str;
         default = "mysql";
-        description = ''
+        description = lib.mdDoc ''
           User account under which MySQL runs.
 
-          <note><para>
+          ::: {.note}
           If left as the default value this user will automatically be created
           on system activation, otherwise you are responsible for
           ensuring the user exists before the MySQL service starts.
-          </para></note>
+          :::
         '';
       };
 
       group = mkOption {
         type = types.str;
         default = "mysql";
-        description = ''
+        description = lib.mdDoc ''
           Group account under which MySQL runs.
 
-          <note><para>
+          ::: {.note}
           If left as the default value this group will automatically be created
           on system activation, otherwise you are responsible for
           ensuring the user exists before the MySQL service starts.
-          </para></note>
+          :::
         '';
       };
 
       dataDir = mkOption {
         type = types.path;
         example = "/var/lib/mysql";
-        description = ''
+        description = lib.mdDoc ''
           The data directory for MySQL.
 
-          <note><para>
-          If left as the default value of <literal>/var/lib/mysql</literal> this directory will automatically be created before the MySQL
+          ::: {.note}
+          If left as the default value of `/var/lib/mysql` this directory will automatically be created before the MySQL
           server starts, otherwise you are responsible for ensuring the directory exists with appropriate ownership and permissions.
-          </para></note>
+          :::
         '';
       };
 
@@ -88,9 +88,9 @@ in
         defaultText = ''
           A configuration file automatically generated by NixOS.
         '';
-        description = ''
+        description = lib.mdDoc ''
           Override the configuration file used by MySQL. By default,
-          NixOS generates one automatically from <option>services.mysql.settings</option>.
+          NixOS generates one automatically from {option}`services.mysql.settings`.
         '';
         example = literalExpression ''
           pkgs.writeText "my.cnf" '''
@@ -107,20 +107,18 @@ in
       settings = mkOption {
         type = format.type;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           MySQL configuration. Refer to
-          <link xlink:href="https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html"/>,
-          <link xlink:href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html"/>,
-          and <link xlink:href="https://mariadb.com/kb/en/server-system-variables/"/>
+          <https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html>,
+          <https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html>,
+          and <https://mariadb.com/kb/en/server-system-variables/>
           for details on supported values.
 
-          <note>
-            <para>
-              MySQL configuration options such as <literal>--quick</literal> should be treated as
-              boolean options and provided values such as <literal>true</literal>, <literal>false</literal>,
-              <literal>1</literal>, or <literal>0</literal>. See the provided example below.
-            </para>
-          </note>
+          ::: {.note}
+          MySQL configuration options such as `--quick` should be treated as
+          boolean options and provided values such as `true`, `false`,
+          `1`, or `0`. See the provided example below.
+          :::
         '';
         example = literalExpression ''
           {
@@ -143,14 +141,14 @@ in
           options = {
             name = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The name of the database to create.
               '';
             };
             schema = mkOption {
               type = types.nullOr types.path;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The initial schema of the database; if null (the default),
                 an empty database is created.
               '';
@@ -158,7 +156,7 @@ in
           };
         });
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of database names and their initial schemas that should be used to create databases on the first startup
           of MySQL. The schema attribute is optional: If not specified, an empty database is created.
         '';
@@ -171,13 +169,13 @@ in
       initialScript = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "A file containing SQL statements to be executed on the first startup. Can be used for granting certain permissions on the database.";
+        description = lib.mdDoc "A file containing SQL statements to be executed on the first startup. Can be used for granting certain permissions on the database.";
       };
 
       ensureDatabases = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Ensures that the specified databases exist.
           This option will never delete existing databases, especially not when the value of this
           option is changed. This means that databases created once through this option or
@@ -194,14 +192,14 @@ in
           options = {
             name = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Name of the user to ensure.
               '';
             };
             ensurePermissions = mkOption {
               type = types.attrsOf types.str;
               default = {};
-              description = ''
+              description = lib.mdDoc ''
                 Permissions to ensure for the user, specified as attribute set.
                 The attribute names specify the database and tables to grant the permissions for,
                 separated by a dot. You may use wildcards here.
@@ -210,8 +208,8 @@ in
 
                 For more information on how to specify the target
                 and on which privileges exist, see the
-                <link xlink:href="https://mariadb.com/kb/en/library/grant/">GRANT syntax</link>.
-                The attributes are used as <code>GRANT ''${attrName} ON ''${attrValue}</code>.
+                [GRANT syntax](https://mariadb.com/kb/en/library/grant/).
+                The attributes are used as `GRANT ''${attrName} ON ''${attrValue}`.
               '';
               example = literalExpression ''
                 {
@@ -223,7 +221,7 @@ in
           };
         });
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Ensures that the specified users exist and have at least the ensured permissions.
           The MySQL users will be identified using Unix socket authentication. This authenticates the Unix user with the
           same name only, and that without the need for a password.
@@ -253,39 +251,39 @@ in
         role = mkOption {
           type = types.enum [ "master" "slave" "none" ];
           default = "none";
-          description = "Role of the MySQL server instance.";
+          description = lib.mdDoc "Role of the MySQL server instance.";
         };
 
         serverId = mkOption {
           type = types.int;
           default = 1;
-          description = "Id of the MySQL server instance. This number must be unique for each instance.";
+          description = lib.mdDoc "Id of the MySQL server instance. This number must be unique for each instance.";
         };
 
         masterHost = mkOption {
           type = types.str;
-          description = "Hostname of the MySQL master server.";
+          description = lib.mdDoc "Hostname of the MySQL master server.";
         };
 
         slaveHost = mkOption {
           type = types.str;
-          description = "Hostname of the MySQL slave server.";
+          description = lib.mdDoc "Hostname of the MySQL slave server.";
         };
 
         masterUser = mkOption {
           type = types.str;
-          description = "Username of the MySQL replication user.";
+          description = lib.mdDoc "Username of the MySQL replication user.";
         };
 
         masterPassword = mkOption {
           type = types.str;
-          description = "Password of the MySQL replication user.";
+          description = lib.mdDoc "Password of the MySQL replication user.";
         };
 
         masterPort = mkOption {
           type = types.port;
           default = 3306;
-          description = "Port number on which the MySQL master server runs.";
+          description = lib.mdDoc "Port number on which the MySQL master server runs.";
         };
       };
     };
diff --git a/nixos/modules/services/databases/neo4j.nix b/nixos/modules/services/databases/neo4j.nix
index 8816f3b2e4b..d78ff8390e4 100644
--- a/nixos/modules/services/databases/neo4j.nix
+++ b/nixos/modules/services/databases/neo4j.nix
@@ -36,48 +36,43 @@ let
   serverConfig = pkgs.writeText "neo4j.conf" ''
     # General
     dbms.allow_upgrade=${boolToString cfg.allowUpgrade}
-    dbms.connectors.default_listen_address=${cfg.defaultListenAddress}
-    dbms.read_only=${boolToString cfg.readOnly}
+    dbms.default_listen_address=${cfg.defaultListenAddress}
+    dbms.databases.default_to_read_only=${boolToString cfg.readOnly}
     ${optionalString (cfg.workerCount > 0) ''
       dbms.threads.worker_count=${toString cfg.workerCount}
     ''}
 
-    # Directories
+    # Directories (readonly)
     dbms.directories.certificates=${cfg.directories.certificates}
-    dbms.directories.data=${cfg.directories.data}
-    dbms.directories.logs=${cfg.directories.home}/logs
     dbms.directories.plugins=${cfg.directories.plugins}
+    dbms.directories.lib=${cfg.package}/share/neo4j/lib
     ${optionalString (cfg.constrainLoadCsv) ''
       dbms.directories.import=${cfg.directories.imports}
-    ''}
+   ''}
+
+    # Directories (read and write)
+    dbms.directories.data=${cfg.directories.data}
+    dbms.directories.logs=${cfg.directories.home}/logs
+    dbms.directories.run=${cfg.directories.home}/run
 
     # HTTP Connector
     ${optionalString (cfg.http.enable) ''
       dbms.connector.http.enabled=${boolToString cfg.http.enable}
       dbms.connector.http.listen_address=${cfg.http.listenAddress}
-    ''}
-    ${optionalString (!cfg.http.enable) ''
-      # It is not possible to disable the HTTP connector. To fully prevent
-      # clients from connecting to HTTP, block the HTTP port (7474 by default)
-      # via firewall. listen_address is set to the loopback interface to
-      # prevent remote clients from connecting.
-      dbms.connector.http.listen_address=127.0.0.1
+      dbms.connector.http.advertised_address=${cfg.http.listenAddress}
     ''}
 
     # HTTPS Connector
     dbms.connector.https.enabled=${boolToString cfg.https.enable}
     dbms.connector.https.listen_address=${cfg.https.listenAddress}
-    https.ssl_policy=${cfg.https.sslPolicy}
+    dbms.connector.https.advertised_address=${cfg.https.listenAddress}
 
     # BOLT Connector
     dbms.connector.bolt.enabled=${boolToString cfg.bolt.enable}
     dbms.connector.bolt.listen_address=${cfg.bolt.listenAddress}
-    bolt.ssl_policy=${cfg.bolt.sslPolicy}
+    dbms.connector.bolt.advertised_address=${cfg.bolt.listenAddress}
     dbms.connector.bolt.tls_level=${cfg.bolt.tlsLevel}
 
-    # neo4j-shell
-    dbms.shell.enabled=${boolToString cfg.shell.enable}
-
     # SSL Policies
     ${concatStringsSep "\n" sslPolicies}
 
@@ -95,8 +90,10 @@ let
     dbms.jvm.additional=-Djdk.tls.rejectClientInitiatedRenegotiation=true
     dbms.jvm.additional=-Dunsupported.dbms.udc.source=tarball
 
-    # Usage Data Collector
-    dbms.udc.enabled=${boolToString cfg.udc.enable}
+    #dbms.memory.heap.initial_size=12000m
+    #dbms.memory.heap.max_size=12000m
+    #dbms.memory.pagecache.size=4g
+    #dbms.tx_state.max_off_heap_memory=8000m
 
     # Extra Configuration
     ${cfg.extraServerConfig}
@@ -114,6 +111,8 @@ in {
     (mkRemovedOptionModule [ "services" "neo4j" "port" ] "Use services.neo4j.http.listenAddress instead.")
     (mkRemovedOptionModule [ "services" "neo4j" "boltPort" ] "Use services.neo4j.bolt.listenAddress instead.")
     (mkRemovedOptionModule [ "services" "neo4j" "httpsPort" ] "Use services.neo4j.https.listenAddress instead.")
+    (mkRemovedOptionModule [ "services" "neo4j" "shell" "enabled" ] "shell.enabled was removed upstream")
+    (mkRemovedOptionModule [ "services" "neo4j" "udc" "enabled" ] "udc.enabled was removed upstream")
   ];
 
   ###### interface
@@ -123,7 +122,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable Neo4j Community Edition.
       '';
     };
@@ -131,7 +130,7 @@ in {
     allowUpgrade = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Allow upgrade of Neo4j database files from an older version.
       '';
     };
@@ -139,15 +138,14 @@ in {
     constrainLoadCsv = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Sets the root directory for file URLs used with the Cypher
-        <literal>LOAD CSV</literal> clause to be that defined by
-        <option>directories.imports</option>. It restricts
+        `LOAD CSV` clause to be that defined by
+        {option}`directories.imports`. It restricts
         access to only those files within that directory and its
         subdirectories.
-        </para>
-        <para>
-        Setting this option to <literal>false</literal> introduces
+
+        Setting this option to `false` introduces
         possible security problems.
       '';
     };
@@ -155,24 +153,23 @@ in {
     defaultListenAddress = mkOption {
       type = types.str;
       default = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         Default network interface to listen for incoming connections. To
         listen for connections on all interfaces, use "0.0.0.0".
-        </para>
-        <para>
+
         Specifies the default IP address and address part of connector
-        specific <option>listenAddress</option> options. To bind specific
+        specific {option}`listenAddress` options. To bind specific
         connectors to a specific network interfaces, specify the entire
-        <option>listenAddress</option> option for that connector.
+        {option}`listenAddress` option for that connector.
       '';
     };
 
     extraServerConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra configuration for Neo4j Community server. Refer to the
-        <link xlink:href="https://neo4j.com/docs/operations-manual/current/reference/configuration-settings/">complete reference</link>
+        [complete reference](https://neo4j.com/docs/operations-manual/current/reference/configuration-settings/)
         of Neo4j configuration settings.
       '';
     };
@@ -181,7 +178,7 @@ in {
       type = types.package;
       default = pkgs.neo4j;
       defaultText = literalExpression "pkgs.neo4j";
-      description = ''
+      description = lib.mdDoc ''
         Neo4j package to use.
       '';
     };
@@ -189,7 +186,7 @@ in {
     readOnly = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Only allow read operations from this Neo4j instance.
       '';
     };
@@ -197,9 +194,9 @@ in {
     workerCount = mkOption {
       type = types.ints.between 0 44738;
       default = 0;
-      description = ''
+      description = lib.mdDoc ''
         Number of Neo4j worker threads, where the default of
-        <literal>0</literal> indicates a worker count equal to the number of
+        `0` indicates a worker count equal to the number of
         available processors.
       '';
     };
@@ -208,9 +205,9 @@ in {
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Enable the BOLT connector for Neo4j. Setting this option to
-          <literal>false</literal> will stop Neo4j from listening for incoming
+          `false` will stop Neo4j from listening for incoming
           connections on the BOLT port (7687 by default).
         '';
       };
@@ -218,36 +215,34 @@ in {
       listenAddress = mkOption {
         type = types.str;
         default = ":7687";
-        description = ''
+        description = lib.mdDoc ''
           Neo4j listen address for BOLT traffic. The listen address is
-          expressed in the format <literal>&lt;ip-address&gt;:&lt;port-number&gt;</literal>.
+          expressed in the format `<ip-address>:<port-number>`.
         '';
       };
 
       sslPolicy = mkOption {
         type = types.str;
         default = "legacy";
-        description = ''
+        description = lib.mdDoc ''
           Neo4j SSL policy for BOLT traffic.
-          </para>
-          <para>
+
           The legacy policy is a special policy which is not defined in
           the policy configuration section, but rather derives from
-          <option>directories.certificates</option> and
-          associated files (by default: <filename>neo4j.key</filename> and
-          <filename>neo4j.cert</filename>). Its use will be deprecated.
-          </para>
-          <para>
+          {option}`directories.certificates` and
+          associated files (by default: {file}`neo4j.key` and
+          {file}`neo4j.cert`). Its use will be deprecated.
+
           Note: This connector must be configured to support/require
           SSL/TLS for the legacy policy to actually be utilized. See
-          <option>bolt.tlsLevel</option>.
+          {option}`bolt.tlsLevel`.
         '';
       };
 
       tlsLevel = mkOption {
         type = types.enum [ "REQUIRED" "OPTIONAL" "DISABLED" ];
         default = "OPTIONAL";
-        description = ''
+        description = lib.mdDoc ''
           SSL/TSL requirement level for BOLT traffic.
         '';
       };
@@ -258,21 +253,19 @@ in {
         type = types.path;
         default = "${cfg.directories.home}/certificates";
         defaultText = literalExpression ''"''${config.${opt.directories.home}}/certificates"'';
-        description = ''
+        description = lib.mdDoc ''
           Directory for storing certificates to be used by Neo4j for
           TLS connections.
-          </para>
-          <para>
+
           When setting this directory to something other than its default,
           ensure the directory's existence, and that read/write permissions are
-          given to the Neo4j daemon user <literal>neo4j</literal>.
-          </para>
-          <para>
+          given to the Neo4j daemon user `neo4j`.
+
           Note that changing this directory from its default will prevent
           the directory structure required for each SSL policy from being
           automatically generated. A policy's directory structure as defined by
-          its <option>baseDirectory</option>,<option>revokedDir</option> and
-          <option>trustedDir</option> must then be setup manually. The
+          its {option}`baseDirectory`,{option}`revokedDir` and
+          {option}`trustedDir` must then be setup manually. The
           existence of these directories is mandatory, as well as the presence
           of the certificate file and the private key. Ensure the correct
           permissions are set on these directories and files.
@@ -283,25 +276,24 @@ in {
         type = types.path;
         default = "${cfg.directories.home}/data";
         defaultText = literalExpression ''"''${config.${opt.directories.home}}/data"'';
-        description = ''
+        description = lib.mdDoc ''
           Path of the data directory. You must not configure more than one
           Neo4j installation to use the same data directory.
-          </para>
-          <para>
+
           When setting this directory to something other than its default,
           ensure the directory's existence, and that read/write permissions are
-          given to the Neo4j daemon user <literal>neo4j</literal>.
+          given to the Neo4j daemon user `neo4j`.
         '';
       };
 
       home = mkOption {
         type = types.path;
         default = "/var/lib/neo4j";
-        description = ''
+        description = lib.mdDoc ''
           Path of the Neo4j home directory. Other default directories are
           subdirectories of this path. This directory will be created if
-          non-existent, and its ownership will be <command>chown</command> to
-          the Neo4j daemon user <literal>neo4j</literal>.
+          non-existent, and its ownership will be {command}`chown` to
+          the Neo4j daemon user `neo4j`.
         '';
       };
 
@@ -309,16 +301,15 @@ in {
         type = types.path;
         default = "${cfg.directories.home}/import";
         defaultText = literalExpression ''"''${config.${opt.directories.home}}/import"'';
-        description = ''
+        description = lib.mdDoc ''
           The root directory for file URLs used with the Cypher
-          <literal>LOAD CSV</literal> clause. Only meaningful when
-          <option>constrainLoadCvs</option> is set to
-          <literal>true</literal>.
-          </para>
-          <para>
+          `LOAD CSV` clause. Only meaningful when
+          {option}`constrainLoadCvs` is set to
+          `true`.
+
           When setting this directory to something other than its default,
           ensure the directory's existence, and that read permission is
-          given to the Neo4j daemon user <literal>neo4j</literal>.
+          given to the Neo4j daemon user `neo4j`.
         '';
       };
 
@@ -326,15 +317,14 @@ in {
         type = types.path;
         default = "${cfg.directories.home}/plugins";
         defaultText = literalExpression ''"''${config.${opt.directories.home}}/plugins"'';
-        description = ''
+        description = lib.mdDoc ''
           Path of the database plugin directory. Compiled Java JAR files that
           contain database procedures will be loaded if they are placed in
           this directory.
-          </para>
-          <para>
+
           When setting this directory to something other than its default,
           ensure the directory's existence, and that read permission is
-          given to the Neo4j daemon user <literal>neo4j</literal>.
+          given to the Neo4j daemon user `neo4j`.
         '';
       };
     };
@@ -343,22 +333,19 @@ in {
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
-          The HTTP connector is required for Neo4j, and cannot be disabled.
-          Setting this option to <literal>false</literal> will force the HTTP
-          connector's <option>listenAddress</option> to the loopback
-          interface to prevent connection of remote clients. To prevent all
-          clients from connecting, block the HTTP port (7474 by default) by
-          firewall.
+        description = lib.mdDoc ''
+          Enable the HTTP connector for Neo4j. Setting this option to
+          `false` will stop Neo4j from listening for incoming
+          connections on the HTTPS port (7474 by default).
         '';
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = ":7474";
-        description = ''
+        description = lib.mdDoc ''
           Neo4j listen address for HTTP traffic. The listen address is
-          expressed in the format <literal>&lt;ip-address&gt;:&lt;port-number&gt;</literal>.
+          expressed in the format `<ip-address>:<port-number>`.
         '';
       };
     };
@@ -367,9 +354,9 @@ in {
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Enable the HTTPS connector for Neo4j. Setting this option to
-          <literal>false</literal> will stop Neo4j from listening for incoming
+          `false` will stop Neo4j from listening for incoming
           connections on the HTTPS port (7473 by default).
         '';
       };
@@ -377,24 +364,23 @@ in {
       listenAddress = mkOption {
         type = types.str;
         default = ":7473";
-        description = ''
+        description = lib.mdDoc ''
           Neo4j listen address for HTTPS traffic. The listen address is
-          expressed in the format <literal>&lt;ip-address&gt;:&lt;port-number&gt;</literal>.
+          expressed in the format `<ip-address>:<port-number>`.
         '';
       };
 
       sslPolicy = mkOption {
         type = types.str;
         default = "legacy";
-        description = ''
+        description = lib.mdDoc ''
           Neo4j SSL policy for HTTPS traffic.
-          </para>
-          <para>
+
           The legacy policy is a special policy which is not defined in the
           policy configuration section, but rather derives from
-          <option>directories.certificates</option> and
-          associated files (by default: <filename>neo4j.key</filename> and
-          <filename>neo4j.cert</filename>). Its use will be deprecated.
+          {option}`directories.certificates` and
+          associated files (by default: {file}`neo4j.key` and
+          {file}`neo4j.cert`). Its use will be deprecated.
         '';
       };
     };
@@ -403,9 +389,9 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable a remote shell server which Neo4j Shell clients can log in to.
-          Only applicable to <command>neo4j-shell</command>.
+          Only applicable to {command}`neo4j-shell`.
         '';
       };
     };
@@ -417,18 +403,16 @@ in {
           allowKeyGeneration = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Allows the generation of a private key and associated self-signed
               certificate. Only performed when both objects cannot be found for
               this policy. It is recommended to turn this off again after keys
               have been generated.
-              </para>
-              <para>
+
               The public certificate is required to be duplicated to the
               directory holding trusted certificates as defined by the
-              <option>trustedDir</option> option.
-              </para>
-              <para>
+              {option}`trustedDir` option.
+
               Keys should in general be generated and distributed offline by a
               trusted certificate authority and not by utilizing this mode.
             '';
@@ -438,17 +422,16 @@ in {
             type = types.path;
             default = "${cfg.directories.certificates}/${name}";
             defaultText = literalExpression ''"''${config.${opt.directories.certificates}}/''${name}"'';
-            description = ''
+            description = lib.mdDoc ''
               The mandatory base directory for cryptographic objects of this
               policy. This path is only automatically generated when this
-              option as well as <option>directories.certificates</option> are
+              option as well as {option}`directories.certificates` are
               left at their default. Ensure read/write permissions are given
-              to the Neo4j daemon user <literal>neo4j</literal>.
-              </para>
-              <para>
+              to the Neo4j daemon user `neo4j`.
+
               It is also possible to override each individual
               configuration with absolute paths. See the
-              <option>privateKey</option> and <option>publicCertificate</option>
+              {option}`privateKey` and {option}`publicCertificate`
               policy options.
             '';
           };
@@ -456,7 +439,7 @@ in {
           ciphers = mkOption {
             type = types.nullOr (types.listOf types.str);
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Restrict the allowed ciphers of this policy to those defined
               here. The default ciphers are those of the JVM platform.
             '';
@@ -465,7 +448,7 @@ in {
           clientAuth = mkOption {
             type = types.enum [ "NONE" "OPTIONAL" "REQUIRE" ];
             default = "REQUIRE";
-            description = ''
+            description = lib.mdDoc ''
               The client authentication stance for this policy.
             '';
           };
@@ -473,9 +456,9 @@ in {
           privateKey = mkOption {
             type = types.str;
             default = "private.key";
-            description = ''
+            description = lib.mdDoc ''
               The name of private PKCS #8 key file for this policy to be found
-              in the <option>baseDirectory</option>, or the absolute path to
+              in the {option}`baseDirectory`, or the absolute path to
               the key file. It is mandatory that a key can be found or generated.
             '';
           };
@@ -483,16 +466,15 @@ in {
           publicCertificate = mkOption {
             type = types.str;
             default = "public.crt";
-            description = ''
+            description = lib.mdDoc ''
               The name of public X.509 certificate (chain) file in PEM format
-              for this policy to be found in the <option>baseDirectory</option>,
+              for this policy to be found in the {option}`baseDirectory`,
               or the absolute path to the certificate file. It is mandatory
               that a certificate can be found or generated.
-              </para>
-              <para>
+
               The public certificate is required to be duplicated to the
               directory holding trusted certificates as defined by the
-              <option>trustedDir</option> option.
+              {option}`trustedDir` option.
             '';
           };
 
@@ -500,22 +482,22 @@ in {
             type = types.path;
             default = "${config.baseDirectory}/revoked";
             defaultText = literalExpression ''"''${config.${options.baseDirectory}}/revoked"'';
-            description = ''
+            description = lib.mdDoc ''
               Path to directory of CRLs (Certificate Revocation Lists) in
               PEM format. Must be an absolute path. The existence of this
               directory is mandatory and will need to be created manually when:
               setting this option to something other than its default; setting
-              either this policy's <option>baseDirectory</option> or
-              <option>directories.certificates</option> to something other than
+              either this policy's {option}`baseDirectory` or
+              {option}`directories.certificates` to something other than
               their default. Ensure read/write permissions are given to the
-              Neo4j daemon user <literal>neo4j</literal>.
+              Neo4j daemon user `neo4j`.
             '';
           };
 
           tlsVersions = mkOption {
             type = types.listOf types.str;
             default = [ "TLSv1.2" ];
-            description = ''
+            description = lib.mdDoc ''
               Restrict the TLS protocol versions of this policy to those
               defined here.
             '';
@@ -524,7 +506,7 @@ in {
           trustAll = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Makes this policy trust all remote parties. Enabling this is not
               recommended and the policy's trusted directory will be ignored.
               Use of this mode is discouraged. It would offer encryption but
@@ -536,19 +518,18 @@ in {
             type = types.path;
             default = "${config.baseDirectory}/trusted";
             defaultText = literalExpression ''"''${config.${options.baseDirectory}}/trusted"'';
-            description = ''
+            description = lib.mdDoc ''
               Path to directory of X.509 certificates in PEM format for
               trusted parties. Must be an absolute path. The existence of this
               directory is mandatory and will need to be created manually when:
               setting this option to something other than its default; setting
-              either this policy's <option>baseDirectory</option> or
-              <option>directories.certificates</option> to something other than
+              either this policy's {option}`baseDirectory` or
+              {option}`directories.certificates` to something other than
               their default. Ensure read/write permissions are given to the
-              Neo4j daemon user <literal>neo4j</literal>.
-              </para>
-              <para>
+              Neo4j daemon user `neo4j`.
+
               The public certificate as defined by
-              <option>publicCertificate</option> is required to be duplicated
+              {option}`publicCertificate` is required to be duplicated
               to this directory.
             '';
           };
@@ -557,7 +538,7 @@ in {
             type = types.listOf types.path;
             internal = true;
             readOnly = true;
-            description = ''
+            description = lib.mdDoc ''
               Directories of this policy that will be created automatically
               when the certificates directory is left at its default value.
               This includes all options of type path that are left at their
@@ -573,29 +554,16 @@ in {
 
       }));
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         Defines the SSL policies for use with Neo4j connectors. Each attribute
         of this set defines a policy, with the attribute name defining the name
         of the policy and its namespace. Refer to the operations manual section
         on Neo4j's
-        <link xlink:href="https://neo4j.com/docs/operations-manual/current/security/ssl-framework/">SSL Framework</link>
+        [SSL Framework](https://neo4j.com/docs/operations-manual/current/security/ssl-framework/)
         for further details.
       '';
     };
 
-    udc = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Enable the Usage Data Collector which Neo4j uses to collect usage
-          data. Refer to the operations manual section on the
-          <link xlink:href="https://neo4j.com/docs/operations-manual/current/configuration/usage-data-collector/">Usage Data Collector</link>
-          for more information.
-        '';
-      };
-    };
-
   };
 
   ###### implementation
@@ -627,7 +595,7 @@ in {
         wantedBy = [ "multi-user.target" ];
         after = [ "network.target" ];
         environment = {
-          NEO4J_HOME = "${cfg.package}/share/neo4j";
+          NEO4J_HOME = "${cfg.directories.home}";
           NEO4J_CONF = "${cfg.directories.home}/conf";
         };
         serviceConfig = {
@@ -668,6 +636,6 @@ in {
     };
 
   meta = {
-    maintainers = with lib.maintainers; [ patternspandemic ];
+    maintainers = with lib.maintainers; [ patternspandemic jonringer erictapen ];
   };
 }
diff --git a/nixos/modules/services/databases/openldap.nix b/nixos/modules/services/databases/openldap.nix
index 2c1e25d4308..7a59de372f2 100644
--- a/nixos/modules/services/databases/openldap.nix
+++ b/nixos/modules/services/databases/openldap.nix
@@ -3,7 +3,6 @@
 with lib;
 let
   cfg = config.services.openldap;
-  legacyOptions = [ "rootpwFile" "suffix" "dataDir" "rootdn" "rootpw" ];
   openldap = cfg.package;
   configDir = if cfg.configDir != null then cfg.configDir else "/etc/openldap/slapd.d";
 
@@ -11,7 +10,15 @@ let
     # Can't do types.either with multiple non-overlapping submodules, so define our own
     singleLdapValueType = lib.mkOptionType rec {
       name = "LDAP";
-      description = "LDAP value";
+      # TODO: It would be nice to define a { secret = ...; } option, using
+      # systemd's LoadCredentials for secrets. That would remove the last
+      # barrier to using DynamicUser for openldap. This is blocked on
+      # systemd/systemd#19604
+      description = ''
+        LDAP value - either a string, or an attrset containing
+        <literal>path</literal> or <literal>base64</literal> for included
+        values or base-64 encoded values respectively.
+      '';
       check = x: lib.isString x || (lib.isAttrs x && (x ? path || x ? base64));
       merge = lib.mergeEqualOption;
     };
@@ -24,7 +31,7 @@ let
         attrs = mkOption {
           type = types.attrsOf ldapValueType;
           default = {};
-          description = "Attributes of the parent entry.";
+          description = lib.mdDoc "Attributes of the parent entry.";
         };
         children = mkOption {
           # Hide the child attributes, to avoid infinite recursion in e.g. documentation
@@ -33,7 +40,7 @@ let
             hiddenOptions = lib.mapAttrs (name: attr: attr // { visible = false; }) options;
           in types.attrsOf (types.submodule { options = hiddenOptions; });
           default = {};
-          description = "Child entries of the current entry, with recursively the same structure.";
+          description = lib.mdDoc "Child entries of the current entry, with recursively the same structure.";
           example = lib.literalExpression ''
             {
                 "cn=schema" = {
@@ -52,7 +59,7 @@ let
         includes = mkOption {
           type = types.listOf types.path;
           default = [];
-          description = ''
+          description = lib.mdDoc ''
             LDIF files to include after the parent's attributes but before its children.
           '';
         };
@@ -76,59 +83,19 @@ let
     lib.flatten (lib.mapAttrsToList (name: value: attrsToLdif "${name},${dn}" value) children)
   );
 in {
-  imports = let
-    deprecationNote = "This option is removed due to the deprecation of `slapd.conf` upstream. Please migrate to `services.openldap.settings`, see the release notes for advice with this process.";
-    mkDatabaseOption = old: new:
-      lib.mkChangedOptionModule [ "services" "openldap" old ] [ "services" "openldap" "settings" "children" ]
-        (config: let
-          database = lib.getAttrFromPath [ "services" "openldap" "database" ] config;
-          value = lib.getAttrFromPath [ "services" "openldap" old ] config;
-        in lib.setAttrByPath ([ "olcDatabase={1}${database}" "attrs" ] ++ new) value);
-  in [
-    (lib.mkRemovedOptionModule [ "services" "openldap" "extraConfig" ] deprecationNote)
-    (lib.mkRemovedOptionModule [ "services" "openldap" "extraDatabaseConfig" ] deprecationNote)
-
-    (lib.mkChangedOptionModule [ "services" "openldap" "logLevel" ] [ "services" "openldap" "settings" "attrs" "olcLogLevel" ]
-      (config: lib.splitString " " (lib.getAttrFromPath [ "services" "openldap" "logLevel" ] config)))
-    (lib.mkChangedOptionModule [ "services" "openldap" "defaultSchemas" ] [ "services" "openldap" "settings" "children" "cn=schema" "includes"]
-      (config: lib.optionals (lib.getAttrFromPath [ "services" "openldap" "defaultSchemas" ] config) (
-        map (schema: "${openldap}/etc/schema/${schema}.ldif") [ "core" "cosine" "inetorgperson" "nis" ])))
-
-    (lib.mkChangedOptionModule [ "services" "openldap" "database" ] [ "services" "openldap" "settings" "children" ]
-      (config: let
-        database = lib.getAttrFromPath [ "services" "openldap" "database" ] config;
-      in {
-        "olcDatabase={1}${database}".attrs = {
-          # objectClass is case-insensitive, so don't need to capitalize ${database}
-          objectClass = [ "olcdatabaseconfig" "olc${database}config" ];
-          olcDatabase = "{1}${database}";
-          olcDbDirectory = lib.mkDefault "/var/db/openldap";
-        };
-        "cn=schema".includes = lib.mkDefault (
-          map (schema: "${openldap}/etc/schema/${schema}.ldif") [ "core" "cosine" "inetorgperson" "nis" ]
-        );
-      }))
-    (mkDatabaseOption "rootpwFile" [ "olcRootPW" "path" ])
-    (mkDatabaseOption "suffix" [ "olcSuffix" ])
-    (mkDatabaseOption "dataDir" [ "olcDbDirectory" ])
-    (mkDatabaseOption "rootdn" [ "olcRootDN" ])
-    (mkDatabaseOption "rootpw" [ "olcRootPW" ])
-  ];
   options = {
     services.openldap = {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "
-          Whether to enable the ldap server.
-        ";
+        description = lib.mdDoc "Whether to enable the ldap server.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.openldap;
         defaultText = literalExpression "pkgs.openldap";
-        description = ''
+        description = lib.mdDoc ''
           OpenLDAP package to use.
 
           This can be used to, for example, set an OpenLDAP package
@@ -140,25 +107,25 @@ in {
       user = mkOption {
         type = types.str;
         default = "openldap";
-        description = "User account under which slapd runs.";
+        description = lib.mdDoc "User account under which slapd runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "openldap";
-        description = "Group account under which slapd runs.";
+        description = lib.mdDoc "Group account under which slapd runs.";
       };
 
       urlList = mkOption {
         type = types.listOf types.str;
         default = [ "ldap:///" ];
-        description = "URL list slapd should listen on.";
+        description = lib.mdDoc "URL list slapd should listen on.";
         example = [ "ldaps:///" ];
       };
 
       settings = mkOption {
         type = ldapAttrsType;
-        description = "Configuration for OpenLDAP, in OLC format";
+        description = lib.mdDoc "Configuration for OpenLDAP, in OLC format";
         example = lib.literalExpression ''
           {
             attrs.olcLogLevel = [ "stats" ];
@@ -186,7 +153,7 @@ in {
                 attrs = {
                   objectClass = [ "olcDatabaseConfig" "olcMdbConfig" ];
                   olcDatabase = "{1}mdb";
-                  olcDbDirectory = "/var/db/ldap";
+                  olcDbDirectory = "/var/lib/openldap/ldap";
                   olcDbIndex = [
                     "objectClass eq"
                     "cn pres,eq"
@@ -206,18 +173,28 @@ in {
       configDir = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Use this config directory instead of generating one from the
-          <literal>settings</literal> option. Overrides all NixOS settings. If
-          you use this option,ensure `olcPidFile` is set to `/run/slapd/slapd.conf`.
+          `settings` option. Overrides all NixOS settings.
+        '';
+        example = "/var/lib/openldap/slapd.d";
+      };
+
+      mutableConfig = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to allow writable on-line configuration. If
+          `true`, the NixOS settings will only be used to
+          initialize the OpenLDAP configuration if it does not exist, and are
+          subsequently ignored.
         '';
-        example = "/var/db/slapd.d";
       };
 
       declarativeContents = mkOption {
         type = with types; attrsOf lines;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Declarative contents for the LDAP database, in LDIF format by suffix.
 
           All data will be erased when starting the LDAP server. Modifications
@@ -225,6 +202,11 @@ in {
           reboot of the server. Performance-wise the database and indexes are
           rebuilt on each server startup, so this will slow down server startup,
           especially with large databases.
+
+          Note that the root of the DB must be defined in
+          `services.openldap.settings` and the
+          `olcDbDirectory` must begin with
+          `"/var/lib/openldap"`.
         '';
         example = lib.literalExpression ''
           {
@@ -245,13 +227,56 @@ in {
     };
   };
 
-  meta.maintainers = with lib.maintainers; [ mic92 kwohlfahrt ];
+  meta.maintainers = with lib.maintainers; [ kwohlfahrt ];
+
+  config = let
+    dbSettings = mapAttrs' (name: { attrs, ... }: nameValuePair attrs.olcSuffix attrs)
+      (filterAttrs (name: { attrs, ... }: (hasPrefix "olcDatabase=" name) && attrs ? olcSuffix) cfg.settings.children);
+    settingsFile = pkgs.writeText "config.ldif" (lib.concatStringsSep "\n" (attrsToLdif "cn=config" cfg.settings));
+    writeConfig = pkgs.writeShellScript "openldap-config" ''
+      set -euo pipefail
 
-  config = mkIf cfg.enable {
-    assertions = map (opt: {
-      assertion = ((getAttr opt cfg) != "_mkMergedOptionModule") -> (cfg.database != "_mkMergedOptionModule");
-      message = "Legacy OpenLDAP option `services.openldap.${opt}` requires `services.openldap.database` (use value \"mdb\" if unsure)";
-    }) legacyOptions;
+      ${lib.optionalString (!cfg.mutableConfig) ''
+        chmod -R u+w ${configDir}
+        rm -rf ${configDir}/*
+      ''}
+      if [ ! -e "${configDir}/cn=config.ldif" ]; then
+        ${openldap}/bin/slapadd -F ${configDir} -bcn=config -l ${settingsFile}
+      fi
+      chmod -R ${if cfg.mutableConfig then "u+rw" else "u+r-w"} ${configDir}
+    '';
+
+    contentsFiles = mapAttrs (dn: ldif: pkgs.writeText "${dn}.ldif" ldif) cfg.declarativeContents;
+    writeContents = pkgs.writeShellScript "openldap-load" ''
+      set -euo pipefail
+
+      rm -rf $2/*
+      ${openldap}/bin/slapadd -F ${configDir} -b $1 -l $3
+    '';
+  in mkIf cfg.enable {
+    assertions = [{
+      assertion = (cfg.declarativeContents != {}) -> cfg.configDir == null;
+      message = ''
+        Declarative DB contents (${attrNames cfg.declarativeContents}) are not
+        supported with user-managed configuration.
+      '';
+    }] ++ (map (dn: {
+      assertion = (getAttr dn dbSettings) ? "olcDbDirectory";
+      # olcDbDirectory is necessary to prepopulate database using `slapadd`.
+      message = ''
+        Declarative DB ${dn} does not exist in `services.openldap.settings`, or does not have
+        `olcDbDirectory` configured.
+      '';
+    }) (attrNames cfg.declarativeContents)) ++ (mapAttrsToList (dn: { olcDbDirectory ? null, ... }: {
+      # For forward compatibility with `DynamicUser`, and to avoid accidentally clobbering
+      # directories with `declarativeContents`.
+      assertion = (olcDbDirectory != null) ->
+      ((hasPrefix "/var/lib/openldap/" olcDbDirectory) && (olcDbDirectory != "/var/lib/openldap/"));
+      message = ''
+        Database ${dn} has `olcDbDirectory` (${olcDbDirectory}) that is not a subdirectory of
+        `/var/lib/openldap/`.
+      '';
+    }) dbSettings);
     environment.systemPackages = [ openldap ];
 
     # Literal attributes must always be set
@@ -259,7 +284,6 @@ in {
       attrs = {
         objectClass = "olcGlobal";
         cn = "config";
-        olcPidFile = "/run/slapd/slapd.pid";
       };
       children."cn=schema".attrs = {
         cn = "schema";
@@ -268,46 +292,39 @@ in {
     };
 
     systemd.services.openldap = {
-      description = "LDAP server";
+      description = "OpenLDAP Server Daemon";
+      documentation = [
+        "man:slapd"
+        "man:slapd-config"
+        "man:slapd-mdb"
+      ];
       wantedBy = [ "multi-user.target" ];
-      after = [ "network.target" ];
-      preStart = let
-        settingsFile = pkgs.writeText "config.ldif" (lib.concatStringsSep "\n" (attrsToLdif "cn=config" cfg.settings));
-
-        dbSettings = lib.filterAttrs (name: value: lib.hasPrefix "olcDatabase=" name) cfg.settings.children;
-        dataDirs = lib.mapAttrs' (name: value: lib.nameValuePair value.attrs.olcSuffix value.attrs.olcDbDirectory)
-          (lib.filterAttrs (_: value: value.attrs ? olcDbDirectory) dbSettings);
-        dataFiles = lib.mapAttrs (dn: contents: pkgs.writeText "${dn}.ldif" contents) cfg.declarativeContents;
-        mkLoadScript = dn: let
-          dataDir = lib.escapeShellArg (getAttr dn dataDirs);
-        in  ''
-          rm -rf ${dataDir}/*
-          ${openldap}/bin/slapadd -F ${lib.escapeShellArg configDir} -b ${dn} -l ${getAttr dn dataFiles}
-          chown -R "${cfg.user}:${cfg.group}" ${dataDir}
-        '';
-      in ''
-        mkdir -p /run/slapd
-        chown -R "${cfg.user}:${cfg.group}" /run/slapd
-
-        mkdir -p ${lib.escapeShellArg configDir} ${lib.escapeShellArgs (lib.attrValues dataDirs)}
-        chown "${cfg.user}:${cfg.group}" ${lib.escapeShellArg configDir} ${lib.escapeShellArgs (lib.attrValues dataDirs)}
-
-        ${lib.optionalString (cfg.configDir == null) (''
-          rm -Rf ${configDir}/*
-          ${openldap}/bin/slapadd -F ${configDir} -bcn=config -l ${settingsFile}
-        '')}
-        chown -R "${cfg.user}:${cfg.group}" ${lib.escapeShellArg configDir}
-
-        ${lib.concatStrings (map mkLoadScript (lib.attrNames cfg.declarativeContents))}
-        ${openldap}/bin/slaptest -u -F ${lib.escapeShellArg configDir}
-      '';
+      after = [ "network-online.target" ];
       serviceConfig = {
+        User = cfg.user;
+        Group = cfg.group;
+        ExecStartPre = [
+          "!${pkgs.coreutils}/bin/mkdir -p ${configDir}"
+          "+${pkgs.coreutils}/bin/chown $USER ${configDir}"
+        ] ++ (lib.optional (cfg.configDir == null) writeConfig)
+        ++ (mapAttrsToList (dn: content: lib.escapeShellArgs [
+          writeContents dn (getAttr dn dbSettings).olcDbDirectory content
+        ]) contentsFiles)
+        ++ [ "${openldap}/bin/slaptest -u -F ${configDir}" ];
         ExecStart = lib.escapeShellArgs ([
-          "${openldap}/libexec/slapd" "-u" cfg.user "-g" cfg.group "-F" configDir
-          "-h" (lib.concatStringsSep " " cfg.urlList)
+          "${openldap}/libexec/slapd" "-d" "0" "-F" configDir "-h" (lib.concatStringsSep " " cfg.urlList)
         ]);
-        Type = "forking";
-        PIDFile = cfg.settings.attrs.olcPidFile;
+        Type = "notify";
+        # Fixes an error where openldap attempts to notify from a thread
+        # outside the main process:
+        #   Got notification message from PID 6378, but reception only permitted for main PID 6377
+        NotifyAccess = "all";
+        RuntimeDirectory = "openldap";
+        StateDirectory = ["openldap"]
+          ++ (map ({olcDbDirectory, ... }: removePrefix "/var/lib/" olcDbDirectory) (attrValues dbSettings));
+        StateDirectoryMode = "700";
+        AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
+        CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
       };
     };
 
diff --git a/nixos/modules/services/databases/opentsdb.nix b/nixos/modules/services/databases/opentsdb.nix
index e873b2f7011..288b716fce0 100644
--- a/nixos/modules/services/databases/opentsdb.nix
+++ b/nixos/modules/services/databases/opentsdb.nix
@@ -15,19 +15,13 @@ in {
 
     services.opentsdb = {
 
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Whether to run OpenTSDB.
-        '';
-      };
+      enable = mkEnableOption (lib.mdDoc "OpenTSDB");
 
       package = mkOption {
         type = types.package;
         default = pkgs.opentsdb;
         defaultText = literalExpression "pkgs.opentsdb";
-        description = ''
+        description = lib.mdDoc ''
           OpenTSDB package to use.
         '';
       };
@@ -35,7 +29,7 @@ in {
       user = mkOption {
         type = types.str;
         default = "opentsdb";
-        description = ''
+        description = lib.mdDoc ''
           User account under which OpenTSDB runs.
         '';
       };
@@ -43,15 +37,15 @@ in {
       group = mkOption {
         type = types.str;
         default = "opentsdb";
-        description = ''
+        description = lib.mdDoc ''
           Group account under which OpenTSDB runs.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 4242;
-        description = ''
+        description = lib.mdDoc ''
           Which port OpenTSDB listens on.
         '';
       };
@@ -62,7 +56,7 @@ in {
           tsd.core.auto_create_metrics = true
           tsd.http.request.enable_chunked  = true
         '';
-        description = ''
+        description = lib.mdDoc ''
           The contents of OpenTSDB's configuration file
         '';
       };
diff --git a/nixos/modules/services/databases/pgmanage.nix b/nixos/modules/services/databases/pgmanage.nix
index f30f71866af..cbf988d596f 100644
--- a/nixos/modules/services/databases/pgmanage.nix
+++ b/nixos/modules/services/databases/pgmanage.nix
@@ -44,13 +44,13 @@ let
 in {
 
   options.services.pgmanage = {
-    enable = mkEnableOption "PostgreSQL Administration for the web";
+    enable = mkEnableOption (lib.mdDoc "PostgreSQL Administration for the web");
 
     package = mkOption {
       type = types.package;
       default = pkgs.pgmanage;
       defaultText = literalExpression "pkgs.pgmanage";
-      description = ''
+      description = lib.mdDoc ''
         The pgmanage package to use.
       '';
     };
@@ -62,12 +62,12 @@ in {
         nuc-server  = "hostaddr=192.168.0.100 port=5432 dbname=postgres";
         mini-server = "hostaddr=127.0.0.1 port=5432 dbname=postgres sslmode=require";
       };
-      description = ''
+      description = lib.mdDoc ''
         pgmanage requires at least one PostgreSQL server be defined.
-        </para><para>
+
         Detailed information about PostgreSQL connection strings is available at:
-        <link xlink:href="http://www.postgresql.org/docs/current/static/libpq-connect.html"/>
-        </para><para>
+        <http://www.postgresql.org/docs/current/static/libpq-connect.html>
+
         Note that you should not specify your user name or password. That
         information will be entered on the login screen. If you specify a
         username or password, it will be removed by pgmanage before attempting to
@@ -78,16 +78,16 @@ in {
     allowCustomConnections = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         This tells pgmanage whether or not to allow anyone to use a custom
         connection from the login screen.
       '';
     };
 
     port = mkOption {
-      type = types.int;
+      type = types.port;
       default = 8080;
-      description = ''
+      description = lib.mdDoc ''
         This tells pgmanage what port to listen on for browser requests.
       '';
     };
@@ -95,7 +95,7 @@ in {
     localOnly = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         This tells pgmanage whether or not to set the listening socket to local
         addresses only.
       '';
@@ -104,7 +104,7 @@ in {
     superOnly = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         This tells pgmanage whether or not to only allow super users to
         login. The recommended value is true and will restrict users who are not
         super users from logging in to any PostgreSQL instance through
@@ -116,7 +116,7 @@ in {
     loginGroup = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         This tells pgmanage to only allow users in a certain PostgreSQL group to
         login to pgmanage. Note that a connection will be made to PostgreSQL in
         order to test if the user is a member of the login group.
@@ -126,7 +126,7 @@ in {
     loginTimeout = mkOption {
       type = types.int;
       default = 3600;
-      description = ''
+      description = lib.mdDoc ''
         Number of seconds of inactivity before user is automatically logged
         out.
       '';
@@ -135,7 +135,7 @@ in {
     sqlRoot = mkOption {
       type = types.str;
       default = "/var/lib/pgmanage";
-      description = ''
+      description = lib.mdDoc ''
         This tells pgmanage where to put the SQL file history. All tabs are saved
         to this location so that if you get disconnected from pgmanage you
         don't lose your work.
@@ -147,16 +147,16 @@ in {
         options = {
           cert = mkOption {
             type = types.str;
-            description = "TLS certificate";
+            description = lib.mdDoc "TLS certificate";
           };
           key = mkOption {
             type = types.str;
-            description = "TLS key";
+            description = lib.mdDoc "TLS key";
           };
         };
       });
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         These options tell pgmanage where the TLS Certificate and Key files
         reside. If you use these options then you'll only be able to access
         pgmanage through a secure TLS connection. These options are only
@@ -165,14 +165,14 @@ in {
         configuration. This allows your web server to terminate the secure
         connection and pass on the request to pgmanage. You can find help to set
         up this configuration in:
-        <link xlink:href="https://github.com/pgManage/pgManage/blob/master/INSTALL_NGINX.md"/>
+        <https://github.com/pgManage/pgManage/blob/master/INSTALL_NGINX.md>
       '';
     };
 
     logLevel = mkOption {
       type = types.enum ["error" "warn" "notice" "info"];
       default = "error";
-      description = ''
+      description = lib.mdDoc ''
         Verbosity of logs
       '';
     };
diff --git a/nixos/modules/services/databases/postgresql.nix b/nixos/modules/services/databases/postgresql.nix
index 15496784053..6665e7a088f 100644
--- a/nixos/modules/services/databases/postgresql.nix
+++ b/nixos/modules/services/databases/postgresql.nix
@@ -40,20 +40,20 @@ in
 
     services.postgresql = {
 
-      enable = mkEnableOption "PostgreSQL Server";
+      enable = mkEnableOption (lib.mdDoc "PostgreSQL Server");
 
       package = mkOption {
         type = types.package;
         example = literalExpression "pkgs.postgresql_11";
-        description = ''
+        description = lib.mdDoc ''
           PostgreSQL package to use.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 5432;
-        description = ''
+        description = lib.mdDoc ''
           The port on which PostgreSQL listens.
         '';
       };
@@ -61,14 +61,14 @@ in
       checkConfig = mkOption {
         type = types.bool;
         default = true;
-        description = "Check the syntax of the configuration file at compile time";
+        description = lib.mdDoc "Check the syntax of the configuration file at compile time";
       };
 
       dataDir = mkOption {
         type = types.path;
         defaultText = literalExpression ''"/var/lib/postgresql/''${config.services.postgresql.package.psqlSchema}"'';
         example = "/var/lib/postgresql/11";
-        description = ''
+        description = lib.mdDoc ''
           The data directory for PostgreSQL. If left as the default value
           this directory will automatically be created before the PostgreSQL server starts, otherwise
           the sysadmin is responsible for ensuring the directory exists with appropriate ownership
@@ -79,16 +79,15 @@ in
       authentication = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Defines how users authenticate themselves to the server. See the
-          <link xlink:href="https://www.postgresql.org/docs/current/auth-pg-hba-conf.html">
-          PostgreSQL documentation for pg_hba.conf</link>
+          [PostgreSQL documentation for pg_hba.conf](https://www.postgresql.org/docs/current/auth-pg-hba-conf.html)
           for details on the expected format of this option. By default,
           peer based authentication will be used for users connecting
           via the Unix socket, and md5 password authentication will be
           used for users connecting via TCP. Any added rules will be
           inserted above the default rules. If you'd like to replace the
-          default rules entirely, you can use <function>lib.mkForce</function> in your
+          default rules entirely, you can use `lib.mkForce` in your
           module.
         '';
       };
@@ -96,7 +95,7 @@ in
       identMap = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Defines the mapping from system users to database users.
 
           The general form is:
@@ -109,8 +108,8 @@ in
         type = with types; listOf str;
         default = [];
         example = [ "--data-checksums" "--allow-group-access" ];
-        description = ''
-          Additional arguments passed to <literal>initdb</literal> during data dir
+        description = lib.mdDoc ''
+          Additional arguments passed to `initdb` during data dir
           initialisation.
         '';
       };
@@ -118,7 +117,7 @@ in
       initialScript = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A file containing SQL statements to execute on first startup.
         '';
       };
@@ -126,7 +125,7 @@ in
       ensureDatabases = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Ensures that the specified databases exist.
           This option will never delete existing databases, especially not when the value of this
           option is changed. This means that databases created once through this option or
@@ -143,7 +142,7 @@ in
           options = {
             name = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Name of the user to ensure.
               '';
             };
@@ -151,7 +150,7 @@ in
             ensurePermissions = mkOption {
               type = types.attrsOf types.str;
               default = {};
-              description = ''
+              description = lib.mdDoc ''
                 Permissions to ensure for the user, specified as an attribute set.
                 The attribute names specify the database and tables to grant the permissions for.
                 The attribute values specify the permissions to grant. You may specify one or
@@ -159,8 +158,8 @@ in
 
                 For more information on how to specify the target
                 and on which privileges exist, see the
-                <link xlink:href="https://www.postgresql.org/docs/current/sql-grant.html">GRANT syntax</link>.
-                The attributes are used as <code>GRANT ''${attrValue} ON ''${attrName}</code>.
+                [GRANT syntax](https://www.postgresql.org/docs/current/sql-grant.html).
+                The attributes are used as `GRANT ''${attrValue} ON ''${attrName}`.
               '';
               example = literalExpression ''
                 {
@@ -320,7 +319,7 @@ in
           };
         });
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Ensures that the specified users exist and have at least the ensured permissions.
           The PostgreSQL users will be identified using peer authentication. This authenticates the Unix user with the
           same name only, and that without the need for a password.
@@ -349,7 +348,7 @@ in
       enableTCPIP = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether PostgreSQL should listen on all network interfaces.
           If disabled, the database can only be accessed via its Unix
           domain socket or via TCP connections to localhost.
@@ -360,9 +359,9 @@ in
         type = types.str;
         default = "[%p] ";
         example = "%m [%p] ";
-        description = ''
+        description = lib.mdDoc ''
           A printf-style string that is output at the beginning of each log line.
-          Upstream default is <literal>'%m [%p] '</literal>, i.e. it includes the timestamp. We do
+          Upstream default is `'%m [%p] '`, i.e. it includes the timestamp. We do
           not include the timestamp, because journal has it anyway.
         '';
       };
@@ -371,24 +370,24 @@ in
         type = types.listOf types.path;
         default = [];
         example = literalExpression "with pkgs.postgresql_11.pkgs; [ postgis pg_repack ]";
-        description = ''
+        description = lib.mdDoc ''
           List of PostgreSQL plugins. PostgreSQL version for each plugin should
-          match version for <literal>services.postgresql.package</literal> value.
+          match version for `services.postgresql.package` value.
         '';
       };
 
       settings = mkOption {
         type = with types; attrsOf (oneOf [ bool float int str ]);
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           PostgreSQL configuration. Refer to
-          <link xlink:href="https://www.postgresql.org/docs/11/config-setting.html#CONFIG-SETTING-CONFIGURATION-FILE"/>
-          for an overview of <literal>postgresql.conf</literal>.
+          <https://www.postgresql.org/docs/11/config-setting.html#CONFIG-SETTING-CONFIGURATION-FILE>
+          for an overview of `postgresql.conf`.
 
-          <note><para>
-            String values will automatically be enclosed in single quotes. Single quotes will be
-            escaped with two single quotes as described by the upstream documentation linked above.
-          </para></note>
+          ::: {.note}
+          String values will automatically be enclosed in single quotes. Single quotes will be
+          escaped with two single quotes as described by the upstream documentation linked above.
+          :::
         '';
         example = literalExpression ''
           {
@@ -404,8 +403,8 @@ in
       recoveryConfig = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
-          Contents of the <filename>recovery.conf</filename> file.
+        description = lib.mdDoc ''
+          Contents of the {file}`recovery.conf` file.
         '';
       };
 
@@ -414,7 +413,7 @@ in
         default = "postgres";
         internal = true;
         readOnly = true;
-        description = ''
+        description = lib.mdDoc ''
           PostgreSQL superuser account to use for various operations. Internal since changing
           this value would lead to breakage while setting up databases.
         '';
@@ -444,7 +443,8 @@ in
       # Note: when changing the default, make it conditional on
       # ‘system.stateVersion’ to maintain compatibility with existing
       # systems!
-      mkDefault (if versionAtLeast config.system.stateVersion "21.11" then pkgs.postgresql_13
+      mkDefault (if versionAtLeast config.system.stateVersion "22.05" then pkgs.postgresql_14
+            else if versionAtLeast config.system.stateVersion "21.11" then pkgs.postgresql_13
             else if versionAtLeast config.system.stateVersion "20.03" then pkgs.postgresql_11
             else if versionAtLeast config.system.stateVersion "17.09" then mkThrow "9_6"
             else mkThrow "9_5");
diff --git a/nixos/modules/services/databases/postgresql.xml b/nixos/modules/services/databases/postgresql.xml
index 0ca9f3faed2..e48c578e6ce 100644
--- a/nixos/modules/services/databases/postgresql.xml
+++ b/nixos/modules/services/databases/postgresql.xml
@@ -72,16 +72,20 @@ Type "help" for help.
 { config, pkgs, ... }:
 {
   <xref linkend="opt-environment.systemPackages" /> = [
-    (pkgs.writeScriptBin "upgrade-pg-cluster" ''
+    (let
+      # XXX specify the postgresql package you'd like to upgrade to.
+      # Do not forget to list the extensions you need.
+      newPostgres = pkgs.postgresql_13.withPackages (pp: [
+        # pp.plv8
+      ]);
+    in pkgs.writeScriptBin "upgrade-pg-cluster" ''
       set -eux
       # XXX it's perhaps advisable to stop all services that depend on postgresql
       systemctl stop postgresql
 
-      # XXX replace `&lt;new version&gt;` with the psqlSchema here
-      export NEWDATA="/var/lib/postgresql/&lt;new version&gt;"
+      export NEWDATA="/var/lib/postgresql/${newPostgres.psqlSchema}"
 
-      # XXX specify the postgresql package you'd like to upgrade to
-      export NEWBIN="${pkgs.postgresql_13}/bin"
+      export NEWBIN="${newPostgres}/bin"
 
       export OLDDATA="${config.<xref linkend="opt-services.postgresql.dataDir"/>}"
       export OLDBIN="${config.<xref linkend="opt-services.postgresql.package"/>}/bin"
@@ -127,12 +131,25 @@ Type "help" for help.
    </listitem>
    <listitem>
     <para>
-     After the upgrade it's advisable to analyze the new cluster (as <literal>su -l postgres</literal> in the
-     <xref linkend="opt-services.postgresql.dataDir" />, in this example <filename>/var/lib/postgresql/13</filename>):
+     After the upgrade it's advisable to analyze the new cluster.
+    </para>
+    <itemizedlist>
+     <listitem>
+      <para>
+       For PostgreSQL ≥ 14, use the <literal>vacuumdb</literal> command printed by the upgrades script.
+      </para>
+     </listitem>
+     <listitem>
+       <para>
+        For PostgreSQL &lt; 14, run (as <literal>su -l postgres</literal> in the <xref linkend="opt-services.postgresql.dataDir" />, in this example <filename>/var/lib/postgresql/13</filename>):
 <programlisting>
 <prompt>$ </prompt>./analyze_new_cluster.sh
 </programlisting>
-     <warning><para>The next step removes the old state-directory!</para></warning>
+       </para>
+     </listitem>
+    </itemizedlist>
+    <para>
+      <warning><para>The next step removes the old state-directory!</para></warning>
 <programlisting>
 <prompt>$ </prompt>./delete_old_cluster.sh
 </programlisting>
diff --git a/nixos/modules/services/databases/redis.nix b/nixos/modules/services/databases/redis.nix
index a1bd73c9e37..1464f4487e3 100644
--- a/nixos/modules/services/databases/redis.nix
+++ b/nixos/modules/services/databases/redis.nix
@@ -58,25 +58,25 @@ in {
         type = types.package;
         default = pkgs.redis;
         defaultText = literalExpression "pkgs.redis";
-        description = "Which Redis derivation to use.";
+        description = lib.mdDoc "Which Redis derivation to use.";
       };
 
-      vmOverCommit = mkEnableOption ''
+      vmOverCommit = mkEnableOption (lib.mdDoc ''
         setting of vm.overcommit_memory to 1
         (Suggested for Background Saving: http://redis.io/topics/faq)
-      '';
+      '');
 
       servers = mkOption {
-        type = with types; attrsOf (submodule ({config, name, ...}@args: {
+        type = with types; attrsOf (submodule ({ config, name, ... }: {
           options = {
-            enable = mkEnableOption ''
+            enable = mkEnableOption (lib.mdDoc ''
               Redis server.
 
               Note that the NixOS module for Redis disables kernel support
               for Transparent Huge Pages (THP),
               because this features causes major performance problems for Redis,
               e.g. (https://redis.io/topics/latency).
-            '';
+            '');
 
             user = mkOption {
               type = types.str;
@@ -84,14 +84,14 @@ in {
               defaultText = literalExpression ''
                 if name == "" then "redis" else "redis-''${name}"
               '';
-              description = "The username and groupname for redis-server.";
+              description = lib.mdDoc "The username and groupname for redis-server.";
             };
 
             port = mkOption {
               type = types.port;
               default = if name == "" then 6379 else 0;
               defaultText = literalExpression ''if name == "" then 6379 else 0'';
-              description = ''
+              description = lib.mdDoc ''
                 The TCP port to accept connections.
                 If port 0 is specified Redis will not listen on a TCP socket.
               '';
@@ -100,17 +100,24 @@ in {
             openFirewall = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 Whether to open ports in the firewall for the server.
               '';
             };
 
+            extraParams = mkOption {
+              type = with types; listOf str;
+              default = [];
+              description = lib.mdDoc "Extra parameters to append to redis-server invocation";
+              example = [ "--sentinel" ];
+            };
+
             bind = mkOption {
               type = with types; nullOr str;
               default = "127.0.0.1";
-              description = ''
+              description = lib.mdDoc ''
                 The IP interface to bind to.
-                <literal>null</literal> means "all interfaces".
+                `null` means "all interfaces".
               '';
               example = "192.0.2.1";
             };
@@ -121,13 +128,13 @@ in {
               defaultText = literalExpression ''
                 if name == "" then "/run/redis/redis.sock" else "/run/redis-''${name}/redis.sock"
               '';
-              description = "The path to the socket to bind to.";
+              description = lib.mdDoc "The path to the socket to bind to.";
             };
 
             unixSocketPerm = mkOption {
               type = types.int;
               default = 660;
-              description = "Change permissions for the socket";
+              description = lib.mdDoc "Change permissions for the socket";
               example = 600;
             };
 
@@ -135,38 +142,42 @@ in {
               type = types.str;
               default = "notice"; # debug, verbose, notice, warning
               example = "debug";
-              description = "Specify the server verbosity level, options: debug, verbose, notice, warning.";
+              description = lib.mdDoc "Specify the server verbosity level, options: debug, verbose, notice, warning.";
             };
 
             logfile = mkOption {
               type = types.str;
               default = "/dev/null";
-              description = "Specify the log file name. Also 'stdout' can be used to force Redis to log on the standard output.";
+              description = lib.mdDoc "Specify the log file name. Also 'stdout' can be used to force Redis to log on the standard output.";
               example = "/var/log/redis.log";
             };
 
             syslog = mkOption {
               type = types.bool;
               default = true;
-              description = "Enable logging to the system logger.";
+              description = lib.mdDoc "Enable logging to the system logger.";
             };
 
             databases = mkOption {
               type = types.int;
               default = 16;
-              description = "Set the number of databases.";
+              description = lib.mdDoc "Set the number of databases.";
             };
 
             maxclients = mkOption {
               type = types.int;
               default = 10000;
-              description = "Set the max number of connected clients at the same time.";
+              description = lib.mdDoc "Set the max number of connected clients at the same time.";
             };
 
             save = mkOption {
               type = with types; listOf (listOf int);
               default = [ [900 1] [300 10] [60 10000] ];
-              description = "The schedule in which data is persisted to disk, represented as a list of lists where the first element represent the amount of seconds and the second the number of changes.";
+              description = mdDoc ''
+                The schedule in which data is persisted to disk, represented as a list of lists where the first element represent the amount of seconds and the second the number of changes.
+
+                If set to the empty list (`[]`) then RDB persistence will be disabled (useful if you are using AOF or don't want any persistence).
+              '';
             };
 
             slaveOf = mkOption {
@@ -174,27 +185,27 @@ in {
                 options = {
                   ip = mkOption {
                     type = str;
-                    description = "IP of the Redis master";
+                    description = lib.mdDoc "IP of the Redis master";
                     example = "192.168.1.100";
                   };
 
                   port = mkOption {
                     type = port;
-                    description = "port of the Redis master";
+                    description = lib.mdDoc "port of the Redis master";
                     default = 6379;
                   };
                 };
               }));
 
               default = null;
-              description = "IP and port to which this redis instance acts as a slave.";
+              description = lib.mdDoc "IP and port to which this redis instance acts as a slave.";
               example = { ip = "192.168.1.100"; port = 6379; };
             };
 
             masterAuth = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''If the master is password protected (using the requirePass configuration)
+              description = lib.mdDoc ''If the master is password protected (using the requirePass configuration)
               it is possible to tell the slave to authenticate before starting the replication synchronization
               process, otherwise the master will refuse the slave request.
               (STORED PLAIN TEXT, WORLD-READABLE IN NIX STORE)'';
@@ -203,7 +214,7 @@ in {
             requirePass = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Password for database (STORED PLAIN TEXT, WORLD-READABLE IN NIX STORE).
                 Use requirePassFile to store it outside of the nix store in a dedicated file.
               '';
@@ -213,42 +224,42 @@ in {
             requirePassFile = mkOption {
               type = with types; nullOr path;
               default = null;
-              description = "File with password for the database.";
+              description = lib.mdDoc "File with password for the database.";
               example = "/run/keys/redis-password";
             };
 
             appendOnly = mkOption {
               type = types.bool;
               default = false;
-              description = "By default data is only periodically persisted to disk, enable this option to use an append-only file for improved persistence.";
+              description = lib.mdDoc "By default data is only periodically persisted to disk, enable this option to use an append-only file for improved persistence.";
             };
 
             appendFsync = mkOption {
               type = types.str;
               default = "everysec"; # no, always, everysec
-              description = "How often to fsync the append-only log, options: no, always, everysec.";
+              description = lib.mdDoc "How often to fsync the append-only log, options: no, always, everysec.";
             };
 
             slowLogLogSlowerThan = mkOption {
               type = types.int;
               default = 10000;
-              description = "Log queries whose execution take longer than X in milliseconds.";
+              description = lib.mdDoc "Log queries whose execution take longer than X in milliseconds.";
               example = 1000;
             };
 
             slowLogMaxLen = mkOption {
               type = types.int;
               default = 128;
-              description = "Maximum number of items to keep in slow log.";
+              description = lib.mdDoc "Maximum number of items to keep in slow log.";
             };
 
             settings = mkOption {
               # TODO: this should be converted to freeformType
               type = with types; attrsOf (oneOf [ bool int str (listOf str) ]);
               default = {};
-              description = ''
+              description = lib.mdDoc ''
                 Redis configuration. Refer to
-                <link xlink:href="https://redis.io/topics/config"/>
+                <https://redis.io/topics/config>
                 for details on supported values.
               '';
               example = literalExpression ''
@@ -260,23 +271,23 @@ in {
           };
           config.settings = mkMerge [
             {
-              port = config.port;
+              inherit (config) port logfile databases maxclients appendOnly;
               daemonize = false;
               supervised = "systemd";
               loglevel = config.logLevel;
-              logfile = config.logfile;
               syslog-enabled = config.syslog;
-              databases = config.databases;
-              maxclients = config.maxclients;
-              save = map (d: "${toString (builtins.elemAt d 0)} ${toString (builtins.elemAt d 1)}") config.save;
+              save = if config.save == []
+                then ''""'' # Disable saving with `save = ""`
+                else map
+                  (d: "${toString (builtins.elemAt d 0)} ${toString (builtins.elemAt d 1)}")
+                  config.save;
               dbfilename = "dump.rdb";
               dir = "/var/lib/${redisName name}";
-              appendOnly = config.appendOnly;
               appendfsync = config.appendFsync;
               slowlog-log-slower-than = config.slowLogLogSlowerThan;
               slowlog-max-len = config.slowLogMaxLen;
             }
-            (mkIf (config.bind != null) { bind = config.bind; })
+            (mkIf (config.bind != null) { inherit (config) bind; })
             (mkIf (config.unixSocket != null) {
               unixsocket = config.unixSocket;
               unixsocketperm = toString config.unixSocketPerm;
@@ -286,7 +297,7 @@ in {
             (mkIf (config.requirePass != null) { requirepass = config.requirePass; })
           ];
         }));
-        description = "Configuration of multiple <literal>redis-server</literal> instances.";
+        description = lib.mdDoc "Configuration of multiple `redis-server` instances.";
         default = {};
       };
     };
@@ -332,16 +343,26 @@ in {
       after = [ "network.target" ];
 
       serviceConfig = {
-        ExecStart = "${cfg.package}/bin/redis-server /run/${redisName name}/redis.conf";
-        ExecStartPre = [("+"+pkgs.writeShellScript "${redisName name}-credentials" (''
-            install -o '${conf.user}' -m 600 ${redisConfig conf.settings} /run/${redisName name}/redis.conf
-          '' + optionalString (conf.requirePassFile != null) ''
+        ExecStart = "${cfg.package}/bin/redis-server /var/lib/${redisName name}/redis.conf ${escapeShellArgs conf.extraParams}";
+        ExecStartPre = "+"+pkgs.writeShellScript "${redisName name}-prep-conf" (let
+          redisConfVar = "/var/lib/${redisName name}/redis.conf";
+          redisConfRun = "/run/${redisName name}/nixos.conf";
+          redisConfStore = redisConfig conf.settings;
+        in ''
+          touch "${redisConfVar}" "${redisConfRun}"
+          chown '${conf.user}' "${redisConfVar}" "${redisConfRun}"
+          chmod 0600 "${redisConfVar}" "${redisConfRun}"
+          if [ ! -s ${redisConfVar} ]; then
+            echo 'include "${redisConfRun}"' > "${redisConfVar}"
+          fi
+          echo 'include "${redisConfStore}"' > "${redisConfRun}"
+          ${optionalString (conf.requirePassFile != null) ''
             {
-              printf requirePass' '
+              echo -n "requirepass "
               cat ${escapeShellArg conf.requirePassFile}
-            } >>/run/${redisName name}/redis.conf
-          '')
-        )];
+            } >> "${redisConfRun}"
+          ''}
+        '');
         Type = "notify";
         # User and group
         User = conf.user;
diff --git a/nixos/modules/services/databases/rethinkdb.nix b/nixos/modules/services/databases/rethinkdb.nix
index c764d6c21c6..f5391b48e89 100644
--- a/nixos/modules/services/databases/rethinkdb.nix
+++ b/nixos/modules/services/databases/rethinkdb.nix
@@ -15,7 +15,7 @@ in
 
     services.rethinkdb = {
 
-      enable = mkEnableOption "RethinkDB server";
+      enable = mkEnableOption (lib.mdDoc "RethinkDB server");
 
       #package = mkOption {
       #  default = pkgs.rethinkdb;
@@ -24,22 +24,22 @@ in
 
       user = mkOption {
         default = "rethinkdb";
-        description = "User account under which RethinkDB runs.";
+        description = lib.mdDoc "User account under which RethinkDB runs.";
       };
 
       group = mkOption {
         default = "rethinkdb";
-        description = "Group which rethinkdb user belongs to.";
+        description = lib.mdDoc "Group which rethinkdb user belongs to.";
       };
 
       dbpath = mkOption {
         default = "/var/db/rethinkdb";
-        description = "Location where RethinkDB stores its data, 1 data directory per instance.";
+        description = lib.mdDoc "Location where RethinkDB stores its data, 1 data directory per instance.";
       };
 
       pidpath = mkOption {
         default = "/run/rethinkdb";
-        description = "Location where each instance's pid file is located.";
+        description = lib.mdDoc "Location where each instance's pid file is located.";
       };
 
       #cfgpath = mkOption {
diff --git a/nixos/modules/services/databases/riak.nix b/nixos/modules/services/databases/riak.nix
deleted file mode 100644
index cc4237d038c..00000000000
--- a/nixos/modules/services/databases/riak.nix
+++ /dev/null
@@ -1,162 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-let
-
-  cfg = config.services.riak;
-
-in
-
-{
-
-  ###### interface
-
-  options = {
-
-    services.riak = {
-
-      enable = mkEnableOption "riak";
-
-      package = mkOption {
-        type = types.package;
-        default = pkgs.riak;
-        defaultText = literalExpression "pkgs.riak";
-        description = ''
-          Riak package to use.
-        '';
-      };
-
-      nodeName = mkOption {
-        type = types.str;
-        default = "riak@127.0.0.1";
-        description = ''
-          Name of the Erlang node.
-        '';
-      };
-
-      distributedCookie = mkOption {
-        type = types.str;
-        default = "riak";
-        description = ''
-          Cookie for distributed node communication.  All nodes in the
-          same cluster should use the same cookie or they will not be able to
-          communicate.
-        '';
-      };
-
-      dataDir = mkOption {
-        type = types.path;
-        default = "/var/db/riak";
-        description = ''
-          Data directory for Riak.
-        '';
-      };
-
-      logDir = mkOption {
-        type = types.path;
-        default = "/var/log/riak";
-        description = ''
-          Log directory for Riak.
-        '';
-      };
-
-      extraConfig = mkOption {
-        type = types.lines;
-        default = "";
-        description = ''
-          Additional text to be appended to <filename>riak.conf</filename>.
-        '';
-      };
-
-      extraAdvancedConfig = mkOption {
-        type = types.lines;
-        default = "";
-        description = ''
-          Additional text to be appended to <filename>advanced.config</filename>.
-        '';
-      };
-
-    };
-
-  };
-
-  ###### implementation
-
-  config = mkIf cfg.enable {
-
-    environment.systemPackages = [ cfg.package ];
-    environment.etc."riak/riak.conf".text = ''
-      nodename = ${cfg.nodeName}
-      distributed_cookie = ${cfg.distributedCookie}
-
-      platform_log_dir = ${cfg.logDir}
-      platform_etc_dir = /etc/riak
-      platform_data_dir = ${cfg.dataDir}
-
-      ${cfg.extraConfig}
-    '';
-
-    environment.etc."riak/advanced.config".text = ''
-      ${cfg.extraAdvancedConfig}
-    '';
-
-    users.users.riak = {
-      name = "riak";
-      uid = config.ids.uids.riak;
-      group = "riak";
-      description = "Riak server user";
-    };
-
-    users.groups.riak.gid = config.ids.gids.riak;
-
-    systemd.services.riak = {
-      description = "Riak Server";
-
-      wantedBy = [ "multi-user.target" ];
-      after = [ "network.target" ];
-
-      path = [
-        pkgs.util-linux # for `logger`
-        pkgs.bash
-      ];
-
-      environment.HOME = "${cfg.dataDir}";
-      environment.RIAK_DATA_DIR = "${cfg.dataDir}";
-      environment.RIAK_LOG_DIR = "${cfg.logDir}";
-      environment.RIAK_ETC_DIR = "/etc/riak";
-
-      preStart = ''
-        if ! test -e ${cfg.logDir}; then
-          mkdir -m 0755 -p ${cfg.logDir}
-          chown -R riak ${cfg.logDir}
-        fi
-
-        if ! test -e ${cfg.dataDir}; then
-          mkdir -m 0700 -p ${cfg.dataDir}
-          chown -R riak ${cfg.dataDir}
-        fi
-      '';
-
-      serviceConfig = {
-        ExecStart = "${cfg.package}/bin/riak console";
-        ExecStop = "${cfg.package}/bin/riak stop";
-        StandardInput = "tty";
-        User = "riak";
-        Group = "riak";
-        PermissionsStartOnly = true;
-        # Give Riak a decent amount of time to clean up.
-        TimeoutStopSec = 120;
-        LimitNOFILE = 65536;
-      };
-
-      unitConfig.RequiresMountsFor = [
-        "${cfg.dataDir}"
-        "${cfg.logDir}"
-        "/etc/riak"
-      ];
-    };
-
-  };
-
-}
diff --git a/nixos/modules/services/databases/surrealdb.nix b/nixos/modules/services/databases/surrealdb.nix
new file mode 100644
index 00000000000..27269eb02f6
--- /dev/null
+++ b/nixos/modules/services/databases/surrealdb.nix
@@ -0,0 +1,79 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let
+
+  cfg = config.services.surrealdb;
+in {
+
+  options = {
+    services.surrealdb = {
+      enable = mkEnableOption (lib.mdDoc "A scalable, distributed, collaborative, document-graph database, for the realtime web ");
+
+      dbPath = mkOption {
+        type = types.str;
+        description = lib.mdDoc ''
+          The path that surrealdb will write data to. Use null for in-memory.
+          Can be one of "memory", "file://:path", "tikv://:addr".
+        '';
+        default = "file:///var/lib/surrealdb/";
+        example = "memory";
+      };
+
+      host = mkOption {
+        type = types.str;
+        description = lib.mdDoc ''
+          The host that surrealdb will connect to.
+        '';
+        default = "127.0.0.1";
+        example = "127.0.0.1";
+      };
+
+      port = mkOption {
+        type = types.port;
+        description = lib.mdDoc ''
+          The port that surrealdb will connect to.
+        '';
+        default = 8000;
+        example = 8000;
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    # Used to connect to the running service
+    environment.systemPackages = [ pkgs.surrealdb ] ;
+
+    systemd.services.surrealdb = {
+      description = "A scalable, distributed, collaborative, document-graph database, for the realtime web ";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+
+      serviceConfig = {
+        ExecStart = "${pkgs.surrealdb}/bin/surreal start --bind ${cfg.host}:${toString cfg.port} ${optionalString (cfg.dbPath != null) "-- ${cfg.dbPath}"}";
+        DynamicUser = true;
+        Restart = "on-failure";
+        StateDirectory = "surrealdb";
+        CapabilityBoundingSet = "";
+        NoNewPrivileges = true;
+        PrivateTmp = true;
+        ProtectHome = true;
+        ProtectClock = true;
+        ProtectProc = "noaccess";
+        ProcSubset = "pid";
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectControlGroups = true;
+        ProtectHostname = true;
+        RestrictSUIDSGID = true;
+        RestrictRealtime = true;
+        RestrictNamespaces = true;
+        LockPersonality = true;
+        RemoveIPC = true;
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/databases/victoriametrics.nix b/nixos/modules/services/databases/victoriametrics.nix
index 0513dcff172..638066a42db 100644
--- a/nixos/modules/services/databases/victoriametrics.nix
+++ b/nixos/modules/services/databases/victoriametrics.nix
@@ -2,36 +2,36 @@
 let cfg = config.services.victoriametrics; in
 {
   options.services.victoriametrics = with lib; {
-    enable = mkEnableOption "victoriametrics";
+    enable = mkEnableOption (lib.mdDoc "victoriametrics");
     package = mkOption {
       type = types.package;
       default = pkgs.victoriametrics;
       defaultText = literalExpression "pkgs.victoriametrics";
-      description = ''
+      description = lib.mdDoc ''
         The VictoriaMetrics distribution to use.
       '';
     };
     listenAddress = mkOption {
       default = ":8428";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The listen address for the http interface.
       '';
     };
     retentionPeriod = mkOption {
       type = types.int;
       default = 1;
-      description = ''
+      description = lib.mdDoc ''
         Retention period in months.
       '';
     };
     extraOptions = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
-        Extra options to pass to VictoriaMetrics. See the README: <link
-        xlink:href="https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/README.md" />
-        or <command>victoriametrics -help</command> for more
+      description = lib.mdDoc ''
+        Extra options to pass to VictoriaMetrics. See the README:
+        <https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/README.md>
+        or {command}`victoriametrics -help` for more
         information.
       '';
     };
diff --git a/nixos/modules/services/desktops/accountsservice.nix b/nixos/modules/services/desktops/accountsservice.nix
index ae2ecb5ffeb..af62850acdc 100644
--- a/nixos/modules/services/desktops/accountsservice.nix
+++ b/nixos/modules/services/desktops/accountsservice.nix
@@ -19,7 +19,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable AccountsService, a DBus service for accessing
           the list of user accounts and information attached to those accounts.
         '';
diff --git a/nixos/modules/services/desktops/bamf.nix b/nixos/modules/services/desktops/bamf.nix
index 13de3a44328..3e40a705534 100644
--- a/nixos/modules/services/desktops/bamf.nix
+++ b/nixos/modules/services/desktops/bamf.nix
@@ -13,7 +13,7 @@ with lib;
 
   options = {
     services.bamf = {
-      enable = mkEnableOption "bamf";
+      enable = mkEnableOption (lib.mdDoc "bamf");
     };
   };
 
diff --git a/nixos/modules/services/desktops/blueman.nix b/nixos/modules/services/desktops/blueman.nix
index 18ad610247e..fad2f21bce5 100644
--- a/nixos/modules/services/desktops/blueman.nix
+++ b/nixos/modules/services/desktops/blueman.nix
@@ -9,7 +9,7 @@ in {
   ###### interface
   options = {
     services.blueman = {
-      enable = mkEnableOption "blueman";
+      enable = mkEnableOption (lib.mdDoc "blueman");
     };
   };
 
diff --git a/nixos/modules/services/desktops/cpupower-gui.nix b/nixos/modules/services/desktops/cpupower-gui.nix
index f66afc0a3dc..47071aebce8 100644
--- a/nixos/modules/services/desktops/cpupower-gui.nix
+++ b/nixos/modules/services/desktops/cpupower-gui.nix
@@ -11,7 +11,7 @@ in {
         type = lib.types.bool;
         default = false;
         example = true;
-        description = ''
+        description = lib.mdDoc ''
           Enables dbus/systemd service needed by cpupower-gui.
           These services are responsible for retrieving and modifying cpu power
           saving settings.
diff --git a/nixos/modules/services/desktops/dleyna-renderer.nix b/nixos/modules/services/desktops/dleyna-renderer.nix
index 7f88605f627..daf65180b36 100644
--- a/nixos/modules/services/desktops/dleyna-renderer.nix
+++ b/nixos/modules/services/desktops/dleyna-renderer.nix
@@ -10,7 +10,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable dleyna-renderer service, a DBus service
           for handling DLNA renderers.
         '';
diff --git a/nixos/modules/services/desktops/dleyna-server.nix b/nixos/modules/services/desktops/dleyna-server.nix
index 9a131a5e700..9cbcd2a9cda 100644
--- a/nixos/modules/services/desktops/dleyna-server.nix
+++ b/nixos/modules/services/desktops/dleyna-server.nix
@@ -10,7 +10,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable dleyna-server service, a DBus service
           for handling DLNA servers.
         '';
diff --git a/nixos/modules/services/desktops/espanso.nix b/nixos/modules/services/desktops/espanso.nix
index 4ef6724dda0..cbc48034795 100644
--- a/nixos/modules/services/desktops/espanso.nix
+++ b/nixos/modules/services/desktops/espanso.nix
@@ -6,7 +6,7 @@ in {
   meta = { maintainers = with lib.maintainers; [ numkem ]; };
 
   options = {
-    services.espanso = { enable = options.mkEnableOption "Espanso"; };
+    services.espanso = { enable = options.mkEnableOption (lib.mdDoc "Espanso"); };
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/desktops/flatpak.nix b/nixos/modules/services/desktops/flatpak.nix
index 5fecc64b4f7..3b14ad75ab3 100644
--- a/nixos/modules/services/desktops/flatpak.nix
+++ b/nixos/modules/services/desktops/flatpak.nix
@@ -14,7 +14,7 @@ in {
   ###### interface
   options = {
     services.flatpak = {
-      enable = mkEnableOption "flatpak";
+      enable = mkEnableOption (lib.mdDoc "flatpak");
     };
   };
 
diff --git a/nixos/modules/services/desktops/geoclue2.nix b/nixos/modules/services/desktops/geoclue2.nix
index 60a34dd6563..b04f46c26a5 100644
--- a/nixos/modules/services/desktops/geoclue2.nix
+++ b/nixos/modules/services/desktops/geoclue2.nix
@@ -16,19 +16,19 @@ let
     options = {
       desktopID = mkOption {
         type = types.str;
-        description = "Desktop ID of the application.";
+        description = lib.mdDoc "Desktop ID of the application.";
       };
 
       isAllowed = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether the application will be allowed access to location information.
         '';
       };
 
       isSystem = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether the application is a system component or not.
         '';
       };
@@ -36,7 +36,7 @@ let
       users = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of UIDs of all users for which this application is allowed location
           info access, Defaults to an empty string to allow it for all users.
         '';
@@ -67,7 +67,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable GeoClue 2 daemon, a DBus service
           that provides location information for accessing.
         '';
@@ -76,7 +76,7 @@ in
       enableDemoAgent = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use the GeoClue demo agent. This should be
           overridden by desktop environments that provide their own
           agent.
@@ -86,7 +86,7 @@ in
       enableNmea = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to fetch location from NMEA sources on local network.
         '';
       };
@@ -94,7 +94,7 @@ in
       enable3G = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable 3G source.
         '';
       };
@@ -102,7 +102,7 @@ in
       enableCDMA = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable CDMA source.
         '';
       };
@@ -110,7 +110,7 @@ in
       enableModemGPS = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Modem-GPS source.
         '';
       };
@@ -118,7 +118,7 @@ in
       enableWifi = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable WiFi source.
         '';
       };
@@ -127,7 +127,7 @@ in
         type = types.str;
         default = "https://location.services.mozilla.com/v1/geolocate?key=geoclue";
         example = "https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_KEY";
-        description = ''
+        description = lib.mdDoc ''
           The url to the wifi GeoLocation Service.
         '';
       };
@@ -135,7 +135,7 @@ in
       submitData = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to submit data to a GeoLocation Service.
         '';
       };
@@ -143,7 +143,7 @@ in
       submissionUrl = mkOption {
         type = types.str;
         default = "https://location.services.mozilla.com/v1/submit?key=geoclue";
-        description = ''
+        description = lib.mdDoc ''
           The url to submit data to a GeoLocation Service.
         '';
       };
@@ -151,7 +151,7 @@ in
       submissionNick = mkOption {
         type = types.str;
         default = "geoclue";
-        description = ''
+        description = lib.mdDoc ''
           A nickname to submit network data with.
           Must be 2-32 characters long.
         '';
@@ -167,7 +167,7 @@ in
             users = [ "300" ];
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Specify extra settings per application.
         '';
       };
@@ -200,6 +200,7 @@ in
     };
 
     systemd.services.geoclue = {
+      after = lib.optionals cfg.enableWifi [ "network-online.target" ];
       # restart geoclue service when the configuration changes
       restartTriggers = [
         config.environment.etc."geoclue/geoclue.conf".source
@@ -216,6 +217,7 @@ in
         # we can't be part of a system service, and the agent should
         # be okay with the main service coming and going
         wantedBy = [ "default.target" ];
+        after = lib.optionals cfg.enableWifi [ "network-online.target" ];
         unitConfig.ConditionUser = "!@system";
         serviceConfig = {
           Type = "exec";
diff --git a/nixos/modules/services/desktops/gnome/at-spi2-core.nix b/nixos/modules/services/desktops/gnome/at-spi2-core.nix
index 1268a9d49b8..10a2f1f9eca 100644
--- a/nixos/modules/services/desktops/gnome/at-spi2-core.nix
+++ b/nixos/modules/services/desktops/gnome/at-spi2-core.nix
@@ -27,12 +27,12 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable at-spi2-core, a service for the Assistive Technologies
           available on the GNOME platform.
 
           Enable this if you get the error or warning
-          <literal>The name org.a11y.Bus was not provided by any .service files</literal>.
+          `The name org.a11y.Bus was not provided by any .service files`.
         '';
       };
 
@@ -51,7 +51,10 @@ with lib;
     })
 
     (mkIf (!config.services.gnome.at-spi2-core.enable) {
-      environment.variables.NO_AT_BRIDGE = "1";
+      environment.variables = {
+        NO_AT_BRIDGE = "1";
+        GTK_A11Y = "none";
+      };
     })
   ];
 }
diff --git a/nixos/modules/services/desktops/gnome/chrome-gnome-shell.nix b/nixos/modules/services/desktops/gnome/chrome-gnome-shell.nix
deleted file mode 100644
index 15c5bfbd821..00000000000
--- a/nixos/modules/services/desktops/gnome/chrome-gnome-shell.nix
+++ /dev/null
@@ -1,41 +0,0 @@
-# Chrome GNOME Shell native host connector.
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-{
-  meta = {
-    maintainers = teams.gnome.members;
-  };
-
-  # Added 2021-05-07
-  imports = [
-    (mkRenamedOptionModule
-      [ "services" "gnome3" "chrome-gnome-shell" "enable" ]
-      [ "services" "gnome" "chrome-gnome-shell" "enable" ]
-    )
-  ];
-
-  ###### interface
-  options = {
-    services.gnome.chrome-gnome-shell.enable = mkEnableOption ''
-      Chrome GNOME Shell native host connector, a DBus service
-      allowing to install GNOME Shell extensions from a web browser.
-    '';
-  };
-
-
-  ###### implementation
-  config = mkIf config.services.gnome.chrome-gnome-shell.enable {
-    environment.etc = {
-      "chromium/native-messaging-hosts/org.gnome.chrome_gnome_shell.json".source = "${pkgs.chrome-gnome-shell}/etc/chromium/native-messaging-hosts/org.gnome.chrome_gnome_shell.json";
-      "opt/chrome/native-messaging-hosts/org.gnome.chrome_gnome_shell.json".source = "${pkgs.chrome-gnome-shell}/etc/opt/chrome/native-messaging-hosts/org.gnome.chrome_gnome_shell.json";
-    };
-
-    environment.systemPackages = [ pkgs.chrome-gnome-shell ];
-
-    services.dbus.packages = [ pkgs.chrome-gnome-shell ];
-
-    nixpkgs.config.firefox.enableGnomeExtensions = true;
-  };
-}
diff --git a/nixos/modules/services/desktops/gnome/evolution-data-server.nix b/nixos/modules/services/desktops/gnome/evolution-data-server.nix
index bd2242d9818..0006ba1a7ba 100644
--- a/nixos/modules/services/desktops/gnome/evolution-data-server.nix
+++ b/nixos/modules/services/desktops/gnome/evolution-data-server.nix
@@ -27,20 +27,20 @@ with lib;
   options = {
 
     services.gnome.evolution-data-server = {
-      enable = mkEnableOption "Evolution Data Server, a collection of services for storing addressbooks and calendars.";
+      enable = mkEnableOption (lib.mdDoc "Evolution Data Server, a collection of services for storing addressbooks and calendars.");
       plugins = mkOption {
         type = types.listOf types.package;
         default = [ ];
-        description = "Plugins for Evolution Data Server.";
+        description = lib.mdDoc "Plugins for Evolution Data Server.";
       };
     };
     programs.evolution = {
-      enable = mkEnableOption "Evolution, a Personal information management application that provides integrated mail, calendaring and address book functionality.";
+      enable = mkEnableOption (lib.mdDoc "Evolution, a Personal information management application that provides integrated mail, calendaring and address book functionality.");
       plugins = mkOption {
         type = types.listOf types.package;
         default = [ ];
         example = literalExpression "[ pkgs.evolution-ews ]";
-        description = "Plugins for Evolution.";
+        description = lib.mdDoc "Plugins for Evolution.";
       };
 
     };
diff --git a/nixos/modules/services/desktops/gnome/glib-networking.nix b/nixos/modules/services/desktops/gnome/glib-networking.nix
index 1039605391a..6b54f46f0cf 100644
--- a/nixos/modules/services/desktops/gnome/glib-networking.nix
+++ b/nixos/modules/services/desktops/gnome/glib-networking.nix
@@ -24,7 +24,7 @@ with lib;
 
     services.gnome.glib-networking = {
 
-      enable = mkEnableOption "network extensions for GLib";
+      enable = mkEnableOption (lib.mdDoc "network extensions for GLib");
 
     };
 
diff --git a/nixos/modules/services/desktops/gnome/gnome-browser-connector.nix b/nixos/modules/services/desktops/gnome/gnome-browser-connector.nix
new file mode 100644
index 00000000000..5d4ddce9422
--- /dev/null
+++ b/nixos/modules/services/desktops/gnome/gnome-browser-connector.nix
@@ -0,0 +1,47 @@
+{ config, lib, pkgs, ... }:
+
+let
+  inherit (lib) mdDoc mkEnableOption mkIf mkRenamedOptionModule teams;
+in
+
+{
+  meta = {
+    maintainers = teams.gnome.members;
+  };
+
+  imports = [
+    # Added 2021-05-07
+    (mkRenamedOptionModule
+      [ "services" "gnome3" "chrome-gnome-shell" "enable" ]
+      [ "services" "gnome" "gnome-browser-connector" "enable" ]
+    )
+    # Added 2022-07-25
+    (mkRenamedOptionModule
+      [ "services" "gnome" "chrome-gnome-shell" "enable" ]
+      [ "services" "gnome" "gnome-browser-connector" "enable" ]
+    )
+  ];
+
+  options = {
+    services.gnome.gnome-browser-connector.enable = mkEnableOption (mdDoc ''
+      Native host connector for the GNOME Shell browser extension, a DBus service
+      allowing to install GNOME Shell extensions from a web browser.
+    '');
+  };
+
+  config = mkIf config.services.gnome.gnome-browser-connector.enable {
+    environment.etc = {
+      "chromium/native-messaging-hosts/org.gnome.browser_connector.json".source = "${pkgs.gnome-browser-connector}/etc/chromium/native-messaging-hosts/org.gnome.browser_connector.json";
+      "opt/chrome/native-messaging-hosts/org.gnome.browser_connector.json".source = "${pkgs.gnome-browser-connector}/etc/opt/chrome/native-messaging-hosts/org.gnome.browser_connector.json";
+      # Legacy paths.
+      "chromium/native-messaging-hosts/org.gnome.chrome_gnome_shell.json".source = "${pkgs.gnome-browser-connector}/etc/chromium/native-messaging-hosts/org.gnome.chrome_gnome_shell.json";
+      "opt/chrome/native-messaging-hosts/org.gnome.chrome_gnome_shell.json".source = "${pkgs.gnome-browser-connector}/etc/opt/chrome/native-messaging-hosts/org.gnome.chrome_gnome_shell.json";
+    };
+
+    environment.systemPackages = [ pkgs.gnome-browser-connector ];
+
+    services.dbus.packages = [ pkgs.gnome-browser-connector ];
+
+    nixpkgs.config.firefox.enableGnomeExtensions = true;
+  };
+}
diff --git a/nixos/modules/services/desktops/gnome/gnome-initial-setup.nix b/nixos/modules/services/desktops/gnome/gnome-initial-setup.nix
index 9e9771cf541..f24e6f1eb15 100644
--- a/nixos/modules/services/desktops/gnome/gnome-initial-setup.nix
+++ b/nixos/modules/services/desktops/gnome/gnome-initial-setup.nix
@@ -62,7 +62,7 @@ in
 
     services.gnome.gnome-initial-setup = {
 
-      enable = mkEnableOption "GNOME Initial Setup, a Simple, easy, and safe way to prepare a new system";
+      enable = mkEnableOption (lib.mdDoc "GNOME Initial Setup, a Simple, easy, and safe way to prepare a new system");
 
     };
 
diff --git a/nixos/modules/services/desktops/gnome/gnome-keyring.nix b/nixos/modules/services/desktops/gnome/gnome-keyring.nix
index d821da164be..6c7e713b32d 100644
--- a/nixos/modules/services/desktops/gnome/gnome-keyring.nix
+++ b/nixos/modules/services/desktops/gnome/gnome-keyring.nix
@@ -27,7 +27,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable GNOME Keyring daemon, a service designed to
           take care of the user's security credentials,
           such as user names and passwords.
diff --git a/nixos/modules/services/desktops/gnome/gnome-online-accounts.nix b/nixos/modules/services/desktops/gnome/gnome-online-accounts.nix
index 01f7e3695cf..ed5e000cae3 100644
--- a/nixos/modules/services/desktops/gnome/gnome-online-accounts.nix
+++ b/nixos/modules/services/desktops/gnome/gnome-online-accounts.nix
@@ -27,7 +27,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable GNOME Online Accounts daemon, a service that provides
           a single sign-on framework for the GNOME desktop.
         '';
diff --git a/nixos/modules/services/desktops/gnome/gnome-online-miners.nix b/nixos/modules/services/desktops/gnome/gnome-online-miners.nix
index 5f9039f68c4..7cf1bfa1b04 100644
--- a/nixos/modules/services/desktops/gnome/gnome-online-miners.nix
+++ b/nixos/modules/services/desktops/gnome/gnome-online-miners.nix
@@ -27,7 +27,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable GNOME Online Miners, a service that
           crawls through your online content.
         '';
diff --git a/nixos/modules/services/desktops/gnome/gnome-remote-desktop.nix b/nixos/modules/services/desktops/gnome/gnome-remote-desktop.nix
index b5573d2fc21..0a5b67eb272 100644
--- a/nixos/modules/services/desktops/gnome/gnome-remote-desktop.nix
+++ b/nixos/modules/services/desktops/gnome/gnome-remote-desktop.nix
@@ -19,7 +19,7 @@ with lib;
   ###### interface
   options = {
     services.gnome.gnome-remote-desktop = {
-      enable = mkEnableOption "Remote Desktop support using Pipewire";
+      enable = mkEnableOption (lib.mdDoc "Remote Desktop support using Pipewire");
     };
   };
 
diff --git a/nixos/modules/services/desktops/gnome/gnome-settings-daemon.nix b/nixos/modules/services/desktops/gnome/gnome-settings-daemon.nix
index 9c68c9b76e9..ca739b06a5a 100644
--- a/nixos/modules/services/desktops/gnome/gnome-settings-daemon.nix
+++ b/nixos/modules/services/desktops/gnome/gnome-settings-daemon.nix
@@ -34,7 +34,7 @@ in
 
     services.gnome.gnome-settings-daemon = {
 
-      enable = mkEnableOption "GNOME Settings Daemon";
+      enable = mkEnableOption (lib.mdDoc "GNOME Settings Daemon");
 
     };
 
diff --git a/nixos/modules/services/desktops/gnome/gnome-user-share.nix b/nixos/modules/services/desktops/gnome/gnome-user-share.nix
index 38256af309c..0c88d13b343 100644
--- a/nixos/modules/services/desktops/gnome/gnome-user-share.nix
+++ b/nixos/modules/services/desktops/gnome/gnome-user-share.nix
@@ -24,7 +24,7 @@ with lib;
 
     services.gnome.gnome-user-share = {
 
-      enable = mkEnableOption "GNOME User Share, a user-level file sharing service for GNOME";
+      enable = mkEnableOption (lib.mdDoc "GNOME User Share, a user-level file sharing service for GNOME");
 
     };
 
diff --git a/nixos/modules/services/desktops/gnome/rygel.nix b/nixos/modules/services/desktops/gnome/rygel.nix
index 7ea9778fc40..9c0faaa4885 100644
--- a/nixos/modules/services/desktops/gnome/rygel.nix
+++ b/nixos/modules/services/desktops/gnome/rygel.nix
@@ -21,10 +21,10 @@ with lib;
     services.gnome.rygel = {
       enable = mkOption {
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Rygel UPnP Mediaserver.
 
-          You will need to also allow UPnP connections in firewall, see the following <link xlink:href="https://github.com/NixOS/nixpkgs/pull/45045#issuecomment-416030795">comment</link>.
+          You will need to also allow UPnP connections in firewall, see the following [comment](https://github.com/NixOS/nixpkgs/pull/45045#issuecomment-416030795).
         '';
         type = types.bool;
       };
diff --git a/nixos/modules/services/desktops/gnome/sushi.nix b/nixos/modules/services/desktops/gnome/sushi.nix
index 3133a3a0d98..446851f434d 100644
--- a/nixos/modules/services/desktops/gnome/sushi.nix
+++ b/nixos/modules/services/desktops/gnome/sushi.nix
@@ -27,7 +27,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Sushi, a quick previewer for nautilus.
         '';
       };
diff --git a/nixos/modules/services/desktops/gnome/tracker-miners.nix b/nixos/modules/services/desktops/gnome/tracker-miners.nix
index 9351007d30b..a3c58f37420 100644
--- a/nixos/modules/services/desktops/gnome/tracker-miners.nix
+++ b/nixos/modules/services/desktops/gnome/tracker-miners.nix
@@ -27,7 +27,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Tracker miners, indexing services for Tracker
           search engine and metadata storage system.
         '';
diff --git a/nixos/modules/services/desktops/gnome/tracker.nix b/nixos/modules/services/desktops/gnome/tracker.nix
index fef399d0112..e6404c84a26 100644
--- a/nixos/modules/services/desktops/gnome/tracker.nix
+++ b/nixos/modules/services/desktops/gnome/tracker.nix
@@ -30,7 +30,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Tracker services, a search engine,
           search tool and metadata storage system.
         '';
@@ -40,7 +40,7 @@ in
         type = types.listOf types.package;
         default = [ ];
         internal = true;
-        description = ''
+        description = lib.mdDoc ''
           List of packages containing tracker3 subcommands.
         '';
       };
diff --git a/nixos/modules/services/desktops/gsignond.nix b/nixos/modules/services/desktops/gsignond.nix
index 465acd73fa6..cf80fd75452 100644
--- a/nixos/modules/services/desktops/gsignond.nix
+++ b/nixos/modules/services/desktops/gsignond.nix
@@ -20,7 +20,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable gSignOn daemon, a DBus service
           which performs user authentication on behalf of its clients.
         '';
@@ -29,7 +29,7 @@ in
       plugins = mkOption {
         type = types.listOf types.package;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           What plugins to use with the gSignOn daemon.
         '';
       };
diff --git a/nixos/modules/services/desktops/gvfs.nix b/nixos/modules/services/desktops/gvfs.nix
index 1aa64ea37db..7e15b433fcc 100644
--- a/nixos/modules/services/desktops/gvfs.nix
+++ b/nixos/modules/services/desktops/gvfs.nix
@@ -29,14 +29,14 @@ in
 
     services.gvfs = {
 
-      enable = mkEnableOption "GVfs, a userspace virtual filesystem";
+      enable = mkEnableOption (lib.mdDoc "GVfs, a userspace virtual filesystem");
 
       # gvfs can be built with multiple configurations
       package = mkOption {
         type = types.package;
         default = pkgs.gnome.gvfs;
         defaultText = literalExpression "pkgs.gnome.gvfs";
-        description = "Which GVfs package to use.";
+        description = lib.mdDoc "Which GVfs package to use.";
       };
 
     };
@@ -56,6 +56,8 @@ in
 
     services.udev.packages = [ pkgs.libmtp.out ];
 
+    services.udisks2.enable = true;
+
     # Needed for unwrapped applications
     environment.sessionVariables.GIO_EXTRA_MODULES = [ "${cfg.package}/lib/gio/modules" ];
 
diff --git a/nixos/modules/services/desktops/malcontent.nix b/nixos/modules/services/desktops/malcontent.nix
index 1fbeb17e6ae..27b4577f4c2 100644
--- a/nixos/modules/services/desktops/malcontent.nix
+++ b/nixos/modules/services/desktops/malcontent.nix
@@ -12,7 +12,7 @@ with lib;
 
     services.malcontent = {
 
-      enable = mkEnableOption "Malcontent, parental control support for applications";
+      enable = mkEnableOption (lib.mdDoc "Malcontent, parental control support for applications");
 
     };
 
diff --git a/nixos/modules/services/desktops/neard.nix b/nixos/modules/services/desktops/neard.nix
index 9b0f8d1b3a7..9130b8d3d21 100644
--- a/nixos/modules/services/desktops/neard.nix
+++ b/nixos/modules/services/desktops/neard.nix
@@ -7,7 +7,7 @@ with lib;
   ###### interface
   options = {
     services.neard = {
-      enable = mkEnableOption "neard, NFC daemon";
+      enable = mkEnableOption (lib.mdDoc "neard, NFC daemon");
     };
   };
 
diff --git a/nixos/modules/services/desktops/pipewire/daemon/filter-chain.conf.json b/nixos/modules/services/desktops/pipewire/daemon/filter-chain.conf.json
new file mode 100644
index 00000000000..689fca88359
--- /dev/null
+++ b/nixos/modules/services/desktops/pipewire/daemon/filter-chain.conf.json
@@ -0,0 +1,28 @@
+{
+  "context.properties": {
+    "log.level": 0
+  },
+  "context.spa-libs": {
+    "audio.convert.*": "audioconvert/libspa-audioconvert",
+    "support.*": "support/libspa-support"
+  },
+  "context.modules": [
+    {
+      "name": "libpipewire-module-rt",
+      "args": {},
+      "flags": [
+        "ifexists",
+        "nofail"
+      ]
+    },
+    {
+      "name": "libpipewire-module-protocol-native"
+    },
+    {
+      "name": "libpipewire-module-client-node"
+    },
+    {
+      "name": "libpipewire-module-adapter"
+    }
+  ]
+}
diff --git a/nixos/modules/services/desktops/pipewire/daemon/minimal.conf.json b/nixos/modules/services/desktops/pipewire/daemon/minimal.conf.json
index c7f58fd5799..0f1ebe5749c 100644
--- a/nixos/modules/services/desktops/pipewire/daemon/minimal.conf.json
+++ b/nixos/modules/services/desktops/pipewire/daemon/minimal.conf.json
@@ -91,6 +91,7 @@
         "adapter.auto-port-config": {
           "mode": "dsp",
           "monitor": false,
+          "control": false,
           "position": "unknown"
         }
       }
@@ -109,6 +110,7 @@
         "adapter.auto-port-config": {
           "mode": "dsp",
           "monitor": false,
+          "control": false,
           "position": "unknown"
         }
       }
diff --git a/nixos/modules/services/desktops/pipewire/daemon/pipewire-avb.conf.json b/nixos/modules/services/desktops/pipewire/daemon/pipewire-avb.conf.json
new file mode 100644
index 00000000000..4f669895d87
--- /dev/null
+++ b/nixos/modules/services/desktops/pipewire/daemon/pipewire-avb.conf.json
@@ -0,0 +1,38 @@
+{
+  "context.properties": {},
+  "context.spa-libs": {
+    "audio.convert.*": "audioconvert/libspa-audioconvert",
+    "support.*": "support/libspa-support"
+  },
+  "context.modules": [
+    {
+      "name": "libpipewire-module-rt",
+      "args": {
+        "nice.level": -11
+      },
+      "flags": [
+        "ifexists",
+        "nofail"
+      ]
+    },
+    {
+      "name": "libpipewire-module-protocol-native"
+    },
+    {
+      "name": "libpipewire-module-client-node"
+    },
+    {
+      "name": "libpipewire-module-adapter"
+    },
+    {
+      "name": "libpipewire-module-avb",
+      "args": {}
+    }
+  ],
+  "context.exec": [],
+  "stream.properties": {},
+  "avb.properties": {
+    "ifname": "enp3s0",
+    "vm.overrides": {}
+  }
+}
diff --git a/nixos/modules/services/desktops/pipewire/daemon/pipewire-pulse.conf.json b/nixos/modules/services/desktops/pipewire/daemon/pipewire-pulse.conf.json
index df0f62556df..114afbfb0ea 100644
--- a/nixos/modules/services/desktops/pipewire/daemon/pipewire-pulse.conf.json
+++ b/nixos/modules/services/desktops/pipewire/daemon/pipewire-pulse.conf.json
@@ -29,14 +29,7 @@
     },
     {
       "name": "libpipewire-module-protocol-pulse",
-      "args": {
-        "server.address": [
-          "unix:native"
-        ],
-        "vm.overrides": {
-          "pulse.min.quantum": "1024/48000"
-        }
-      }
+      "args": {}
     }
   ],
   "context.exec": [
@@ -46,6 +39,14 @@
     }
   ],
   "stream.properties": {},
+  "pulse.properties": {
+    "server.address": [
+      "unix:native"
+    ],
+    "vm.overrides": {
+      "pulse.min.quantum": "1024/48000"
+    }
+  },
   "pulse.rules": [
     {
       "matches": [
@@ -61,6 +62,9 @@
           "application.process.binary": "teams"
         },
         {
+          "application.process.binary": "teams-insiders"
+        },
+        {
           "application.process.binary": "skypeforlinux"
         }
       ],
diff --git a/nixos/modules/services/desktops/pipewire/daemon/pipewire.conf.json b/nixos/modules/services/desktops/pipewire/daemon/pipewire.conf.json
index 7c79f0168c0..bf3b2d66082 100644
--- a/nixos/modules/services/desktops/pipewire/daemon/pipewire.conf.json
+++ b/nixos/modules/services/desktops/pipewire/daemon/pipewire.conf.json
@@ -10,6 +10,7 @@
   },
   "context.spa-libs": {
     "audio.convert.*": "audioconvert/libspa-audioconvert",
+    "avb.*": "avb/libspa-avb",
     "api.alsa.*": "alsa/libspa-alsa",
     "api.v4l2.*": "v4l2/libspa-v4l2",
     "api.libcamera.*": "libcamera/libspa-libcamera",
diff --git a/nixos/modules/services/desktops/pipewire/pipewire-media-session.nix b/nixos/modules/services/desktops/pipewire/pipewire-media-session.nix
index 6027e4f3d4b..203139294c6 100644
--- a/nixos/modules/services/desktops/pipewire/pipewire-media-session.nix
+++ b/nixos/modules/services/desktops/pipewire/pipewire-media-session.nix
@@ -39,14 +39,14 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the deprecated example Pipewire session manager";
+        description = lib.mdDoc "Whether to enable the deprecated example Pipewire session manager";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.pipewire-media-session;
         defaultText = literalExpression "pkgs.pipewire-media-session";
-        description = ''
+        description = lib.mdDoc ''
           The pipewire-media-session derivation to use.
         '';
       };
@@ -54,38 +54,38 @@ in {
       config = {
         media-session = mkOption {
           type = json.type;
-          description = ''
+          description = lib.mdDoc ''
             Configuration for the media session core. For details see
             https://gitlab.freedesktop.org/pipewire/media-session/-/blob/${cfg.package.version}/src/daemon/media-session.d/media-session.conf
           '';
-          default = {};
+          default = defaults.media-session;
         };
 
         alsa-monitor = mkOption {
           type = json.type;
-          description = ''
+          description = lib.mdDoc ''
             Configuration for the alsa monitor. For details see
             https://gitlab.freedesktop.org/pipewire/media-session/-/blob/${cfg.package.version}/src/daemon/media-session.d/alsa-monitor.conf
           '';
-          default = {};
+          default = defaults.alsa-monitor;
         };
 
         bluez-monitor = mkOption {
           type = json.type;
-          description = ''
+          description = lib.mdDoc ''
             Configuration for the bluez5 monitor. For details see
             https://gitlab.freedesktop.org/pipewire/media-session/-/blob/${cfg.package.version}/src/daemon/media-session.d/bluez-monitor.conf
           '';
-          default = {};
+          default = defaults.bluez-monitor;
         };
 
         v4l2-monitor = mkOption {
           type = json.type;
-          description = ''
+          description = lib.mdDoc ''
             Configuration for the V4L2 monitor. For details see
             https://gitlab.freedesktop.org/pipewire/media-session/-/blob/${cfg.package.version}/src/daemon/media-session.d/v4l2-monitor.conf
           '';
-          default = {};
+          default = defaults.v4l2-monitor;
         };
       };
     };
diff --git a/nixos/modules/services/desktops/pipewire/pipewire.nix b/nixos/modules/services/desktops/pipewire/pipewire.nix
index 1323336d866..a4ef88a45ad 100644
--- a/nixos/modules/services/desktops/pipewire/pipewire.nix
+++ b/nixos/modules/services/desktops/pipewire/pipewire.nix
@@ -50,13 +50,13 @@ in {
   ###### interface
   options = {
     services.pipewire = {
-      enable = mkEnableOption "pipewire service";
+      enable = mkEnableOption (lib.mdDoc "pipewire service");
 
       package = mkOption {
         type = types.package;
         default = pkgs.pipewire;
         defaultText = literalExpression "pkgs.pipewire";
-        description = ''
+        description = lib.mdDoc ''
           The pipewire derivation to use.
         '';
       };
@@ -64,7 +64,7 @@ in {
       socketActivation = mkOption {
         default = true;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Automatically run pipewire when connections are made to the pipewire socket.
         '';
       };
@@ -73,7 +73,7 @@ in {
         client = mkOption {
           type = json.type;
           default = {};
-          description = ''
+          description = lib.mdDoc ''
             Configuration for pipewire clients. For details see
             https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/${cfg.package.version}/src/daemon/client.conf.in
           '';
@@ -82,7 +82,7 @@ in {
         client-rt = mkOption {
           type = json.type;
           default = {};
-          description = ''
+          description = lib.mdDoc ''
             Configuration for realtime pipewire clients. For details see
             https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/${cfg.package.version}/src/daemon/client-rt.conf.in
           '';
@@ -91,7 +91,7 @@ in {
         jack = mkOption {
           type = json.type;
           default = {};
-          description = ''
+          description = lib.mdDoc ''
             Configuration for the pipewire daemon's jack module. For details see
             https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/${cfg.package.version}/src/daemon/jack.conf.in
           '';
@@ -100,7 +100,7 @@ in {
         pipewire = mkOption {
           type = json.type;
           default = {};
-          description = ''
+          description = lib.mdDoc ''
             Configuration for the pipewire daemon. For details see
             https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/${cfg.package.version}/src/daemon/pipewire.conf.in
           '';
@@ -109,7 +109,7 @@ in {
         pipewire-pulse = mkOption {
           type = json.type;
           default = {};
-          description = ''
+          description = lib.mdDoc ''
             Configuration for the pipewire-pulse daemon. For details see
             https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/${cfg.package.version}/src/daemon/pipewire-pulse.conf.in
           '';
@@ -122,27 +122,27 @@ in {
           # this is for backwards compatibility
           default = cfg.alsa.enable || cfg.jack.enable || cfg.pulse.enable;
           defaultText = lib.literalExpression "config.services.pipewire.alsa.enable || config.services.pipewire.jack.enable || config.services.pipewire.pulse.enable";
-          description = "Whether to use PipeWire as the primary sound server";
+          description = lib.mdDoc "Whether to use PipeWire as the primary sound server";
         };
       };
 
       alsa = {
-        enable = mkEnableOption "ALSA support";
-        support32Bit = mkEnableOption "32-bit ALSA support on 64-bit systems";
+        enable = mkEnableOption (lib.mdDoc "ALSA support");
+        support32Bit = mkEnableOption (lib.mdDoc "32-bit ALSA support on 64-bit systems");
       };
 
       jack = {
-        enable = mkEnableOption "JACK audio emulation";
+        enable = mkEnableOption (lib.mdDoc "JACK audio emulation");
       };
 
       pulse = {
-        enable = mkEnableOption "PulseAudio server emulation";
+        enable = mkEnableOption (lib.mdDoc "PulseAudio server emulation");
       };
 
       systemWide = lib.mkOption {
         type = lib.types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If true, a system-wide PipeWire service and socket is enabled
           allowing all users in the "pipewire" group to use it simultaneously.
           If false, then user units are used instead, restricting access to
@@ -234,12 +234,12 @@ in {
     environment.etc."pipewire/pipewire.conf" = {
       source = json.generate "pipewire.conf" configs.pipewire;
     };
-    environment.etc."pipewire/pipewire-pulse.conf" = {
+    environment.etc."pipewire/pipewire-pulse.conf" = mkIf cfg.pulse.enable {
       source = json.generate "pipewire-pulse.conf" configs.pipewire-pulse;
     };
 
     environment.sessionVariables.LD_LIBRARY_PATH =
-      lib.optional cfg.jack.enable "${cfg.package.jack}/lib";
+      lib.mkIf cfg.jack.enable [ "${cfg.package.jack}/lib" ];
 
     users = lib.mkIf cfg.systemWide {
       users.pipewire = {
@@ -251,6 +251,8 @@ in {
         ] ++ lib.optional config.security.rtkit.enable "rtkit";
         description = "Pipewire system service user";
         isSystemUser = true;
+        home = "/var/lib/pipewire";
+        createHome = true;
       };
       groups.pipewire.gid = config.ids.gids.pipewire;
     };
@@ -258,5 +260,8 @@ in {
     # https://gitlab.freedesktop.org/pipewire/pipewire/-/issues/464#note_723554
     systemd.services.pipewire.environment."PIPEWIRE_LINK_PASSIVE" = "1";
     systemd.user.services.pipewire.environment."PIPEWIRE_LINK_PASSIVE" = "1";
+
+    # pipewire-pulse default config expects pactl to be in PATH
+    systemd.user.services.pipewire-pulse.path = lib.mkIf cfg.pulse.enable [ pkgs.pulseaudio ];
   };
 }
diff --git a/nixos/modules/services/desktops/pipewire/wireplumber.nix b/nixos/modules/services/desktops/pipewire/wireplumber.nix
index 32206ccb4e6..32490773b5e 100644
--- a/nixos/modules/services/desktops/pipewire/wireplumber.nix
+++ b/nixos/modules/services/desktops/pipewire/wireplumber.nix
@@ -14,14 +14,14 @@ in
         type = lib.types.bool;
         default = config.services.pipewire.enable;
         defaultText = lib.literalExpression "config.services.pipewire.enable";
-        description = "Whether to enable Wireplumber, a modular session / policy manager for PipeWire";
+        description = lib.mdDoc "Whether to enable Wireplumber, a modular session / policy manager for PipeWire";
       };
 
       package = lib.mkOption {
         type = lib.types.package;
         default = pkgs.wireplumber;
         defaultText = lib.literalExpression "pkgs.wireplumber";
-        description = "The wireplumber derivation to use.";
+        description = lib.mdDoc "The wireplumber derivation to use.";
       };
     };
   };
@@ -37,11 +37,25 @@ in
     environment.systemPackages = [ cfg.package ];
 
     environment.etc."wireplumber/main.lua.d/80-nixos.lua" = lib.mkIf (!pwUsedForAudio) {
-     text = ''
-        # Pipewire is not used for audio, so prevent it from grabbing audio devices
+      text = ''
+        -- Pipewire is not used for audio, so prevent it from grabbing audio devices
         alsa_monitor.enable = function() end
       '';
     };
+    environment.etc."wireplumber/main.lua.d/80-systemwide.lua" = lib.mkIf config.services.pipewire.systemWide {
+      text = ''
+        -- When running system-wide, these settings need to be disabled (they
+        -- use functions that aren't available on the system dbus).
+        alsa_monitor.properties["alsa.reserve"] = false
+        default_access.properties["enable-flatpak-portal"] = false
+      '';
+    };
+    environment.etc."wireplumber/bluetooth.lua.d/80-systemwide.lua" = lib.mkIf config.services.pipewire.systemWide {
+      text = ''
+        -- When running system-wide, logind-integration needs to be disabled.
+        bluez_monitor.properties["with-logind"] = false
+      '';
+    };
 
     systemd.packages = [ cfg.package ];
 
@@ -50,5 +64,10 @@ in
 
     systemd.services.wireplumber.wantedBy = [ "pipewire.service" ];
     systemd.user.services.wireplumber.wantedBy = [ "pipewire.service" ];
+
+    systemd.services.wireplumber.environment = lib.mkIf config.services.pipewire.systemWide {
+      # Force wireplumber to use system dbus.
+      DBUS_SESSION_BUS_ADDRESS = "unix:path=/run/dbus/system_bus_socket";
+    };
   };
 }
diff --git a/nixos/modules/services/desktops/profile-sync-daemon.nix b/nixos/modules/services/desktops/profile-sync-daemon.nix
index 6206295272f..e307c673500 100644
--- a/nixos/modules/services/desktops/profile-sync-daemon.nix
+++ b/nixos/modules/services/desktops/profile-sync-daemon.nix
@@ -9,7 +9,7 @@ in {
     enable = mkOption {
       type = bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable the Profile Sync daemon.
       '';
     };
@@ -17,7 +17,7 @@ in {
       type = str;
       default = "1h";
       example = "1h 30min";
-      description = ''
+      description = lib.mdDoc ''
         The amount of time to wait before syncing browser profiles back to the
         disk.
 
diff --git a/nixos/modules/services/desktops/system-config-printer.nix b/nixos/modules/services/desktops/system-config-printer.nix
index 09c68c587b4..caebfabf146 100644
--- a/nixos/modules/services/desktops/system-config-printer.nix
+++ b/nixos/modules/services/desktops/system-config-printer.nix
@@ -10,7 +10,7 @@ with lib;
 
     services.system-config-printer = {
 
-      enable = mkEnableOption "system-config-printer, a service for CUPS administration used by printing interfaces";
+      enable = mkEnableOption (lib.mdDoc "system-config-printer, a service for CUPS administration used by printing interfaces");
 
     };
 
@@ -34,7 +34,8 @@ with lib;
     ];
 
     # for $out/bin/install-printer-driver
-    services.packagekit.enable = true;
+    # TODO: Enable once #177946 is resolved
+    # services.packagekit.enable = true;
 
   };
 
diff --git a/nixos/modules/services/desktops/telepathy.nix b/nixos/modules/services/desktops/telepathy.nix
index b5f6a5fcbcf..cdc6eb26de7 100644
--- a/nixos/modules/services/desktops/telepathy.nix
+++ b/nixos/modules/services/desktops/telepathy.nix
@@ -19,7 +19,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Telepathy service, a communications framework
           that enables real-time communication via pluggable protocol backends.
         '';
diff --git a/nixos/modules/services/desktops/tumbler.nix b/nixos/modules/services/desktops/tumbler.nix
index f5341df2f7a..203071ec660 100644
--- a/nixos/modules/services/desktops/tumbler.nix
+++ b/nixos/modules/services/desktops/tumbler.nix
@@ -28,7 +28,7 @@ in
 
     services.tumbler = {
 
-      enable = mkEnableOption "Tumbler, A D-Bus thumbnailer service";
+      enable = mkEnableOption (lib.mdDoc "Tumbler, A D-Bus thumbnailer service");
 
     };
 
diff --git a/nixos/modules/services/desktops/zeitgeist.nix b/nixos/modules/services/desktops/zeitgeist.nix
index 297fd1d3ff2..0eb2a4c9c37 100644
--- a/nixos/modules/services/desktops/zeitgeist.nix
+++ b/nixos/modules/services/desktops/zeitgeist.nix
@@ -14,7 +14,7 @@ with lib;
 
   options = {
     services.zeitgeist = {
-      enable = mkEnableOption "zeitgeist";
+      enable = mkEnableOption (lib.mdDoc "zeitgeist");
     };
   };
 
diff --git a/nixos/modules/services/development/blackfire.nix b/nixos/modules/services/development/blackfire.nix
index 8564aabc6a3..054cef9ae80 100644
--- a/nixos/modules/services/development/blackfire.nix
+++ b/nixos/modules/services/development/blackfire.nix
@@ -16,9 +16,9 @@ in {
 
   options = {
     services.blackfire-agent = {
-      enable = lib.mkEnableOption "Blackfire profiler agent";
+      enable = lib.mkEnableOption (lib.mdDoc "Blackfire profiler agent");
       settings = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           See https://blackfire.io/docs/up-and-running/configuration/agent
         '';
         type = lib.types.submodule {
@@ -27,7 +27,7 @@ in {
           options = {
             server-id = lib.mkOption {
               type = lib.types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Sets the server id used to authenticate with Blackfire
 
                 You can find your personal server-id at https://blackfire.io/my/settings/credentials
@@ -36,7 +36,7 @@ in {
 
             server-token = lib.mkOption {
               type = lib.types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Sets the server token used to authenticate with Blackfire
 
                 You can find your personal server-token at https://blackfire.io/my/settings/credentials
diff --git a/nixos/modules/services/development/bloop.nix b/nixos/modules/services/development/bloop.nix
index c1180a8bbdd..27da76a7443 100644
--- a/nixos/modules/services/development/bloop.nix
+++ b/nixos/modules/services/development/bloop.nix
@@ -17,7 +17,7 @@ in {
         "-J-XX:MaxInlineLevel=20"
         "-J-XX:+UseParallelGC"
       ];
-      description = ''
+      description = lib.mdDoc ''
         Specifies additional command line argument to pass to bloop
         java process.
       '';
@@ -26,7 +26,7 @@ in {
     install = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to install a user service for the Bloop server.
 
         The service must be manually started for each user with
diff --git a/nixos/modules/services/development/distccd.nix b/nixos/modules/services/development/distccd.nix
index 9f6d5c813c4..a3c909eb195 100644
--- a/nixos/modules/services/development/distccd.nix
+++ b/nixos/modules/services/development/distccd.nix
@@ -8,13 +8,13 @@ in
 {
   options = {
     services.distccd = {
-      enable = mkEnableOption "distccd";
+      enable = mkEnableOption (lib.mdDoc "distccd");
 
       allowedClients = mkOption {
         type = types.listOf types.str;
         default = [ "127.0.0.1" ];
         example = [ "127.0.0.1" "192.168.0.0/24" "10.0.0.0/24" ];
-        description = ''
+        description = lib.mdDoc ''
           Client IPs which are allowed to connect to distccd in CIDR notation.
 
           Anyone who can connect to the distccd server can run arbitrary
@@ -26,7 +26,7 @@ in
       jobTimeout = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Maximum duration, in seconds, of a single compilation request.
         '';
       };
@@ -34,7 +34,7 @@ in
       logLevel = mkOption {
         type = types.nullOr (types.enum [ "critical" "error" "warning" "notice" "info" "debug" ]);
         default = "warning";
-        description = ''
+        description = lib.mdDoc ''
           Set the minimum severity of error that will be included in the log
           file. Useful if you only want to see error messages rather than an
           entry for each connection.
@@ -44,7 +44,7 @@ in
       maxJobs = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of tasks distccd should execute at any time.
         '';
       };
@@ -53,7 +53,7 @@ in
       nice = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Niceness of the compilation tasks.
         '';
       };
@@ -61,7 +61,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Opens the specified TCP port for distcc.
         '';
       };
@@ -70,7 +70,7 @@ in
         type = types.package;
         default = pkgs.distcc;
         defaultText = literalExpression "pkgs.distcc";
-        description = ''
+        description = lib.mdDoc ''
           The distcc package to use.
         '';
       };
@@ -78,17 +78,17 @@ in
       port = mkOption {
         type = types.port;
         default = 3632;
-        description = ''
+        description = lib.mdDoc ''
           The TCP port which distccd will listen on.
         '';
       };
 
       stats = {
-        enable = mkEnableOption "statistics reporting via HTTP server";
+        enable = mkEnableOption (lib.mdDoc "statistics reporting via HTTP server");
         port = mkOption {
           type = types.port;
           default = 3633;
-          description = ''
+          description = lib.mdDoc ''
             The TCP port which the distccd statistics HTTP server will listen
             on.
           '';
@@ -98,7 +98,7 @@ in
       zeroconf = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to register via mDNS/DNS-SD
         '';
       };
diff --git a/nixos/modules/services/development/hoogle.nix b/nixos/modules/services/development/hoogle.nix
index 7c2a1c8e162..88dd01fd8aa 100644
--- a/nixos/modules/services/development/hoogle.nix
+++ b/nixos/modules/services/development/hoogle.nix
@@ -14,12 +14,12 @@ let
 in {
 
   options.services.hoogle = {
-    enable = mkEnableOption "Haskell documentation server";
+    enable = mkEnableOption (lib.mdDoc "Haskell documentation server");
 
     port = mkOption {
       type = types.port;
       default = 8080;
-      description = ''
+      description = lib.mdDoc ''
         Port number Hoogle will be listening to.
       '';
     };
@@ -29,17 +29,17 @@ in {
       default = hp: [];
       defaultText = literalExpression "hp: []";
       example = literalExpression "hp: with hp; [ text lens ]";
-      description = ''
+      description = lib.mdDoc ''
         The Haskell packages to generate documentation for.
 
         The option value is a function that takes the package set specified in
-        the <varname>haskellPackages</varname> option as its sole parameter and
+        the {var}`haskellPackages` option as its sole parameter and
         returns a list of packages.
       '';
     };
 
     haskellPackages = mkOption {
-      description = "Which haskell package set to use.";
+      description = lib.mdDoc "Which haskell package set to use.";
       type = types.attrs;
       default = pkgs.haskellPackages;
       defaultText = literalExpression "pkgs.haskellPackages";
@@ -47,13 +47,13 @@ in {
 
     home = mkOption {
       type = types.str;
-      description = "Url for hoogle logo";
+      description = lib.mdDoc "Url for hoogle logo";
       default = "https://hoogle.haskell.org";
     };
 
     host = mkOption {
       type = types.str;
-      description = "Set the host to bind on.";
+      description = lib.mdDoc "Set the host to bind on.";
       default = "127.0.0.1";
     };
   };
diff --git a/nixos/modules/services/development/jupyter/default.nix b/nixos/modules/services/development/jupyter/default.nix
index bebb3c3f13f..c3ef040ebe6 100644
--- a/nixos/modules/services/development/jupyter/default.nix
+++ b/nixos/modules/services/development/jupyter/default.nix
@@ -24,12 +24,12 @@ in {
   meta.maintainers = with maintainers; [ aborsu ];
 
   options.services.jupyter = {
-    enable = mkEnableOption "Jupyter development server";
+    enable = mkEnableOption (lib.mdDoc "Jupyter development server");
 
     ip = mkOption {
       type = types.str;
       default = "localhost";
-      description = ''
+      description = lib.mdDoc ''
         IP address Jupyter will be listening on.
       '';
     };
@@ -41,7 +41,7 @@ in {
       # saving a rebuild.
       default = pkgs.python3.pkgs.notebook;
       defaultText = literalExpression "pkgs.python3.pkgs.notebook";
-      description = ''
+      description = lib.mdDoc ''
         Jupyter package to use.
       '';
     };
@@ -50,7 +50,7 @@ in {
       type = types.str;
       default = "jupyter-notebook";
       example = "jupyter-lab";
-      description = ''
+      description = lib.mdDoc ''
         Which command the service runs. Note that not all jupyter packages
         have all commands, e.g. jupyter-lab isn't present in the default package.
        '';
@@ -59,7 +59,7 @@ in {
     port = mkOption {
       type = types.int;
       default = 8888;
-      description = ''
+      description = lib.mdDoc ''
         Port number Jupyter will be listening on.
       '';
     };
@@ -67,7 +67,7 @@ in {
     notebookDir = mkOption {
       type = types.str;
       default = "~/";
-      description = ''
+      description = lib.mdDoc ''
         Root directory for notebooks.
       '';
     };
@@ -75,7 +75,7 @@ in {
     user = mkOption {
       type = types.str;
       default = "jupyter";
-      description = ''
+      description = lib.mdDoc ''
         Name of the user used to run the jupyter service.
         For security reason, jupyter should really not be run as root.
         If not set (jupyter), the service will create a jupyter user with appropriate settings.
@@ -86,7 +86,7 @@ in {
     group = mkOption {
       type = types.str;
       default = "jupyter";
-      description = ''
+      description = lib.mdDoc ''
         Name of the group used to run the jupyter service.
         Use this if you want to create a group of users that are able to view the notebook directory's content.
       '';
@@ -95,7 +95,7 @@ in {
 
     password = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Password to use with notebook.
         Can be generated using:
           In [1]: from notebook.auth import passwd
@@ -112,14 +112,14 @@ in {
     notebookConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Raw jupyter config.
       '';
     };
 
     kernels = mkOption {
       type = types.nullOr (types.attrsOf(types.submodule (import ./kernel-options.nix {
-        inherit lib;
+        inherit lib pkgs;
       })));
 
       default = null;
@@ -143,16 +143,20 @@ in {
             language = "python";
             logo32 = "''${env.sitePackages}/ipykernel/resources/logo-32x32.png";
             logo64 = "''${env.sitePackages}/ipykernel/resources/logo-64x64.png";
+            extraPaths = {
+              "cool.txt" = pkgs.writeText "cool" "cool content";
+            };
           };
         }
       '';
-      description = "Declarative kernel config
+      description = lib.mdDoc ''
+        Declarative kernel config.
 
-      Kernels can be declared in any language that supports and has the required
-      dependencies to communicate with a jupyter server.
-      In python's case, it means that ipykernel package must always be included in
-      the list of packages of the targeted environment.
-      ";
+        Kernels can be declared in any language that supports and has the required
+        dependencies to communicate with a jupyter server.
+        In python's case, it means that ipykernel package must always be included in
+        the list of packages of the targeted environment.
+      '';
     };
   };
 
@@ -194,6 +198,7 @@ in {
         extraGroups = [ cfg.group ];
         home = "/var/lib/jupyter";
         createHome = true;
+        isSystemUser = true;
         useDefaultShell = true; # needed so that the user can start a terminal.
       };
     })
diff --git a/nixos/modules/services/development/jupyter/kernel-options.nix b/nixos/modules/services/development/jupyter/kernel-options.nix
index 348a8b44b38..6e406152de4 100644
--- a/nixos/modules/services/development/jupyter/kernel-options.nix
+++ b/nixos/modules/services/development/jupyter/kernel-options.nix
@@ -1,9 +1,11 @@
 # Options that can be used for creating a jupyter kernel.
-{lib }:
+{ lib, pkgs }:
 
 with lib;
 
 {
+  freeformType = (pkgs.formats.json { }).type;
+
   options = {
 
     displayName = mkOption {
@@ -13,7 +15,7 @@ with lib;
         "Python 3"
         "Python 3 for Data Science"
       '';
-      description = ''
+      description = lib.mdDoc ''
         Name that will be shown to the user.
       '';
     };
@@ -27,7 +29,7 @@ with lib;
         "-f"
         "{connection_file}"
       ];
-      description = ''
+      description = lib.mdDoc ''
         Command and arguments to start the kernel.
       '';
     };
@@ -35,16 +37,25 @@ with lib;
     language = mkOption {
       type = types.str;
       example = "python";
-      description = ''
+      description = lib.mdDoc ''
         Language of the environment. Typically the name of the binary.
       '';
     };
 
+    env = mkOption {
+      type = types.attrsOf types.str;
+      default = { };
+      example = { OMP_NUM_THREADS = "1"; };
+      description = lib.mdDoc ''
+        Environment variables to set for the kernel.
+      '';
+    };
+
     logo32 = mkOption {
       type = types.nullOr types.path;
       default = null;
       example = literalExpression ''"''${env.sitePackages}/ipykernel/resources/logo-32x32.png"'';
-      description = ''
+      description = lib.mdDoc ''
         Path to 32x32 logo png.
       '';
     };
@@ -52,9 +63,18 @@ with lib;
       type = types.nullOr types.path;
       default = null;
       example = literalExpression ''"''${env.sitePackages}/ipykernel/resources/logo-64x64.png"'';
-      description = ''
+      description = lib.mdDoc ''
         Path to 64x64 logo png.
       '';
     };
+
+    extraPaths = mkOption {
+      type = types.attrsOf types.path;
+      default = { };
+      example = literalExpression ''"{ examples = ''${env.sitePack}/IRkernel/kernelspec/kernel.js"; }'';
+      description = lib.mdDoc ''
+        Extra paths to link in kernel directory
+      '';
+    };
   };
 }
diff --git a/nixos/modules/services/development/jupyterhub/default.nix b/nixos/modules/services/development/jupyterhub/default.nix
index fa6b3be960a..cebc35a5047 100644
--- a/nixos/modules/services/development/jupyterhub/default.nix
+++ b/nixos/modules/services/development/jupyterhub/default.nix
@@ -30,12 +30,12 @@ in {
   meta.maintainers = with maintainers; [ costrouc ];
 
   options.services.jupyterhub = {
-    enable = mkEnableOption "Jupyterhub development server";
+    enable = mkEnableOption (lib.mdDoc "Jupyterhub development server");
 
     authentication = mkOption {
       type = types.str;
       default = "jupyterhub.auth.PAMAuthenticator";
-      description = ''
+      description = lib.mdDoc ''
         Jupyterhub authentication to use
 
         There are many authenticators available including: oauth, pam,
@@ -46,7 +46,7 @@ in {
     spawner = mkOption {
       type = types.str;
       default = "systemdspawner.SystemdSpawner";
-      description = ''
+      description = lib.mdDoc ''
         Jupyterhub spawner to use
 
         There are many spawners available including: local process,
@@ -57,7 +57,7 @@ in {
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra contents appended to the jupyterhub configuration
 
         Jupyterhub configuration is a normal python file using
@@ -84,7 +84,7 @@ in {
           jupyterhub-systemdspawner
         ])
       '';
-      description = ''
+      description = lib.mdDoc ''
         Python environment to run jupyterhub
 
         Customizing will affect the packages available in the hub and
@@ -106,7 +106,7 @@ in {
           jupyterlab
         ])
       '';
-      description = ''
+      description = lib.mdDoc ''
         Python environment to run jupyterlab
 
         Customizing will affect the packages available in the
@@ -119,7 +119,7 @@ in {
 
     kernels = mkOption {
       type = types.nullOr (types.attrsOf(types.submodule (import ../jupyter/kernel-options.nix {
-        inherit lib;
+        inherit lib pkgs;
       })));
 
       default = null;
@@ -146,7 +146,7 @@ in {
           };
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Declarative kernel config
 
         Kernels can be declared in any language that supports and has
@@ -159,7 +159,7 @@ in {
     port = mkOption {
       type = types.port;
       default = 8000;
-      description = ''
+      description = lib.mdDoc ''
         Port number Jupyterhub will be listening on
       '';
     };
@@ -167,7 +167,7 @@ in {
     host = mkOption {
       type = types.str;
       default = "0.0.0.0";
-      description = ''
+      description = lib.mdDoc ''
         Bind IP JupyterHub will be listening on
       '';
     };
@@ -175,7 +175,7 @@ in {
     stateDirectory = mkOption {
       type = types.str;
       default = "jupyterhub";
-      description = ''
+      description = lib.mdDoc ''
         Directory for jupyterhub state (token + database)
       '';
     };
diff --git a/nixos/modules/services/development/lorri.nix b/nixos/modules/services/development/lorri.nix
index bda63518bfd..8c64e3d9a56 100644
--- a/nixos/modules/services/development/lorri.nix
+++ b/nixos/modules/services/development/lorri.nix
@@ -9,7 +9,7 @@ in {
       enable = lib.mkOption {
         default = false;
         type = lib.types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Enables the daemon for `lorri`, a nix-shell replacement for project
           development. The socket-activated daemon starts on the first request
           issued by the `lorri` command.
@@ -18,7 +18,7 @@ in {
       package = lib.mkOption {
         default = pkgs.lorri;
         type = lib.types.package;
-        description = ''
+        description = lib.mdDoc ''
           The lorri package to use.
         '';
         defaultText = lib.literalExpression "pkgs.lorri";
diff --git a/nixos/modules/services/development/rstudio-server/default.nix b/nixos/modules/services/development/rstudio-server/default.nix
index cd903c7e55b..bf4c7727bf7 100644
--- a/nixos/modules/services/development/rstudio-server/default.nix
+++ b/nixos/modules/services/development/rstudio-server/default.nix
@@ -21,12 +21,12 @@ in
   meta.maintainers = with maintainers; [ jbedo cfhammill ];
 
   options.services.rstudio-server = {
-    enable = mkEnableOption "RStudio server";
+    enable = mkEnableOption (lib.mdDoc "RStudio server");
 
     serverWorkingDir = mkOption {
       type = types.str;
       default = "/var/lib/rstudio-server";
-      description = ''
+      description = lib.mdDoc ''
         Default working directory for server (server-working-dir in rserver.conf).
       '';
     };
@@ -34,7 +34,7 @@ in
     listenAddr = mkOption {
       type = types.str;
       default = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         Address to listen on (www-address in rserver.conf).
       '';
     };
@@ -44,7 +44,7 @@ in
       default = pkgs.rstudio-server;
       defaultText = literalExpression "pkgs.rstudio-server";
       example = literalExpression "pkgs.rstudioServerWrapper.override { packages = [ pkgs.rPackages.ggplot2 ]; }";
-      description = ''
+      description = lib.mdDoc ''
         Rstudio server package to use. Can be set to rstudioServerWrapper to provide packages.
       '';
     };
@@ -52,7 +52,7 @@ in
     rserverExtraConfig = mkOption {
       type = types.str;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra contents for rserver.conf.
       '';
     };
@@ -60,7 +60,7 @@ in
     rsessionExtraConfig = mkOption {
       type = types.str;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra contents for resssion.conf.
       '';
     };
diff --git a/nixos/modules/services/development/zammad.nix b/nixos/modules/services/development/zammad.nix
index d457a607187..7de11b08b7e 100644
--- a/nixos/modules/services/development/zammad.nix
+++ b/nixos/modules/services/development/zammad.nix
@@ -28,19 +28,19 @@ in
 
   options = {
     services.zammad = {
-      enable = mkEnableOption "Zammad, a web-based, open source user support/ticketing solution.";
+      enable = mkEnableOption (lib.mdDoc "Zammad, a web-based, open source user support/ticketing solution.");
 
       package = mkOption {
         type = types.package;
         default = pkgs.zammad;
         defaultText = literalExpression "pkgs.zammad";
-        description = "Zammad package to use.";
+        description = lib.mdDoc "Zammad package to use.";
       };
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/zammad";
-        description = ''
+        description = lib.mdDoc ''
           Path to a folder that will contain Zammad working directory.
         '';
       };
@@ -49,25 +49,25 @@ in
         type = types.str;
         default = "127.0.0.1";
         example = "192.168.23.42";
-        description = "Host address.";
+        description = lib.mdDoc "Host address.";
       };
 
       openPorts = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to open firewall ports for Zammad";
+        description = lib.mdDoc "Whether to open firewall ports for Zammad";
       };
 
       port = mkOption {
         type = types.port;
         default = 3000;
-        description = "Web service port.";
+        description = lib.mdDoc "Web service port.";
       };
 
       websocketPort = mkOption {
         type = types.port;
         default = 6042;
-        description = "Websocket service port.";
+        description = lib.mdDoc "Websocket service port.";
       };
 
       database = {
@@ -75,7 +75,7 @@ in
           type = types.enum [ "PostgreSQL" "MySQL" ];
           default = "PostgreSQL";
           example = "MySQL";
-          description = "Database engine to use.";
+          description = lib.mdDoc "Database engine to use.";
         };
 
         host = mkOption {
@@ -90,7 +90,7 @@ in
               MySQL = "localhost";
             }.''${config.services.zammad.database.type};
           '';
-          description = ''
+          description = lib.mdDoc ''
             Database host address.
           '';
         };
@@ -98,13 +98,13 @@ in
         port = mkOption {
           type = types.nullOr types.port;
           default = null;
-          description = "Database port. Use <literal>null</literal> for default port.";
+          description = lib.mdDoc "Database port. Use `null` for default port.";
         };
 
         name = mkOption {
           type = types.str;
           default = "zammad";
-          description = ''
+          description = lib.mdDoc ''
             Database name.
           '';
         };
@@ -112,22 +112,22 @@ in
         user = mkOption {
           type = types.nullOr types.str;
           default = "zammad";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/zammad-dbpassword";
-          description = ''
-            A file containing the password for <option>services.zammad.database.user</option>.
+          description = lib.mdDoc ''
+            A file containing the password for {option}`services.zammad.database.user`.
           '';
         };
 
         createLocally = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether to create a local database automatically.";
+          description = lib.mdDoc "Whether to create a local database automatically.";
         };
 
         settings = mkOption {
@@ -137,9 +137,9 @@ in
             {
             }
           '';
-          description = ''
-            The <filename>database.yml</filename> configuration file as key value set.
-            See <link xlink:href='TODO' />
+          description = lib.mdDoc ''
+            The {file}`database.yml` configuration file as key value set.
+            See \<TODO\>
             for list of configuration parameters.
           '';
         };
@@ -149,20 +149,20 @@ in
         type = types.nullOr types.path;
         default = null;
         example = "/run/keys/secret_key_base";
-        description = ''
+        description = lib.mdDoc ''
           The path to a file containing the
-          <literal>secret_key_base</literal> secret.
+          `secret_key_base` secret.
 
-          Zammad uses <literal>secret_key_base</literal> to encrypt
+          Zammad uses `secret_key_base` to encrypt
           the cookie store, which contains session data, and to digest
           user auth tokens.
 
           Needs to be a 64 byte long string of hexadecimal
           characters. You can generate one by running
 
-          <screen>
-          <prompt>$ </prompt>openssl rand -hex 64 >/path/to/secret_key_base_file
-          </screen>
+          ```
+          openssl rand -hex 64 >/path/to/secret_key_base_file
+          ```
 
           This should be a string, not a nix path, since nix paths are
           copied into the world-readable nix store.
diff --git a/nixos/modules/services/display-managers/greetd.nix b/nixos/modules/services/display-managers/greetd.nix
index 895961707d3..fa3f8fdf4f1 100644
--- a/nixos/modules/services/display-managers/greetd.nix
+++ b/nixos/modules/services/display-managers/greetd.nix
@@ -8,13 +8,13 @@ let
 in
 {
   options.services.greetd = {
-    enable = mkEnableOption "greetd";
+    enable = mkEnableOption (lib.mdDoc "greetd");
 
     package = mkOption {
       type = types.package;
       default = pkgs.greetd.greetd;
       defaultText = literalExpression "pkgs.greetd.greetd";
-      description = "The greetd package that should be used.";
+      description = lib.mdDoc "The greetd package that should be used.";
     };
 
     settings = mkOption {
@@ -26,8 +26,8 @@ in
           };
         }
       '';
-      description = ''
-        greetd configuration (<link xlink:href="https://man.sr.ht/~kennylevinsen/greetd/">documentation</link>)
+      description = lib.mdDoc ''
+        greetd configuration ([documentation](https://man.sr.ht/~kennylevinsen/greetd/))
         as a Nix attribute set.
       '';
     };
@@ -35,7 +35,7 @@ in
     vt = mkOption  {
       type = types.int;
       default = 1;
-      description = ''
+      description = lib.mdDoc ''
         The virtual console (tty) that greetd should use. This option also disables getty on that tty.
       '';
     };
@@ -44,7 +44,7 @@ in
       type = types.bool;
       default = !(cfg.settings ? initial_session);
       defaultText = literalExpression "!(config.services.greetd.settings ? initial_session)";
-      description = ''
+      description = lib.mdDoc ''
         Wether to restart greetd when it terminates (e.g. on failure).
         This is usually desirable so a user can always log in, but should be disabled when using 'settings.initial_session' (autologin),
         because every greetd restart will trigger the autologin again.
@@ -54,7 +54,7 @@ in
   config = mkIf cfg.enable {
 
     services.greetd.settings.terminal.vt = mkDefault cfg.vt;
-    services.greetd.settings.default_session = mkDefault "greeter";
+    services.greetd.settings.default_session.user = mkDefault "greeter";
 
     security.pam.services.greetd = {
       allowNullPassword = true;
diff --git a/nixos/modules/services/editors/emacs.nix b/nixos/modules/services/editors/emacs.nix
index e2bbd27f6e5..5ae28cd9bbb 100644
--- a/nixos/modules/services/editors/emacs.nix
+++ b/nixos/modules/services/editors/emacs.nix
@@ -41,24 +41,24 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
-        Whether to enable a user service for the Emacs daemon. Use <literal>emacsclient</literal> to connect to the
-        daemon. If <literal>true</literal>, <varname>services.emacs.install</varname> is
-        considered <literal>true</literal>, whatever its value.
+      description = lib.mdDoc ''
+        Whether to enable a user service for the Emacs daemon. Use `emacsclient` to connect to the
+        daemon. If `true`, {var}`services.emacs.install` is
+        considered `true`, whatever its value.
       '';
     };
 
     install = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to install a user service for the Emacs daemon. Once
         the service is started, use emacsclient to connect to the
         daemon.
 
         The service must be manually started for each user with
         "systemctl --user start emacs" or globally through
-        <varname>services.emacs.enable</varname>.
+        {var}`services.emacs.enable`.
       '';
     };
 
@@ -67,7 +67,7 @@ in
       type = types.package;
       default = pkgs.emacs;
       defaultText = literalExpression "pkgs.emacs";
-      description = ''
+      description = lib.mdDoc ''
         emacs derivation to use.
       '';
     };
@@ -75,7 +75,7 @@ in
     defaultEditor = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         When enabled, configures emacsclient to be the default editor
         using the EDITOR environment variable.
       '';
diff --git a/nixos/modules/services/editors/haste.nix b/nixos/modules/services/editors/haste.nix
new file mode 100644
index 00000000000..a46415d4363
--- /dev/null
+++ b/nixos/modules/services/editors/haste.nix
@@ -0,0 +1,86 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  pkg = pkgs.haste-server;
+  cfg = config.services.haste-server;
+
+  format = pkgs.formats.json {};
+in
+{
+  options.services.haste-server = {
+    enable = mkEnableOption (lib.mdDoc "haste-server");
+    openFirewall = mkEnableOption (lib.mdDoc "firewall passthrough for haste-server");
+
+    settings = mkOption {
+      description = lib.mdDoc ''
+        Configuration for haste-server.
+        For documentation see [project readme](https://github.com/toptal/haste-server#settings)
+      '';
+      type = format.type;
+    };
+  };
+
+  config = mkIf (cfg.enable) {
+    networking.firewall.allowedTCPPorts = mkIf (cfg.openFirewall) [ cfg.settings.port ];
+
+    services.haste-server = {
+      settings = {
+        host = mkDefault "::";
+        port = mkDefault 7777;
+
+        keyLength = mkDefault 10;
+        maxLength = mkDefault 400000;
+
+        staticMaxAge = mkDefault 86400;
+        recompressStaticAssets = mkDefault false;
+
+        logging = mkDefault [
+          {
+            level = "verbose";
+            type = "Console";
+            colorize = true;
+          }
+        ];
+
+        keyGenerator = mkDefault {
+          type = "phonetic";
+        };
+
+        rateLimits = {
+          categories = {
+            normal = {
+              totalRequests = mkDefault 500;
+              every = mkDefault 60000;
+            };
+          };
+        };
+
+        storage = mkDefault {
+          type = "file";
+        };
+
+        documents = {
+          about = mkDefault "${pkg}/share/haste-server/about.md";
+        };
+      };
+    };
+
+    systemd.services.haste-server = {
+      wantedBy = [ "multi-user.target" ];
+      requires = [ "network.target" ];
+      after = [ "network.target" ];
+
+      serviceConfig = {
+        User = "haste-server";
+        DynamicUser = true;
+        StateDirectory = "haste-server";
+        WorkingDirectory = "/var/lib/haste-server";
+        ExecStart = "${pkg}/bin/haste-server ${format.generate "config.json" cfg.settings}";
+      };
+
+      path = with pkgs; [ pkg coreutils ];
+    };
+  };
+}
diff --git a/nixos/modules/services/editors/infinoted.nix b/nixos/modules/services/editors/infinoted.nix
index 16fe52a232b..de098999401 100644
--- a/nixos/modules/services/editors/infinoted.nix
+++ b/nixos/modules/services/editors/infinoted.nix
@@ -6,13 +6,13 @@ let
   cfg = config.services.infinoted;
 in {
   options.services.infinoted = {
-    enable = mkEnableOption "infinoted";
+    enable = mkEnableOption (lib.mdDoc "infinoted");
 
     package = mkOption {
       type = types.package;
       default = pkgs.libinfinity;
       defaultText = literalExpression "pkgs.libinfinity";
-      description = ''
+      description = lib.mdDoc ''
         Package providing infinoted
       '';
     };
@@ -20,7 +20,7 @@ in {
     keyFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Private key to use for TLS
       '';
     };
@@ -28,7 +28,7 @@ in {
     certificateFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Server certificate to use for TLS
       '';
     };
@@ -36,7 +36,7 @@ in {
     certificateChain = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Chain of CA-certificates to which our `certificateFile` is relative.
         Optional for TLS.
       '';
@@ -45,7 +45,7 @@ in {
     securityPolicy = mkOption {
       type = types.enum ["no-tls" "allow-tls" "require-tls"];
       default = "require-tls";
-      description = ''
+      description = lib.mdDoc ''
         How strictly to enforce clients connection with TLS.
       '';
     };
@@ -53,7 +53,7 @@ in {
     port = mkOption {
       type = types.port;
       default = 6523;
-      description = ''
+      description = lib.mdDoc ''
         Port to listen on
       '';
     };
@@ -61,7 +61,7 @@ in {
     rootDirectory = mkOption {
       type = types.path;
       default = "/var/lib/infinoted/documents/";
-      description = ''
+      description = lib.mdDoc ''
         Root of the directory structure to serve
       '';
     };
@@ -69,7 +69,7 @@ in {
     plugins = mkOption {
       type = types.listOf types.str;
       default = [ "note-text" "note-chat" "logging" "autosave" ];
-      description = ''
+      description = lib.mdDoc ''
         Plugins to enable
       '';
     };
@@ -77,7 +77,7 @@ in {
     passwordFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         File to read server-wide password from
       '';
     };
@@ -88,7 +88,7 @@ in {
         [autosave]
         interval=10
       '';
-      description = ''
+      description = lib.mdDoc ''
         Additional configuration to append to infinoted.conf
       '';
     };
@@ -96,7 +96,7 @@ in {
     user = mkOption {
       type = types.str;
       default = "infinoted";
-      description = ''
+      description = lib.mdDoc ''
         What to call the dedicated user under which infinoted is run
       '';
     };
@@ -104,7 +104,7 @@ in {
     group = mkOption {
       type = types.str;
       default = "infinoted";
-      description = ''
+      description = lib.mdDoc ''
         What to call the primary group of the dedicated user under which infinoted is run
       '';
     };
diff --git a/nixos/modules/services/finance/odoo.nix b/nixos/modules/services/finance/odoo.nix
index 422ee951007..fee9af574b5 100644
--- a/nixos/modules/services/finance/odoo.nix
+++ b/nixos/modules/services/finance/odoo.nix
@@ -9,33 +9,33 @@ in
 {
   options = {
     services.odoo = {
-      enable = mkEnableOption "odoo";
+      enable = mkEnableOption (lib.mdDoc "odoo");
 
       package = mkOption {
         type = types.package;
         default = pkgs.odoo;
         defaultText = literalExpression "pkgs.odoo";
-        description = "Odoo package to use.";
+        description = lib.mdDoc "Odoo package to use.";
       };
 
       addons = mkOption {
         type = with types; listOf package;
         default = [];
         example = literalExpression "[ pkgs.odoo_enterprise ]";
-        description = "Odoo addons.";
+        description = lib.mdDoc "Odoo addons.";
       };
 
       settings = mkOption {
         type = format.type;
         default = {};
-        description = ''
-          Odoo configuration settings. For more details see <link xlink:href="https://www.odoo.com/documentation/15.0/administration/install/deploy.html"/>
+        description = lib.mdDoc ''
+          Odoo configuration settings. For more details see <https://www.odoo.com/documentation/15.0/administration/install/deploy.html>
         '';
       };
 
       domain = mkOption {
         type = with types; nullOr str;
-        description = "Domain to host Odoo with nginx";
+        description = lib.mdDoc "Domain to host Odoo with nginx";
         default = null;
       };
     };
diff --git a/nixos/modules/services/games/asf.nix b/nixos/modules/services/games/asf.nix
index ea2bfd40fff..10847e8f11f 100644
--- a/nixos/modules/services/games/asf.nix
+++ b/nixos/modules/services/games/asf.nix
@@ -13,6 +13,8 @@ let
     # is in theory not needed as this is already the default for default builds
     UpdateChannel = 0;
     Headless = true;
+  } // lib.optionalAttrs (cfg.ipcPasswordFile != null) {
+    IPCPassword = "#ipcPassword#";
   });
 
   ipc-config = format.generate "IPC.config" cfg.ipcSettings;
@@ -30,7 +32,7 @@ in
   options.services.archisteamfarm = {
     enable = mkOption {
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         If enabled, starts the ArchisSteamFarm service.
         For configuring the SteamGuard token you will need to use the web-ui, which is enabled by default over on 127.0.0.1:1242.
         You cannot configure ASF in any way outside of nix, since all the config files get wiped on restart and replaced with the programatically set ones by nix.
@@ -42,13 +44,13 @@ in
       type = types.submodule {
         options = {
           enable = mkEnableOption
-            "Wheter to start the web-ui. This is the preferred way of configuring things such as the steam guard token";
+            (lib.mdDoc "Wheter to start the web-ui. This is the preferred way of configuring things such as the steam guard token");
 
           package = mkOption {
             type = types.package;
             default = pkgs.ArchiSteamFarm.ui;
             description =
-              "Web-UI package to use. Contents must be in lib/dist.";
+              lib.mdDoc "Web-UI package to use. Contents must be in lib/dist.";
           };
         };
       };
@@ -59,32 +61,31 @@ in
       example = {
         enable = false;
       };
-      description = "The Web-UI hosted on 127.0.0.1:1242.";
+      description = lib.mdDoc "The Web-UI hosted on 127.0.0.1:1242.";
     };
 
     package = mkOption {
       type = types.package;
       default = pkgs.ArchiSteamFarm;
       description =
-        "Package to use. Should always be the latest version, for security reasons, since this module uses very new features and to not get out of sync with the Steam API.";
+        lib.mdDoc "Package to use. Should always be the latest version, for security reasons, since this module uses very new features and to not get out of sync with the Steam API.";
     };
 
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/asf";
-      description = ''
+      description = lib.mdDoc ''
         The ASF home directory used to store all data.
         If left as the default value this directory will automatically be created before the ASF server starts, otherwise the sysadmin is responsible for ensuring the directory exists with appropriate ownership and permissions.'';
     };
 
     settings = mkOption {
       type = format.type;
-      description = ''
-        The ASF.json file, all the options are documented <link xlink:href="https://github.com/JustArchiNET/ArchiSteamFarm/wiki/Configuration#global-config">here</link>.
-        Do note that `AutoRestart`  and `UpdateChannel` is always to `false`
-respectively `0` because NixOS takes care of updating everything.
+      description = lib.mdDoc ''
+        The ASF.json file, all the options are documented [here](https://github.com/JustArchiNET/ArchiSteamFarm/wiki/Configuration#global-config).
+        Do note that `AutoRestart`  and `UpdateChannel` is always to `false` respectively `0` because NixOS takes care of updating everything.
         `Headless` is also always set to `true` because there is no way to provide inputs via a systemd service.
-        You should try to keep ASF up to date since upstream does not provide support for anything but the latest version and you're exposing yourself to all kinds of issues - as is outlined <link xlink:href="https://github.com/JustArchiNET/ArchiSteamFarm/wiki/Configuration#updateperiod">here</link>.
+        You should try to keep ASF up to date since upstream does not provide support for anything but the latest version and you're exposing yourself to all kinds of issues - as is outlined [here](https://github.com/JustArchiNET/ArchiSteamFarm/wiki/Configuration#updateperiod).
       '';
       example = {
         Statistics = false;
@@ -92,11 +93,17 @@ respectively `0` because NixOS takes care of updating everything.
       default = { };
     };
 
+    ipcPasswordFile = mkOption {
+      type = types.nullOr types.path;
+      default = null;
+      description = lib.mdDoc "Path to a file containig the password. The file must be readable by the `asf` user/group.";
+    };
+
     ipcSettings = mkOption {
       type = format.type;
-      description = ''
+      description = lib.mdDoc ''
         Settings to write to IPC.config.
-        All options can be found <link xlink:href="https://github.com/JustArchiNET/ArchiSteamFarm/wiki/IPC#custom-configuration">here</link>.
+        All options can be found [here](https://github.com/JustArchiNET/ArchiSteamFarm/wiki/IPC#custom-configuration).
       '';
       example = {
         Kestrel = {
@@ -115,29 +122,28 @@ respectively `0` because NixOS takes care of updating everything.
         options = {
           username = mkOption {
             type = types.str;
-            description =
-              "Name of the user to log in. Default is attribute name.";
+            description = lib.mdDoc "Name of the user to log in. Default is attribute name.";
             default = "";
           };
           passwordFile = mkOption {
             type = types.path;
-            description =
-              "Path to a file containig the password. The file must be readable by the <literal>asf</literal> user/group.";
+            description = lib.mdDoc "Path to a file containig the password. The file must be readable by the `asf` user/group.";
           };
           enabled = mkOption {
             type = types.bool;
             default = true;
-            description = "Whether to enable the bot on startup.";
+            description = lib.mdDoc "Whether to enable the bot on startup.";
           };
           settings = mkOption {
             type = types.attrs;
-            description =
-              "Additional settings that are documented <link xlink:href=\"https://github.com/JustArchiNET/ArchiSteamFarm/wiki/Configuration#bot-config\">here</link>.";
+            description = lib.mdDoc ''
+              Additional settings that are documented [here](https://github.com/JustArchiNET/ArchiSteamFarm/wiki/Configuration#bot-config).
+            '';
             default = { };
           };
         };
       });
-      description = ''
+      description = lib.mdDoc ''
         Bots name and configuration.
       '';
       example = {
@@ -170,14 +176,17 @@ respectively `0` because NixOS takes care of updating everything.
         wantedBy = [ "multi-user.target" ];
 
         serviceConfig = mkMerge [
-          (mkIf (cfg.dataDir == "/var/lib/asf") { StateDirectory = "asf"; })
+          (mkIf (cfg.dataDir == "/var/lib/asf") {
+            StateDirectory = "asf";
+            StateDirectoryMode = "700";
+          })
           {
             User = "asf";
             Group = "asf";
             WorkingDirectory = cfg.dataDir;
             Type = "simple";
-            ExecStart =
-              "${cfg.package}/bin/ArchiSteamFarm --path ${cfg.dataDir} --process-required --no-restart --service --no-config-migrate";
+            ExecStart = "${cfg.package}/bin/ArchiSteamFarm --path ${cfg.dataDir} --process-required --no-restart --service --no-config-migrate";
+            Restart = "always";
 
             # mostly copied from the default systemd service
             PrivateTmp = true;
@@ -202,35 +211,47 @@ respectively `0` because NixOS takes care of updating everything.
           }
         ];
 
-        preStart = ''
-          mkdir -p config
-          rm -f www
-          rm -f config/{*.json,*.config}
-
-          ln -s ${asf-config} config/ASF.json
-
-          ${strings.optionalString (cfg.ipcSettings != {}) ''
-            ln -s ${ipc-config} config/IPC.config
-          ''}
-
-          ln -s ${pkgs.runCommandLocal "ASF-bots" {} ''
-            mkdir -p $out/lib/asf/bots
-            for i in ${strings.concatStringsSep " " (lists.map (x: "${getName x},${x}") (attrsets.mapAttrsToList mkBot cfg.bots))}; do IFS=",";
-              set -- $i
-              ln -s $2 $out/lib/asf/bots/$1
-            done
-          ''}/lib/asf/bots/* config/
-
-          ${strings.optionalString cfg.web-ui.enable ''
-            ln -s ${cfg.web-ui.package}/lib/dist www
-          ''}
-        '';
+        preStart =
+          let
+            createBotsScript = pkgs.runCommandLocal "ASF-bots" { } ''
+              mkdir -p $out
+              # clean potential removed bots
+              rm -rf $out/*.json
+              for i in ${strings.concatStringsSep " " (lists.map (x: "${getName x},${x}") (attrsets.mapAttrsToList mkBot cfg.bots))}; do IFS=",";
+                set -- $i
+                ln -fs $2 $out/$1
+              done
+            '';
+            replaceSecretBin = "${pkgs.replace-secret}/bin/replace-secret";
+          in
+          ''
+            mkdir -p config
+
+            cp --no-preserve=mode ${asf-config} config/ASF.json
+
+            ${optionalString (cfg.ipcPasswordFile != null) ''
+              ${replaceSecretBin} '#ipcPassword#' '${cfg.ipcPasswordFile}' config/ASF.json
+            ''}
+
+            ${optionalString (cfg.ipcSettings != {}) ''
+              ln -fs ${ipc-config} config/IPC.config
+            ''}
+
+            ${optionalString (cfg.ipcSettings != {}) ''
+              ln -fs ${createBotsScript}/* config/
+            ''}
+
+            rm -f www
+            ${optionalString cfg.web-ui.enable ''
+              ln -s ${cfg.web-ui.package}/lib/dist www
+            ''}
+          '';
       };
     };
   };
 
   meta = {
     buildDocsInSandbox = false;
-    maintainers = with maintainers; [ lom ];
+    maintainers = with maintainers; [ lom SuperSandro2000 ];
   };
 }
diff --git a/nixos/modules/services/games/crossfire-server.nix b/nixos/modules/services/games/crossfire-server.nix
index a33025e0c3e..0849667e61c 100644
--- a/nixos/modules/services/games/crossfire-server.nix
+++ b/nixos/modules/services/games/crossfire-server.nix
@@ -10,7 +10,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         If enabled, the Crossfire game server will be started at boot.
       '';
     };
@@ -19,7 +19,7 @@ in {
       type = types.package;
       default = pkgs.crossfire-server;
       defaultText = literalExpression "pkgs.crossfire-server";
-      description = ''
+      description = lib.mdDoc ''
         The package to use for the Crossfire server (and map/arch data, if you
         don't change dataDir).
       '';
@@ -29,7 +29,7 @@ in {
       type = types.str;
       default = "${cfg.package}/share/crossfire";
       defaultText = literalExpression ''"''${config.services.crossfire.package}/share/crossfire"'';
-      description = ''
+      description = lib.mdDoc ''
         Where to load readonly data from -- maps, archetypes, treasure tables,
         and the like. If you plan to edit the data on the live server (rather
         than overlaying the crossfire-maps and crossfire-arch packages and
@@ -41,7 +41,7 @@ in {
     stateDir = mkOption {
       type = types.str;
       default = "/var/lib/crossfire";
-      description = ''
+      description = lib.mdDoc ''
         Where to store runtime data (save files, persistent items, etc).
 
         If left at the default, this will be automatically created on server
@@ -54,14 +54,14 @@ in {
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to open ports in the firewall for the server.
       '';
     };
 
     configFiles = mkOption {
       type = types.attrsOf types.str;
-      description = ''
+      description = lib.mdDoc ''
         Text to append to the corresponding configuration files. Note that the
         files given in the example are *not* the complete set of files available
         to customize; look in /etc/crossfire after enabling the server to see
@@ -76,7 +76,7 @@ in {
         {
           dm_file = '''
             admin:secret_password:localhost
-            jane:xyzzy:*
+            alice:xyzzy:*
           ''';
           ban_file = '''
             # Bob is a jerk
@@ -131,9 +131,9 @@ in {
         exp_table = "";
         forbid = "";
         metaserver2 = "";
-        motd = (fileContents "${cfg.package}/etc/crossfire/motd");
-        news = (fileContents "${cfg.package}/etc/crossfire/news");
-        rules = (fileContents "${cfg.package}/etc/crossfire/rules");
+        motd = fileContents "${cfg.package}/etc/crossfire/motd";
+        news = fileContents "${cfg.package}/etc/crossfire/news";
+        rules = fileContents "${cfg.package}/etc/crossfire/rules";
         settings = "";
         stat_bonus = "";
       } // cfg.configFiles);
diff --git a/nixos/modules/services/games/deliantra-server.nix b/nixos/modules/services/games/deliantra-server.nix
index b7011f4c354..f39044eda7c 100644
--- a/nixos/modules/services/games/deliantra-server.nix
+++ b/nixos/modules/services/games/deliantra-server.nix
@@ -10,7 +10,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         If enabled, the Deliantra game server will be started at boot.
       '';
     };
@@ -19,7 +19,7 @@ in {
       type = types.package;
       default = pkgs.deliantra-server;
       defaultText = literalExpression "pkgs.deliantra-server";
-      description = ''
+      description = lib.mdDoc ''
         The package to use for the Deliantra server (and map/arch data, if you
         don't change dataDir).
       '';
@@ -29,7 +29,7 @@ in {
       type = types.str;
       default = "${pkgs.deliantra-data}";
       defaultText = literalExpression ''"''${pkgs.deliantra-data}"'';
-      description = ''
+      description = lib.mdDoc ''
         Where to store readonly data (maps, archetypes, sprites, etc).
         Note that if you plan to use the live map editor (rather than editing
         the maps offline and then nixos-rebuilding), THIS MUST BE WRITEABLE --
@@ -41,7 +41,7 @@ in {
     stateDir = mkOption {
       type = types.str;
       default = "/var/lib/deliantra";
-      description = ''
+      description = lib.mdDoc ''
         Where to store runtime data (save files, persistent items, etc).
 
         If left at the default, this will be automatically created on server
@@ -54,14 +54,14 @@ in {
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to open ports in the firewall for the server.
       '';
     };
 
     configFiles = mkOption {
       type = types.attrsOf types.str;
-      description = ''
+      description = lib.mdDoc ''
         Contents of the server configuration files. These will be appended to
         the example configurations the server comes with and overwrite any
         default settings defined therein.
@@ -73,7 +73,7 @@ in {
         {
           dm_file = '''
             admin:secret_password:localhost
-            jane:xyzzy:*
+            alice:xyzzy:*
           ''';
           motd = "Welcome to Deliantra!";
           settings = '''
diff --git a/nixos/modules/services/games/factorio.nix b/nixos/modules/services/games/factorio.nix
index 96fcd6d2c8b..844fd2bce51 100644
--- a/nixos/modules/services/games/factorio.nix
+++ b/nixos/modules/services/games/factorio.nix
@@ -44,20 +44,28 @@ in
 {
   options = {
     services.factorio = {
-      enable = mkEnableOption name;
+      enable = mkEnableOption (lib.mdDoc name);
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 34197;
-        description = ''
+        description = lib.mdDoc ''
           The port to which the service should bind.
         '';
       };
 
+      bind = mkOption {
+        type = types.str;
+        default = "0.0.0.0";
+        description = lib.mdDoc ''
+          The address to which the service should bind.
+        '';
+      };
+
       admins = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "username" ];
-        description = ''
+        description = lib.mdDoc ''
           List of player names which will be admin.
         '';
       };
@@ -65,20 +73,32 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to automatically open the specified UDP port in the firewall.
         '';
       };
       saveName = mkOption {
         type = types.str;
         default = "default";
-        description = ''
+        description = lib.mdDoc ''
           The name of the savegame that will be used by the server.
 
           When not present in /var/lib/''${config.services.factorio.stateDirName}/saves,
           a new map with default settings will be generated before starting the service.
         '';
       };
+      loadLatestSave = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Load the latest savegame on startup. This overrides saveName, in that the latest
+          save will always be used even if a saved game of the given name exists. It still
+          controls the 'canonical' name of the savegame.
+
+          Set this to true to have the server automatically reload a recent autosave after
+          a crash or desync.
+        '';
+      };
       # TODO Add more individual settings as nixos-options?
       # TODO XXX The server tries to copy a newly created config file over the old one
       #   on shutdown, but fails, because it's in the nix store. When is this needed?
@@ -87,7 +107,7 @@ in
         type = types.path;
         default = configFile;
         defaultText = literalExpression "configFile";
-        description = ''
+        description = lib.mdDoc ''
           The server's configuration file.
 
           The default file generated by this module contains lines essential to
@@ -98,7 +118,7 @@ in
       stateDirName = mkOption {
         type = types.str;
         default = "factorio";
-        description = ''
+        description = lib.mdDoc ''
           Name of the directory under /var/lib holding the server's data.
 
           The configuration and map will be stored here.
@@ -107,7 +127,7 @@ in
       mods = mkOption {
         type = types.listOf types.package;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Mods the server should install and activate.
 
           The derivations in this list must "build" the mod by simply copying
@@ -119,14 +139,14 @@ in
       game-name = mkOption {
         type = types.nullOr types.str;
         default = "Factorio Game";
-        description = ''
+        description = lib.mdDoc ''
           Name of the game as it will appear in the game listing.
         '';
       };
       description = mkOption {
         type = types.nullOr types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Description of the game that will appear in the listing.
         '';
       };
@@ -134,28 +154,28 @@ in
         type = types.attrs;
         default = {};
         example = { admins = [ "username" ];};
-        description = ''
+        description = lib.mdDoc ''
           Extra game configuration that will go into server-settings.json
         '';
       };
       public = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Game will be published on the official Factorio matching server.
         '';
       };
       lan = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Game will be broadcast on LAN.
         '';
       };
       username = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Your factorio.com login credentials. Required for games with visibility public.
         '';
       };
@@ -164,35 +184,35 @@ in
         default = pkgs.factorio-headless;
         defaultText = literalExpression "pkgs.factorio-headless";
         example = literalExpression "pkgs.factorio-headless-experimental";
-        description = ''
+        description = lib.mdDoc ''
           Factorio version to use. This defaults to the stable channel.
         '';
       };
       password = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Your factorio.com login credentials. Required for games with visibility public.
         '';
       };
       token = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Authentication token. May be used instead of 'password' above.
         '';
       };
       game-password = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Game password.
         '';
       };
       requireUserVerification = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           When set to true, the server will only allow clients that have a valid factorio.com account.
         '';
       };
@@ -200,14 +220,14 @@ in
         type = types.nullOr types.int;
         default = null;
         example = 10;
-        description = ''
+        description = lib.mdDoc ''
           Autosave interval in minutes.
         '';
       };
       nonBlockingSaving = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Highly experimental feature, enable only at your own risk of losing your saves.
           On UNIX systems, server will fork itself to create an autosave.
           Autosaving on connected Windows clients will be disabled regardless of autosave_only_on_server option.
@@ -241,8 +261,10 @@ in
           "${cfg.package}/bin/factorio"
           "--config=${cfg.configFile}"
           "--port=${toString cfg.port}"
-          "--start-server=${mkSavePath cfg.saveName}"
+          "--bind=${cfg.bind}"
+          (optionalString (!cfg.loadLatestSave) "--start-server=${mkSavePath cfg.saveName}")
           "--server-settings=${serverSettingsFile}"
+          (optionalString cfg.loadLatestSave "--start-server-load-latest")
           (optionalString (cfg.mods != []) "--mod-directory=${modDir}")
           (optionalString (cfg.admins != []) "--server-adminlist=${serverAdminsFile}")
         ];
diff --git a/nixos/modules/services/games/freeciv.nix b/nixos/modules/services/games/freeciv.nix
index 4923891a617..8b340bb161a 100644
--- a/nixos/modules/services/games/freeciv.nix
+++ b/nixos/modules/services/games/freeciv.nix
@@ -25,9 +25,9 @@ in
 {
   options = {
     services.freeciv = {
-      enable = mkEnableOption ''freeciv'';
+      enable = mkEnableOption (lib.mdDoc ''freeciv'');
       settings = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Parameters of freeciv-server.
         '';
         default = {};
@@ -36,9 +36,9 @@ in
           options.Announce = mkOption {
             type = types.enum ["IPv4" "IPv6" "none"];
             default = "none";
-            description = "Announce game in LAN using given protocol.";
+            description = lib.mdDoc "Announce game in LAN using given protocol.";
           };
-          options.auth = mkEnableOption "server authentication";
+          options.auth = mkEnableOption (lib.mdDoc "server authentication");
           options.Database = mkOption {
             type = types.nullOr types.str;
             apply = pkgs.writeText "auth.conf";
@@ -47,25 +47,25 @@ in
                 backend="sqlite"
                 database="/var/lib/freeciv/auth.sqlite"
             '';
-            description = "Enable database connection with given configuration.";
+            description = lib.mdDoc "Enable database connection with given configuration.";
           };
           options.debug = mkOption {
             type = types.ints.between 0 3;
             default = 0;
-            description = "Set debug log level.";
+            description = lib.mdDoc "Set debug log level.";
           };
-          options.exit-on-end = mkEnableOption "exit instead of restarting when a game ends.";
-          options.Guests = mkEnableOption "guests to login if auth is enabled";
-          options.Newusers = mkEnableOption "new users to login if auth is enabled";
+          options.exit-on-end = mkEnableOption (lib.mdDoc "exit instead of restarting when a game ends.");
+          options.Guests = mkEnableOption (lib.mdDoc "guests to login if auth is enabled");
+          options.Newusers = mkEnableOption (lib.mdDoc "new users to login if auth is enabled");
           options.port = mkOption {
             type = types.port;
             default = 5556;
-            description = "Listen for clients on given port";
+            description = lib.mdDoc "Listen for clients on given port";
           };
           options.quitidle = mkOption {
             type = types.nullOr types.int;
             default = null;
-            description = "Quit if no players for given time in seconds.";
+            description = lib.mdDoc "Quit if no players for given time in seconds.";
           };
           options.read = mkOption {
             type = types.lines;
@@ -73,12 +73,12 @@ in
             default = ''
               /fcdb lua sqlite_createdb()
             '';
-            description = "Startup script.";
+            description = lib.mdDoc "Startup script.";
           };
           options.saves = mkOption {
             type = types.nullOr types.str;
             default = "/var/lib/freeciv/saves/";
-            description = ''
+            description = lib.mdDoc ''
               Save games to given directory,
               a sub-directory named after the starting date of the service
               will me inserted to preserve older saves.
@@ -86,7 +86,7 @@ in
           };
         };
       };
-      openFirewall = mkEnableOption "opening the firewall for the port listening for clients";
+      openFirewall = mkEnableOption (lib.mdDoc "opening the firewall for the port listening for clients");
     };
   };
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/games/minecraft-server.nix b/nixos/modules/services/games/minecraft-server.nix
index 8233962c1a2..77f92ab97db 100644
--- a/nixos/modules/services/games/minecraft-server.nix
+++ b/nixos/modules/services/games/minecraft-server.nix
@@ -22,6 +22,15 @@ let
   '' + concatStringsSep "\n" (mapAttrsToList
     (n: v: "${n}=${cfgToString v}") cfg.serverProperties));
 
+  stopScript = pkgs.writeShellScript "minecraft-server-stop" ''
+    echo stop > ${config.systemd.sockets.minecraft-server.socketConfig.ListenFIFO}
+
+    # Wait for the PID of the minecraft server to disappear before
+    # returning, so systemd doesn't attempt to SIGKILL it.
+    while kill -0 "$1" 2> /dev/null; do
+      sleep 1s
+    done
+  '';
 
   # To be able to open the firewall, we need to read out port values in the
   # server properties, but fall back to the defaults when those don't exist.
@@ -45,21 +54,21 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, start a Minecraft Server. The server
           data will be loaded from and saved to
-          <option>services.minecraft-server.dataDir</option>.
+          {option}`services.minecraft-server.dataDir`.
         '';
       };
 
       declarative = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use a declarative Minecraft server configuration.
-          Only if set to <literal>true</literal>, the options
-          <option>services.minecraft-server.whitelist</option> and
-          <option>services.minecraft-server.serverProperties</option> will be
+          Only if set to `true`, the options
+          {option}`services.minecraft-server.whitelist` and
+          {option}`services.minecraft-server.serverProperties` will be
           applied.
         '';
       };
@@ -67,18 +76,18 @@ in {
       eula = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether you agree to
-          <link xlink:href="https://account.mojang.com/documents/minecraft_eula">
-          Mojangs EULA</link>. This option must be set to
-          <literal>true</literal> to run Minecraft server.
+          [
+          Mojangs EULA](https://account.mojang.com/documents/minecraft_eula). This option must be set to
+          `true` to run Minecraft server.
         '';
       };
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/minecraft";
-        description = ''
+        description = lib.mdDoc ''
           Directory to store Minecraft database and other state/data files.
         '';
       };
@@ -86,7 +95,7 @@ in {
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to open ports in the firewall for the server.
         '';
       };
@@ -99,14 +108,14 @@ in {
             };
           in types.attrsOf minecraftUUID;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Whitelisted players, only has an effect when
-          <option>services.minecraft-server.declarative</option> is
-          <literal>true</literal> and the whitelist is enabled
-          via <option>services.minecraft-server.serverProperties</option> by
-          setting <literal>white-list</literal> to <literal>true</literal>.
+          {option}`services.minecraft-server.declarative` is
+          `true` and the whitelist is enabled
+          via {option}`services.minecraft-server.serverProperties` by
+          setting `white-list` to `true`.
           This is a mapping from Minecraft usernames to UUIDs.
-          You can use <link xlink:href="https://mcuuid.net/"/> to get a
+          You can use <https://mcuuid.net/> to get a
           Minecraft UUID for a username.
         '';
         example = literalExpression ''
@@ -132,11 +141,11 @@ in {
             "rcon.password" = "hunter2";
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Minecraft server properties for the server.properties file. Only has
-          an effect when <option>services.minecraft-server.declarative</option>
-          is set to <literal>true</literal>. See
-          <link xlink:href="https://minecraft.gamepedia.com/Server.properties#Java_Edition_3"/>
+          an effect when {option}`services.minecraft-server.declarative`
+          is set to `true`. See
+          <https://minecraft.gamepedia.com/Server.properties#Java_Edition_3>
           for documentation on these values.
         '';
       };
@@ -146,7 +155,7 @@ in {
         default = pkgs.minecraft-server;
         defaultText = literalExpression "pkgs.minecraft-server";
         example = literalExpression "pkgs.minecraft-server_1_12_2";
-        description = "Version of minecraft-server to run.";
+        description = lib.mdDoc "Version of minecraft-server to run.";
       };
 
       jvmOpts = mkOption {
@@ -156,7 +165,7 @@ in {
         example = "-Xms4092M -Xmx4092M -XX:+UseG1GC -XX:+CMSIncrementalPacing "
           + "-XX:+CMSClassUnloadingEnabled -XX:ParallelGCThreads=2 "
           + "-XX:MinHeapFreeRatio=5 -XX:MaxHeapFreeRatio=10";
-        description = "JVM options for the Minecraft server.";
+        description = lib.mdDoc "JVM options for the Minecraft server.";
       };
     };
   };
@@ -172,16 +181,35 @@ in {
     };
     users.groups.minecraft = {};
 
+    systemd.sockets.minecraft-server = {
+      bindsTo = [ "minecraft-server.service" ];
+      socketConfig = {
+        ListenFIFO = "/run/minecraft-server.stdin";
+        SocketMode = "0660";
+        SocketUser = "minecraft";
+        SocketGroup = "minecraft";
+        RemoveOnStop = true;
+        FlushPending = true;
+      };
+    };
+
     systemd.services.minecraft-server = {
       description   = "Minecraft Server Service";
       wantedBy      = [ "multi-user.target" ];
-      after         = [ "network.target" ];
+      requires      = [ "minecraft-server.socket" ];
+      after         = [ "network.target" "minecraft-server.socket" ];
 
       serviceConfig = {
         ExecStart = "${cfg.package}/bin/minecraft-server ${cfg.jvmOpts}";
+        ExecStop = "${stopScript} $MAINPID";
         Restart = "always";
         User = "minecraft";
         WorkingDirectory = cfg.dataDir;
+
+        StandardInput = "socket";
+        StandardOutput = "journal";
+        StandardError = "journal";
+
         # Hardening
         CapabilityBoundingSet = [ "" ];
         DeviceAllow = [ "" ];
diff --git a/nixos/modules/services/games/minetest-server.nix b/nixos/modules/services/games/minetest-server.nix
index 2111c970d4f..34e0ba8c8e5 100644
--- a/nixos/modules/services/games/minetest-server.nix
+++ b/nixos/modules/services/games/minetest-server.nix
@@ -19,13 +19,13 @@ in
       enable = mkOption {
         type        = types.bool;
         default     = false;
-        description = "If enabled, starts a Minetest Server.";
+        description = lib.mdDoc "If enabled, starts a Minetest Server.";
       };
 
       gameId = mkOption {
         type        = types.nullOr types.str;
         default     = null;
-        description = ''
+        description = lib.mdDoc ''
           Id of the game to use. To list available games run
           `minetestserver --gameid list`.
 
@@ -36,7 +36,7 @@ in
       world = mkOption {
         type        = types.nullOr types.path;
         default     = null;
-        description = ''
+        description = lib.mdDoc ''
           Name of the world to use. To list available worlds run
           `minetestserver --world list`.
 
@@ -47,7 +47,7 @@ in
       configPath = mkOption {
         type        = types.nullOr types.path;
         default     = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to the config to use.
 
           If set to null, the config of the running user will be used:
@@ -58,7 +58,7 @@ in
       logPath = mkOption {
         type        = types.nullOr types.path;
         default     = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to logfile for logging.
 
           If set to null, logging will be output to stdout which means
@@ -69,7 +69,7 @@ in
       port = mkOption {
         type        = types.nullOr types.int;
         default     = null;
-        description = ''
+        description = lib.mdDoc ''
           Port number to bind to.
 
           If set to null, the default 30000 will be used.
diff --git a/nixos/modules/services/games/openarena.nix b/nixos/modules/services/games/openarena.nix
index 9c441e98b20..89e30d7c12a 100644
--- a/nixos/modules/services/games/openarena.nix
+++ b/nixos/modules/services/games/openarena.nix
@@ -8,18 +8,18 @@ in
 {
   options = {
     services.openarena = {
-      enable = mkEnableOption "OpenArena";
+      enable = mkEnableOption (lib.mdDoc "OpenArena");
 
       openPorts = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to open firewall ports for OpenArena";
+        description = lib.mdDoc "Whether to open firewall ports for OpenArena";
       };
 
       extraFlags = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Extra flags to pass to <command>oa_ded</command>";
+        description = lib.mdDoc "Extra flags to pass to {command}`oa_ded`";
         example = [
           "+set dedicated 2"
           "+set sv_hostname 'My NixOS OpenArena Server'"
diff --git a/nixos/modules/services/games/quake3-server.nix b/nixos/modules/services/games/quake3-server.nix
index 175af4a8382..2d2148237da 100644
--- a/nixos/modules/services/games/quake3-server.nix
+++ b/nixos/modules/services/games/quake3-server.nix
@@ -37,12 +37,12 @@ let
 in {
   options = {
     services.quake3-server = {
-      enable = mkEnableOption "Quake 3 dedicated server";
+      enable = mkEnableOption (lib.mdDoc "Quake 3 dedicated server");
 
       port = mkOption {
         type = types.port;
         default = 27960;
-        description = ''
+        description = lib.mdDoc ''
           UDP Port the server should listen on.
         '';
       };
@@ -50,7 +50,7 @@ in {
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open the firewall.
         '';
       };
@@ -62,7 +62,7 @@ in {
           seta rconPassword "superSecret"      // sets RCON password for remote console
           seta sv_hostname "My Quake 3 server"      // name that appears in server list
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration options. Note that options changed via RCON will not be persisted. To list all possible
           options, use "cvarlist 1" via RCON.
         '';
@@ -71,9 +71,9 @@ in {
       baseq3 = mkOption {
         type = types.either types.package types.path;
         default = defaultBaseq3;
-        defaultText = literalDocBook "Manually downloaded Quake 3 installation directory.";
+        defaultText = literalMD "Manually downloaded Quake 3 installation directory.";
         example = "/var/lib/q3ds";
-        description = ''
+        description = lib.mdDoc ''
           Path to the baseq3 files (pak*.pk3). If this is on the nix store (type = package) all .pk3 files should be saved
           in the top-level directory. If this is on another filesystem (e.g /var/lib/baseq3) the .pk3 files are searched in
           $baseq3/.q3a/baseq3/
diff --git a/nixos/modules/services/games/teeworlds.nix b/nixos/modules/services/games/teeworlds.nix
index babf989c98c..ffef440330c 100644
--- a/nixos/modules/services/games/teeworlds.nix
+++ b/nixos/modules/services/games/teeworlds.nix
@@ -20,18 +20,18 @@ in
 {
   options = {
     services.teeworlds = {
-      enable = mkEnableOption "Teeworlds Server";
+      enable = mkEnableOption (lib.mdDoc "Teeworlds Server");
 
       openPorts = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to open firewall ports for Teeworlds";
+        description = lib.mdDoc "Whether to open firewall ports for Teeworlds";
       };
 
       name = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Name of the server. Defaults to 'unnamed server'.
         '';
       };
@@ -40,7 +40,7 @@ in
         type = types.bool;
         example = true;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether the server registers as public server in the global server list. This is disabled by default because of privacy.
         '';
       };
@@ -48,7 +48,7 @@ in
       motd = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Set the server message of the day text.
         '';
       };
@@ -56,7 +56,7 @@ in
       password = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Password to connect to the server.
         '';
       };
@@ -64,15 +64,15 @@ in
       rconPassword = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Password to access the remote console. If not set, a randomly generated one is displayed in the server log.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8303;
-        description = ''
+        description = lib.mdDoc ''
           Port the server will listen on.
         '';
       };
@@ -80,8 +80,8 @@ in
       extraOptions = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
-          Extra configuration lines for the <filename>teeworlds.cfg</filename>. See <link xlink:href="https://www.teeworlds.com/?page=docs&amp;wiki=server_settings">Teeworlds Documentation</link>.
+        description = lib.mdDoc ''
+          Extra configuration lines for the {file}`teeworlds.cfg`. See [Teeworlds Documentation](https://www.teeworlds.com/?page=docs&wiki=server_settings).
         '';
         example = [ "sv_map dm1" "sv_gametype dm" ];
       };
diff --git a/nixos/modules/services/games/terraria.nix b/nixos/modules/services/games/terraria.nix
index 29f976b3c2a..571bcde2c5b 100644
--- a/nixos/modules/services/games/terraria.nix
+++ b/nixos/modules/services/games/terraria.nix
@@ -36,16 +36,16 @@ in
       enable = mkOption {
         type        = types.bool;
         default     = false;
-        description = ''
-          If enabled, starts a Terraria server. The server can be connected to via <literal>tmux -S ''${config.${opt.dataDir}}/terraria.sock attach</literal>
-          for administration by users who are a part of the <literal>terraria</literal> group (use <literal>C-b d</literal> shortcut to detach again).
+        description = lib.mdDoc ''
+          If enabled, starts a Terraria server. The server can be connected to via `tmux -S ''${config.${opt.dataDir}}/terraria.sock attach`
+          for administration by users who are a part of the `terraria` group (use `C-b d` shortcut to detach again).
         '';
       };
 
       port = mkOption {
         type        = types.port;
         default     = 7777;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the port to listen on.
         '';
       };
@@ -53,7 +53,7 @@ in
       maxPlayers = mkOption {
         type        = types.ints.u8;
         default     = 255;
-        description = ''
+        description = lib.mdDoc ''
           Sets the max number of players (between 1 and 255).
         '';
       };
@@ -61,15 +61,15 @@ in
       password = mkOption {
         type        = types.nullOr types.str;
         default     = null;
-        description = ''
-          Sets the server password. Leave <literal>null</literal> for no password.
+        description = lib.mdDoc ''
+          Sets the server password. Leave `null` for no password.
         '';
       };
 
       messageOfTheDay = mkOption {
         type        = types.nullOr types.str;
         default     = null;
-        description = ''
+        description = lib.mdDoc ''
           Set the server message of the day text.
         '';
       };
@@ -77,18 +77,18 @@ in
       worldPath = mkOption {
         type        = types.nullOr types.path;
         default     = null;
-        description = ''
-          The path to the world file (<literal>.wld</literal>) which should be loaded.
+        description = lib.mdDoc ''
+          The path to the world file (`.wld`) which should be loaded.
           If no world exists at this path, one will be created with the size
-          specified by <literal>autoCreatedWorldSize</literal>.
+          specified by `autoCreatedWorldSize`.
         '';
       };
 
       autoCreatedWorldSize = mkOption {
         type        = types.enum [ "small" "medium" "large" ];
         default     = "medium";
-        description = ''
-          Specifies the size of the auto-created world if <literal>worldPath</literal> does not
+        description = lib.mdDoc ''
+          Specifies the size of the auto-created world if `worldPath` does not
           point to an existing world.
         '';
       };
@@ -96,7 +96,7 @@ in
       banListPath = mkOption {
         type        = types.nullOr types.path;
         default     = null;
-        description = ''
+        description = lib.mdDoc ''
           The path to the ban list.
         '';
       };
@@ -104,26 +104,26 @@ in
       secure = mkOption {
         type        = types.bool;
         default     = false;
-        description = "Adds additional cheat protection to the server.";
+        description = lib.mdDoc "Adds additional cheat protection to the server.";
       };
 
       noUPnP = mkOption {
         type        = types.bool;
         default     = false;
-        description = "Disables automatic Universal Plug and Play.";
+        description = lib.mdDoc "Disables automatic Universal Plug and Play.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Wheter to open ports in the firewall";
+        description = lib.mdDoc "Wheter to open ports in the firewall";
       };
 
       dataDir = mkOption {
         type        = types.str;
         default     = "/var/lib/terraria";
         example     = "/srv/terraria";
-        description = "Path to variable state data directory for terraria.";
+        description = lib.mdDoc "Path to variable state data directory for terraria.";
       };
     };
   };
@@ -131,6 +131,7 @@ in
   config = mkIf cfg.enable {
     users.users.terraria = {
       description = "Terraria server service user";
+      group       = "terraria";
       home        = cfg.dataDir;
       createHome  = true;
       uid         = config.ids.uids.terraria;
@@ -138,7 +139,6 @@ in
 
     users.groups.terraria = {
       gid = config.ids.gids.terraria;
-      members = [ "terraria" ];
     };
 
     systemd.services.terraria = {
diff --git a/nixos/modules/services/hardware/acpid.nix b/nixos/modules/services/hardware/acpid.nix
index 883ef083003..821f4ef205f 100644
--- a/nixos/modules/services/hardware/acpid.nix
+++ b/nixos/modules/services/hardware/acpid.nix
@@ -48,12 +48,12 @@ in
 
     services.acpid = {
 
-      enable = mkEnableOption "the ACPI daemon";
+      enable = mkEnableOption (lib.mdDoc "the ACPI daemon");
 
       logEvents = mkOption {
         type = types.bool;
         default = false;
-        description = "Log all event activity.";
+        description = lib.mdDoc "Log all event activity.";
       };
 
       handlers = mkOption {
@@ -62,22 +62,22 @@ in
             event = mkOption {
               type = types.str;
               example = literalExpression ''"button/power.*" "button/lid.*" "ac_adapter.*" "button/mute.*" "button/volumedown.*" "cd/play.*" "cd/next.*"'';
-              description = "Event type.";
+              description = lib.mdDoc "Event type.";
             };
 
             action = mkOption {
               type = types.lines;
-              description = "Shell commands to execute when the event is triggered.";
+              description = lib.mdDoc "Shell commands to execute when the event is triggered.";
             };
           };
         });
 
-        description = ''
+        description = lib.mdDoc ''
           Event handlers.
 
-          <note><para>
-            Handler can be a single command.
-          </para></note>
+          ::: {.note}
+          Handler can be a single command.
+          :::
         '';
         default = {};
         example = {
@@ -104,19 +104,19 @@ in
       powerEventCommands = mkOption {
         type = types.lines;
         default = "";
-        description = "Shell commands to execute on a button/power.* event.";
+        description = lib.mdDoc "Shell commands to execute on a button/power.* event.";
       };
 
       lidEventCommands = mkOption {
         type = types.lines;
         default = "";
-        description = "Shell commands to execute on a button/lid.* event.";
+        description = lib.mdDoc "Shell commands to execute on a button/lid.* event.";
       };
 
       acEventCommands = mkOption {
         type = types.lines;
         default = "";
-        description = "Shell commands to execute on an ac_adapter.* event.";
+        description = lib.mdDoc "Shell commands to execute on an ac_adapter.* event.";
       };
 
     };
diff --git a/nixos/modules/services/hardware/actkbd.nix b/nixos/modules/services/hardware/actkbd.nix
index b499de97b2c..1718d179bf5 100644
--- a/nixos/modules/services/hardware/actkbd.nix
+++ b/nixos/modules/services/hardware/actkbd.nix
@@ -20,25 +20,25 @@ let
 
       keys = mkOption {
         type = types.listOf types.int;
-        description = "List of keycodes to match.";
+        description = lib.mdDoc "List of keycodes to match.";
       };
 
       events = mkOption {
         type = types.listOf (types.enum ["key" "rep" "rel"]);
         default = [ "key" ];
-        description = "List of events to match.";
+        description = lib.mdDoc "List of events to match.";
       };
 
       attributes = mkOption {
         type = types.listOf types.str;
         default = [ "exec" ];
-        description = "List of attributes.";
+        description = lib.mdDoc "List of attributes.";
       };
 
       command = mkOption {
         type = types.str;
         default = "";
-        description = "What to run.";
+        description = lib.mdDoc "What to run.";
       };
 
     };
@@ -57,13 +57,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          Whether to enable the <command>actkbd</command> key mapping daemon.
+        description = lib.mdDoc ''
+          Whether to enable the {command}`actkbd` key mapping daemon.
 
-          Turning this on will start an <command>actkbd</command>
+          Turning this on will start an {command}`actkbd`
           instance for every evdev input that has at least one key
           (which is okay even for systems with tiny memory footprint,
-          since actkbd normally uses &lt;100 bytes of memory per
+          since actkbd normally uses \<100 bytes of memory per
           instance).
 
           This allows binding keys globally without the need for e.g.
@@ -78,19 +78,19 @@ in
           [ { keys = [ 113 ]; events = [ "key" ]; command = "''${pkgs.alsa-utils}/bin/amixer -q set Master toggle"; }
           ]
         '';
-        description = ''
-          Key bindings for <command>actkbd</command>.
+        description = lib.mdDoc ''
+          Key bindings for {command}`actkbd`.
 
-          See <command>actkbd</command> <filename>README</filename> for documentation.
+          See {command}`actkbd` {file}`README` for documentation.
 
-          The example shows a piece of what <option>sound.mediaKeys.enable</option> does when enabled.
+          The example shows a piece of what {option}`sound.mediaKeys.enable` does when enabled.
         '';
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Literal contents to append to the end of actkbd configuration file.
         '';
       };
diff --git a/nixos/modules/services/hardware/argonone.nix b/nixos/modules/services/hardware/argonone.nix
new file mode 100644
index 00000000000..dc90e09e985
--- /dev/null
+++ b/nixos/modules/services/hardware/argonone.nix
@@ -0,0 +1,58 @@
+{ config, lib, pkgs, ... }:
+
+let
+  cfg = config.services.hardware.argonone;
+in
+{
+  options.services.hardware.argonone = {
+    enable = lib.mkEnableOption (lib.mdDoc "the driver for Argon One Raspberry Pi case fan and power button");
+    package = lib.mkOption {
+      type = lib.types.package;
+      default = pkgs.argononed;
+      defaultText = "pkgs.argononed";
+      description = lib.mdDoc ''
+        The package implementing the Argon One driver
+      '';
+    };
+  };
+
+  config = lib.mkIf cfg.enable {
+    hardware.i2c.enable = true;
+    hardware.deviceTree.overlays = [
+      {
+        name = "argononed";
+        dtboFile = "${cfg.package}/boot/overlays/argonone.dtbo";
+      }
+      {
+        name = "i2c1-okay-overlay";
+        dtsText = ''
+          /dts-v1/;
+          /plugin/;
+          / {
+            compatible = "brcm,bcm2711";
+            fragment@0 {
+              target = <&i2c1>;
+              __overlay__ {
+                status = "okay";
+              };
+            };
+          };
+        '';
+      }
+    ];
+    environment.systemPackages = [ cfg.package ];
+    systemd.services.argononed = {
+      description = "Argon One Raspberry Pi case Daemon Service";
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        Type = "forking";
+        ExecStart = "${cfg.package}/bin/argononed";
+        PIDFile = "/run/argononed.pid";
+        Restart = "on-failure";
+      };
+    };
+  };
+
+  meta.maintainers = with lib.maintainers; [ misterio77 ];
+
+}
diff --git a/nixos/modules/services/hardware/auto-cpufreq.nix b/nixos/modules/services/hardware/auto-cpufreq.nix
index f846476b30b..9698e72eb31 100644
--- a/nixos/modules/services/hardware/auto-cpufreq.nix
+++ b/nixos/modules/services/hardware/auto-cpufreq.nix
@@ -5,7 +5,7 @@ let
 in {
   options = {
     services.auto-cpufreq = {
-      enable = mkEnableOption "auto-cpufreq daemon";
+      enable = mkEnableOption (lib.mdDoc "auto-cpufreq daemon");
     };
   };
 
diff --git a/nixos/modules/services/hardware/bluetooth.nix b/nixos/modules/services/hardware/bluetooth.nix
index 69a66723e76..8b90c1913bc 100644
--- a/nixos/modules/services/hardware/bluetooth.nix
+++ b/nixos/modules/services/hardware/bluetooth.nix
@@ -36,14 +36,14 @@ in
   options = {
 
     hardware.bluetooth = {
-      enable = mkEnableOption "support for Bluetooth";
+      enable = mkEnableOption (lib.mdDoc "support for Bluetooth");
 
-      hsphfpd.enable = mkEnableOption "support for hsphfpd[-prototype] implementation";
+      hsphfpd.enable = mkEnableOption (lib.mdDoc "support for hsphfpd[-prototype] implementation");
 
       powerOnBoot = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to power up the default Bluetooth controller on boot.";
+        description = lib.mdDoc "Whether to power up the default Bluetooth controller on boot.";
       };
 
       package = mkOption {
@@ -51,20 +51,20 @@ in
         default = pkgs.bluez;
         defaultText = literalExpression "pkgs.bluez";
         example = literalExpression "pkgs.bluezFull";
-        description = ''
+        description = lib.mdDoc ''
           Which BlueZ package to use.
 
-          <note><para>
-            Use the <literal>pkgs.bluezFull</literal> package to enable all
-            bluez plugins.
-          </para></note>
+          ::: {.note}
+          Use the `pkgs.bluezFull` package to enable all
+          bluez plugins.
+          :::
         '';
       };
 
       disabledPlugins = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = "Built-in plugins to disable";
+        description = lib.mdDoc "Built-in plugins to disable";
       };
 
       settings = mkOption {
@@ -75,7 +75,7 @@ in
             ControllerMode = "bredr";
           };
         };
-        description = "Set configuration for system-wide bluetooth (/etc/bluetooth/main.conf).";
+        description = lib.mdDoc "Set configuration for system-wide bluetooth (/etc/bluetooth/main.conf).";
       };
     };
   };
diff --git a/nixos/modules/services/hardware/bolt.nix b/nixos/modules/services/hardware/bolt.nix
index 32b60af0603..6990a9ea63b 100644
--- a/nixos/modules/services/hardware/bolt.nix
+++ b/nixos/modules/services/hardware/bolt.nix
@@ -12,7 +12,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Bolt, a userspace daemon to enable
           security levels for Thunderbolt 3 on GNU/Linux.
 
diff --git a/nixos/modules/services/hardware/brltty.nix b/nixos/modules/services/hardware/brltty.nix
index 73056017532..3133804f485 100644
--- a/nixos/modules/services/hardware/brltty.nix
+++ b/nixos/modules/services/hardware/brltty.nix
@@ -25,7 +25,7 @@ in {
     services.brltty.enable = mkOption {
       type = types.bool;
       default = false;
-      description = "Whether to enable the BRLTTY daemon.";
+      description = lib.mdDoc "Whether to enable the BRLTTY daemon.";
     };
 
   };
diff --git a/nixos/modules/services/hardware/ddccontrol.nix b/nixos/modules/services/hardware/ddccontrol.nix
index f0b5a9c8196..0f1e8bf0d26 100644
--- a/nixos/modules/services/hardware/ddccontrol.nix
+++ b/nixos/modules/services/hardware/ddccontrol.nix
@@ -13,7 +13,7 @@ in
 
   options = {
     services.ddccontrol = {
-      enable = lib.mkEnableOption "ddccontrol for controlling displays";
+      enable = lib.mkEnableOption (lib.mdDoc "ddccontrol for controlling displays");
     };
   };
 
diff --git a/nixos/modules/services/hardware/fancontrol.nix b/nixos/modules/services/hardware/fancontrol.nix
index 861b70970b8..e7eb8ebf92b 100644
--- a/nixos/modules/services/hardware/fancontrol.nix
+++ b/nixos/modules/services/hardware/fancontrol.nix
@@ -9,11 +9,11 @@ let
 in
 {
   options.hardware.fancontrol = {
-    enable = mkEnableOption "software fan control (requires fancontrol.config)";
+    enable = mkEnableOption (lib.mdDoc "software fan control (requires fancontrol.config)");
 
     config = mkOption {
       type = types.lines;
-      description = "Required fancontrol configuration file content. See <citerefentry><refentrytitle>pwmconfig</refentrytitle><manvolnum>8</manvolnum></citerefentry> from the lm_sensors package.";
+      description = lib.mdDoc "Required fancontrol configuration file content. See {manpage}`pwmconfig(8)` from the lm_sensors package.";
       example = ''
         # Configuration file generated by pwmconfig
         INTERVAL=10
diff --git a/nixos/modules/services/hardware/freefall.nix b/nixos/modules/services/hardware/freefall.nix
index 3f7b1592449..7b794264ff3 100644
--- a/nixos/modules/services/hardware/freefall.nix
+++ b/nixos/modules/services/hardware/freefall.nix
@@ -13,7 +13,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to protect HP/Dell laptop hard drives (not SSDs) in free fall.
       '';
     };
@@ -22,7 +22,7 @@ in {
       type = types.package;
       default = pkgs.freefall;
       defaultText = literalExpression "pkgs.freefall";
-      description = ''
+      description = lib.mdDoc ''
         freefall derivation to use.
       '';
     };
@@ -30,7 +30,7 @@ in {
     devices = mkOption {
       type = types.listOf types.str;
       default = [ "/dev/sda" ];
-      description = ''
+      description = lib.mdDoc ''
         Device paths to all internal spinning hard drives.
       '';
     };
diff --git a/nixos/modules/services/hardware/fwupd.nix b/nixos/modules/services/hardware/fwupd.nix
index e0506416ffa..98f837bd782 100644
--- a/nixos/modules/services/hardware/fwupd.nix
+++ b/nixos/modules/services/hardware/fwupd.nix
@@ -15,9 +15,9 @@ let
         DisabledPlugins=${lib.concatStringsSep ";" cfg.disabledPlugins}
       '';
     };
-    "fwupd/uefi.conf" = {
-      source = pkgs.writeText "uefi.conf" ''
-        [uefi]
+    "fwupd/uefi_capsule.conf" = {
+      source = pkgs.writeText "uefi_capsule.conf" ''
+        [uefi_capsule]
         OverrideESPMountPoint=${config.boot.loader.efi.efiSysMountPoint}
       '';
     };
@@ -33,18 +33,26 @@ let
       mkEtcFile = p: nameValuePair (mkName p) { source = p; };
     in listToAttrs (map mkEtcFile cfg.extraTrustedKeys);
 
-  # We cannot include the file in $out and rely on filesInstalledToEtc
-  # to install it because it would create a cyclic dependency between
-  # the outputs. We also need to enable the remote,
-  # which should not be done by default.
-  testRemote = if cfg.enableTestRemote then {
-    "fwupd/remotes.d/fwupd-tests.conf" = {
-      source = pkgs.runCommand "fwupd-tests-enabled.conf" {} ''
+  enableRemote = base: remote: {
+    "fwupd/remotes.d/${remote}.conf" = {
+      source = pkgs.runCommand "${remote}-enabled.conf" {} ''
         sed "s,^Enabled=false,Enabled=true," \
-        "${cfg.package.installedTests}/etc/fwupd/remotes.d/fwupd-tests.conf" > "$out"
+        "${base}/etc/fwupd/remotes.d/${remote}.conf" > "$out"
       '';
     };
-  } else {};
+  };
+  remotes = (foldl'
+    (configFiles: remote: configFiles // (enableRemote cfg.package remote))
+    {}
+    cfg.extraRemotes
+  ) // (
+    # We cannot include the file in $out and rely on filesInstalledToEtc
+    # to install it because it would create a cyclic dependency between
+    # the outputs. We also need to enable the remote,
+    # which should not be done by default.
+    if cfg.enableTestRemote then (enableRemote cfg.package.installedTests "fwupd-tests") else {}
+  );
+
 in {
 
   ###### interface
@@ -53,7 +61,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable fwupd, a DBus service that allows
           applications to update firmware.
         '';
@@ -63,7 +71,7 @@ in {
         type = types.listOf types.str;
         default = [];
         example = [ "2082b5e0-7a64-478a-b1b2-e3404fab6dad" ];
-        description = ''
+        description = lib.mdDoc ''
           Allow disabling specific devices by their GUID
         '';
       };
@@ -72,7 +80,7 @@ in {
         type = types.listOf types.str;
         default = [];
         example = [ "udev" ];
-        description = ''
+        description = lib.mdDoc ''
           Allow disabling specific plugins
         '';
       };
@@ -81,17 +89,26 @@ in {
         type = types.listOf types.path;
         default = [];
         example = literalExpression "[ /etc/nixos/fwupd/myfirmware.pem ]";
-        description = ''
+        description = lib.mdDoc ''
           Installing a public key allows firmware signed with a matching private key to be recognized as trusted, which may require less authentication to install than for untrusted files. By default trusted firmware can be upgraded (but not downgraded) without the user or administrator password. Only very few keys are installed by default.
         '';
       };
 
+      extraRemotes = mkOption {
+        type = with types; listOf str;
+        default = [];
+        example = [ "lvfs-testing" ];
+        description = lib.mdDoc ''
+          Enables extra remotes in fwupd. See `/etc/fwupd/remotes.d`.
+        '';
+      };
+
       enableTestRemote = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable test remote. This is used by
-          <link xlink:href="https://github.com/fwupd/fwupd/blob/master/data/installed-tests/README.md">installed tests</link>.
+          [installed tests](https://github.com/fwupd/fwupd/blob/master/data/installed-tests/README.md).
         '';
       };
 
@@ -99,7 +116,7 @@ in {
         type = types.package;
         default = pkgs.fwupd;
         defaultText = literalExpression "pkgs.fwupd";
-        description = ''
+        description = lib.mdDoc ''
           Which fwupd package to use.
         '';
       };
@@ -119,13 +136,15 @@ in {
     environment.systemPackages = [ cfg.package ];
 
     # customEtc overrides some files from the package
-    environment.etc = originalEtc // customEtc // extraTrustedKeys // testRemote;
+    environment.etc = originalEtc // customEtc // extraTrustedKeys // remotes;
 
     services.dbus.packages = [ cfg.package ];
 
     services.udev.packages = [ cfg.package ];
 
     systemd.packages = [ cfg.package ];
+
+    security.polkit.enable = true;
   };
 
   meta = {
diff --git a/nixos/modules/services/hardware/illum.nix b/nixos/modules/services/hardware/illum.nix
index ff73c99a653..46172fb7b53 100644
--- a/nixos/modules/services/hardware/illum.nix
+++ b/nixos/modules/services/hardware/illum.nix
@@ -13,7 +13,7 @@ in {
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Enable illum, a daemon for controlling screen brightness with brightness buttons.
         '';
       };
@@ -28,6 +28,7 @@ in {
       description = "Backlight Adjustment Service";
       wantedBy = [ "multi-user.target" ];
       serviceConfig.ExecStart = "${pkgs.illum}/bin/illum-d";
+      serviceConfig.Restart = "on-failure";
     };
 
   };
diff --git a/nixos/modules/services/hardware/interception-tools.nix b/nixos/modules/services/hardware/interception-tools.nix
index e69c05841ee..4f86bd470ea 100644
--- a/nixos/modules/services/hardware/interception-tools.nix
+++ b/nixos/modules/services/hardware/interception-tools.nix
@@ -9,14 +9,14 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = "Whether to enable the interception tools service.";
+      description = lib.mdDoc "Whether to enable the interception tools service.";
     };
 
     plugins = mkOption {
       type = types.listOf types.package;
       default = [ pkgs.interception-tools-plugins.caps2esc ];
       defaultText = literalExpression "[ pkgs.interception-tools-plugins.caps2esc ]";
-      description = ''
+      description = lib.mdDoc ''
         A list of interception tools plugins that will be made available to use
         inside the udevmon configuration.
       '';
@@ -36,7 +36,7 @@ in {
             EVENTS:
               EV_KEY: [KEY_X, KEY_Y]
       '';
-      description = ''
+      description = lib.mdDoc ''
         String of udevmon YAML configuration, or path to a udevmon YAML
         configuration file.
       '';
diff --git a/nixos/modules/services/hardware/irqbalance.nix b/nixos/modules/services/hardware/irqbalance.nix
index c79e0eb83ec..8ba0a73d895 100644
--- a/nixos/modules/services/hardware/irqbalance.nix
+++ b/nixos/modules/services/hardware/irqbalance.nix
@@ -9,7 +9,7 @@ let
 
 in
 {
-  options.services.irqbalance.enable = mkEnableOption "irqbalance daemon";
+  options.services.irqbalance.enable = mkEnableOption (lib.mdDoc "irqbalance daemon");
 
   config = mkIf cfg.enable {
 
diff --git a/nixos/modules/services/hardware/joycond.nix b/nixos/modules/services/hardware/joycond.nix
index ffef4f8a4e1..f4da00762a4 100644
--- a/nixos/modules/services/hardware/joycond.nix
+++ b/nixos/modules/services/hardware/joycond.nix
@@ -9,26 +9,22 @@ with lib;
 
 {
   options.services.joycond = {
-    enable = mkEnableOption "support for Nintendo Pro Controllers and Joycons";
+    enable = mkEnableOption (lib.mdDoc "support for Nintendo Pro Controllers and Joycons");
 
     package = mkOption {
       type = types.package;
       default = pkgs.joycond;
       defaultText = "pkgs.joycond";
-      description = ''
+      description = lib.mdDoc ''
         The joycond package to use.
       '';
     };
   };
 
   config = mkIf cfg.enable {
-    environment.systemPackages = [
-      kernelPackages.hid-nintendo
-      cfg.package
-    ];
+    environment.systemPackages = [ cfg.package ];
 
-    boot.extraModulePackages = [ kernelPackages.hid-nintendo ];
-    boot.kernelModules = [ "hid_nintendo" ];
+    boot.extraModulePackages = optional (versionOlder kernelPackages.kernel.version "5.16") kernelPackages.hid-nintendo;
 
     services.udev.packages = [ cfg.package ];
 
diff --git a/nixos/modules/services/hardware/kanata.nix b/nixos/modules/services/hardware/kanata.nix
new file mode 100644
index 00000000000..84265eb8f94
--- /dev/null
+++ b/nixos/modules/services/hardware/kanata.nix
@@ -0,0 +1,215 @@
+{ config, lib, pkgs, utils, ... }:
+
+with lib;
+
+let
+  cfg = config.services.kanata;
+
+  keyboard = {
+    options = {
+      devices = mkOption {
+        type = types.addCheck (types.listOf types.str)
+          (devices: (length devices) > 0);
+        example = [ "/dev/input/by-id/usb-0000_0000-event-kbd" ];
+        # TODO replace note with tip, which has not been implemented yet in
+        # nixos/lib/make-options-doc/mergeJSON.py
+        description = mdDoc ''
+          Paths to keyboard devices.
+
+          ::: {.note}
+          To avoid unnecessary triggers of the service unit, unplug devices in
+          the order of the list.
+          :::
+        '';
+      };
+      config = mkOption {
+        type = types.lines;
+        example = ''
+          (defsrc
+            grv  1    2    3    4    5    6    7    8    9    0    -    =    bspc
+            tab  q    w    e    r    t    y    u    i    o    p    [    ]    \
+            caps a    s    d    f    g    h    j    k    l    ;    '    ret
+            lsft z    x    c    v    b    n    m    ,    .    /    rsft
+            lctl lmet lalt           spc            ralt rmet rctl)
+
+          (deflayer qwerty
+            grv  1    2    3    4    5    6    7    8    9    0    -    =    bspc
+            tab  q    w    e    r    t    y    u    i    o    p    [    ]    \
+            @cap a    s    d    f    g    h    j    k    l    ;    '    ret
+            lsft z    x    c    v    b    n    m    ,    .    /    rsft
+            lctl lmet lalt           spc            ralt rmet rctl)
+
+          (defalias
+            ;; tap within 100ms for capslk, hold more than 100ms for lctl
+            cap (tap-hold 100 100 caps lctl))
+        '';
+        description = mdDoc ''
+          Configuration other than `defcfg`. See [example config
+          files](https://github.com/jtroo/kanata) for more information.
+        '';
+      };
+      extraDefCfg = mkOption {
+        type = types.lines;
+        default = "";
+        example = "danger-enable-cmd yes";
+        description = mdDoc ''
+          Configuration of `defcfg` other than `linux-dev`. See [example
+          config files](https://github.com/jtroo/kanata) for more information.
+        '';
+      };
+      extraArgs = mkOption {
+        type = types.listOf types.str;
+        default = [ ];
+        description = mdDoc "Extra command line arguments passed to kanata.";
+      };
+      port = mkOption {
+        type = types.nullOr types.port;
+        default = null;
+        example = 6666;
+        description = mdDoc ''
+          Port to run the notification server on. `null` will not run the
+          server.
+        '';
+      };
+    };
+  };
+
+  mkName = name: "kanata-${name}";
+
+  mkDevices = devices: concatStringsSep ":" devices;
+
+  mkConfig = name: keyboard: pkgs.writeText "${mkName name}-config.kdb" ''
+    (defcfg
+      ${keyboard.extraDefCfg}
+      linux-dev ${mkDevices keyboard.devices})
+
+    ${keyboard.config}
+  '';
+
+  mkService = name: keyboard: nameValuePair (mkName name) {
+    description = "kanata for ${mkDevices keyboard.devices}";
+
+    # Because path units are used to activate service units, which
+    # will start the old stopped services during "nixos-rebuild
+    # switch", stopIfChanged here is a workaround to make sure new
+    # services are running after "nixos-rebuild switch".
+    stopIfChanged = false;
+
+    serviceConfig = {
+      ExecStart = ''
+        ${cfg.package}/bin/kanata \
+          --cfg ${mkConfig name keyboard} \
+          --symlink-path ''${RUNTIME_DIRECTORY}/${name} \
+          ${optionalString (keyboard.port != null) "--port ${toString keyboard.port}"} \
+          ${utils.escapeSystemdExecArgs keyboard.extraArgs}
+      '';
+
+      DynamicUser = true;
+      RuntimeDirectory = mkName name;
+      SupplementaryGroups = with config.users.groups; [
+        input.name
+        uinput.name
+      ];
+
+      # hardening
+      DeviceAllow = [
+        "/dev/uinput rw"
+        "char-input r"
+      ];
+      CapabilityBoundingSet = [ "" ];
+      DevicePolicy = "closed";
+      IPAddressAllow = optional (keyboard.port != null) "localhost";
+      IPAddressDeny = [ "any" ];
+      LockPersonality = true;
+      MemoryDenyWriteExecute = true;
+      PrivateNetwork = keyboard.port == null;
+      PrivateUsers = true;
+      ProcSubset = "pid";
+      ProtectClock = true;
+      ProtectControlGroups = true;
+      ProtectHome = true;
+      ProtectHostname = true;
+      ProtectKernelLogs = true;
+      ProtectKernelModules = true;
+      ProtectKernelTunables = true;
+      ProtectProc = "invisible";
+      RestrictAddressFamilies =
+        if (keyboard.port == null) then "none" else [ "AF_INET" ];
+      RestrictNamespaces = true;
+      RestrictRealtime = true;
+      SystemCallArchitectures = [ "native" ];
+      SystemCallFilter = [
+        "@system-service"
+        "~@privileged"
+        "~@resources"
+      ];
+      UMask = "0077";
+    };
+  };
+
+  mkPathName = i: name: "${mkName name}-${toString i}";
+
+  mkPath = name: n: i: device:
+    nameValuePair (mkPathName i name) {
+      description =
+        "${toString (i+1)}/${toString n} kanata trigger for ${name}, watching ${device}";
+      wantedBy = optional (i == 0) "multi-user.target";
+      pathConfig = {
+        PathExists = device;
+        # (ab)use systemd.path to construct a trigger chain so that the
+        # service unit is only started when all paths exist
+        # however, manual of systemd.path says Unit's suffix is not ".path"
+        Unit =
+          if (i + 1) == n
+          then "${mkName name}.service"
+          else "${mkPathName (i + 1) name}.path";
+      };
+      unitConfig.StopPropagatedFrom = optional (i > 0) "${mkName name}.service";
+    };
+
+  mkPaths = name: keyboard:
+    let
+      n = length keyboard.devices;
+    in
+    imap0 (mkPath name n) keyboard.devices
+  ;
+in
+{
+  options.services.kanata = {
+    enable = mkEnableOption (lib.mdDoc "kanata");
+    package = mkOption {
+      type = types.package;
+      default = pkgs.kanata;
+      defaultText = literalExpression "pkgs.kanata";
+      example = literalExpression "pkgs.kanata-with-cmd";
+      description = mdDoc ''
+        The kanata package to use.
+
+        ::: {.note}
+        If `danger-enable-cmd` is enabled in any of the keyboards, the
+        `kanata-with-cmd` package should be used.
+        :::
+      '';
+    };
+    keyboards = mkOption {
+      type = types.attrsOf (types.submodule keyboard);
+      default = { };
+      description = mdDoc "Keyboard configurations.";
+    };
+  };
+
+  config = mkIf cfg.enable {
+    hardware.uinput.enable = true;
+
+    systemd = {
+      paths = trivial.pipe cfg.keyboards [
+        (mapAttrsToList mkPaths)
+        concatLists
+        listToAttrs
+      ];
+      services = mapAttrs' mkService cfg.keyboards;
+    };
+  };
+
+  meta.maintainers = with maintainers; [ linj ];
+}
diff --git a/nixos/modules/services/hardware/lcd.nix b/nixos/modules/services/hardware/lcd.nix
index dc8595ea60c..8d682d137f4 100644
--- a/nixos/modules/services/hardware/lcd.nix
+++ b/nixos/modules/services/hardware/lcd.nix
@@ -36,49 +36,46 @@ in with lib; {
       serverHost = mkOption {
         type = str;
         default = "localhost";
-        description = "Host on which LCDd is listening.";
+        description = lib.mdDoc "Host on which LCDd is listening.";
       };
 
       serverPort = mkOption {
         type = int;
         default = 13666;
-        description = "Port on which LCDd is listening.";
+        description = lib.mdDoc "Port on which LCDd is listening.";
       };
 
       server = {
         enable = mkOption {
           type = bool;
           default = false;
-          description = "Enable the LCD panel server (LCDd)";
+          description = lib.mdDoc "Enable the LCD panel server (LCDd)";
         };
 
         openPorts = mkOption {
           type = bool;
           default = false;
-          description = "Open the ports in the firewall";
+          description = lib.mdDoc "Open the ports in the firewall";
         };
 
         usbPermissions = mkOption {
           type = bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Set group-write permissions on a USB device.
-            </para>
-            <para>
+
             A USB connected LCD panel will most likely require having its
             permissions modified for lcdd to write to it. Enabling this option
             sets group-write permissions on the device identified by
-            <option>services.hardware.lcd.usbVid</option> and
-            <option>services.hardware.lcd.usbPid</option>. In order to find the
-            values, you can run the <command>lsusb</command> command. Example
+            {option}`services.hardware.lcd.usbVid` and
+            {option}`services.hardware.lcd.usbPid`. In order to find the
+            values, you can run the {command}`lsusb` command. Example
             output:
-            </para>
-            <para>
-            <literal>
+
+            ```
             Bus 005 Device 002: ID 0403:c630 Future Technology Devices International, Ltd lcd2usb interface
-            </literal>
-            </para>
-            <para>
+            ```
+
             In this case the vendor id is 0403 and the product id is c630.
           '';
         };
@@ -86,25 +83,25 @@ in with lib; {
         usbVid = mkOption {
           type = str;
           default = "";
-          description = "The vendor ID of the USB device to claim.";
+          description = lib.mdDoc "The vendor ID of the USB device to claim.";
         };
 
         usbPid = mkOption {
           type = str;
           default = "";
-          description = "The product ID of the USB device to claim.";
+          description = lib.mdDoc "The product ID of the USB device to claim.";
         };
 
         usbGroup = mkOption {
           type = str;
           default = "dialout";
-          description = "The group to use for settings permissions. This group must exist or you will have to create it.";
+          description = lib.mdDoc "The group to use for settings permissions. This group must exist or you will have to create it.";
         };
 
         extraConfig = mkOption {
           type = lines;
           default = "";
-          description = "Additional configuration added verbatim to the server config.";
+          description = lib.mdDoc "Additional configuration added verbatim to the server config.";
         };
       };
 
@@ -112,19 +109,19 @@ in with lib; {
         enable = mkOption {
           type = bool;
           default = false;
-          description = "Enable the LCD panel client (LCDproc)";
+          description = lib.mdDoc "Enable the LCD panel client (LCDproc)";
         };
 
         extraConfig = mkOption {
           type = lines;
           default = "";
-          description = "Additional configuration added verbatim to the client config.";
+          description = lib.mdDoc "Additional configuration added verbatim to the client config.";
         };
 
         restartForever = mkOption {
           type = bool;
           default = true;
-          description = "Try restarting the client forever.";
+          description = lib.mdDoc "Try restarting the client forever.";
         };
       };
     };
diff --git a/nixos/modules/services/hardware/lirc.nix b/nixos/modules/services/hardware/lirc.nix
index f970b0a095c..acc43cd4186 100644
--- a/nixos/modules/services/hardware/lirc.nix
+++ b/nixos/modules/services/hardware/lirc.nix
@@ -11,7 +11,7 @@ in {
   options = {
     services.lirc = {
 
-      enable = mkEnableOption "LIRC daemon";
+      enable = mkEnableOption (lib.mdDoc "LIRC daemon");
 
       options = mkOption {
         type = types.lines;
@@ -19,18 +19,18 @@ in {
           [lircd]
           nodaemon = False
         '';
-        description = "LIRC default options descriped in man:lircd(8) (<filename>lirc_options.conf</filename>)";
+        description = lib.mdDoc "LIRC default options descriped in man:lircd(8) ({file}`lirc_options.conf`)";
       };
 
       configs = mkOption {
         type = types.listOf types.lines;
-        description = "Configurations for lircd to load, see man:lircd.conf(5) for details (<filename>lircd.conf</filename>)";
+        description = lib.mdDoc "Configurations for lircd to load, see man:lircd.conf(5) for details ({file}`lircd.conf`)";
       };
 
       extraArguments = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Extra arguments to lircd.";
+        description = lib.mdDoc "Extra arguments to lircd.";
       };
     };
   };
diff --git a/nixos/modules/services/hardware/nvidia-optimus.nix b/nixos/modules/services/hardware/nvidia-optimus.nix
index d53175052c7..5b5273ed782 100644
--- a/nixos/modules/services/hardware/nvidia-optimus.nix
+++ b/nixos/modules/services/hardware/nvidia-optimus.nix
@@ -11,7 +11,7 @@ let kernel = config.boot.kernelPackages; in
     hardware.nvidiaOptimus.disable = lib.mkOption {
       default = false;
       type = lib.types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Completely disable the NVIDIA graphics card and use the
         integrated graphics processor instead.
       '';
diff --git a/nixos/modules/services/hardware/openrgb.nix b/nixos/modules/services/hardware/openrgb.nix
new file mode 100644
index 00000000000..12438f01e52
--- /dev/null
+++ b/nixos/modules/services/hardware/openrgb.nix
@@ -0,0 +1,52 @@
+{ pkgs, lib, config, ... }:
+
+with lib;
+
+let
+  cfg = config.services.hardware.openrgb;
+in {
+  options.services.hardware.openrgb = {
+    enable = mkEnableOption (lib.mdDoc "OpenRGB server");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.openrgb;
+      defaultText = literalMD "pkgs.openrgb";
+      description = lib.mdDoc "Set version of openrgb package to use.";
+    };
+
+    motherboard = mkOption {
+      type = types.nullOr (types.enum [ "amd" "intel" ]);
+      default = null;
+      description = lib.mdDoc "CPU family of motherboard. Allows for addition motherboard i2c support.";
+    };
+
+    server.port = mkOption {
+      type = types.port;
+      default = 6742;
+      description = lib.mdDoc "Set server port of openrgb.";
+    };
+
+  };
+
+  config = mkIf cfg.enable {
+    environment.systemPackages = [ cfg.package ];
+    services.udev.packages = [ cfg.package ];
+
+    boot.kernelModules = [ "i2c-dev" ]
+     ++ lib.optionals (cfg.motherboard == "amd") [ "i2c-piix" ]
+     ++ lib.optionals (cfg.motherboard == "intel") [ "i2c-i801" ];
+
+    systemd.services.openrgb = {
+      description = "OpenRGB server daemon";
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = {
+        ExecStart = "${cfg.package}/bin/openrgb --server --server-port ${toString cfg.server.port}";
+        Restart = "always";
+      };
+    };
+  };
+
+  meta.maintainers = with lib.maintainers; [ jonringer ];
+}
diff --git a/nixos/modules/services/hardware/pcscd.nix b/nixos/modules/services/hardware/pcscd.nix
index b1a5c680a02..a09c64645c4 100644
--- a/nixos/modules/services/hardware/pcscd.nix
+++ b/nixos/modules/services/hardware/pcscd.nix
@@ -5,6 +5,10 @@ with lib;
 let
   cfgFile = pkgs.writeText "reader.conf" config.services.pcscd.readerConfig;
 
+  package = if config.security.polkit.enable
+              then pkgs.pcscliteWithPolkit
+              else pkgs.pcsclite;
+
   pluginEnv = pkgs.buildEnv {
     name = "pcscd-plugins";
     paths = map (p: "${p}/pcsc/drivers") config.services.pcscd.plugins;
@@ -16,14 +20,14 @@ in
   ###### interface
 
   options.services.pcscd = {
-    enable = mkEnableOption "PCSC-Lite daemon";
+    enable = mkEnableOption (lib.mdDoc "PCSC-Lite daemon");
 
     plugins = mkOption {
       type = types.listOf types.package;
       default = [ pkgs.ccid ];
       defaultText = literalExpression "[ pkgs.ccid ]";
       example = literalExpression "[ pkgs.pcsc-cyberjack ]";
-      description = "Plugin packages to be used for PCSC-Lite.";
+      description = lib.mdDoc "Plugin packages to be used for PCSC-Lite.";
     };
 
     readerConfig = mkOption {
@@ -35,11 +39,10 @@ in
         LIBPATH           /path/to/serial_reader.so
         CHANNELID         1
       '';
-      description = ''
+      description = lib.mdDoc ''
         Configuration for devices that aren't hotpluggable.
 
-        See <citerefentry><refentrytitle>reader.conf</refentrytitle>
-        <manvolnum>5</manvolnum></citerefentry> for valid options.
+        See {manpage}`reader.conf(5)` for valid options.
       '';
     };
   };
@@ -50,8 +53,8 @@ in
 
     environment.etc."reader.conf".source = cfgFile;
 
-    environment.systemPackages = [ pkgs.pcsclite ];
-    systemd.packages = [ (getBin pkgs.pcsclite) ];
+    environment.systemPackages = [ package ];
+    systemd.packages = [ (getBin package) ];
 
     systemd.sockets.pcscd.wantedBy = [ "sockets.target" ];
 
@@ -67,7 +70,7 @@ in
       # around it, we force the path to the cfgFile.
       #
       # https://github.com/NixOS/nixpkgs/issues/121088
-      serviceConfig.ExecStart = [ "" "${getBin pkgs.pcsclite}/bin/pcscd -f -x -c ${cfgFile}" ];
+      serviceConfig.ExecStart = [ "" "${getBin package}/bin/pcscd -f -x -c ${cfgFile}" ];
     };
   };
 }
diff --git a/nixos/modules/services/hardware/pommed.nix b/nixos/modules/services/hardware/pommed.nix
index bf7d6a46a29..a71004c1767 100644
--- a/nixos/modules/services/hardware/pommed.nix
+++ b/nixos/modules/services/hardware/pommed.nix
@@ -13,7 +13,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use the pommed tool to handle Apple laptop
           keyboard hotkeys.
         '';
@@ -22,12 +22,12 @@ in {
       configFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
-          The path to the <filename>pommed.conf</filename> file. Leave
+        description = lib.mdDoc ''
+          The path to the {file}`pommed.conf` file. Leave
           to null to use the default config file
-          (<filename>/etc/pommed.conf.mactel</filename>). See the
-          files <filename>/etc/pommed.conf.mactel</filename> and
-          <filename>/etc/pommed.conf.pmac</filename> for examples to
+          ({file}`/etc/pommed.conf.mactel`). See the
+          files {file}`/etc/pommed.conf.mactel` and
+          {file}`/etc/pommed.conf.pmac` for examples to
           build on.
         '';
       };
diff --git a/nixos/modules/services/hardware/power-profiles-daemon.nix b/nixos/modules/services/hardware/power-profiles-daemon.nix
index 4144bc66708..101da01b4a7 100644
--- a/nixos/modules/services/hardware/power-profiles-daemon.nix
+++ b/nixos/modules/services/hardware/power-profiles-daemon.nix
@@ -18,7 +18,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable power-profiles-daemon, a DBus daemon that allows
           changing system behavior based upon user-selected power profiles.
         '';
diff --git a/nixos/modules/services/hardware/rasdaemon.nix b/nixos/modules/services/hardware/rasdaemon.nix
index 2d4c6d2ce95..a1334684b7d 100644
--- a/nixos/modules/services/hardware/rasdaemon.nix
+++ b/nixos/modules/services/hardware/rasdaemon.nix
@@ -10,18 +10,18 @@ in
 {
   options.hardware.rasdaemon = {
 
-    enable = mkEnableOption "RAS logging daemon";
+    enable = mkEnableOption (lib.mdDoc "RAS logging daemon");
 
     record = mkOption {
       type = types.bool;
       default = true;
-      description = "record events via sqlite3, required for ras-mc-ctl";
+      description = lib.mdDoc "record events via sqlite3, required for ras-mc-ctl";
     };
 
     mainboard = mkOption {
       type = types.lines;
       default = "";
-      description = "Custom mainboard description, see <citerefentry><refentrytitle>ras-mc-ctl</refentrytitle><manvolnum>8</manvolnum></citerefentry> for more details.";
+      description = lib.mdDoc "Custom mainboard description, see {manpage}`ras-mc-ctl(8)` for more details.";
       example = ''
         vendor = ASRock
         model = B450M Pro4
@@ -40,7 +40,7 @@ in
     labels = mkOption {
       type = types.lines;
       default = "";
-      description = "Additional memory module label descriptions to be placed in /etc/ras/dimm_labels.d/labels";
+      description = lib.mdDoc "Additional memory module label descriptions to be placed in /etc/ras/dimm_labels.d/labels";
       example = ''
         # vendor and model may be shown by 'ras-mc-ctl --mainboard'
         vendor: ASRock
@@ -57,7 +57,7 @@ in
     config = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         rasdaemon configuration, currently only used for CE PFA
         for details, read rasdaemon.outPath/etc/sysconfig/rasdaemon's comments
       '';
@@ -72,11 +72,11 @@ in
     extraModules = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = "extra kernel modules to load";
+      description = lib.mdDoc "extra kernel modules to load";
       example = [ "i7core_edac" ];
     };
 
-    testing = mkEnableOption "error injection infrastructure";
+    testing = mkEnableOption (lib.mdDoc "error injection infrastructure");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/hardware/ratbagd.nix b/nixos/modules/services/hardware/ratbagd.nix
index 01a8276750f..c939d5e40a2 100644
--- a/nixos/modules/services/hardware/ratbagd.nix
+++ b/nixos/modules/services/hardware/ratbagd.nix
@@ -10,7 +10,7 @@ in
 
   options = {
     services.ratbagd = {
-      enable = mkEnableOption "ratbagd for configuring gaming mice";
+      enable = mkEnableOption (lib.mdDoc "ratbagd for configuring gaming mice");
     };
   };
 
diff --git a/nixos/modules/services/hardware/sane.nix b/nixos/modules/services/hardware/sane.nix
index caf232e234e..fe6dd268df6 100644
--- a/nixos/modules/services/hardware/sane.nix
+++ b/nixos/modules/services/hardware/sane.nix
@@ -28,8 +28,8 @@ let
   };
 
   env = {
-    SANE_CONFIG_DIR = config.hardware.sane.configDir;
-    LD_LIBRARY_PATH = [ "${saneConfig}/lib/sane" ];
+    SANE_CONFIG_DIR = "/etc/sane.d";
+    LD_LIBRARY_PATH = [ "/etc/sane-libs" ];
   };
 
   backends = [ pkg netConf ] ++ optional config.services.saned.enable sanedConf ++ config.hardware.sane.extraBackends;
@@ -48,55 +48,57 @@ in
     hardware.sane.enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable support for SANE scanners.
 
-        <note><para>
-          Users in the "scanner" group will gain access to the scanner, or the "lp" group if it's also a printer.
-        </para></note>
+        ::: {.note}
+        Users in the "scanner" group will gain access to the scanner, or the "lp" group if it's also a printer.
+        :::
       '';
     };
 
     hardware.sane.snapshot = mkOption {
       type = types.bool;
       default = false;
-      description = "Use a development snapshot of SANE scanner drivers.";
+      description = lib.mdDoc "Use a development snapshot of SANE scanner drivers.";
     };
 
     hardware.sane.extraBackends = mkOption {
       type = types.listOf types.path;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Packages providing extra SANE backends to enable.
 
-        <note><para>
-          The example contains the package for HP scanners.
-        </para></note>
+        ::: {.note}
+        The example contains the package for HP scanners, and the package for
+        Apple AirScan and Microsoft WSD support (supports many
+        vendors/devices).
+        :::
       '';
-      example = literalExpression "[ pkgs.hplipWithPlugin ]";
+      example = literalExpression "[ pkgs.hplipWithPlugin pkgs.sane-airscan ]";
     };
 
     hardware.sane.disabledDefaultBackends = mkOption {
       type = types.listOf types.str;
       default = [];
       example = [ "v4l" ];
-      description = ''
+      description = lib.mdDoc ''
         Names of backends which are enabled by default but should be disabled.
-        See <literal>$SANE_CONFIG_DIR/dll.conf</literal> for the list of possible names.
+        See `$SANE_CONFIG_DIR/dll.conf` for the list of possible names.
       '';
     };
 
     hardware.sane.configDir = mkOption {
       type = types.str;
       internal = true;
-      description = "The value of SANE_CONFIG_DIR.";
+      description = lib.mdDoc "The value of SANE_CONFIG_DIR.";
     };
 
     hardware.sane.netConf = mkOption {
       type = types.lines;
       default = "";
       example = "192.168.0.16";
-      description = ''
+      description = lib.mdDoc ''
         Network hosts that should be probed for remote scanners.
       '';
     };
@@ -105,7 +107,7 @@ in
       type = types.bool;
       default = false;
       example = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable drivers for the Fujitsu ScanSnap scanners.
 
         The driver files are unfree and extracted from the Windows driver image.
@@ -116,22 +118,31 @@ in
       type = types.package;
       default = pkgs.sane-drivers.epjitsu;
       defaultText = literalExpression "pkgs.sane-drivers.epjitsu";
-      description = ''
+      description = lib.mdDoc ''
         Epjitsu driver package to use. Useful if you want to extract the driver files yourself.
 
-        The process is described in the <literal>/etc/sane.d/epjitsu.conf</literal> file in
-        the <literal>sane-backends</literal> package.
+        The process is described in the `/etc/sane.d/epjitsu.conf` file in
+        the `sane-backends` package.
+      '';
+    };
+
+    hardware.sane.openFirewall = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Open ports needed for discovery of scanners on the local network, e.g.
+        needed for Canon scanners (BJNP protocol).
       '';
     };
 
     services.saned.enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable saned network daemon for remote connection to scanners.
 
-        saned would be runned from <literal>scanner</literal> user; to allow
-        access to hardware that doesn't have <literal>scanner</literal> group
+        saned would be runned from `scanner` user; to allow
+        access to hardware that doesn't have `scanner` group
         you should add needed groups to this user.
       '';
     };
@@ -140,7 +151,7 @@ in
       type = types.lines;
       default = "";
       example = "192.168.0.0/24";
-      description = ''
+      description = lib.mdDoc ''
         Extra saned configuration lines.
       '';
     };
@@ -156,9 +167,12 @@ in
 
       environment.systemPackages = backends;
       environment.sessionVariables = env;
+      environment.etc."sane.d".source = config.hardware.sane.configDir;
+      environment.etc."sane-libs".source = "${saneConfig}/lib/sane";
       services.udev.packages = backends;
 
       users.groups.scanner.gid = config.ids.gids.scanner;
+      networking.firewall.allowedUDPPorts = mkIf config.hardware.sane.openFirewall [ 8612 ];
     })
 
     (mkIf config.services.saned.enable {
diff --git a/nixos/modules/services/hardware/sane_extra_backends/brscan4.nix b/nixos/modules/services/hardware/sane_extra_backends/brscan4.nix
index 8f999810840..e737a4ce20d 100644
--- a/nixos/modules/services/hardware/sane_extra_backends/brscan4.nix
+++ b/nixos/modules/services/hardware/sane_extra_backends/brscan4.nix
@@ -15,7 +15,7 @@ let
 
       name = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The friendly name you give to the network device. If undefined,
           the name of attribute will be used.
         '';
@@ -25,7 +25,7 @@ let
 
       model = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The model of the network device.
         '';
 
@@ -35,7 +35,7 @@ let
       ip = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The ip address of the device. If undefined, you will have to
           provide a nodename.
         '';
@@ -46,7 +46,7 @@ let
       nodename = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The node name of the device. If undefined, you will have to
           provide an ip.
         '';
@@ -68,8 +68,8 @@ in
   options = {
 
     hardware.sane.brscan4.enable =
-      mkEnableOption "Brother's brscan4 scan backend" // {
-      description = ''
+      mkEnableOption (lib.mdDoc "Brother's brscan4 scan backend") // {
+      description = lib.mdDoc ''
         When enabled, will automatically register the "brscan4" sane
         backend and bring configuration files to their expected location.
       '';
@@ -82,7 +82,7 @@ in
           office2 = { model = "MFC-7860DW"; nodename = "BRW0080927AFBCE"; };
         };
       type = with types; attrsOf (submodule netDeviceOpts);
-      description = ''
+      description = lib.mdDoc ''
         The list of network devices that will be registered against the brscan4
         sane backend.
       '';
diff --git a/nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix b/nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix
index 9d083a615a2..f76ab701c5b 100644
--- a/nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix
+++ b/nixos/modules/services/hardware/sane_extra_backends/brscan4_etc_files.nix
@@ -33,7 +33,8 @@ in
 
 stdenv.mkDerivation {
 
-  name = "brscan4-etc-files-0.4.3-3";
+  pname = "brscan4-etc-files";
+  version = "0.4.3-3";
   src = "${brscan4}/opt/brother/scanner/brscan4";
 
   nativeBuildInputs = [ brscan4 ];
diff --git a/nixos/modules/services/hardware/sane_extra_backends/brscan5.nix b/nixos/modules/services/hardware/sane_extra_backends/brscan5.nix
index 2e4ad8cc3ba..d29e0f542f5 100644
--- a/nixos/modules/services/hardware/sane_extra_backends/brscan5.nix
+++ b/nixos/modules/services/hardware/sane_extra_backends/brscan5.nix
@@ -15,7 +15,7 @@ let
 
       name = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The friendly name you give to the network device. If undefined,
           the name of attribute will be used.
         '';
@@ -25,7 +25,7 @@ let
 
       model = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The model of the network device.
         '';
 
@@ -35,7 +35,7 @@ let
       ip = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The ip address of the device. If undefined, you will have to
           provide a nodename.
         '';
@@ -46,7 +46,7 @@ let
       nodename = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The node name of the device. If undefined, you will have to
           provide an ip.
         '';
@@ -68,7 +68,7 @@ in
   options = {
 
     hardware.sane.brscan5.enable =
-      mkEnableOption "the Brother brscan5 sane backend";
+      mkEnableOption (lib.mdDoc "the Brother brscan5 sane backend");
 
     hardware.sane.brscan5.netDevices = mkOption {
       default = {};
@@ -77,7 +77,7 @@ in
           office2 = { model = "MFC-7860DW"; nodename = "BRW0080927AFBCE"; };
         };
       type = with types; attrsOf (submodule netDeviceOpts);
-      description = ''
+      description = lib.mdDoc ''
         The list of network devices that will be registered against the brscan5
         sane backend.
       '';
diff --git a/nixos/modules/services/hardware/sane_extra_backends/dsseries.nix b/nixos/modules/services/hardware/sane_extra_backends/dsseries.nix
index d71a17f5ea6..5b05694abc0 100644
--- a/nixos/modules/services/hardware/sane_extra_backends/dsseries.nix
+++ b/nixos/modules/services/hardware/sane_extra_backends/dsseries.nix
@@ -6,8 +6,8 @@ with lib;
   options = {
 
     hardware.sane.dsseries.enable =
-      mkEnableOption "Brother DSSeries scan backend" // {
-      description = ''
+      mkEnableOption (lib.mdDoc "Brother DSSeries scan backend") // {
+      description = lib.mdDoc ''
         When enabled, will automatically register the "dsseries" SANE backend.
 
         This supports the Brother DSmobile scanner series, including the
diff --git a/nixos/modules/services/hardware/spacenavd.nix b/nixos/modules/services/hardware/spacenavd.nix
index 69ca6f102ef..36f13243937 100644
--- a/nixos/modules/services/hardware/spacenavd.nix
+++ b/nixos/modules/services/hardware/spacenavd.nix
@@ -8,7 +8,7 @@ in {
 
   options = {
     hardware.spacenavd = {
-      enable = mkEnableOption "spacenavd to support 3DConnexion devices";
+      enable = mkEnableOption (lib.mdDoc "spacenavd to support 3DConnexion devices");
     };
   };
 
diff --git a/nixos/modules/services/hardware/tcsd.nix b/nixos/modules/services/hardware/tcsd.nix
index e414b9647c9..f22924d410d 100644
--- a/nixos/modules/services/hardware/tcsd.nix
+++ b/nixos/modules/services/hardware/tcsd.nix
@@ -40,7 +40,7 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable tcsd, a Trusted Computing management service
           that provides TCG Software Stack (TSS).  The tcsd daemon is
           the only portal to the Trusted Platform Module (TPM), a hardware
@@ -51,19 +51,19 @@ in
       user = mkOption {
         default = "tss";
         type = types.str;
-        description = "User account under which tcsd runs.";
+        description = lib.mdDoc "User account under which tcsd runs.";
       };
 
       group = mkOption {
         default = "tss";
         type = types.str;
-        description = "Group account under which tcsd runs.";
+        description = lib.mdDoc "Group account under which tcsd runs.";
       };
 
       stateDir = mkOption {
         default = "/var/lib/tpm";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The location of the system persistent storage file.
           The system persistent storage file holds keys and data across
           restarts of the TCSD and system reboots.
@@ -73,20 +73,20 @@ in
       firmwarePCRs = mkOption {
         default = "0,1,2,3,4,5,6,7";
         type = types.str;
-        description = "PCR indices used in the TPM for firmware measurements.";
+        description = lib.mdDoc "PCR indices used in the TPM for firmware measurements.";
       };
 
       kernelPCRs = mkOption {
         default = "8,9,10,11,12";
         type = types.str;
-        description = "PCR indices used in the TPM for kernel measurements.";
+        description = lib.mdDoc "PCR indices used in the TPM for kernel measurements.";
       };
 
       platformCred = mkOption {
         default = "${cfg.stateDir}/platform.cert";
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/platform.cert"'';
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to the platform credential for your TPM. Your TPM
           manufacturer may have provided you with a set of credentials
           (certificates) that should be used when creating identities
@@ -100,7 +100,7 @@ in
         default = "${cfg.stateDir}/conformance.cert";
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/conformance.cert"'';
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to the conformance credential for your TPM.
           See also the platformCred option'';
       };
@@ -109,7 +109,7 @@ in
         default = "${cfg.stateDir}/endorsement.cert";
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/endorsement.cert"'';
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to the endorsement credential for your TPM.
           See also the platformCred option'';
       };
diff --git a/nixos/modules/services/hardware/thermald.nix b/nixos/modules/services/hardware/thermald.nix
index fcd02ea90c6..6b694ede588 100644
--- a/nixos/modules/services/hardware/thermald.nix
+++ b/nixos/modules/services/hardware/thermald.nix
@@ -9,12 +9,12 @@ in
   ###### interface
   options = {
     services.thermald = {
-      enable = mkEnableOption "thermald, the temperature management daemon";
+      enable = mkEnableOption (lib.mdDoc "thermald, the temperature management daemon");
 
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable debug logging.
         '';
       };
@@ -22,14 +22,14 @@ in
       configFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "the thermald manual configuration file.";
+        description = lib.mdDoc "the thermald manual configuration file.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.thermald;
         defaultText = literalExpression "pkgs.thermald";
-        description = "Which thermald package to use.";
+        description = lib.mdDoc "Which thermald package to use.";
       };
     };
   };
diff --git a/nixos/modules/services/hardware/thinkfan.nix b/nixos/modules/services/hardware/thinkfan.nix
index 4ea829e496e..8fa7b456f20 100644
--- a/nixos/modules/services/hardware/thinkfan.nix
+++ b/nixos/modules/services/hardware/thinkfan.nix
@@ -29,45 +29,47 @@ let
     options = {
       type = mkOption {
         type = types.enum [ "hwmon" "atasmart" "tpacpi" "nvml" ];
-        description = ''
+        description = lib.mdDoc ''
           The ${name} type, can be
-          <literal>hwmon</literal> for standard ${name}s,
+          `hwmon` for standard ${name}s,
 
-          <literal>atasmart</literal> to read the temperature via
+          `atasmart` to read the temperature via
           S.M.A.R.T (requires smartSupport to be enabled),
 
-          <literal>tpacpi</literal> for the legacy thinkpac_acpi driver, or
+          `tpacpi` for the legacy thinkpac_acpi driver, or
 
-          <literal>nvml</literal> for the (proprietary) nVidia driver.
+          `nvml` for the (proprietary) nVidia driver.
         '';
       };
       query = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The query string used to match one or more ${name}s: can be
           a fullpath to the temperature file (single ${name}) or a fullpath
           to a driver directory (multiple ${name}s).
 
-          <note><para>
-            When multiple ${name}s match, the query can be restricted using the
-            <option>name</option> or <option>indices</option> options.
-          </para></note>
+          ::: {.note}
+          When multiple ${name}s match, the query can be restricted using the
+          {option}`name` or {option}`indices` options.
+          :::
         '';
       };
       indices = mkOption {
         type = with types; nullOr (listOf ints.unsigned);
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A list of ${name}s to pick in case multiple ${name}s match the query.
 
-          <note><para>Indices start from 0.</para></note>
+          ::: {.note}
+          Indices start from 0.
+          :::
         '';
       };
     } // optionalAttrs (name == "sensor") {
       correction = mkOption {
         type = with types; nullOr (listOf int);
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A list of values to be added to the temperature of each sensor,
           can be used to equalize small discrepancies in temperature ratings.
         '';
@@ -81,18 +83,18 @@ let
     // { "${type}" = query; };
 
   syntaxNote = name: ''
-    <note><para>
-      This section slightly departs from the thinkfan.conf syntax.
-      The type and path must be specified like this:
-      <literal>
-        type = "tpacpi";
-        query = "/proc/acpi/ibm/${name}";
-      </literal>
-      instead of a single declaration like:
-      <literal>
-        - tpacpi: /proc/acpi/ibm/${name}
-      </literal>
-    </para></note>
+    ::: {.note}
+    This section slightly departs from the thinkfan.conf syntax.
+    The type and path must be specified like this:
+    ```
+      type = "tpacpi";
+      query = "/proc/acpi/ibm/${name}";
+    ```
+    instead of a single declaration like:
+    ```
+      - tpacpi: /proc/acpi/ibm/${name}
+    ```
+    :::
   '';
 
 in {
@@ -104,13 +106,13 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable thinkfan, a fan control program.
 
-          <note><para>
-            This module targets IBM/Lenovo thinkpads by default, for
-            other hardware you will have configure it more carefully.
-          </para></note>
+          ::: {.note}
+          This module targets IBM/Lenovo thinkpads by default, for
+          other hardware you will have configure it more carefully.
+          :::
         '';
         relatedPackages = [ "thinkfan" ];
       };
@@ -118,7 +120,7 @@ in {
       smartSupport = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to build thinkfan with S.M.A.R.T. support to read temperatures
           directly from hard disks.
         '';
@@ -131,9 +133,11 @@ in {
             query = "/proc/acpi/ibm/thermal";
           }
         ];
-        description = ''
+        description = lib.mdDoc ''
           List of temperature sensors thinkfan will monitor.
-        '' + syntaxNote "thermal";
+
+          ${syntaxNote "thermal"}
+        '';
       };
 
       fans = mkOption {
@@ -143,9 +147,11 @@ in {
             query = "/proc/acpi/ibm/fan";
           }
         ];
-        description = ''
+        description = lib.mdDoc ''
           List of fans thinkfan will control.
-        '' + syntaxNote "fan";
+
+          ${syntaxNote "fan"}
+        '';
       };
 
       levels = mkOption {
@@ -159,7 +165,7 @@ in {
           [7  60  85]
           ["level auto" 80 32767]
         ];
-        description = ''
+        description = lib.mdDoc ''
           [LEVEL LOW HIGH]
 
           LEVEL is the fan level to use: it can be an integer (0-7 with thinkpad_acpi),
@@ -175,7 +181,7 @@ in {
         type = types.listOf types.str;
         default = [ ];
         example = [ "-b" "0" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of extra command line arguments to pass to thinkfan.
           Check the thinkfan(1) manpage for available arguments.
         '';
@@ -184,12 +190,12 @@ in {
       settings = mkOption {
         type = types.attrsOf settingsFormat.type;
         default = { };
-        description = ''
+        description = lib.mdDoc ''
           Thinkfan settings. Use this option to configure thinkfan
           settings not exposed in a NixOS option or to bypass one.
-          Before changing this, read the <literal>thinkfan.conf(5)</literal>
+          Before changing this, read the `thinkfan.conf(5)`
           manpage and take a look at the example config file at
-          <link xlink:href="https://github.com/vmatare/thinkfan/blob/master/examples/thinkfan.yaml"/>
+          <https://github.com/vmatare/thinkfan/blob/master/examples/thinkfan.yaml>
         '';
       };
 
diff --git a/nixos/modules/services/hardware/throttled.nix b/nixos/modules/services/hardware/throttled.nix
index 1905eb565c6..99735ff6519 100644
--- a/nixos/modules/services/hardware/throttled.nix
+++ b/nixos/modules/services/hardware/throttled.nix
@@ -7,12 +7,12 @@ let
 in {
   options = {
     services.throttled = {
-      enable = mkEnableOption "fix for Intel CPU throttling";
+      enable = mkEnableOption (lib.mdDoc "fix for Intel CPU throttling");
 
       extraConfig = mkOption {
         type = types.str;
         default = "";
-        description = "Alternative configuration";
+        description = lib.mdDoc "Alternative configuration";
       };
     };
   };
diff --git a/nixos/modules/services/hardware/tlp.nix b/nixos/modules/services/hardware/tlp.nix
index eb53f565a67..d2cc7c661c6 100644
--- a/nixos/modules/services/hardware/tlp.nix
+++ b/nixos/modules/services/hardware/tlp.nix
@@ -20,7 +20,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the TLP power management daemon.";
+        description = lib.mdDoc "Whether to enable the TLP power management daemon.";
       };
 
       settings = mkOption {type = with types; attrsOf (oneOf [bool int float str (listOf str)]);
@@ -29,7 +29,7 @@ in
           SATA_LINKPWR_ON_BAT = "med_power_with_dipm";
           USB_BLACKLIST_PHONE = 1;
         };
-        description = ''
+        description = lib.mdDoc ''
           Options passed to TLP. See https://linrunner.de/tlp for all supported options..
         '';
       };
@@ -37,7 +37,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Verbatim additional configuration variables for TLP.
           DEPRECATED: use services.tlp.settings instead.
         '';
diff --git a/nixos/modules/services/hardware/trezord.nix b/nixos/modules/services/hardware/trezord.nix
index a65d4250c2e..70c1fd09860 100644
--- a/nixos/modules/services/hardware/trezord.nix
+++ b/nixos/modules/services/hardware/trezord.nix
@@ -18,7 +18,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable Trezor bridge daemon, for use with Trezor hardware bitcoin wallets.
         '';
       };
@@ -26,7 +26,7 @@ in {
       emulator.enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable Trezor emulator support.
           '';
        };
@@ -34,7 +34,7 @@ in {
       emulator.port = mkOption {
         type = types.port;
         default = 21324;
-        description = ''
+        description = lib.mdDoc ''
           Listening port for the Trezor emulator.
           '';
       };
diff --git a/nixos/modules/services/hardware/triggerhappy.nix b/nixos/modules/services/hardware/triggerhappy.nix
index c2fa87875e1..54eac70643f 100644
--- a/nixos/modules/services/hardware/triggerhappy.nix
+++ b/nixos/modules/services/hardware/triggerhappy.nix
@@ -22,18 +22,18 @@ let
 
       keys = mkOption {
         type = types.listOf types.str;
-        description = "List of keys to match.  Key names as defined in linux/input-event-codes.h";
+        description = lib.mdDoc "List of keys to match.  Key names as defined in linux/input-event-codes.h";
       };
 
       event = mkOption {
         type = types.enum ["press" "hold" "release"];
         default = "press";
-        description = "Event to match.";
+        description = lib.mdDoc "Event to match.";
       };
 
       cmd = mkOption {
         type = types.str;
-        description = "What to run.";
+        description = lib.mdDoc "What to run.";
       };
 
     };
@@ -52,8 +52,8 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          Whether to enable the <command>triggerhappy</command> hotkey daemon.
+        description = lib.mdDoc ''
+          Whether to enable the {command}`triggerhappy` hotkey daemon.
         '';
       };
 
@@ -61,8 +61,8 @@ in
         type = types.str;
         default = "nobody";
         example = "root";
-        description = ''
-          User account under which <command>triggerhappy</command> runs.
+        description = lib.mdDoc ''
+          User account under which {command}`triggerhappy` runs.
         '';
       };
 
@@ -72,16 +72,16 @@ in
         example = lib.literalExpression ''
           [ { keys = ["PLAYPAUSE"];  cmd = "''${pkgs.mpc-cli}/bin/mpc -q toggle"; } ]
         '';
-        description = ''
-          Key bindings for <command>triggerhappy</command>.
+        description = lib.mdDoc ''
+          Key bindings for {command}`triggerhappy`.
         '';
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
-          Literal contents to append to the end of <command>triggerhappy</command> configuration file.
+        description = lib.mdDoc ''
+          Literal contents to append to the end of {command}`triggerhappy` configuration file.
         '';
       };
 
diff --git a/nixos/modules/services/hardware/udev.nix b/nixos/modules/services/hardware/udev.nix
index 61448af2d33..d9526133241 100644
--- a/nixos/modules/services/hardware/udev.nix
+++ b/nixos/modules/services/hardware/udev.nix
@@ -8,6 +8,24 @@ let
 
   cfg = config.services.udev;
 
+  initrdUdevRules = pkgs.runCommand "initrd-udev-rules" {} ''
+    mkdir -p $out/etc/udev/rules.d
+    for f in 60-cdrom_id 60-persistent-storage 75-net-description 80-drivers 80-net-setup-link; do
+      ln -s ${config.boot.initrd.systemd.package}/lib/udev/rules.d/$f.rules $out/etc/udev/rules.d
+    done
+  '';
+
+
+  # networkd link files are used early by udev to set up interfaces early.
+  # This must be done in stage 1 to avoid race conditions between udev and
+  # network daemons.
+  # TODO move this into the initrd-network module when it exists
+  initrdLinkUnits = pkgs.runCommand "initrd-link-units" {} ''
+    mkdir -p $out
+    ln -s ${udev}/lib/systemd/network/*.link $out/
+    ${lib.concatMapStringsSep "\n" (file: "ln -s ${file} $out/") (lib.mapAttrsToList (n: v: "${v.unit}/${n}") (lib.filterAttrs (n: _: hasSuffix ".link" n) config.systemd.network.units))}
+  '';
+
   extraUdevRules = pkgs.writeTextFile {
     name = "extra-udev-rules";
     text = cfg.extraRules;
@@ -23,17 +41,21 @@ let
   nixosRules = ''
     # Miscellaneous devices.
     KERNEL=="kvm",                  MODE="0666"
-    KERNEL=="kqemu",                MODE="0666"
 
     # Needed for gpm.
     SUBSYSTEM=="input", KERNEL=="mice", TAG+="systemd"
   '';
 
+  nixosInitrdRules = ''
+    # Mark dm devices as db_persist so that they are kept active after switching root
+    SUBSYSTEM=="block", KERNEL=="dm-[0-9]*", ACTION=="add|change", OPTIONS+="db_persist"
+  '';
+
   # Perform substitutions in all udev rules files.
-  udevRules = pkgs.runCommand "udev-rules"
+  udevRulesFor = { name, udevPackages, udevPath, udev, systemd, binPackages, initrdBin ? null }: pkgs.runCommand name
     { preferLocalBuild = true;
       allowSubstitutes = false;
-      packages = unique (map toString cfg.packages);
+      packages = unique (map toString udevPackages);
     }
     ''
       mkdir -p $out
@@ -61,6 +83,9 @@ let
           --replace \"/bin/mount \"${pkgs.util-linux}/bin/mount \
           --replace /usr/bin/readlink ${pkgs.coreutils}/bin/readlink \
           --replace /usr/bin/basename ${pkgs.coreutils}/bin/basename
+      ${optionalString (initrdBin != null) ''
+        substituteInPlace $i --replace '/run/current-system/systemd' "${removeSuffix "/bin" initrdBin}"
+      ''}
       done
 
       echo -n "Checking that all programs called by relative paths in udev rules exist in ${udev}/lib/udev... "
@@ -85,8 +110,9 @@ let
       for i in $import_progs $run_progs; do
         # if the path refers to /run/current-system/systemd, replace with config.systemd.package
         if [[ $i == /run/current-system/systemd* ]]; then
-          i="${config.systemd.package}/''${i#/run/current-system/systemd/}"
+          i="${systemd}/''${i#/run/current-system/systemd/}"
         fi
+
         if [[ ! -x $i ]]; then
           echo "FAIL"
           echo "$i is called in udev rules but is not executable or does not exist"
@@ -103,7 +129,7 @@ let
         echo "Consider fixing the following udev rules:"
         echo "$filesToFixup" | while read localFile; do
           remoteFile="origin unknown"
-          for i in ${toString cfg.packages}; do
+          for i in ${toString binPackages}; do
             for j in "$i"/*/udev/rules.d/*; do
               [ -e "$out/$(basename "$j")" ] || continue
               [ "$(basename "$j")" = "$(basename "$localFile")" ] || continue
@@ -126,7 +152,7 @@ let
       ${optionalString (!config.boot.hardwareScan) ''
         ln -s /dev/null $out/80-drivers.rules
       ''}
-    ''; # */
+    '';
 
   hwdbBin = pkgs.runCommand "hwdb.bin"
     { preferLocalBuild = true;
@@ -150,6 +176,11 @@ let
       mv etc/udev/hwdb.bin $out
     '';
 
+  compressFirmware = firmware: if (config.boot.kernelPackages.kernelAtLeast "5.3" && (firmware.compressFirmware or true)) then
+    pkgs.compressFirmwareXz firmware
+  else
+    id firmware;
+
   # Udev has a 512-character limit for ENV{PATH}, so create a symlink
   # tree to work around this.
   udevPath = pkgs.buildEnv {
@@ -166,11 +197,10 @@ in
   ###### interface
 
   options = {
-
     boot.hardwareScan = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to try to load kernel modules for all detected hardware.
         Usually this does a good job of providing you with the modules
         you need, but sometimes it can crash the system or cause other
@@ -179,15 +209,18 @@ in
     };
 
     services.udev = {
+      enable = mkEnableOption (lib.mdDoc "udev") // {
+        default = true;
+      };
 
       packages = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
-          List of packages containing <command>udev</command> rules.
+        description = lib.mdDoc ''
+          List of packages containing {command}`udev` rules.
           All files found in
-          <filename><replaceable>pkg</replaceable>/etc/udev/rules.d</filename> and
-          <filename><replaceable>pkg</replaceable>/lib/udev/rules.d</filename>
+          {file}`«pkg»/etc/udev/rules.d` and
+          {file}`«pkg»/lib/udev/rules.d`
           will be included.
         '';
         apply = map getBin;
@@ -196,35 +229,21 @@ in
       path = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
-          Packages added to the <envar>PATH</envar> environment variable when
+        description = lib.mdDoc ''
+          Packages added to the {env}`PATH` environment variable when
           executing programs from Udev rules.
         '';
       };
 
-      initrdRules = mkOption {
-        default = "";
-        example = ''
-          SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:1D:60:B9:6D:4F", KERNEL=="eth*", NAME="my_fast_network_card"
-        '';
-        type = types.lines;
-        description = ''
-          <command>udev</command> rules to include in the initrd
-          <emphasis>only</emphasis>. They'll be written into file
-          <filename>99-local.rules</filename>. Thus they are read and applied
-          after the essential initrd rules.
-        '';
-      };
-
       extraRules = mkOption {
         default = "";
         example = ''
           ENV{ID_VENDOR_ID}=="046d", ENV{ID_MODEL_ID}=="0825", ENV{PULSE_IGNORE}="1"
         '';
         type = types.lines;
-        description = ''
-          Additional <command>udev</command> rules. They'll be written
-          into file <filename>99-local.rules</filename>. Thus they are
+        description = lib.mdDoc ''
+          Additional {command}`udev` rules. They'll be written
+          into file {file}`99-local.rules`. Thus they are
           read and applied after all other rules.
         '';
       };
@@ -237,9 +256,9 @@ in
             KEYBOARD_KEY_700e2=leftctrl
         '';
         type = types.lines;
-        description = ''
-          Additional <command>hwdb</command> files. They'll be written
-          into file <filename>99-local.hwdb</filename>. Thus they are
+        description = lib.mdDoc ''
+          Additional {command}`hwdb` files. They'll be written
+          into file {file}`99-local.hwdb`. Thus they are
           read after all other files.
         '';
       };
@@ -249,7 +268,7 @@ in
     hardware.firmware = mkOption {
       type = types.listOf types.package;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         List of packages containing firmware files.  Such files
         will be loaded automatically if the kernel asks for them
         (i.e., when it has detected specific hardware that requires
@@ -260,7 +279,7 @@ in
       '';
       apply = list: pkgs.buildEnv {
         name = "firmware";
-        paths = list;
+        paths = map compressFirmware list;
         pathsToLink = [ "/lib/firmware" ];
         ignoreCollisions = true;
       };
@@ -269,26 +288,71 @@ in
     networking.usePredictableInterfaceNames = mkOption {
       default = true;
       type = types.bool;
-      description = ''
-        Whether to assign <link
-        xlink:href='http://www.freedesktop.org/wiki/Software/systemd/PredictableNetworkInterfaceNames'>predictable
-        names to network interfaces</link>.  If enabled, interfaces
+      description = lib.mdDoc ''
+        Whether to assign [predictable names to network interfaces](http://www.freedesktop.org/wiki/Software/systemd/PredictableNetworkInterfaceNames).
+        If enabled, interfaces
         are assigned names that contain topology information
-        (e.g. <literal>wlp3s0</literal>) and thus should be stable
+        (e.g. `wlp3s0`) and thus should be stable
         across reboots.  If disabled, names depend on the order in
         which interfaces are discovered by the kernel, which may
         change randomly across reboots; for instance, you may find
-        <literal>eth0</literal> and <literal>eth1</literal> flipping
+        `eth0` and `eth1` flipping
         unpredictably.
       '';
     };
 
+    boot.initrd.services.udev = {
+
+      packages = mkOption {
+        type = types.listOf types.path;
+        default = [];
+        visible = false;
+        description = lib.mdDoc ''
+          *This will only be used when systemd is used in stage 1.*
+
+          List of packages containing {command}`udev` rules that will be copied to stage 1.
+          All files found in
+          {file}`«pkg»/etc/udev/rules.d` and
+          {file}`«pkg»/lib/udev/rules.d`
+          will be included.
+        '';
+      };
+
+      binPackages = mkOption {
+        type = types.listOf types.path;
+        default = [];
+        visible = false;
+        description = lib.mdDoc ''
+          *This will only be used when systemd is used in stage 1.*
+
+          Packages to search for binaries that are referenced by the udev rules in stage 1.
+          This list always contains /bin of the initrd.
+        '';
+        apply = map getBin;
+      };
+
+      rules = mkOption {
+        default = "";
+        example = ''
+          SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:1D:60:B9:6D:4F", KERNEL=="eth*", NAME="my_fast_network_card"
+        '';
+        type = types.lines;
+        description = lib.mdDoc ''
+          {command}`udev` rules to include in the initrd
+          *only*. They'll be written into file
+          {file}`99-local.rules`. Thus they are read and applied
+          after the essential initrd rules.
+        '';
+      };
+
+    };
+
   };
 
 
   ###### implementation
 
-  config = mkIf (!config.boot.isContainer) {
+  config = mkIf cfg.enable {
 
     services.udev.extraRules = nixosRules;
 
@@ -298,16 +362,63 @@ in
 
     boot.kernelParams = mkIf (!config.networking.usePredictableInterfaceNames) [ "net.ifnames=0" ];
 
-    boot.initrd.extraUdevRulesCommands = optionalString (cfg.initrdRules != "")
+    boot.initrd.extraUdevRulesCommands = optionalString (!config.boot.initrd.systemd.enable && config.boot.initrd.services.udev.rules != "")
       ''
         cat <<'EOF' > $out/99-local.rules
-        ${cfg.initrdRules}
+        ${config.boot.initrd.services.udev.rules}
         EOF
       '';
 
+    boot.initrd.services.udev.rules = nixosInitrdRules;
+
+    boot.initrd.systemd.additionalUpstreamUnits = [
+      "initrd-udevadm-cleanup-db.service"
+      "systemd-udevd-control.socket"
+      "systemd-udevd-kernel.socket"
+      "systemd-udevd.service"
+      "systemd-udev-settle.service"
+      "systemd-udev-trigger.service"
+    ];
+    boot.initrd.systemd.storePaths = [
+      "${config.boot.initrd.systemd.package}/lib/systemd/systemd-udevd"
+      "${config.boot.initrd.systemd.package}/lib/udev/ata_id"
+      "${config.boot.initrd.systemd.package}/lib/udev/cdrom_id"
+      "${config.boot.initrd.systemd.package}/lib/udev/scsi_id"
+      "${config.boot.initrd.systemd.package}/lib/udev/rules.d"
+    ] ++ map (x: "${x}/bin") config.boot.initrd.services.udev.binPackages;
+
+    # Generate the udev rules for the initrd
+    boot.initrd.systemd.contents = {
+      "/etc/udev/rules.d".source = udevRulesFor {
+        name = "initrd-udev-rules";
+        initrdBin = config.boot.initrd.systemd.contents."/bin".source;
+        udevPackages = config.boot.initrd.services.udev.packages;
+        udevPath = config.boot.initrd.systemd.contents."/bin".source;
+        udev = config.boot.initrd.systemd.package;
+        systemd = config.boot.initrd.systemd.package;
+        binPackages = config.boot.initrd.services.udev.binPackages ++ [ config.boot.initrd.systemd.contents."/bin".source ];
+      };
+      "/etc/systemd/network".source = initrdLinkUnits;
+    };
+    # Insert initrd rules
+    boot.initrd.services.udev.packages = [
+      initrdUdevRules
+      (mkIf (config.boot.initrd.services.udev.rules != "") (pkgs.writeTextFile {
+        name = "initrd-udev-rules";
+        destination = "/etc/udev/rules.d/99-local.rules";
+        text = config.boot.initrd.services.udev.rules;
+      }))
+    ];
+
     environment.etc =
       {
-        "udev/rules.d".source = udevRules;
+        "udev/rules.d".source = udevRulesFor {
+          name = "udev-rules";
+          udevPackages = cfg.packages;
+          systemd = config.systemd.package;
+          binPackages = cfg.packages;
+          inherit udevPath udev;
+        };
         "udev/hwdb.bin".source = hwdbBin;
       };
 
@@ -338,4 +449,8 @@ in
       };
 
   };
+
+  imports = [
+    (mkRenamedOptionModule [ "services" "udev" "initrdRules" ] [ "boot" "initrd" "services" "udev" "rules" ])
+  ];
 }
diff --git a/nixos/modules/services/hardware/udisks2.nix b/nixos/modules/services/hardware/udisks2.nix
index 6be23f39754..7368845dafd 100644
--- a/nixos/modules/services/hardware/udisks2.nix
+++ b/nixos/modules/services/hardware/udisks2.nix
@@ -4,6 +4,13 @@
 
 with lib;
 
+let
+  settingsFormat = pkgs.formats.ini {
+    listToValue = concatMapStringsSep "," (generators.mkValueStringDefault {});
+  };
+  configFiles = mapAttrs (name: value: (settingsFormat.generate name value)) (mapAttrs' (name: value: nameValuePair name value ) config.services.udisks2.settings);
+in
+
 {
 
   ###### interface
@@ -12,12 +19,35 @@ with lib;
 
     services.udisks2 = {
 
-      enable = mkOption {
-        type = types.bool;
-        default = true;
-        description = ''
-          Whether to enable Udisks, a DBus service that allows
-          applications to query and manipulate storage devices.
+      enable = mkEnableOption (lib.mdDoc "udisks2, a DBus service that allows applications to query and manipulate storage devices.");
+
+      settings = mkOption rec {
+        type = types.attrsOf settingsFormat.type;
+        apply = recursiveUpdate default;
+        default = {
+          "udisks2.conf" = {
+            udisks2 = {
+              modules = [ "*" ];
+              modules_load_preference = "ondemand";
+            };
+            defaults = {
+              encryption = "luks2";
+            };
+          };
+        };
+        example = literalExpression ''
+        {
+          "WDC-WD10EZEX-60M2NA0-WD-WCC3F3SJ0698.conf" = {
+            ATA = {
+              StandbyTimeout = 50;
+            };
+          };
+        };
+        '';
+        description = lib.mdDoc ''
+          Options passed to udisksd.
+          See [here](http://manpages.ubuntu.com/manpages/latest/en/man5/udisks2.conf.5.html) and
+          drive configuration in [here](http://manpages.ubuntu.com/manpages/latest/en/man8/udisks.8.html) for supported options.
         '';
       };
 
@@ -32,6 +62,13 @@ with lib;
 
     environment.systemPackages = [ pkgs.udisks2 ];
 
+    environment.etc = (mapAttrs' (name: value: nameValuePair "udisks2/${name}" { source = value; } ) configFiles) // {
+      # We need to make sure /etc/libblockdev/conf.d is populated to avoid
+      # warnings
+      "libblockdev/conf.d/00-default.cfg".source = "${pkgs.libblockdev}/etc/libblockdev/conf.d/00-default.cfg";
+      "libblockdev/conf.d/10-lvm-dbus.cfg".source = "${pkgs.libblockdev}/etc/libblockdev/conf.d/10-lvm-dbus.cfg";
+    };
+
     security.polkit.enable = true;
 
     services.dbus.packages = [ pkgs.udisks2 ];
diff --git a/nixos/modules/services/hardware/undervolt.nix b/nixos/modules/services/hardware/undervolt.nix
index a743bbf21c8..c49d944cdc1 100644
--- a/nixos/modules/services/hardware/undervolt.nix
+++ b/nixos/modules/services/hardware/undervolt.nix
@@ -33,16 +33,16 @@ let
 in
 {
   options.services.undervolt = {
-    enable = mkEnableOption ''
+    enable = mkEnableOption (lib.mdDoc ''
        Undervolting service for Intel CPUs.
 
        Warning: This service is not endorsed by Intel and may permanently damage your hardware. Use at your own risk!
-    '';
+    '');
 
     verbose = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable verbose logging.
       '';
     };
@@ -51,7 +51,7 @@ in
       type = types.package;
       default = pkgs.undervolt;
       defaultText = literalExpression "pkgs.undervolt";
-      description = ''
+      description = lib.mdDoc ''
         undervolt derivation to use.
       '';
     };
@@ -59,7 +59,7 @@ in
     coreOffset = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The amount of voltage in mV to offset the CPU cores by.
       '';
     };
@@ -67,7 +67,7 @@ in
     gpuOffset = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The amount of voltage in mV to offset the GPU by.
       '';
     };
@@ -75,7 +75,7 @@ in
     uncoreOffset = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The amount of voltage in mV to offset uncore by.
       '';
     };
@@ -83,7 +83,7 @@ in
     analogioOffset = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The amount of voltage in mV to offset analogio by.
       '';
     };
@@ -91,7 +91,7 @@ in
     temp = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The temperature target in Celsius degrees.
       '';
     };
@@ -99,7 +99,7 @@ in
     tempAc = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The temperature target on AC power in Celsius degrees.
       '';
     };
@@ -107,7 +107,7 @@ in
     tempBat = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The temperature target on battery power in Celsius degrees.
       '';
     };
@@ -115,7 +115,7 @@ in
     p1.limit = mkOption {
       type = with types; nullOr int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The P1 Power Limit in Watts.
         Both limit and window must be set.
       '';
@@ -123,7 +123,7 @@ in
     p1.window = mkOption {
       type = with types; nullOr (oneOf [ float int ]);
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The P1 Time Window in seconds.
         Both limit and window must be set.
       '';
@@ -132,7 +132,7 @@ in
     p2.limit = mkOption {
       type = with types; nullOr int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The P2 Power Limit in Watts.
         Both limit and window must be set.
       '';
@@ -140,7 +140,7 @@ in
     p2.window = mkOption {
       type = with types; nullOr (oneOf [ float int ]);
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The P2 Time Window in seconds.
         Both limit and window must be set.
       '';
@@ -149,7 +149,7 @@ in
     useTimer = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to set a timer that applies the undervolt settings every 30s.
         This will cause spam in the journal but might be required for some
         hardware under specific conditions.
diff --git a/nixos/modules/services/hardware/upower.nix b/nixos/modules/services/hardware/upower.nix
index 81bf497c993..aacc8a63dbe 100644
--- a/nixos/modules/services/hardware/upower.nix
+++ b/nixos/modules/services/hardware/upower.nix
@@ -21,7 +21,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Upower, a DBus service that provides power
           management support to applications.
         '';
@@ -31,7 +31,7 @@ in
         type = types.package;
         default = pkgs.upower;
         defaultText = literalExpression "pkgs.upower";
-        description = ''
+        description = lib.mdDoc ''
           Which upower package to use.
         '';
       };
@@ -39,7 +39,7 @@ in
       enableWattsUpPro = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the Watts Up Pro device.
 
           The Watts Up Pro contains a generic FTDI USB device without a specific
@@ -49,17 +49,15 @@ in
 
           The generic FTDI device is known to also be used on:
 
-          <itemizedlist>
-            <listitem><para>Sparkfun FT232 breakout board</para></listitem>
-            <listitem><para>Parallax Propeller</para></listitem>
-          </itemizedlist>
+          - Sparkfun FT232 breakout board
+          - Parallax Propeller
         '';
       };
 
       noPollBatteries = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Don't poll the kernel for battery level changes.
 
           Some hardware will send us battery level changes through
@@ -71,7 +69,7 @@ in
       ignoreLid = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Do we ignore the lid state
 
           Some laptops are broken. The lid state is either inverted, or stuck
@@ -85,7 +83,7 @@ in
       usePercentageForPolicy = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Policy for warnings and action based on battery levels
 
           Whether battery percentage based policy should be used. The default
@@ -99,17 +97,17 @@ in
       percentageLow = mkOption {
         type = types.ints.unsigned;
         default = 10;
-        description = ''
-          When <literal>usePercentageForPolicy</literal> is
-          <literal>true</literal>, the levels at which UPower will consider the
+        description = lib.mdDoc ''
+          When `usePercentageForPolicy` is
+          `true`, the levels at which UPower will consider the
           battery low.
 
           This will also be used for batteries which don't have time information
           such as that of peripherals.
 
-          If any value (of <literal>percentageLow</literal>,
-          <literal>percentageCritical</literal> and
-          <literal>percentageAction</literal>) is invalid, or not in descending
+          If any value (of `percentageLow`,
+          `percentageCritical` and
+          `percentageAction`) is invalid, or not in descending
           order, the defaults will be used.
         '';
       };
@@ -117,17 +115,17 @@ in
       percentageCritical = mkOption {
         type = types.ints.unsigned;
         default = 3;
-        description = ''
-          When <literal>usePercentageForPolicy</literal> is
-          <literal>true</literal>, the levels at which UPower will consider the
+        description = lib.mdDoc ''
+          When `usePercentageForPolicy` is
+          `true`, the levels at which UPower will consider the
           battery critical.
 
           This will also be used for batteries which don't have time information
           such as that of peripherals.
 
-          If any value (of <literal>percentageLow</literal>,
-          <literal>percentageCritical</literal> and
-          <literal>percentageAction</literal>) is invalid, or not in descending
+          If any value (of `percentageLow`,
+          `percentageCritical` and
+          `percentageAction`) is invalid, or not in descending
           order, the defaults will be used.
         '';
       };
@@ -135,17 +133,17 @@ in
       percentageAction = mkOption {
         type = types.ints.unsigned;
         default = 2;
-        description = ''
-          When <literal>usePercentageForPolicy</literal> is
-          <literal>true</literal>, the levels at which UPower will take action
+        description = lib.mdDoc ''
+          When `usePercentageForPolicy` is
+          `true`, the levels at which UPower will take action
           for the critical battery level.
 
           This will also be used for batteries which don't have time information
           such as that of peripherals.
 
-          If any value (of <literal>percentageLow</literal>,
-          <literal>percentageCritical</literal> and
-          <literal>percentageAction</literal>) is invalid, or not in descending
+          If any value (of `percentageLow`,
+          `percentageCritical` and
+          `percentageAction`) is invalid, or not in descending
           order, the defaults will be used.
         '';
       };
@@ -153,13 +151,13 @@ in
       timeLow = mkOption {
         type = types.ints.unsigned;
         default = 1200;
-        description = ''
-          When <literal>usePercentageForPolicy</literal> is
-          <literal>false</literal>, the time remaining in seconds at which
+        description = lib.mdDoc ''
+          When `usePercentageForPolicy` is
+          `false`, the time remaining in seconds at which
           UPower will consider the battery low.
 
-          If any value (of <literal>timeLow</literal>,
-          <literal>timeCritical</literal> and <literal>timeAction</literal>) is
+          If any value (of `timeLow`,
+          `timeCritical` and `timeAction`) is
           invalid, or not in descending order, the defaults will be used.
         '';
       };
@@ -167,13 +165,13 @@ in
       timeCritical = mkOption {
         type = types.ints.unsigned;
         default = 300;
-        description = ''
-          When <literal>usePercentageForPolicy</literal> is
-          <literal>false</literal>, the time remaining in seconds at which
+        description = lib.mdDoc ''
+          When `usePercentageForPolicy` is
+          `false`, the time remaining in seconds at which
           UPower will consider the battery critical.
 
-          If any value (of <literal>timeLow</literal>,
-          <literal>timeCritical</literal> and <literal>timeAction</literal>) is
+          If any value (of `timeLow`,
+          `timeCritical` and `timeAction`) is
           invalid, or not in descending order, the defaults will be used.
         '';
       };
@@ -181,13 +179,13 @@ in
       timeAction = mkOption {
         type = types.ints.unsigned;
         default = 120;
-        description = ''
-          When <literal>usePercentageForPolicy</literal> is
-          <literal>false</literal>, the time remaining in seconds at which
+        description = lib.mdDoc ''
+          When `usePercentageForPolicy` is
+          `false`, the time remaining in seconds at which
           UPower will take action for the critical battery level.
 
-          If any value (of <literal>timeLow</literal>,
-          <literal>timeCritical</literal> and <literal>timeAction</literal>) is
+          If any value (of `timeLow`,
+          `timeCritical` and `timeAction`) is
           invalid, or not in descending order, the defaults will be used.
         '';
       };
@@ -195,9 +193,9 @@ in
       criticalPowerAction = mkOption {
         type = types.enum [ "PowerOff" "Hibernate" "HybridSleep" ];
         default = "HybridSleep";
-        description = ''
-          The action to take when <literal>timeAction</literal> or
-          <literal>percentageAction</literal> has been reached for the batteries
+        description = lib.mdDoc ''
+          The action to take when `timeAction` or
+          `percentageAction` has been reached for the batteries
           (UPS or laptop batteries) supplying the computer
         '';
       };
diff --git a/nixos/modules/services/hardware/usbmuxd.nix b/nixos/modules/services/hardware/usbmuxd.nix
index 11a4b0a858f..b4c954906dd 100644
--- a/nixos/modules/services/hardware/usbmuxd.nix
+++ b/nixos/modules/services/hardware/usbmuxd.nix
@@ -16,7 +16,7 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable the usbmuxd ("USB multiplexing daemon") service. This daemon is
         in charge of multiplexing connections over USB to an iOS device. This is
         needed for transferring data from and to iOS devices (see ifuse). Also
@@ -27,7 +27,7 @@ in
     user = mkOption {
       type = types.str;
       default = defaultUserGroup;
-      description = ''
+      description = lib.mdDoc ''
         The user usbmuxd should use to run after startup.
       '';
     };
@@ -35,7 +35,7 @@ in
     group = mkOption {
       type = types.str;
       default = defaultUserGroup;
-      description = ''
+      description = lib.mdDoc ''
         The group usbmuxd should use to run after startup.
       '';
     };
diff --git a/nixos/modules/services/hardware/usbrelayd.nix b/nixos/modules/services/hardware/usbrelayd.nix
new file mode 100644
index 00000000000..01d3a5ba8be
--- /dev/null
+++ b/nixos/modules/services/hardware/usbrelayd.nix
@@ -0,0 +1,43 @@
+{ config, lib, pkgs, ... }:
+with lib;
+let
+  cfg = config.services.usbrelayd;
+in
+{
+  options.services.usbrelayd = with types; {
+    enable = mkEnableOption (lib.mdDoc "USB Relay MQTT daemon");
+
+    broker = mkOption {
+      type = str;
+      description = lib.mdDoc "Hostname or IP address of your MQTT Broker.";
+      default = "127.0.0.1";
+      example = [
+        "mqtt"
+        "192.168.1.1"
+      ];
+    };
+
+    clientName = mkOption {
+      type = str;
+      description = lib.mdDoc "Name, your client connects as.";
+      default = "MyUSBRelay";
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    environment.etc."usbrelayd.conf".text = ''
+      [MQTT]
+      BROKER = ${cfg.broker}
+      CLIENTNAME = ${cfg.clientName}
+    '';
+
+    services.udev.packages = [ pkgs.usbrelayd ];
+    systemd.packages = [ pkgs.usbrelayd ];
+    users.groups.usbrelay = { };
+  };
+
+  meta = {
+    maintainers = with lib.maintainers; [ wentasah ];
+  };
+}
diff --git a/nixos/modules/services/hardware/vdr.nix b/nixos/modules/services/hardware/vdr.nix
index 5ec222b805c..de63ed893b0 100644
--- a/nixos/modules/services/hardware/vdr.nix
+++ b/nixos/modules/services/hardware/vdr.nix
@@ -12,29 +12,29 @@ in {
   options = {
 
     services.vdr = {
-      enable = mkEnableOption "VDR. Please put config into ${libDir}";
+      enable = mkEnableOption (lib.mdDoc "VDR. Please put config into ${libDir}");
 
       package = mkOption {
         type = types.package;
         default = pkgs.vdr;
         defaultText = literalExpression "pkgs.vdr";
         example = literalExpression "pkgs.wrapVdr.override { plugins = with pkgs.vdrPlugins; [ hello ]; }";
-        description = "Package to use.";
+        description = lib.mdDoc "Package to use.";
       };
 
       videoDir = mkOption {
         type = types.path;
         default = "/srv/vdr/video";
-        description = "Recording directory";
+        description = lib.mdDoc "Recording directory";
       };
 
       extraArguments = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Additional command line arguments to pass to VDR.";
+        description = lib.mdDoc "Additional command line arguments to pass to VDR.";
       };
 
-      enableLirc = mkEnableOption "LIRC";
+      enableLirc = mkEnableOption (lib.mdDoc "LIRC");
     };
   };
 
diff --git a/nixos/modules/services/hardware/xow.nix b/nixos/modules/services/hardware/xow.nix
deleted file mode 100644
index 311181176bd..00000000000
--- a/nixos/modules/services/hardware/xow.nix
+++ /dev/null
@@ -1,20 +0,0 @@
-{ config, pkgs, lib, ... }:
-
-let
-  cfg = config.services.hardware.xow;
-in {
-  options.services.hardware.xow = {
-    enable = lib.mkEnableOption "xow as a systemd service";
-  };
-
-  config = lib.mkIf cfg.enable {
-    hardware.uinput.enable = true;
-
-    boot.extraModprobeConfig = lib.readFile "${pkgs.xow}/lib/modprobe.d/xow-blacklist.conf";
-
-    systemd.packages = [ pkgs.xow ];
-    systemd.services.xow.wantedBy = [ "multi-user.target" ];
-
-    services.udev.packages = [ pkgs.xow ];
-  };
-}
diff --git a/nixos/modules/services/home-automation/evcc.nix b/nixos/modules/services/home-automation/evcc.nix
new file mode 100644
index 00000000000..c12ba9d0c1e
--- /dev/null
+++ b/nixos/modules/services/home-automation/evcc.nix
@@ -0,0 +1,92 @@
+{ lib
+, pkgs
+, config
+, ...
+}:
+
+with lib;
+
+let
+  cfg = config.services.evcc;
+
+  format = pkgs.formats.yaml {};
+  configFile = format.generate "evcc.yml" cfg.settings;
+
+  package = pkgs.evcc;
+in
+
+{
+  meta.maintainers = with lib.maintainers; [ hexa ];
+
+  options.services.evcc = with types; {
+    enable = mkEnableOption (lib.mdDoc "EVCC, the extensible EV Charge Controller with PV integration");
+
+    extraArgs = mkOption {
+      type = listOf str;
+      default = [];
+      description = lib.mdDoc ''
+        Extra arguments to pass to the evcc executable.
+      '';
+    };
+
+    settings = mkOption {
+      type = format.type;
+      description = lib.mdDoc ''
+        evcc configuration as a Nix attribute set.
+
+        Check for possible options in the sample [evcc.dist.yaml](https://github.com/andig/evcc/blob/${package.version}/evcc.dist.yaml].
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.evcc = {
+      after = [
+        "network-online.target"
+        "mosquitto.target"
+      ];
+      wantedBy = [
+        "multi-user.target"
+      ];
+
+      serviceConfig = {
+        ExecStart = "${package}/bin/evcc --config ${configFile} ${escapeShellArgs cfg.extraArgs}";
+        CapabilityBoundingSet = [ "" ];
+        DeviceAllow = [
+          "char-ttyUSB"
+        ];
+        DevicePolicy = "closed";
+        DynamicUser = true;
+        LockPersonality = true;
+        MemoryDenyWriteExecute = true;
+        RestrictAddressFamilies = [
+          "AF_INET"
+          "AF_INET6"
+          "AF_UNIX"
+        ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        PrivateTmp = true;
+        PrivateUsers = true;
+        ProcSubset = "pid";
+        ProtectClock = true;
+        ProtectControlGroups= true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectProc = "invisible";
+        SystemCallArchitectures = "native";
+        SystemCallFilter = [
+          "@system-service"
+          "~@privileged"
+        ];
+        UMask = "0077";
+        User = "evcc";
+      };
+    };
+  };
+
+  meta.buildDocsInSandbox = false;
+}
diff --git a/nixos/modules/services/home-automation/home-assistant.nix b/nixos/modules/services/home-automation/home-assistant.nix
index 6022227f6ea..2962e52c08b 100644
--- a/nixos/modules/services/home-automation/home-assistant.nix
+++ b/nixos/modules/services/home-automation/home-assistant.nix
@@ -77,12 +77,12 @@ in {
   options.services.home-assistant = {
     # Running home-assistant on NixOS is considered an installation method that is unsupported by the upstream project.
     # https://github.com/home-assistant/architecture/blob/master/adr/0012-define-supported-installation-method.md#decision
-    enable = mkEnableOption "Home Assistant. Please note that this installation method is unsupported upstream";
+    enable = mkEnableOption (lib.mdDoc "Home Assistant. Please note that this installation method is unsupported upstream");
 
     configDir = mkOption {
       default = "/var/lib/hass";
       type = types.path;
-      description = "The config directory, where your <filename>configuration.yaml</filename> is located.";
+      description = lib.mdDoc "The config directory, where your {file}`configuration.yaml` is located.";
     };
 
     extraComponents = mkOption {
@@ -92,7 +92,7 @@ in {
         "default_config"
         "met"
         "esphome"
-      ] ++ optionals (pkgs.stdenv.hostPlatform.isAarch32 || pkgs.stdenv.hostPlatform.isAarch64) [
+      ] ++ optionals pkgs.stdenv.hostPlatform.isAarch [
         # Use the platform as an indicator that we might be running on a RaspberryPi and include
         # relevant components
         "rpi_power"
@@ -107,10 +107,10 @@ in {
           "wled"
         ]
       '';
-      description = ''
-        List of <link xlink:href="https://www.home-assistant.io/integrations/">components</link> that have their dependencies included in the package.
+      description = lib.mdDoc ''
+        List of [components](https://www.home-assistant.io/integrations/) that have their dependencies included in the package.
 
-        The component name can be found in the URL, for example <literal>https://www.home-assistant.io/integrations/ffmpeg/</literal> would map to <literal>ffmpeg</literal>.
+        The component name can be found in the URL, for example `https://www.home-assistant.io/integrations/ffmpeg/` would map to `ffmpeg`.
       '';
     };
 
@@ -126,10 +126,10 @@ in {
           psycopg2
         ];
       '';
-      description = ''
+      description = lib.mdDoc ''
         List of packages to add to propagatedBuildInputs.
 
-        A popular example is <package>python3Packages.psycopg2</package>
+        A popular example is `python3Packages.psycopg2`
         for PostgreSQL support in the recorder component.
       '';
     };
@@ -148,7 +148,7 @@ in {
               type = types.nullOr types.str;
               default = null;
               example = "Home";
-              description = ''
+              description = lib.mdDoc ''
                 Name of the location where Home Assistant is running.
               '';
             };
@@ -157,7 +157,7 @@ in {
               type = types.nullOr (types.either types.float types.str);
               default = null;
               example = 52.3;
-              description = ''
+              description = lib.mdDoc ''
                 Latitude of your location required to calculate the time the sun rises and sets.
               '';
             };
@@ -166,7 +166,7 @@ in {
               type = types.nullOr (types.either types.float types.str);
               default = null;
               example = 4.9;
-              description = ''
+              description = lib.mdDoc ''
                 Longitude of your location required to calculate the time the sun rises and sets.
               '';
             };
@@ -175,7 +175,7 @@ in {
               type = types.nullOr (types.enum [ "metric" "imperial" ]);
               default = null;
               example = "metric";
-              description = ''
+              description = lib.mdDoc ''
                 The unit system to use. This also sets temperature_unit, Celsius for Metric and Fahrenheit for Imperial.
               '';
             };
@@ -184,8 +184,8 @@ in {
               type = types.nullOr (types.enum [ "C" "F" ]);
               default = null;
               example = "C";
-              description = ''
-                Override temperature unit set by unit_system. <literal>C</literal> for Celsius, <literal>F</literal> for Fahrenheit.
+              description = lib.mdDoc ''
+                Override temperature unit set by unit_system. `C` for Celsius, `F` for Fahrenheit.
               '';
             };
 
@@ -196,8 +196,8 @@ in {
                 config.time.timeZone or null
               '';
               example = "Europe/Amsterdam";
-              description = ''
-                Pick your time zone from the column TZ of Wikipedia’s <link xlink:href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">list of tz database time zones</link>.
+              description = lib.mdDoc ''
+                Pick your time zone from the column TZ of Wikipedia’s [list of tz database time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
               '';
             };
           };
@@ -211,7 +211,7 @@ in {
                 "::"
               ];
               example = "::1";
-              description = ''
+              description = lib.mdDoc ''
                 Only listen to incoming requests on specific IP/host. The default listed assumes support for IPv4 and IPv6.
               '';
             };
@@ -219,7 +219,7 @@ in {
             server_port = mkOption {
               default = 8123;
               type = types.port;
-              description = ''
+              description = lib.mdDoc ''
                 The port on which to listen.
               '';
             };
@@ -238,8 +238,8 @@ in {
                 else "storage";
               '';
               example = "yaml";
-              description = ''
-                In what mode should the main Lovelace panel be, <literal>yaml</literal> or <literal>storage</literal> (UI managed).
+              description = lib.mdDoc ''
+                In what mode should the main Lovelace panel be, `yaml` or `storage` (UI managed).
               '';
             };
           };
@@ -262,14 +262,14 @@ in {
           feedreader.urls = [ "https://nixos.org/blogs.xml" ];
         }
       '';
-      description = ''
-        Your <filename>configuration.yaml</filename> as a Nix attribute set.
+      description = lib.mdDoc ''
+        Your {file}`configuration.yaml` as a Nix attribute set.
 
-        YAML functions like <link xlink:href="https://www.home-assistant.io/docs/configuration/secrets/">secrets</link>
+        YAML functions like [secrets](https://www.home-assistant.io/docs/configuration/secrets/)
         can be passed as a string and will be unquoted automatically.
 
-        Unless this option is explicitly set to <literal>null</literal>
-        we assume your <filename>configuration.yaml</filename> is
+        Unless this option is explicitly set to `null`
+        we assume your {file}`configuration.yaml` is
         managed through this module and thereby overwritten on startup.
       '';
     };
@@ -277,12 +277,12 @@ in {
     configWritable = mkOption {
       default = false;
       type = types.bool;
-      description = ''
-        Whether to make <filename>configuration.yaml</filename> writable.
+      description = lib.mdDoc ''
+        Whether to make {file}`configuration.yaml` writable.
 
         This will allow you to edit it from Home Assistant's web interface.
 
-        This only has an effect if <option>config</option> is set.
+        This only has an effect if {option}`config` is set.
         However, bear in mind that it will be overwritten at every start of the service.
       '';
     };
@@ -304,23 +304,23 @@ in {
           } ];
         }
       '';
-      description = ''
-        Your <filename>ui-lovelace.yaml</filename> as a Nix attribute set.
-        Setting this option will automatically set <literal>lovelace.mode</literal> to <literal>yaml</literal>.
+      description = lib.mdDoc ''
+        Your {file}`ui-lovelace.yaml` as a Nix attribute set.
+        Setting this option will automatically set `lovelace.mode` to `yaml`.
 
-        Beware that setting this option will delete your previous <filename>ui-lovelace.yaml</filename>
+        Beware that setting this option will delete your previous {file}`ui-lovelace.yaml`
       '';
     };
 
     lovelaceConfigWritable = mkOption {
       default = false;
       type = types.bool;
-      description = ''
-        Whether to make <filename>ui-lovelace.yaml</filename> writable.
+      description = lib.mdDoc ''
+        Whether to make {file}`ui-lovelace.yaml` writable.
 
         This will allow you to edit it from Home Assistant's web interface.
 
-        This only has an effect if <option>lovelaceConfig</option> is set.
+        This only has an effect if {option}`lovelaceConfig` is set.
         However, bear in mind that it will be overwritten at every start of the service.
       '';
     };
@@ -347,7 +347,7 @@ in {
           ];
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         The Home Assistant package to use.
       '';
     };
@@ -355,12 +355,30 @@ in {
     openFirewall = mkOption {
       default = false;
       type = types.bool;
-      description = "Whether to open the firewall for the specified port.";
+      description = lib.mdDoc "Whether to open the firewall for the specified port.";
     };
   };
 
   config = mkIf cfg.enable {
-    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ];
+    assertions = [
+      {
+        assertion = cfg.openFirewall -> !isNull cfg.config;
+        message = "openFirewall can only be used with a declarative config";
+      }
+    ];
+
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.config.http.server_port ];
+
+    # symlink the configuration to /etc/home-assistant
+    environment.etc = lib.mkMerge [
+      (lib.mkIf (cfg.config != null && !cfg.configWritable) {
+        "home-assistant/configuration.yaml".source = configFile;
+      })
+
+      (lib.mkIf (cfg.lovelaceConfig != null && !cfg.lovelaceConfigWritable) {
+        "home-assistant/ui-lovelace.yaml".source = lovelaceConfigFile;
+      })
+    ];
 
     systemd.services.home-assistant = {
       description = "Home Assistant";
@@ -371,18 +389,21 @@ in {
         "mysql.service"
         "postgresql.service"
       ];
+      reloadTriggers = lib.optional (cfg.config != null) configFile
+      ++ lib.optional (cfg.lovelaceConfig != null) lovelaceConfigFile;
+
       preStart = let
         copyConfig = if cfg.configWritable then ''
           cp --no-preserve=mode ${configFile} "${cfg.configDir}/configuration.yaml"
         '' else ''
           rm -f "${cfg.configDir}/configuration.yaml"
-          ln -s ${configFile} "${cfg.configDir}/configuration.yaml"
+          ln -s /etc/home-assistant/configuration.yaml "${cfg.configDir}/configuration.yaml"
         '';
         copyLovelaceConfig = if cfg.lovelaceConfigWritable then ''
           cp --no-preserve=mode ${lovelaceConfigFile} "${cfg.configDir}/ui-lovelace.yaml"
         '' else ''
           rm -f "${cfg.configDir}/ui-lovelace.yaml"
-          ln -s ${lovelaceConfigFile} "${cfg.configDir}/ui-lovelace.yaml"
+          ln -s /etc/home-assistant/ui-lovelace.yaml "${cfg.configDir}/ui-lovelace.yaml"
         '';
       in
         (optionalString (cfg.config != null) copyConfig) +
@@ -390,12 +411,12 @@ in {
       ;
       serviceConfig = let
         # List of capabilities to equip home-assistant with, depending on configured components
-        capabilities = [
+        capabilities = lib.unique ([
           # Empty string first, so we will never accidentally have an empty capability bounding set
           # https://github.com/NixOS/nixpkgs/issues/120617#issuecomment-830685115
           ""
-        ] ++ (unique (optionals (useComponent "bluetooth_tracker" || useComponent "bluetooth_le_tracker") [
-          # Required for interaction with hci devices and bluetooth sockets
+        ] ++ lib.optionals (builtins.any useComponent componentsUsingBluetooth) [
+          # Required for interaction with hci devices and bluetooth sockets, identified by bluetooth-adapters dependency
           # https://www.home-assistant.io/integrations/bluetooth_le_tracker/#rootless-setup-on-core-installs
           "CAP_NET_ADMIN"
           "CAP_NET_RAW"
@@ -408,11 +429,39 @@ in {
           "CAP_NET_ADMIN"
           "CAP_NET_BIND_SERVICE"
           "CAP_NET_RAW"
-        ]));
+        ]);
         componentsUsingBluetooth = [
           # Components that require the AF_BLUETOOTH address family
-          "bluetooth_tracker"
+          "august"
+          "august_ble"
+          "airthings_ble"
+          "bluemaestro"
+          "bluetooth"
           "bluetooth_le_tracker"
+          "bluetooth_tracker"
+          "bthome"
+          "default_config"
+          "eq3btsmart"
+          "esphome"
+          "fjaraskupan"
+          "govee_ble"
+          "homekit_controller"
+          "inkbird"
+          "keymitt_ble"
+          "led_ble"
+          "melnor"
+          "moat"
+          "oralb"
+          "qingping"
+          "sensorpro"
+          "sensorpush"
+          "snooz"
+          "switchbot"
+          "thermobeacon"
+          "thermopro"
+          "tilt_ble"
+          "xiaomi_ble"
+          "yalexs_ble"
         ];
         componentsUsingPing = [
           # Components that require the capset syscall for the ping wrapper
@@ -429,7 +478,6 @@ in {
           # mostly the ones using config flows already.
           "acer_projector"
           "alarmdecoder"
-          "arduino"
           "blackbird"
           "deconz"
           "dsmr"
@@ -443,7 +491,6 @@ in {
           "insteon"
           "kwb"
           "lacrosse"
-          "mhz19"
           "modbus"
           "modem_callerid"
           "mysensors"
@@ -459,7 +506,6 @@ in {
           "usb"
           "velbus"
           "w800rf32"
-          "xbee"
           "zha"
           "zwave"
           "zwave_js"
diff --git a/nixos/modules/services/home-automation/zigbee2mqtt.nix b/nixos/modules/services/home-automation/zigbee2mqtt.nix
index ff6d595e5a6..71f6e7a2584 100644
--- a/nixos/modules/services/home-automation/zigbee2mqtt.nix
+++ b/nixos/modules/services/home-automation/zigbee2mqtt.nix
@@ -18,10 +18,10 @@ in
   ];
 
   options.services.zigbee2mqtt = {
-    enable = mkEnableOption "enable zigbee2mqtt service";
+    enable = mkEnableOption (lib.mdDoc "zigbee2mqtt service");
 
     package = mkOption {
-      description = "Zigbee2mqtt package to use";
+      description = lib.mdDoc "Zigbee2mqtt package to use";
       default = pkgs.zigbee2mqtt;
       defaultText = literalExpression ''
         pkgs.zigbee2mqtt
@@ -30,7 +30,7 @@ in
     };
 
     dataDir = mkOption {
-      description = "Zigbee2mqtt data directory";
+      description = lib.mdDoc "Zigbee2mqtt data directory";
       default = "/var/lib/zigbee2mqtt";
       type = types.path;
     };
@@ -47,9 +47,9 @@ in
           };
         }
       '';
-      description = ''
-        Your <filename>configuration.yaml</filename> as a Nix attribute set.
-        Check the <link xlink:href="https://www.zigbee2mqtt.io/information/configuration.html">documentation</link>
+      description = lib.mdDoc ''
+        Your {file}`configuration.yaml` as a Nix attribute set.
+        Check the [documentation](https://www.zigbee2mqtt.io/information/configuration.html)
         for possible options.
       '';
     };
diff --git a/nixos/modules/services/logging/SystemdJournal2Gelf.nix b/nixos/modules/services/logging/SystemdJournal2Gelf.nix
index f28ecab8ac2..3d85c2b62c6 100644
--- a/nixos/modules/services/logging/SystemdJournal2Gelf.nix
+++ b/nixos/modules/services/logging/SystemdJournal2Gelf.nix
@@ -10,7 +10,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable SystemdJournal2Gelf.
         '';
       };
@@ -18,7 +18,7 @@ in
       graylogServer = mkOption {
         type = types.str;
         example = "graylog2.example.com:11201";
-        description = ''
+        description = lib.mdDoc ''
           Host and port of your graylog2 input. This should be a GELF
           UDP input.
         '';
@@ -27,9 +27,9 @@ in
       extraOptions = mkOption {
         type = types.separatedString " ";
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Any extra flags to pass to SystemdJournal2Gelf. Note that
-          these are basically <literal>journalctl</literal> flags.
+          these are basically `journalctl` flags.
         '';
       };
 
@@ -37,7 +37,7 @@ in
         type = types.package;
         default = pkgs.systemd-journal2gelf;
         defaultText = literalExpression "pkgs.systemd-journal2gelf";
-        description = ''
+        description = lib.mdDoc ''
           SystemdJournal2Gelf package to use.
         '';
       };
diff --git a/nixos/modules/services/logging/awstats.nix b/nixos/modules/services/logging/awstats.nix
index df0124380ff..708775bfcf0 100644
--- a/nixos/modules/services/logging/awstats.nix
+++ b/nixos/modules/services/logging/awstats.nix
@@ -11,40 +11,40 @@ let
         type = types.enum [ "mail" "web" ];
         default = "web";
         example = "mail";
-        description = ''
+        description = lib.mdDoc ''
           The type of log being collected.
         '';
       };
       domain = mkOption {
         type = types.str;
         default = name;
-        description = "The domain name to collect stats for.";
+        description = lib.mdDoc "The domain name to collect stats for.";
         example = "example.com";
       };
 
       logFile = mkOption {
         type = types.str;
         example = "/var/log/nginx/access.log";
-        description = ''
+        description = lib.mdDoc ''
           The log file to be scanned.
 
           For mail, set this to
-          <literal>
+          ```
           journalctl $OLD_CURSOR -u postfix.service | ''${pkgs.perl}/bin/perl ''${pkgs.awstats.out}/share/awstats/tools/maillogconvert.pl standard |
-          </literal>
+          ```
         '';
       };
 
       logFormat = mkOption {
         type = types.str;
         default = "1";
-        description = ''
+        description = lib.mdDoc ''
           The log format being used.
 
           For mail, set this to
-          <literal>
+          ```
           %time2 %email %email_r %host %host_r %method %url %code %bytesd
-          </literal>
+          ```
         '';
       };
 
@@ -52,7 +52,7 @@ let
         type = types.listOf types.str;
         default = [];
         example = [ "www.example.org" ];
-        description = ''
+        description = lib.mdDoc ''
           List of aliases the site has.
         '';
       };
@@ -65,22 +65,22 @@ let
             "ValidHTTPCodes" = "404";
           }
         '';
-        description = "Extra configuration to be appended to awstats.\${name}.conf.";
+        description = lib.mdDoc "Extra configuration to be appended to awstats.\${name}.conf.";
       };
 
       webService = {
-        enable = mkEnableOption "awstats web service";
+        enable = mkEnableOption (lib.mdDoc "awstats web service");
 
         hostname = mkOption {
           type = types.str;
           default = config.domain;
-          description = "The hostname the web service appears under.";
+          description = lib.mdDoc "The hostname the web service appears under.";
         };
 
         urlPrefix = mkOption {
           type = types.str;
           default = "/awstats";
-          description = "The URL prefix under which the awstats pages appear.";
+          description = lib.mdDoc "The URL prefix under which the awstats pages appear.";
         };
       };
     };
@@ -95,12 +95,12 @@ in
   ];
 
   options.services.awstats = {
-    enable = mkEnableOption "awstats";
+    enable = mkEnableOption (lib.mdDoc "awstats");
 
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/awstats";
-      description = "The directory where awstats data will be stored.";
+      description = lib.mdDoc "The directory where awstats data will be stored.";
     };
 
     configs = mkOption {
@@ -114,18 +114,16 @@ in
           };
         }
       '';
-      description = "Attribute set of domains to collect stats for.";
+      description = lib.mdDoc "Attribute set of domains to collect stats for.";
     };
 
     updateAt = mkOption {
       type = types.nullOr types.str;
       default = null;
       example = "hourly";
-      description = ''
+      description = lib.mdDoc ''
         Specification of the time at which awstats will get updated.
-        (in the format described by <citerefentry>
-          <refentrytitle>systemd.time</refentrytitle>
-          <manvolnum>7</manvolnum></citerefentry>)
+        (in the format described by {manpage}`systemd.time(7)`)
       '';
     };
   };
diff --git a/nixos/modules/services/logging/filebeat.nix b/nixos/modules/services/logging/filebeat.nix
index 223a993c505..5b5e7fd5ae8 100644
--- a/nixos/modules/services/logging/filebeat.nix
+++ b/nixos/modules/services/logging/filebeat.nix
@@ -18,33 +18,33 @@ in
 
     services.filebeat = {
 
-      enable = mkEnableOption "filebeat";
+      enable = mkEnableOption (lib.mdDoc "filebeat");
 
       package = mkOption {
         type = types.package;
         default = pkgs.filebeat;
         defaultText = literalExpression "pkgs.filebeat";
         example = literalExpression "pkgs.filebeat7";
-        description = ''
+        description = lib.mdDoc ''
           The filebeat package to use.
         '';
       };
 
       inputs = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Inputs specify how Filebeat locates and processes input data.
 
-          This is like <literal>services.filebeat.settings.filebeat.inputs</literal>,
+          This is like `services.filebeat.settings.filebeat.inputs`,
           but structured as an attribute set. This has the benefit
           that multiple NixOS modules can contribute settings to a
           single filebeat input.
 
           An input type can be specified multiple times by choosing a
-          different <literal>&lt;name></literal> for each, but setting
-          <xref linkend="opt-services.filebeat.inputs._name_.type"/>
+          different `<name>` for each, but setting
+          [](#opt-services.filebeat.inputs._name_.type)
           to the same value.
 
-          See <link xlink:href="https://www.elastic.co/guide/en/beats/filebeat/current/configuration-filebeat-options.html"/>.
+          See <https://www.elastic.co/guide/en/beats/filebeat/current/configuration-filebeat-options.html>.
         '';
         default = {};
         type = types.attrsOf (types.submodule ({ name, ... }: {
@@ -53,12 +53,12 @@ in
             type = mkOption {
               type = types.str;
               default = name;
-              description = ''
+              description = lib.mdDoc ''
                 The input type.
 
-                Look for the value after <literal>type:</literal> on
+                Look for the value after `type:` on
                 the individual input pages linked from
-                <link xlink:href="https://www.elastic.co/guide/en/beats/filebeat/current/configuration-filebeat-options.html"/>.
+                <https://www.elastic.co/guide/en/beats/filebeat/current/configuration-filebeat-options.html>.
               '';
             };
           };
@@ -77,24 +77,24 @@ in
       };
 
       modules = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Filebeat modules provide a quick way to get started
           processing common log formats. They contain default
           configurations, Elasticsearch ingest pipeline definitions,
           and Kibana dashboards to help you implement and deploy a log
           monitoring solution.
 
-          This is like <literal>services.filebeat.settings.filebeat.modules</literal>,
+          This is like `services.filebeat.settings.filebeat.modules`,
           but structured as an attribute set. This has the benefit
           that multiple NixOS modules can contribute settings to a
           single filebeat module.
 
           A module can be specified multiple times by choosing a
-          different <literal>&lt;name></literal> for each, but setting
-          <xref linkend="opt-services.filebeat.modules._name_.module"/>
+          different `<name>` for each, but setting
+          [](#opt-services.filebeat.modules._name_.module)
           to the same value.
 
-          See <link xlink:href="https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-modules.html"/>.
+          See <https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-modules.html>.
         '';
         default = {};
         type = types.attrsOf (types.submodule ({ name, ... }: {
@@ -103,12 +103,12 @@ in
             module = mkOption {
               type = types.str;
               default = name;
-              description = ''
+              description = lib.mdDoc ''
                 The name of the module.
 
-                Look for the value after <literal>module:</literal> on
+                Look for the value after `module:` on
                 the individual input pages linked from
-                <link xlink:href="https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-modules.html"/>.
+                <https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-modules.html>.
               '';
             };
           };
@@ -139,7 +139,7 @@ in
               type = with types; listOf str;
               default = [ "127.0.0.1:9200" ];
               example = [ "myEShost:9200" ];
-              description = ''
+              description = lib.mdDoc ''
                 The list of Elasticsearch nodes to connect to.
 
                 The events are distributed to these nodes in round
@@ -147,10 +147,10 @@ in
                 event is automatically sent to another node. Each
                 Elasticsearch node can be defined as a URL or
                 IP:PORT. For example:
-                <literal>http://192.15.3.2</literal>,
-                <literal>https://es.found.io:9230</literal> or
-                <literal>192.24.3.2:9300</literal>. If no port is
-                specified, <literal>9200</literal> is used.
+                `http://192.15.3.2`,
+                `https://es.found.io:9230` or
+                `192.24.3.2:9300`. If no port is
+                specified, `9200` is used.
               '';
             };
 
@@ -159,28 +159,27 @@ in
                 type = types.listOf json.type;
                 default = [];
                 internal = true;
-                description = ''
+                description = lib.mdDoc ''
                   Inputs specify how Filebeat locates and processes
-                  input data. Use <xref
-                  linkend="opt-services.filebeat.inputs"/> instead.
+                  input data. Use [](#opt-services.filebeat.inputs) instead.
 
-                  See <link xlink:href="https://www.elastic.co/guide/en/beats/filebeat/current/configuration-filebeat-options.html"/>.
+                  See <https://www.elastic.co/guide/en/beats/filebeat/current/configuration-filebeat-options.html>.
                 '';
               };
               modules = mkOption {
                 type = types.listOf json.type;
                 default = [];
                 internal = true;
-                description = ''
+                description = lib.mdDoc ''
                   Filebeat modules provide a quick way to get started
                   processing common log formats. They contain default
                   configurations, Elasticsearch ingest pipeline
                   definitions, and Kibana dashboards to help you
                   implement and deploy a log monitoring solution.
 
-                  Use <xref linkend="opt-services.filebeat.modules"/> instead.
+                  Use [](#opt-services.filebeat.modules) instead.
 
-                  See <link xlink:href="https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-modules.html"/>.
+                  See <https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-modules.html>.
                 '';
               };
             };
@@ -200,20 +199,20 @@ in
           };
         '';
 
-        description = ''
+        description = lib.mdDoc ''
           Configuration for filebeat. See
-          <link xlink:href="https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-reference-yml.html"/>
+          <https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-reference-yml.html>
           for supported values.
 
           Options containing secret data should be set to an attribute
-          set containing the attribute <literal>_secret</literal> - a
+          set containing the attribute `_secret` - a
           string pointing to a file containing the value the option
           should be set to. See the example to get a better picture of
           this: in the resulting
-          <filename>filebeat.yml</filename> file, the
-          <literal>output.elasticsearch.password</literal>
+          {file}`filebeat.yml` file, the
+          `output.elasticsearch.password`
           key will be set to the contents of the
-          <filename>/var/keys/elasticsearch_password</filename> file.
+          {file}`/var/keys/elasticsearch_password` file.
         '';
       };
     };
diff --git a/nixos/modules/services/logging/fluentd.nix b/nixos/modules/services/logging/fluentd.nix
index dd19617a13f..7764aafb2d1 100644
--- a/nixos/modules/services/logging/fluentd.nix
+++ b/nixos/modules/services/logging/fluentd.nix
@@ -12,29 +12,25 @@ in {
   options = {
 
     services.fluentd = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Whether to enable fluentd.";
-      };
+      enable = mkEnableOption (lib.mdDoc "fluentd");
 
       config = mkOption {
         type = types.lines;
         default = "";
-        description = "Fluentd config.";
+        description = lib.mdDoc "Fluentd config.";
       };
 
       package = mkOption {
         type = types.path;
         default = pkgs.fluentd;
         defaultText = literalExpression "pkgs.fluentd";
-        description = "The fluentd package to use.";
+        description = lib.mdDoc "The fluentd package to use.";
       };
 
       plugins = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of plugin paths to pass into fluentd. It will make plugins defined in ruby files
           there available in your config.
         '';
diff --git a/nixos/modules/services/logging/graylog.nix b/nixos/modules/services/logging/graylog.nix
index 28e2d18bf03..70c3ca50888 100644
--- a/nixos/modules/services/logging/graylog.nix
+++ b/nixos/modules/services/logging/graylog.nix
@@ -33,36 +33,36 @@ in
 
     services.graylog = {
 
-      enable = mkEnableOption "Graylog";
+      enable = mkEnableOption (lib.mdDoc "Graylog");
 
       package = mkOption {
         type = types.package;
         default = pkgs.graylog;
         defaultText = literalExpression "pkgs.graylog";
-        description = "Graylog package to use.";
+        description = lib.mdDoc "Graylog package to use.";
       };
 
       user = mkOption {
         type = types.str;
         default = "graylog";
-        description = "User account under which graylog runs";
+        description = lib.mdDoc "User account under which graylog runs";
       };
 
       isMaster = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether this is the master instance of your Graylog cluster";
+        description = lib.mdDoc "Whether this is the master instance of your Graylog cluster";
       };
 
       nodeIdFile = mkOption {
         type = types.str;
         default = "/var/lib/graylog/server/node-id";
-        description = "Path of the file containing the graylog node-id";
+        description = lib.mdDoc "Path of the file containing the graylog node-id";
       };
 
       passwordSecret = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           You MUST set a secret to secure/pepper the stored user passwords here. Use at least 64 characters.
           Generate one by using for example: pwgen -N 1 -s 96
         '';
@@ -71,13 +71,13 @@ in
       rootUsername = mkOption {
         type = types.str;
         default = "admin";
-        description = "Name of the default administrator user";
+        description = lib.mdDoc "Name of the default administrator user";
       };
 
       rootPasswordSha2 = mkOption {
         type = types.str;
         example = "e3c652f0ba0b4801205814f8b6bc49672c4c74e25b497770bb89b22cdeb4e952";
-        description = ''
+        description = lib.mdDoc ''
           You MUST specify a hash password for the root user (which you only need to initially set up the
           system and in case you lose connectivity to your authentication backend)
           This password cannot be changed using the API or via the web interface. If you need to change it,
@@ -90,29 +90,29 @@ in
       elasticsearchHosts = mkOption {
         type = types.listOf types.str;
         example = literalExpression ''[ "http://node1:9200" "http://user:password@node2:19200" ]'';
-        description = "List of valid URIs of the http ports of your elastic nodes. If one or more of your elasticsearch hosts require authentication, include the credentials in each node URI that requires authentication";
+        description = lib.mdDoc "List of valid URIs of the http ports of your elastic nodes. If one or more of your elasticsearch hosts require authentication, include the credentials in each node URI that requires authentication";
       };
 
       messageJournalDir = mkOption {
         type = types.str;
         default = "/var/lib/graylog/data/journal";
-        description = "The directory which will be used to store the message journal. The directory must be exclusively used by Graylog and must not contain any other files than the ones created by Graylog itself";
+        description = lib.mdDoc "The directory which will be used to store the message journal. The directory must be exclusively used by Graylog and must not contain any other files than the ones created by Graylog itself";
       };
 
       mongodbUri = mkOption {
         type = types.str;
         default = "mongodb://localhost/graylog";
-        description = "MongoDB connection string. See http://docs.mongodb.org/manual/reference/connection-string/ for details";
+        description = lib.mdDoc "MongoDB connection string. See http://docs.mongodb.org/manual/reference/connection-string/ for details";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Any other configuration options you might want to add";
+        description = lib.mdDoc "Any other configuration options you might want to add";
       };
 
       plugins = mkOption {
-        description = "Extra graylog plugins";
+        description = lib.mdDoc "Extra graylog plugins";
         default = [ ];
         type = types.listOf types.package;
       };
diff --git a/nixos/modules/services/logging/heartbeat.nix b/nixos/modules/services/logging/heartbeat.nix
index 56fb4deabda..a9ae11ec66e 100644
--- a/nixos/modules/services/logging/heartbeat.nix
+++ b/nixos/modules/services/logging/heartbeat.nix
@@ -18,24 +18,34 @@ in
 
     services.heartbeat = {
 
-      enable = mkEnableOption "heartbeat";
+      enable = mkEnableOption (lib.mdDoc "heartbeat");
+
+      package = mkOption {
+        type = types.package;
+        default = pkgs.heartbeat;
+        defaultText = literalExpression "pkgs.heartbeat";
+        example = literalExpression "pkgs.heartbeat7";
+        description = lib.mdDoc ''
+          The heartbeat package to use.
+        '';
+      };
 
       name = mkOption {
         type = types.str;
         default = "heartbeat";
-        description = "Name of the beat";
+        description = lib.mdDoc "Name of the beat";
       };
 
       tags = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Tags to place on the shipped log messages";
+        description = lib.mdDoc "Tags to place on the shipped log messages";
       };
 
       stateDir = mkOption {
         type = types.str;
         default = "/var/lib/heartbeat";
-        description = "The state directory. heartbeat's own logs and other data are stored here.";
+        description = lib.mdDoc "The state directory. heartbeat's own logs and other data are stored here.";
       };
 
       extraConfig = mkOption {
@@ -46,7 +56,7 @@ in
             urls: ["http://localhost:9200"]
             schedule: '@every 10s'
         '';
-        description = "Any other configuration options you want to add";
+        description = lib.mdDoc "Any other configuration options you want to add";
       };
 
     };
@@ -67,7 +77,7 @@ in
       serviceConfig = {
         User = "nobody";
         AmbientCapabilities = "cap_net_raw";
-        ExecStart = "${pkgs.heartbeat}/bin/heartbeat -c \"${heartbeatYml}\" -path.data \"${cfg.stateDir}/data\" -path.logs \"${cfg.stateDir}/logs\"";
+        ExecStart = "${cfg.package}/bin/heartbeat -c \"${heartbeatYml}\" -path.data \"${cfg.stateDir}/data\" -path.logs \"${cfg.stateDir}/logs\"";
       };
     };
   };
diff --git a/nixos/modules/services/logging/journalbeat.nix b/nixos/modules/services/logging/journalbeat.nix
index 4035ab48b4b..e761380552d 100644
--- a/nixos/modules/services/logging/journalbeat.nix
+++ b/nixos/modules/services/logging/journalbeat.nix
@@ -18,13 +18,13 @@ in
 
     services.journalbeat = {
 
-      enable = mkEnableOption "journalbeat";
+      enable = mkEnableOption (lib.mdDoc "journalbeat");
 
       package = mkOption {
         type = types.package;
         default = pkgs.journalbeat;
         defaultText = literalExpression "pkgs.journalbeat";
-        description = ''
+        description = lib.mdDoc ''
           The journalbeat package to use
         '';
       };
@@ -32,20 +32,20 @@ in
       name = mkOption {
         type = types.str;
         default = "journalbeat";
-        description = "Name of the beat";
+        description = lib.mdDoc "Name of the beat";
       };
 
       tags = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Tags to place on the shipped log messages";
+        description = lib.mdDoc "Tags to place on the shipped log messages";
       };
 
       stateDir = mkOption {
         type = types.str;
         default = "journalbeat";
-        description = ''
-          Directory below <literal>/var/lib/</literal> to store journalbeat's
+        description = lib.mdDoc ''
+          Directory below `/var/lib/` to store journalbeat's
           own logs and other data. This directory will be created automatically
           using systemd's StateDirectory mechanism.
         '';
@@ -54,7 +54,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Any other configuration options you want to add";
+        description = lib.mdDoc "Any other configuration options you want to add";
       };
 
     };
diff --git a/nixos/modules/services/logging/journaldriver.nix b/nixos/modules/services/logging/journaldriver.nix
index 9bd581e9ec0..59eedff90d6 100644
--- a/nixos/modules/services/logging/journaldriver.nix
+++ b/nixos/modules/services/logging/journaldriver.nix
@@ -17,7 +17,7 @@ in {
     enable = mkOption {
       type        = types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable journaldriver to forward journald logs to
         Stackdriver Logging.
       '';
@@ -26,7 +26,7 @@ in {
     logLevel = mkOption {
       type        = types.str;
       default     = "info";
-      description = ''
+      description = lib.mdDoc ''
         Log level at which journaldriver logs its own output.
       '';
     };
@@ -34,7 +34,7 @@ in {
     logName = mkOption {
       type        = with types; nullOr str;
       default     = null;
-      description = ''
+      description = lib.mdDoc ''
         Configures the name of the target log in Stackdriver Logging.
         This option can be set to, for example, the hostname of a
         machine to improve the user experience in the logging
@@ -45,7 +45,7 @@ in {
     googleCloudProject = mkOption {
       type        = with types; nullOr str;
       default     = null;
-      description = ''
+      description = lib.mdDoc ''
         Configures the name of the Google Cloud project to which to
         forward journald logs.
 
@@ -57,7 +57,7 @@ in {
     logStream = mkOption {
       type        = with types; nullOr str;
       default     = null;
-      description = ''
+      description = lib.mdDoc ''
         Configures the name of the Stackdriver Logging log stream into
         which to write journald entries.
 
@@ -69,7 +69,7 @@ in {
     applicationCredentials = mkOption {
       type        = with types; nullOr path;
       default     = null;
-      description = ''
+      description = lib.mdDoc ''
         Path to the service account private key (in JSON-format) used
         to forward log entries to Stackdriver Logging on non-GCP
         instances.
diff --git a/nixos/modules/services/logging/journalwatch.nix b/nixos/modules/services/logging/journalwatch.nix
index fb86904d1ea..55e2d600ee4 100644
--- a/nixos/modules/services/logging/journalwatch.nix
+++ b/nixos/modules/services/logging/journalwatch.nix
@@ -51,7 +51,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, periodically check the journal with journalwatch and report the results by mail.
         '';
       };
@@ -59,12 +59,12 @@ in {
       priority = mkOption {
         type = types.int;
         default = 6;
-        description = ''
+        description = lib.mdDoc ''
           Lowest priority of message to be considered.
           A value between 7 ("debug"), and 0 ("emerg"). Defaults to 6 ("info").
           If you don't care about anything with "info" priority, you can reduce
           this to e.g. 5 ("notice") to considerably reduce the amount of
-          messages without needing many <option>filterBlocks</option>.
+          messages without needing many {option}`filterBlocks`.
         '';
       };
 
@@ -75,7 +75,7 @@ in {
         type = types.str;
         default = "journalwatch@${config.networking.hostName}";
         defaultText = literalExpression ''"journalwatch@''${config.networking.hostName}"'';
-        description = ''
+        description = lib.mdDoc ''
           Mail address to send journalwatch reports from.
         '';
       };
@@ -83,7 +83,7 @@ in {
       mailTo = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Mail address to send journalwatch reports to.
         '';
       };
@@ -91,7 +91,7 @@ in {
       mailBinary = mkOption {
         type = types.path;
         default = "/run/wrappers/bin/sendmail";
-        description = ''
+        description = lib.mdDoc ''
           Sendmail-compatible binary to be used to send the messages.
         '';
       };
@@ -99,10 +99,10 @@ in {
       extraConfig = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to the journalwatch/config configuration file.
           You can add any commandline argument to the config, without the '--'.
-          See <literal>journalwatch --help</literal> for all arguments and their description.
+          See `journalwatch --help` for all arguments and their description.
           '';
       };
 
@@ -112,12 +112,12 @@ in {
            match = mkOption {
               type = types.str;
               example = "SYSLOG_IDENTIFIER = systemd";
-              description = ''
-                Syntax: <literal>field = value</literal>
-                Specifies the log entry <literal>field</literal> this block should apply to.
-                If the <literal>field</literal> of a message matches this <literal>value</literal>,
-                this patternBlock's <option>filters</option> are applied.
-                If <literal>value</literal> starts and ends with a slash, it is interpreted as
+              description = lib.mdDoc ''
+                Syntax: `field = value`
+                Specifies the log entry `field` this block should apply to.
+                If the `field` of a message matches this `value`,
+                this patternBlock's {option}`filters` are applied.
+                If `value` starts and ends with a slash, it is interpreted as
                 an extended python regular expression, if not, it's an exact match.
                 The journal fields are explained in systemd.journal-fields(7).
               '';
@@ -129,8 +129,8 @@ in {
                 (Stopped|Stopping|Starting|Started) .*
                 (Reached target|Stopped target) .*
               '';
-              description = ''
-                The filters to apply on all messages which satisfy <option>match</option>.
+              description = lib.mdDoc ''
+                The filters to apply on all messages which satisfy {option}`match`.
                 Any of those messages that match any specified filter will be removed from journalwatch's output.
                 Each filter is an extended Python regular expression.
                 You can specify multiple filters and separate them by newlines.
@@ -175,7 +175,7 @@ in {
         ];
 
 
-        description = ''
+        description = lib.mdDoc ''
           filterBlocks can be defined to blacklist journal messages which are not errors.
           Each block matches on a log entry field, and the filters in that block then are matched
           against all messages with a matching log entry field.
@@ -191,7 +191,7 @@ in {
       interval = mkOption {
         type = types.str;
         default = "hourly";
-        description = ''
+        description = lib.mdDoc ''
           How often to run journalwatch.
 
           The format is described in systemd.time(7).
@@ -200,7 +200,7 @@ in {
       accuracy = mkOption {
         type = types.str;
         default = "10min";
-        description = ''
+        description = lib.mdDoc ''
           The time window around the interval in which the journalwatch run will be scheduled.
 
           The format is described in systemd.time(7).
@@ -239,7 +239,7 @@ in {
         Type = "oneshot";
         # requires a relative directory name to create beneath /var/lib
         StateDirectory = user;
-        StateDirectoryMode = 0750;
+        StateDirectoryMode = "0750";
         ExecStart = "${pkgs.python3Packages.journalwatch}/bin/journalwatch mail";
         # lowest CPU and IO priority, but both still in best-effort class to prevent starvation
         Nice=19;
diff --git a/nixos/modules/services/logging/klogd.nix b/nixos/modules/services/logging/klogd.nix
index 8d371c161eb..1de0e58abbb 100644
--- a/nixos/modules/services/logging/klogd.nix
+++ b/nixos/modules/services/logging/klogd.nix
@@ -1,38 +1,9 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
+{ lib, ... }:
 
 {
-  ###### interface
-
-  options = {
-
-    services.klogd.enable = mkOption {
-      type = types.bool;
-      default = versionOlder (getVersion config.boot.kernelPackages.kernel) "3.5";
-      defaultText = literalExpression ''versionOlder (getVersion config.boot.kernelPackages.kernel) "3.5"'';
-      description = ''
-        Whether to enable klogd, the kernel log message processing
-        daemon.  Since systemd handles logging of kernel messages on
-        Linux 3.5 and later, this is only useful if you're running an
-        older kernel.
-      '';
-    };
-
-  };
-
-
-  ###### implementation
-
-  config = mkIf config.services.klogd.enable {
-    systemd.services.klogd = {
-      description = "Kernel Log Daemon";
-      wantedBy = [ "multi-user.target" ];
-      path = [ pkgs.sysklogd ];
-      unitConfig.ConditionVirtualization = "!systemd-nspawn";
-      script =
-        "klogd -c 1 -2 -n " +
-        "-k $(dirname $(readlink -f /run/booted-system/kernel))/System.map";
-    };
-  };
+  imports = [
+    (lib.mkRemovedOptionModule [ "security" "klogd" "enable" ] ''
+      Logging of kernel messages is now handled by systemd.
+    '')
+  ];
 }
diff --git a/nixos/modules/services/logging/logcheck.nix b/nixos/modules/services/logging/logcheck.nix
index c8738b734f9..8a277cea6e4 100644
--- a/nixos/modules/services/logging/logcheck.nix
+++ b/nixos/modules/services/logging/logcheck.nix
@@ -56,7 +56,7 @@ let
   levelOption = mkOption {
     default = "server";
     type = types.enum [ "workstation" "server" "paranoid" ];
-    description = ''
+    description = lib.mdDoc ''
       Set the logcheck level.
     '';
   };
@@ -68,7 +68,7 @@ let
       regex = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Regex specifying which log lines to ignore.
         '';
       };
@@ -80,7 +80,7 @@ let
       user = mkOption {
         default = "root";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User that runs the cronjob.
         '';
       };
@@ -88,7 +88,7 @@ let
       cmdline = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Command line for the cron job. Will be turned into a regex for the logcheck ignore rule.
         '';
       };
@@ -97,7 +97,7 @@ let
         default = null;
         type = types.nullOr (types.str);
         example = "02 06 * * *";
-        description = ''
+        description = lib.mdDoc ''
           "min hr dom mon dow" crontab time args, to auto-create a cronjob too.
           Leave at null to not do this and just add a logcheck ignore rule.
         '';
@@ -109,18 +109,12 @@ in
 {
   options = {
     services.logcheck = {
-      enable = mkOption {
-        default = false;
-        type = types.bool;
-        description = ''
-          Enable the logcheck cron job.
-        '';
-      };
+      enable = mkEnableOption (lib.mdDoc "logcheck cron job");
 
       user = mkOption {
         default = "logcheck";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Username for the logcheck user.
         '';
       };
@@ -129,7 +123,7 @@ in
         default = "*";
         example = "6";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Time of day to run logcheck. A logcheck will be scheduled at xx:02 each day.
           Leave default (*) to run every hour. Of course when nothing special was logged,
           logcheck will be silent.
@@ -140,7 +134,7 @@ in
         default = "root";
         example = "you@domain.com";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Email address to send reports to.
         '';
       };
@@ -148,7 +142,7 @@ in
       level = mkOption {
         default = "server";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Set the logcheck level. Either "workstation", "server", or "paranoid".
         '';
       };
@@ -156,7 +150,7 @@ in
       config = mkOption {
         default = "FQDN=1";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Config options that you would like in logcheck.conf.
         '';
       };
@@ -165,7 +159,7 @@ in
         default = [ "/var/log/messages" ];
         type = types.listOf types.path;
         example = [ "/var/log/messages" "/var/log/mail" ];
-        description = ''
+        description = lib.mdDoc ''
           Which log files to check.
         '';
       };
@@ -174,14 +168,14 @@ in
         default = [];
         example = [ "/etc/logcheck" ];
         type = types.listOf types.path;
-        description = ''
+        description = lib.mdDoc ''
           Directories with extra rules.
         '';
       };
 
       ignore = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           This option defines extra ignore rules.
         '';
         type = with types; attrsOf (submodule ignoreOptions);
@@ -189,7 +183,7 @@ in
 
       ignoreCron = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           This option defines extra ignore rules for cronjobs.
         '';
         type = with types; attrsOf (submodule ignoreCronOptions);
@@ -199,7 +193,7 @@ in
         default = [];
         type = types.listOf types.str;
         example = [ "postdrop" "mongodb" ];
-        description = ''
+        description = lib.mdDoc ''
           Extra groups for the logcheck user, for example to be able to use sendmail,
           or to access certain log files.
         '';
diff --git a/nixos/modules/services/logging/logrotate.nix b/nixos/modules/services/logging/logrotate.nix
index 082cf92ff4e..fd41b982678 100644
--- a/nixos/modules/services/logging/logrotate.nix
+++ b/nixos/modules/services/logging/logrotate.nix
@@ -5,166 +5,226 @@ with lib;
 let
   cfg = config.services.logrotate;
 
-  pathOpts = { name, ... }:  {
-    options = {
-      enable = mkOption {
-        type = types.bool;
-        default = true;
-        description = ''
-          Whether to enable log rotation for this path. This can be used to explicitly disable
-          logging that has been configured by NixOS.
-        '';
-      };
-
-      name = mkOption {
-        type = types.str;
-        internal = true;
-      };
-
-      path = mkOption {
-        type = with types; either str (listOf str);
-        default = name;
-        defaultText = "attribute name";
-        description = ''
-          The path to log files to be rotated.
-          Spaces are allowed and normal shell quoting rules apply,
-          with ', ", and \ characters supported.
-        '';
-      };
-
-      user = mkOption {
-        type = with types; nullOr str;
-        default = null;
-        description = ''
-          The user account to use for rotation.
-        '';
-      };
-
-      group = mkOption {
-        type = with types; nullOr str;
-        default = null;
-        description = ''
-          The group to use for rotation.
-        '';
-      };
-
-      frequency = mkOption {
-        type = types.enum [ "hourly" "daily" "weekly" "monthly" "yearly" ];
-        default = "daily";
-        description = ''
-          How often to rotate the logs.
-        '';
-      };
-
-      keep = mkOption {
-        type = types.int;
-        default = 20;
-        description = ''
-          How many rotations to keep.
-        '';
-      };
-
-      extraConfig = mkOption {
-        type = types.lines;
-        default = "";
-        description = ''
-          Extra logrotate config options for this path. Refer to
-          <link xlink:href="https://linux.die.net/man/8/logrotate"/> for details.
-        '';
-      };
-
-      priority = mkOption {
-        type = types.int;
-        default = 1000;
-        description = ''
-          Order of this logrotate block in relation to the others. The semantics are
-          the same as with `lib.mkOrder`. Smaller values have a greater priority.
-        '';
-      };
-    };
+  generateLine = n: v:
+    if builtins.elem n [ "files" "priority" "enable" "global" ] || v == null then null
+    else if builtins.elem n [ "frequency" ] then "${v}\n"
+    else if builtins.elem n [ "firstaction" "lastaction" "prerotate" "postrotate" "preremove" ]
+         then "${n}\n    ${v}\n  endscript\n"
+    else if isInt v then "${n} ${toString v}\n"
+    else if v == true then "${n}\n"
+    else if v == false then "no${n}\n"
+    else "${n} ${v}\n";
+  generateSection = indent: settings: concatStringsSep (fixedWidthString indent " " "") (
+    filter (x: x != null) (mapAttrsToList generateLine settings)
+  );
 
-    config.name = name;
+  # generateSection includes a final newline hence weird closing brace
+  mkConf = settings:
+    if settings.global or false then generateSection 0 settings
+    else ''
+      ${concatMapStringsSep "\n" (files: ''"${files}"'') (toList settings.files)} {
+        ${generateSection 2 settings}}
+    '';
+
+  settings = sortProperties (attrValues (filterAttrs (_: settings: settings.enable) (
+    foldAttrs recursiveUpdate { } [
+      {
+        header = {
+          enable = true;
+          missingok = true;
+          notifempty = true;
+          frequency = "weekly";
+          rotate = 4;
+        };
+      }
+      cfg.settings
+      { header = { global = true; priority = 100; }; }
+    ]
+  )));
+  configFile = pkgs.writeTextFile {
+    name = "logrotate.conf";
+    text = concatStringsSep "\n" (
+      map mkConf settings
+    );
+    checkPhase = optionalString cfg.checkConfig ''
+      # logrotate --debug also checks that users specified in config
+      # file exist, but we only have sandboxed users here so brown these
+      # out. according to man page that means su, create and createolddir.
+      # files required to exist also won't be present, so missingok is forced.
+      user=$(${pkgs.buildPackages.coreutils}/bin/id -un)
+      group=$(${pkgs.buildPackages.coreutils}/bin/id -gn)
+      sed -e "s/\bsu\s.*/su $user $group/" \
+          -e "s/\b\(create\s\+[0-9]*\s*\|createolddir\s\+[0-9]*\s\+\).*/\1$user $group/" \
+          -e "1imissingok" -e "s/\bnomissingok\b//" \
+          $out > logrotate.conf
+      # Since this makes for very verbose builds only show real error.
+      # There is no way to control log level, but logrotate hardcodes
+      # 'error:' at common log level, so we can use grep, taking care
+      # to keep error codes
+      set -o pipefail
+      if ! ${pkgs.buildPackages.logrotate}/sbin/logrotate -s logrotate.status \
+                      --debug logrotate.conf 2>&1 \
+                  | ( ! grep "error:" ) > logrotate-error; then
+              echo "Logrotate configuration check failed."
+              echo "The failing configuration (after adjustments to pass tests in sandbox) was:"
+              printf "%s\n" "-------"
+              cat logrotate.conf
+              printf "%s\n" "-------"
+              echo "The error reported by logrotate was as follow:"
+              printf "%s\n" "-------"
+              cat logrotate-error
+              printf "%s\n" "-------"
+              echo "You can disable this check with services.logrotate.checkConfig = false,"
+              echo "but if you think it should work please report this failure along with"
+              echo "the config file being tested!"
+              false
+      fi
+    '';
   };
 
-  mkConf = pathOpts: ''
-    # generated by NixOS using the `services.logrotate.paths.${pathOpts.name}` attribute set
-    ${concatMapStringsSep " " (path: ''"${path}"'') (toList pathOpts.path)} {
-      ${optionalString (pathOpts.user != null || pathOpts.group != null) "su ${pathOpts.user} ${pathOpts.group}"}
-      ${pathOpts.frequency}
-      rotate ${toString pathOpts.keep}
-      ${pathOpts.extraConfig}
-    }
-  '';
-
-  paths = sortProperties (attrValues (filterAttrs (_: pathOpts: pathOpts.enable) cfg.paths));
-  configFile = pkgs.writeText "logrotate.conf" (
-    concatStringsSep "\n" (
-      [ "missingok" "notifempty" cfg.extraConfig ] ++ (map mkConf paths)
-    )
-  );
-
+  mailOption =
+    if foldr (n: a: a || (n.mail or false) != false) false (attrValues cfg.settings)
+    then "--mail=${pkgs.mailutils}/bin/mail"
+    else "";
 in
 {
   imports = [
-    (mkRenamedOptionModule [ "services" "logrotate" "config" ] [ "services" "logrotate" "extraConfig" ])
+    (mkRemovedOptionModule [ "services" "logrotate" "config" ] "Modify services.logrotate.settings.header instead")
+    (mkRemovedOptionModule [ "services" "logrotate" "extraConfig" ] "Modify services.logrotate.settings.header instead")
+    (mkRemovedOptionModule [ "services" "logrotate" "paths" ] "Add attributes to services.logrotate.settings instead")
   ];
 
   options = {
     services.logrotate = {
-      enable = mkEnableOption "the logrotate systemd service" // {
-        default = foldr (n: a: a || n.enable) false (attrValues cfg.paths);
-        defaultText = literalExpression "cfg.paths != {}";
+      enable = mkEnableOption (lib.mdDoc "the logrotate systemd service") // {
+        default = foldr (n: a: a || n.enable) false (attrValues cfg.settings);
+        defaultText = literalExpression "cfg.settings != {}";
       };
 
-      paths = mkOption {
-        type = with types; attrsOf (submodule pathOpts);
-        default = {};
-        description = ''
-          Attribute set of paths to rotate. The order each block appears in the generated configuration file
-          can be controlled by the <link linkend="opt-services.logrotate.paths._name_.priority">priority</link> option
-          using the same semantics as `lib.mkOrder`. Smaller values have a greater priority.
+      settings = mkOption {
+        default = { };
+        description = lib.mdDoc ''
+          logrotate freeform settings: each attribute here will define its own section,
+          ordered by priority, which can either define files to rotate with their settings
+          or settings common to all further files settings.
+          Refer to <https://linux.die.net/man/8/logrotate> for details.
         '';
         example = literalExpression ''
           {
-            httpd = {
-              path = "/var/log/httpd/*.log";
-              user = config.services.httpd.user;
-              group = config.services.httpd.group;
-              keep = 7;
+            # global options
+            header = {
+              dateext = true;
+            };
+            # example custom files
+            "/var/log/mylog.log" = {
+              frequency = "daily";
+              rotate = 3;
+            };
+            "multiple paths" = {
+               files = [
+                "/var/log/first*.log"
+                "/var/log/second.log"
+              ];
+            };
+          };
+          '';
+        type = types.attrsOf (types.submodule ({ name, ... }: {
+          freeformType = with types; attrsOf (nullOr (oneOf [ int bool str ]));
+
+          options = {
+            enable = mkEnableOption (lib.mdDoc "setting individual kill switch") // {
+              default = true;
+            };
+
+            global = mkOption {
+              type = types.bool;
+              default = false;
+              description = lib.mdDoc ''
+                Whether this setting is a global option or not: set to have these
+                settings apply to all files settings with a higher priority.
+              '';
+            };
+            files = mkOption {
+              type = with types; either str (listOf str);
+              default = name;
+              defaultText = ''
+                The attrset name if not specified
+              '';
+              description = lib.mdDoc ''
+                Single or list of files for which rules are defined.
+                The files are quoted with double-quotes in logrotate configuration,
+                so globs and spaces are supported.
+                Note this setting is ignored if globals is true.
+              '';
             };
 
-            myapp = {
-              path = "/var/log/myapp/*.log";
-              user = "myuser";
-              group = "mygroup";
-              frequency = "weekly";
-              keep = 5;
-              priority = 1;
+            frequency = mkOption {
+              type = types.nullOr types.str;
+              default = null;
+              description = lib.mdDoc ''
+                How often to rotate the logs. Defaults to previously set global setting,
+                which itself defauts to weekly.
+              '';
             };
-          }
+
+            priority = mkOption {
+              type = types.int;
+              default = 1000;
+              description = lib.mdDoc ''
+                Order of this logrotate block in relation to the others. The semantics are
+                the same as with `lib.mkOrder`. Smaller values are inserted first.
+              '';
+            };
+          };
+
+        }));
+      };
+
+      configFile = mkOption {
+        type = types.path;
+        default = configFile;
+        defaultText = ''
+          A configuration file automatically generated by NixOS.
+        '';
+        description = lib.mdDoc ''
+          Override the configuration file used by MySQL. By default,
+          NixOS generates one automatically from [](#opt-services.logrotate.settings).
+        '';
+        example = literalExpression ''
+          pkgs.writeText "logrotate.conf" '''
+            missingok
+            "/var/log/*.log" {
+              rotate 4
+              weekly
+            }
+          ''';
         '';
       };
 
-      extraConfig = mkOption {
-        default = "";
-        type = types.lines;
-        description = ''
-          Extra contents to append to the logrotate configuration file. Refer to
-          <link xlink:href="https://linux.die.net/man/8/logrotate"/> for details.
+      checkConfig = mkOption {
+        type = types.bool;
+        default = true;
+        description = lib.mdDoc ''
+          Whether the config should be checked at build time.
+
+          Some options are not checkable at build time because of the build sandbox:
+          for example, the test does not know about existing files and system users are
+          not known.
+          These limitations mean we must adjust the file for tests (missingok is forced
+          and users are replaced by dummy users), so tests are complemented by a
+          logrotate-checkconf service that is enabled by default.
+          This extra check can be disabled by disabling it at the systemd level with the
+          {option}`services.systemd.services.logrotate-checkconf.enable` option.
+
+          Conversely there are still things that might make this check fail incorrectly
+          (e.g. a file path where we don't have access to intermediate directories):
+          in this case you can disable the failing check with this option.
         '';
       };
     };
   };
 
   config = mkIf cfg.enable {
-    assertions = mapAttrsToList (name: pathOpts:
-      { assertion = (pathOpts.user != null) == (pathOpts.group != null);
-        message = ''
-          If either of `services.logrotate.paths.${name}.user` or `services.logrotate.paths.${name}.group` are specified then *both* must be specified.
-        '';
-      }
-    ) cfg.paths;
-
     systemd.services.logrotate = {
       description = "Logrotate Service";
       startAt = "hourly";
@@ -172,7 +232,16 @@ in
       serviceConfig = {
         Restart = "no";
         User = "root";
-        ExecStart = "${pkgs.logrotate}/sbin/logrotate ${configFile}";
+        ExecStart = "${pkgs.logrotate}/sbin/logrotate ${mailOption} ${cfg.configFile}";
+      };
+    };
+    systemd.services.logrotate-checkconf = {
+      description = "Logrotate configuration check";
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        Type = "oneshot";
+        RemainAfterExit = true;
+        ExecStart = "${pkgs.logrotate}/sbin/logrotate --debug ${cfg.configFile}";
       };
     };
   };
diff --git a/nixos/modules/services/logging/logstash.nix b/nixos/modules/services/logging/logstash.nix
index a08203dffe7..e9e3ae1f14c 100644
--- a/nixos/modules/services/logging/logstash.nix
+++ b/nixos/modules/services/logging/logstash.nix
@@ -51,27 +51,27 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable logstash.";
+        description = lib.mdDoc "Enable logstash.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.logstash;
         defaultText = literalExpression "pkgs.logstash";
-        description = "Logstash package to use.";
+        description = lib.mdDoc "Logstash package to use.";
       };
 
       plugins = mkOption {
         type = types.listOf types.path;
         default = [ ];
         example = literalExpression "[ pkgs.logstash-contrib ]";
-        description = "The paths to find other logstash plugins in.";
+        description = lib.mdDoc "The paths to find other logstash plugins in.";
       };
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/logstash";
-        description = ''
+        description = lib.mdDoc ''
           A path to directory writable by logstash that it uses to store data.
           Plugins will also have access to this path.
         '';
@@ -80,36 +80,36 @@ in
       logLevel = mkOption {
         type = types.enum [ "debug" "info" "warn" "error" "fatal" ];
         default = "warn";
-        description = "Logging verbosity level.";
+        description = lib.mdDoc "Logging verbosity level.";
       };
 
       filterWorkers = mkOption {
         type = types.int;
         default = 1;
-        description = "The quantity of filter workers to run.";
+        description = lib.mdDoc "The quantity of filter workers to run.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "Address on which to start webserver.";
+        description = lib.mdDoc "Address on which to start webserver.";
       };
 
       port = mkOption {
         type = types.str;
         default = "9292";
-        description = "Port on which to start webserver.";
+        description = lib.mdDoc "Port on which to start webserver.";
       };
 
       inputConfig = mkOption {
         type = types.lines;
         default = "generator { }";
-        description = "Logstash input configuration.";
+        description = lib.mdDoc "Logstash input configuration.";
         example = literalExpression ''
           '''
             # Read from journal
             pipe {
-              command => "''${pkgs.systemd}/bin/journalctl -f -o json"
+              command => "''${config.systemd.package}/bin/journalctl -f -o json"
               type => "syslog" codec => json {}
             }
           '''
@@ -119,7 +119,7 @@ in
       filterConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "logstash filter configuration.";
+        description = lib.mdDoc "logstash filter configuration.";
         example = ''
           if [type] == "syslog" {
             # Keep only relevant systemd fields
@@ -137,7 +137,7 @@ in
       outputConfig = mkOption {
         type = types.lines;
         default = "stdout { codec => rubydebug }";
-        description = "Logstash output configuration.";
+        description = lib.mdDoc "Logstash output configuration.";
         example = ''
           redis { host => ["localhost"] data_type => "list" key => "logstash" codec => json }
           elasticsearch { }
@@ -147,7 +147,7 @@ in
       extraSettings = mkOption {
         type = types.lines;
         default = "";
-        description = "Extra Logstash settings in YAML format.";
+        description = lib.mdDoc "Extra Logstash settings in YAML format.";
         example = ''
           pipeline:
             batch:
@@ -159,7 +159,7 @@ in
       extraJvmOptions = mkOption {
         type = types.lines;
         default = "";
-        description = "Extra JVM options, one per line (jvm.options format).";
+        description = lib.mdDoc "Extra JVM options, one per line (jvm.options format).";
         example = ''
           -Xms2g
           -Xmx2g
diff --git a/nixos/modules/services/logging/promtail.nix b/nixos/modules/services/logging/promtail.nix
index a34bc07b6ab..9db82fd42b2 100644
--- a/nixos/modules/services/logging/promtail.nix
+++ b/nixos/modules/services/logging/promtail.nix
@@ -12,12 +12,12 @@ let
   positionsFile = cfg.configuration.positions.filename;
 in {
   options.services.promtail = with types; {
-    enable = mkEnableOption "the Promtail ingresser";
+    enable = mkEnableOption (lib.mdDoc "the Promtail ingresser");
 
 
     configuration = mkOption {
       type = (pkgs.formats.json {}).type;
-      description = ''
+      description = lib.mdDoc ''
         Specify the configuration for Promtail in Nix.
       '';
     };
@@ -26,7 +26,7 @@ in {
       type = listOf str;
       default = [];
       example = [ "--server.http-listen-port=3101" ];
-      description = ''
+      description = lib.mdDoc ''
         Specify a list of additional command line flags,
         which get escaped and are then passed to Loki.
       '';
diff --git a/nixos/modules/services/logging/rsyslogd.nix b/nixos/modules/services/logging/rsyslogd.nix
index b924d94e0b0..207d416c1a8 100644
--- a/nixos/modules/services/logging/rsyslogd.nix
+++ b/nixos/modules/services/logging/rsyslogd.nix
@@ -39,7 +39,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable syslogd.  Note that systemd also logs
           syslog messages, so you normally don't need to run syslogd.
         '';
@@ -48,10 +48,10 @@ in
       defaultConfig = mkOption {
         type = types.lines;
         default = defaultConf;
-        description = ''
-          The default <filename>syslog.conf</filename> file configures a
+        description = lib.mdDoc ''
+          The default {file}`syslog.conf` file configures a
           fairly standard setup of log files, which can be extended by
-          means of <varname>extraConfig</varname>.
+          means of {var}`extraConfig`.
         '';
       };
 
@@ -59,9 +59,9 @@ in
         type = types.lines;
         default = "";
         example = "news.* -/var/log/news";
-        description = ''
-          Additional text appended to <filename>syslog.conf</filename>,
-          i.e. the contents of <varname>defaultConfig</varname>.
+        description = lib.mdDoc ''
+          Additional text appended to {file}`syslog.conf`,
+          i.e. the contents of {var}`defaultConfig`.
         '';
       };
 
@@ -69,8 +69,8 @@ in
         type = types.listOf types.str;
         default = [ ];
         example = [ "-m 0" ];
-        description = ''
-          Additional parameters passed to <command>rsyslogd</command>.
+        description = lib.mdDoc ''
+          Additional parameters passed to {command}`rsyslogd`.
         '';
       };
 
diff --git a/nixos/modules/services/logging/syslog-ng.nix b/nixos/modules/services/logging/syslog-ng.nix
index 0a57bf20bd0..d22acbeaa70 100644
--- a/nixos/modules/services/logging/syslog-ng.nix
+++ b/nixos/modules/services/logging/syslog-ng.nix
@@ -36,7 +36,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the syslog-ng daemon.
         '';
       };
@@ -44,27 +44,24 @@ in {
         type = types.package;
         default = pkgs.syslogng;
         defaultText = literalExpression "pkgs.syslogng";
-        description = ''
+        description = lib.mdDoc ''
           The package providing syslog-ng binaries.
         '';
       };
       extraModulePaths = mkOption {
         type = types.listOf types.str;
         default = [];
-        example = literalExpression ''
-          [ "''${pkgs.syslogng_incubator}/lib/syslog-ng" ]
-        '';
-        description = ''
+        description = lib.mdDoc ''
           A list of paths that should be included in syslog-ng's
-          <literal>--module-path</literal> option. They should usually
-          end in <literal>/lib/syslog-ng</literal>
+          `--module-path` option. They should usually
+          end in `/lib/syslog-ng`
         '';
       };
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
-          Configuration added to the end of <literal>syslog-ng.conf</literal>.
+        description = lib.mdDoc ''
+          Configuration added to the end of `syslog-ng.conf`.
         '';
       };
       configHeader = mkOption {
@@ -73,7 +70,7 @@ in {
           @version: 3.6
           @include "scl.conf"
         '';
-        description = ''
+        description = lib.mdDoc ''
           The very first lines of the configuration file. Should usually contain
           the syslog-ng version header.
         '';
diff --git a/nixos/modules/services/logging/syslogd.nix b/nixos/modules/services/logging/syslogd.nix
index fe0b0490811..43969402588 100644
--- a/nixos/modules/services/logging/syslogd.nix
+++ b/nixos/modules/services/logging/syslogd.nix
@@ -39,7 +39,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable syslogd.  Note that systemd also logs
           syslog messages, so you normally don't need to run syslogd.
         '';
@@ -48,7 +48,7 @@ in
       tty = mkOption {
         type = types.str;
         default = "tty10";
-        description = ''
+        description = lib.mdDoc ''
           The tty device on which syslogd will print important log
           messages. Leave this option blank to disable tty logging.
         '';
@@ -57,17 +57,17 @@ in
       defaultConfig = mkOption {
         type = types.lines;
         default = defaultConf;
-        description = ''
-          The default <filename>syslog.conf</filename> file configures a
+        description = lib.mdDoc ''
+          The default {file}`syslog.conf` file configures a
           fairly standard setup of log files, which can be extended by
-          means of <varname>extraConfig</varname>.
+          means of {var}`extraConfig`.
         '';
       };
 
       enableNetworkInput = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Accept logging through UDP. Option -r of syslogd(8).
         '';
       };
@@ -76,9 +76,9 @@ in
         type = types.lines;
         default = "";
         example = "news.* -/var/log/news";
-        description = ''
-          Additional text appended to <filename>syslog.conf</filename>,
-          i.e. the contents of <varname>defaultConfig</varname>.
+        description = lib.mdDoc ''
+          Additional text appended to {file}`syslog.conf`,
+          i.e. the contents of {var}`defaultConfig`.
         '';
       };
 
@@ -86,8 +86,8 @@ in
         type = types.listOf types.str;
         default = [ ];
         example = [ "-m 0" ];
-        description = ''
-          Additional parameters passed to <command>syslogd</command>.
+        description = lib.mdDoc ''
+          Additional parameters passed to {command}`syslogd`.
         '';
       };
 
diff --git a/nixos/modules/services/logging/vector.nix b/nixos/modules/services/logging/vector.nix
index be36b2a41bb..1803ea85e49 100644
--- a/nixos/modules/services/logging/vector.nix
+++ b/nixos/modules/services/logging/vector.nix
@@ -6,12 +6,12 @@ let cfg = config.services.vector;
 in
 {
   options.services.vector = {
-    enable = mkEnableOption "Vector";
+    enable = mkEnableOption (lib.mdDoc "Vector");
 
     journaldAccess = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable Vector to access journald.
       '';
     };
@@ -19,7 +19,7 @@ in
     settings = mkOption {
       type = (pkgs.formats.json { }).type;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Specify the configuration for Vector in Nix.
       '';
     };
@@ -43,8 +43,10 @@ in
           format = pkgs.formats.toml { };
           conf = format.generate "vector.toml" cfg.settings;
           validateConfig = file:
-            pkgs.runCommand "validate-vector-conf" { } ''
-              ${pkgs.vector}/bin/vector validate --no-environment "${file}"
+          pkgs.runCommand "validate-vector-conf" {
+            nativeBuildInputs = [ pkgs.vector ];
+          } ''
+              vector validate --no-environment "${file}"
               ln -s "${file}" "$out"
             '';
         in
diff --git a/nixos/modules/services/mail/clamsmtp.nix b/nixos/modules/services/mail/clamsmtp.nix
index fc1267c5d28..a0de2596284 100644
--- a/nixos/modules/services/mail/clamsmtp.nix
+++ b/nixos/modules/services/mail/clamsmtp.nix
@@ -12,17 +12,17 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable clamsmtp.";
+        description = lib.mdDoc "Whether to enable clamsmtp.";
       };
 
       instances = mkOption {
-        description = "Instances of clamsmtp to run.";
+        description = lib.mdDoc "Instances of clamsmtp to run.";
         type = types.listOf (types.submodule { options = {
           action = mkOption {
             type = types.enum [ "bounce" "drop" "pass" ];
             default = "drop";
             description =
-              ''
+              lib.mdDoc ''
                 Action to take when a virus is detected.
 
                 Note that viruses often spoof sender addresses, so bouncing is
@@ -35,7 +35,7 @@ in
             default = "";
             example = "X-Virus-Scanned: ClamAV using ClamSMTP";
             description =
-              ''
+              lib.mdDoc ''
                 A header to add to scanned messages. See clamsmtpd.conf(5) for
                 more details. Empty means no header.
               '';
@@ -45,7 +45,7 @@ in
             type = types.int;
             default = 0;
             description =
-              ''
+              lib.mdDoc ''
                 Number of seconds to wait between each NOOP sent to the sending
                 server. 0 to disable.
 
@@ -58,7 +58,7 @@ in
             type = types.str;
             example = "127.0.0.1:10025";
             description =
-              ''
+              lib.mdDoc ''
                 Address to wait for incoming SMTP connections on. See
                 clamsmtpd.conf(5) for more details.
               '';
@@ -68,7 +68,7 @@ in
             type = types.bool;
             default = false;
             description =
-              ''
+              lib.mdDoc ''
                 Whether to quarantine files that contain viruses by leaving them
                 in the temporary directory.
               '';
@@ -77,13 +77,13 @@ in
           maxConnections = mkOption {
             type = types.int;
             default = 64;
-            description = "Maximum number of connections to accept at once.";
+            description = lib.mdDoc "Maximum number of connections to accept at once.";
           };
 
           outAddress = mkOption {
             type = types.str;
             description =
-              ''
+              lib.mdDoc ''
                 Address of the SMTP server to send email to once it has been
                 scanned.
               '';
@@ -93,7 +93,7 @@ in
             type = types.str;
             default = "/tmp";
             description =
-              ''
+              lib.mdDoc ''
                 Temporary directory that needs to be accessible to both clamd
                 and clamsmtpd.
               '';
@@ -102,20 +102,20 @@ in
           timeout = mkOption {
             type = types.int;
             default = 180;
-            description = "Time-out for network connections.";
+            description = lib.mdDoc "Time-out for network connections.";
           };
 
           transparentProxy = mkOption {
             type = types.bool;
             default = false;
-            description = "Enable clamsmtp's transparent proxy support.";
+            description = lib.mdDoc "Enable clamsmtp's transparent proxy support.";
           };
 
           virusAction = mkOption {
             type = with types; nullOr path;
             default = null;
             description =
-              ''
+              lib.mdDoc ''
                 Command to run when a virus is found. Please see VIRUS ACTION in
                 clamsmtpd(8) for a discussion of this option and its safe use.
               '';
@@ -125,7 +125,7 @@ in
             type = types.bool;
             default = false;
             description =
-              ''
+              lib.mdDoc ''
                 Send the XCLIENT command to the receiving server, for forwarding
                 client addresses and connection information if the receiving
                 server supports this feature.
diff --git a/nixos/modules/services/mail/davmail.nix b/nixos/modules/services/mail/davmail.nix
index e9f31e6fb39..483f591a726 100644
--- a/nixos/modules/services/mail/davmail.nix
+++ b/nixos/modules/services/mail/davmail.nix
@@ -25,21 +25,21 @@ in
 
   {
     options.services.davmail = {
-      enable = mkEnableOption "davmail, an MS Exchange gateway";
+      enable = mkEnableOption (lib.mdDoc "davmail, an MS Exchange gateway");
 
       url = mkOption {
         type = types.str;
-        description = "Outlook Web Access URL to access the exchange server, i.e. the base webmail URL.";
+        description = lib.mdDoc "Outlook Web Access URL to access the exchange server, i.e. the base webmail URL.";
         example = "https://outlook.office365.com/EWS/Exchange.asmx";
       };
 
       config = mkOption {
         type = configType;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Davmail configuration. Refer to
-          <link xlink:href="http://davmail.sourceforge.net/serversetup.html"/>
-          and <link xlink:href="http://davmail.sourceforge.net/advanced.html"/>
+          <http://davmail.sourceforge.net/serversetup.html>
+          and <http://davmail.sourceforge.net/advanced.html>
           for details on supported values.
         '';
         example = literalExpression ''
diff --git a/nixos/modules/services/mail/dkimproxy-out.nix b/nixos/modules/services/mail/dkimproxy-out.nix
index f4ac9e47007..6f9cbc4e9d4 100644
--- a/nixos/modules/services/mail/dkimproxy-out.nix
+++ b/nixos/modules/services/mail/dkimproxy-out.nix
@@ -15,7 +15,7 @@ in
         type = types.bool;
         default = false;
         description =
-          ''
+          lib.mdDoc ''
             Whether to enable dkimproxy_out.
 
             Note that a key will be auto-generated, and can be found in
@@ -26,26 +26,26 @@ in
       listen = mkOption {
         type = types.str;
         example = "127.0.0.1:10027";
-        description = "Address:port DKIMproxy should listen on.";
+        description = lib.mdDoc "Address:port DKIMproxy should listen on.";
       };
 
       relay = mkOption {
         type = types.str;
         example = "127.0.0.1:10028";
-        description = "Address:port DKIMproxy should forward mail to.";
+        description = lib.mdDoc "Address:port DKIMproxy should forward mail to.";
       };
 
       domains = mkOption {
         type = with types; listOf str;
         example = [ "example.org" "example.com" ];
-        description = "List of domains DKIMproxy can sign for.";
+        description = lib.mdDoc "List of domains DKIMproxy can sign for.";
       };
 
       selector = mkOption {
         type = types.str;
         example = "selector1";
         description =
-          ''
+          lib.mdDoc ''
             The selector to use for DKIM key identification.
 
             For example, if 'selector1' is used here, then for each domain
@@ -59,7 +59,7 @@ in
         type = types.int;
         default = 2048;
         description =
-          ''
+          lib.mdDoc ''
             Size of the RSA key to use to sign outgoing emails. Note that the
             maximum mandatorily verified as per RFC6376 is 2048.
           '';
diff --git a/nixos/modules/services/mail/dovecot.nix b/nixos/modules/services/mail/dovecot.nix
index a8c1f176782..f6a167572f7 100644
--- a/nixos/modules/services/mail/dovecot.nix
+++ b/nixos/modules/services/mail/dovecot.nix
@@ -137,25 +137,25 @@ let
         example = "Spam";
         default = name;
         readOnly = true;
-        description = "The name of the mailbox.";
+        description = lib.mdDoc "The name of the mailbox.";
       };
       auto = mkOption {
         type = types.enum [ "no" "create" "subscribe" ];
         default = "no";
         example = "subscribe";
-        description = "Whether to automatically create or create and subscribe to the mailbox or not.";
+        description = lib.mdDoc "Whether to automatically create or create and subscribe to the mailbox or not.";
       };
       specialUse = mkOption {
         type = types.nullOr (types.enum [ "All" "Archive" "Drafts" "Flagged" "Junk" "Sent" "Trash" ]);
         default = null;
         example = "Junk";
-        description = "Null if no special use flag is set. Other than that every use flag mentioned in the RFC is valid.";
+        description = lib.mdDoc "Null if no special use flag is set. Other than that every use flag mentioned in the RFC is valid.";
       };
       autoexpunge = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "60d";
-        description = ''
+        description = lib.mdDoc ''
           To automatically remove all email from the mailbox which is older than the
           specified time.
         '';
@@ -169,37 +169,37 @@ in
   ];
 
   options.services.dovecot2 = {
-    enable = mkEnableOption "the dovecot 2.x POP3/IMAP server";
+    enable = mkEnableOption (lib.mdDoc "the dovecot 2.x POP3/IMAP server");
 
-    enablePop3 = mkEnableOption "starting the POP3 listener (when Dovecot is enabled).";
+    enablePop3 = mkEnableOption (lib.mdDoc "starting the POP3 listener (when Dovecot is enabled).");
 
-    enableImap = mkEnableOption "starting the IMAP listener (when Dovecot is enabled)." // { default = true; };
+    enableImap = mkEnableOption (lib.mdDoc "starting the IMAP listener (when Dovecot is enabled).") // { default = true; };
 
-    enableLmtp = mkEnableOption "starting the LMTP listener (when Dovecot is enabled).";
+    enableLmtp = mkEnableOption (lib.mdDoc "starting the LMTP listener (when Dovecot is enabled).");
 
     protocols = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = "Additional listeners to start when Dovecot is enabled.";
+      description = lib.mdDoc "Additional listeners to start when Dovecot is enabled.";
     };
 
     user = mkOption {
       type = types.str;
       default = "dovecot2";
-      description = "Dovecot user name.";
+      description = lib.mdDoc "Dovecot user name.";
     };
 
     group = mkOption {
       type = types.str;
       default = "dovecot2";
-      description = "Dovecot group name.";
+      description = lib.mdDoc "Dovecot group name.";
     };
 
     extraConfig = mkOption {
       type = types.lines;
       default = "";
       example = "mail_debug = yes";
-      description = "Additional entries to put verbatim into Dovecot's config file.";
+      description = lib.mdDoc "Additional entries to put verbatim into Dovecot's config file.";
     };
 
     mailPlugins =
@@ -209,7 +209,7 @@ in
             enable = mkOption {
               type = types.listOf types.str;
               default = [];
-              description = "mail plugins to enable as a list of strings to append to the ${hint} <literal>$mail_plugins</literal> configuration variable";
+              description = lib.mdDoc "mail plugins to enable as a list of strings to append to the ${hint} `$mail_plugins` configuration variable";
             };
           };
         };
@@ -218,20 +218,20 @@ in
           type = with types; submodule {
             options = {
               globally = mkOption {
-                description = "Additional entries to add to the mail_plugins variable for all protocols";
+                description = lib.mdDoc "Additional entries to add to the mail_plugins variable for all protocols";
                 type = plugins "top-level";
                 example = { enable = [ "virtual" ]; };
                 default = { enable = []; };
               };
               perProtocol = mkOption {
-                description = "Additional entries to add to the mail_plugins variable, per protocol";
+                description = lib.mdDoc "Additional entries to add to the mail_plugins variable, per protocol";
                 type = attrsOf (plugins "corresponding per-protocol");
                 default = {};
                 example = { imap = [ "imap_acl" ]; };
               };
             };
           };
-          description = "Additional entries to add to the mail_plugins variable, globally and per protocol";
+          description = lib.mdDoc "Additional entries to add to the mail_plugins variable, globally and per protocol";
           example = {
             globally.enable = [ "acl" ];
             perProtocol.imap.enable = [ "imap_acl" ];
@@ -242,7 +242,7 @@ in
     configFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = "Config file used for the whole dovecot configuration.";
+      description = lib.mdDoc "Config file used for the whole dovecot configuration.";
       apply = v: if v != null then v else pkgs.writeText "dovecot.conf" dovecotConf;
     };
 
@@ -250,7 +250,7 @@ in
       type = types.str;
       default = "maildir:/var/spool/mail/%u"; /* Same as inbox, as postfix */
       example = "maildir:~/mail:INBOX=/var/spool/mail/%u";
-      description = ''
+      description = lib.mdDoc ''
         Location that dovecot will use for mail folders. Dovecot mail_location option.
       '';
     };
@@ -258,24 +258,24 @@ in
     mailUser = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = "Default user to store mail for virtual users.";
+      description = lib.mdDoc "Default user to store mail for virtual users.";
     };
 
     mailGroup = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = "Default group to store mail for virtual users.";
+      description = lib.mdDoc "Default group to store mail for virtual users.";
     };
 
-    createMailUser = mkEnableOption ''automatically creating the user
-      given in <option>services.dovecot.user</option> and the group
-      given in <option>services.dovecot.group</option>.'' // { default = true; };
+    createMailUser = mkEnableOption (lib.mdDoc ''automatically creating the user
+      given in {option}`services.dovecot.user` and the group
+      given in {option}`services.dovecot.group`.'') // { default = true; };
 
     modules = mkOption {
       type = types.listOf types.package;
       default = [];
       example = literalExpression "[ pkgs.dovecot_pigeonhole ]";
-      description = ''
+      description = lib.mdDoc ''
         Symlinks the contents of lib/dovecot of every given package into
         /etc/dovecot/modules. This will make the given modules available
         if a dovecot package with the module_dir patch applied is being used.
@@ -285,32 +285,32 @@ in
     sslCACert = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = "Path to the server's CA certificate key.";
+      description = lib.mdDoc "Path to the server's CA certificate key.";
     };
 
     sslServerCert = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = "Path to the server's public key.";
+      description = lib.mdDoc "Path to the server's public key.";
     };
 
     sslServerKey = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = "Path to the server's private key.";
+      description = lib.mdDoc "Path to the server's private key.";
     };
 
-    enablePAM = mkEnableOption "creating a own Dovecot PAM service and configure PAM user logins." // { default = true; };
+    enablePAM = mkEnableOption (lib.mdDoc "creating a own Dovecot PAM service and configure PAM user logins.") // { default = true; };
 
-    enableDHE = mkEnableOption "enable ssl_dh and generation of primes for the key exchange." // { default = true; };
+    enableDHE = mkEnableOption (lib.mdDoc "enable ssl_dh and generation of primes for the key exchange.") // { default = true; };
 
     sieveScripts = mkOption {
       type = types.attrsOf types.path;
       default = {};
-      description = "Sieve scripts to be executed. Key is a sequence, e.g. 'before2', 'after' etc.";
+      description = lib.mdDoc "Sieve scripts to be executed. Key is a sequence, e.g. 'before2', 'after' etc.";
     };
 
-    showPAMFailure = mkEnableOption "showing the PAM failure message on authentication error (useful for OTPW).";
+    showPAMFailure = mkEnableOption (lib.mdDoc "showing the PAM failure message on authentication error (useful for OTPW).");
 
     mailboxes = mkOption {
       type = with types; coercedTo
@@ -323,15 +323,15 @@ in
           Spam = { specialUse = "Junk"; auto = "create"; };
         }
       '';
-      description = "Configure mailboxes and auto create or subscribe them.";
+      description = lib.mdDoc "Configure mailboxes and auto create or subscribe them.";
     };
 
-    enableQuota = mkEnableOption "the dovecot quota service.";
+    enableQuota = mkEnableOption (lib.mdDoc "the dovecot quota service.");
 
     quotaPort = mkOption {
       type = types.str;
       default = "12340";
-      description = ''
+      description = lib.mdDoc ''
         The Port the dovecot quota service binds to.
         If using postfix, add check_policy_service inet:localhost:12340 to your smtpd_recipient_restrictions in your postfix config.
       '';
@@ -340,7 +340,7 @@ in
       type = types.str;
       default = "100G";
       example = "10G";
-      description = "Quota limit for the user in bytes. Supports suffixes b, k, M, G, T and %.";
+      description = lib.mdDoc "Quota limit for the user in bytes. Supports suffixes b, k, M, G, T and %.";
     };
 
   };
diff --git a/nixos/modules/services/mail/dspam.nix b/nixos/modules/services/mail/dspam.nix
index 766ebc8095a..4fccd452a4f 100644
--- a/nixos/modules/services/mail/dspam.nix
+++ b/nixos/modules/services/mail/dspam.nix
@@ -38,43 +38,43 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the dspam spam filter.";
+        description = lib.mdDoc "Whether to enable the dspam spam filter.";
       };
 
       user = mkOption {
         type = types.str;
         default = "dspam";
-        description = "User for the dspam daemon.";
+        description = lib.mdDoc "User for the dspam daemon.";
       };
 
       group = mkOption {
         type = types.str;
         default = "dspam";
-        description = "Group for the dspam daemon.";
+        description = lib.mdDoc "Group for the dspam daemon.";
       };
 
       storageDriver = mkOption {
         type = types.str;
         default = "hash";
-        description =  "Storage driver backend to use for dspam.";
+        description =  lib.mdDoc "Storage driver backend to use for dspam.";
       };
 
       domainSocket = mkOption {
         type = types.nullOr types.path;
         default = defaultSock;
-        description = "Path to local domain socket which is used for communication with the daemon. Set to null to disable UNIX socket.";
+        description = lib.mdDoc "Path to local domain socket which is used for communication with the daemon. Set to null to disable UNIX socket.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Additional dspam configuration.";
+        description = lib.mdDoc "Additional dspam configuration.";
       };
 
       maintenanceInterval = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "If set, maintenance script will be run at specified (in systemd.timer format) interval";
+        description = lib.mdDoc "If set, maintenance script will be run at specified (in systemd.timer format) interval";
       };
 
     };
diff --git a/nixos/modules/services/mail/exim.nix b/nixos/modules/services/mail/exim.nix
index 7356db2b6a6..cd0da4fc509 100644
--- a/nixos/modules/services/mail/exim.nix
+++ b/nixos/modules/services/mail/exim.nix
@@ -17,13 +17,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the Exim mail transfer agent.";
+        description = lib.mdDoc "Whether to enable the Exim mail transfer agent.";
       };
 
       config = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Verbatim Exim configuration.  This should not contain exim_user,
           exim_group, exim_path, or spool_directory.
         '';
@@ -32,7 +32,7 @@ in
       user = mkOption {
         type = types.str;
         default = "exim";
-        description = ''
+        description = lib.mdDoc ''
           User to use when no root privileges are required.
           In particular, this applies when receiving messages and when doing
           remote deliveries.  (Local deliveries run as various non-root users,
@@ -44,7 +44,7 @@ in
       group = mkOption {
         type = types.str;
         default = "exim";
-        description = ''
+        description = lib.mdDoc ''
           Group to use when no root privileges are required.
         '';
       };
@@ -52,7 +52,7 @@ in
       spoolDir = mkOption {
         type = types.path;
         default = "/var/spool/exim";
-        description = ''
+        description = lib.mdDoc ''
           Location of the spool directory of exim.
         '';
       };
@@ -61,7 +61,7 @@ in
         type = types.package;
         default = pkgs.exim;
         defaultText = literalExpression "pkgs.exim";
-        description = ''
+        description = lib.mdDoc ''
           The Exim derivation to use.
           This can be used to enable features such as LDAP or PAM support.
         '';
@@ -70,7 +70,7 @@ in
       queueRunnerInterval = mkOption {
         type = types.str;
         default = "5m";
-        description = ''
+        description = lib.mdDoc ''
           How often to spawn a new queue runner.
         '';
       };
diff --git a/nixos/modules/services/mail/listmonk.nix b/nixos/modules/services/mail/listmonk.nix
new file mode 100644
index 00000000000..c4ea6747196
--- /dev/null
+++ b/nixos/modules/services/mail/listmonk.nix
@@ -0,0 +1,222 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let
+  cfg = config.services.listmonk;
+  tomlFormat = pkgs.formats.toml { };
+  cfgFile = tomlFormat.generate "listmonk.toml" cfg.settings;
+  # Escaping is done according to https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
+  setDatabaseOption = key: value:
+    "UPDATE settings SET value = '${
+      lib.replaceChars [ "'" ] [ "''" ] (builtins.toJSON value)
+    }' WHERE key = '${key}';";
+  updateDatabaseConfigSQL = pkgs.writeText "update-database-config.sql"
+    (concatStringsSep "\n" (mapAttrsToList setDatabaseOption
+      (if (cfg.database.settings != null) then
+        cfg.database.settings
+      else
+        { })));
+  updateDatabaseConfigScript =
+    pkgs.writeShellScriptBin "update-database-config.sh" ''
+      ${if cfg.database.mutableSettings then ''
+        if [ ! -f /var/lib/listmonk/.db_settings_initialized ]; then
+          ${pkgs.postgresql}/bin/psql -d listmonk -f ${updateDatabaseConfigSQL} ;
+          touch /var/lib/listmonk/.db_settings_initialized
+        fi
+      '' else
+        "${pkgs.postgresql}/bin/psql -d listmonk -f ${updateDatabaseConfigSQL}"}
+    '';
+
+  databaseSettingsOpts = with types; {
+    freeformType =
+      oneOf [ (listOf str) (listOf (attrsOf anything)) str int bool ];
+
+    options = {
+      "app.notify_emails" = mkOption {
+        type = listOf str;
+        default = [ ];
+        description = lib.mdDoc "Administrator emails for system notifications";
+      };
+
+      "privacy.exportable" = mkOption {
+        type = listOf str;
+        default = [ "profile" "subscriptions" "campaign_views" "link_clicks" ];
+        description = lib.mdDoc
+          "List of fields which can be exported through an automatic export request";
+      };
+
+      "privacy.domain_blocklist" = mkOption {
+        type = listOf str;
+        default = [ ];
+        description = lib.mdDoc
+          "E-mail addresses with these domains are disallowed from subscribing.";
+      };
+
+      smtp = mkOption {
+        type = listOf (submodule {
+          freeformType = with types; attrsOf (oneOf [ str int bool ]);
+
+          options = {
+            enabled = mkEnableOption (lib.mdDoc "this SMTP server for listmonk");
+            host = mkOption {
+              type = types.str;
+              description = lib.mdDoc "Hostname for the SMTP server";
+            };
+            port = mkOption {
+              type = types.port;
+              description = lib.mdDoc "Port for the SMTP server";
+            };
+            max_conns = mkOption {
+              type = types.int;
+              description = lib.mdDoc
+                "Maximum number of simultaneous connections, defaults to 1";
+              default = 1;
+            };
+            tls_type = mkOption {
+              type = types.enum [ "none" "STARTTLS" "TLS" ];
+              description =
+                lib.mdDoc "Type of TLS authentication with the SMTP server";
+            };
+          };
+        });
+
+        description = lib.mdDoc "List of outgoing SMTP servers";
+      };
+
+      # TODO: refine this type based on the smtp one.
+      "bounce.mailboxes" = mkOption {
+        type = listOf
+          (submodule { freeformType = with types; oneOf [ str int bool ]; });
+        default = [ ];
+        description = lib.mdDoc "List of bounce mailboxes";
+      };
+
+      messengers = mkOption {
+        type = listOf str;
+        default = [ ];
+        description = lib.mdDoc
+          "List of messengers, see: <https://github.com/knadh/listmonk/blob/master/models/settings.go#L64-L74> for options.";
+      };
+    };
+  };
+in {
+  ###### interface
+  options = {
+    services.listmonk = {
+      enable = mkEnableOption
+        (lib.mdDoc "Listmonk, this module assumes a reverse proxy to be set");
+      database = {
+        createLocally = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc
+            "Create the PostgreSQL database and database user locally.";
+        };
+
+        settings = mkOption {
+          default = null;
+          type = with types; nullOr (submodule databaseSettingsOpts);
+          description = lib.mdDoc
+            "Dynamic settings in the PostgreSQL database, set by a SQL script, see <https://github.com/knadh/listmonk/blob/master/schema.sql#L177-L230> for details.";
+        };
+        mutableSettings = mkOption {
+          type = types.bool;
+          default = true;
+          description = lib.mdDoc ''
+            Database settings will be reset to the value set in this module if this is not enabled.
+            Enable this if you want to persist changes you have done in the application.
+          '';
+        };
+      };
+      package = mkPackageOption pkgs "listmonk" {};
+      settings = mkOption {
+        type = types.submodule { freeformType = tomlFormat.type; };
+        description = lib.mdDoc ''
+          Static settings set in the config.toml, see <https://github.com/knadh/listmonk/blob/master/config.toml.sample> for details.
+          You can set secrets using the secretFile option with environment variables following <https://listmonk.app/docs/configuration/#environment-variables>.
+        '';
+      };
+      secretFile = mkOption {
+        type = types.nullOr types.str;
+        default = null;
+        description = lib.mdDoc
+          "A file containing secrets as environment variables. See <https://listmonk.app/docs/configuration/#environment-variables> for details on supported values.";
+      };
+    };
+  };
+
+  ###### implementation
+  config = mkIf cfg.enable {
+    # Default parameters from https://github.com/knadh/listmonk/blob/master/config.toml.sample
+    services.listmonk.settings."app".address = mkDefault "localhost:9000";
+    services.listmonk.settings."db" = mkMerge [
+      ({
+        max_open = mkDefault 25;
+        max_idle = mkDefault 25;
+        max_lifetime = mkDefault "300s";
+      })
+      (mkIf cfg.database.createLocally {
+        host = mkDefault "/run/postgresql";
+        port = mkDefault 5432;
+        user = mkDefault "listmonk";
+        database = mkDefault "listmonk";
+      })
+    ];
+
+    services.postgresql = mkIf cfg.database.createLocally {
+      enable = true;
+
+      ensureUsers = [{
+        name = "listmonk";
+        ensurePermissions = { "DATABASE listmonk" = "ALL PRIVILEGES"; };
+      }];
+
+      ensureDatabases = [ "listmonk" ];
+    };
+
+    systemd.services.listmonk = {
+      description = "Listmonk - newsletter and mailing list manager";
+      after = [ "network.target" ]
+        ++ optional cfg.database.createLocally "postgresql.service";
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        Type = "exec";
+        EnvironmentFile = mkIf (cfg.secretFile != null) [ cfg.secretFile ];
+        ExecStartPre = [
+          # StateDirectory cannot be used when DynamicUser = true is set this way.
+          # Indeed, it will try to create all the folders and realize one of them already exist.
+          # Therefore, we have to create it ourselves.
+          ''${pkgs.coreutils}/bin/mkdir -p "''${STATE_DIRECTORY}/listmonk/uploads"''
+          "${cfg.package}/bin/listmonk --config ${cfgFile} --idempotent --install --upgrade --yes"
+          "${updateDatabaseConfigScript}/bin/update-database-config.sh"
+        ];
+        ExecStart = "${cfg.package}/bin/listmonk --config ${cfgFile}";
+
+        Restart = "on-failure";
+
+        StateDirectory = [ "listmonk" ];
+
+        User = "listmonk";
+        Group = "listmonk";
+        DynamicUser = true;
+        NoNewPrivileges = true;
+        CapabilityBoundingSet = "";
+        SystemCallArchitecture = "native";
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
+        ProtectDevices = true;
+        ProtectControlGroups = true;
+        ProtectKernelTunables = true;
+        ProtectHome = true;
+        DeviceAllow = false;
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        UMask = "0027";
+        MemoryDenyWriteExecute = true;
+        LockPersonality = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+        ProtectKernelModules = true;
+        PrivateUsers = true;
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/mail/maddy.nix b/nixos/modules/services/mail/maddy.nix
index 0b06905ac6f..eeb113e204c 100644
--- a/nixos/modules/services/mail/maddy.nix
+++ b/nixos/modules/services/mail/maddy.nix
@@ -139,33 +139,33 @@ in {
   options = {
     services.maddy = {
 
-      enable = mkEnableOption "Maddy, a free an open source mail server";
+      enable = mkEnableOption (lib.mdDoc "Maddy, a free an open source mail server");
 
       user = mkOption {
         default = "maddy";
         type = with types; uniq string;
-        description = ''
+        description = lib.mdDoc ''
           User account under which maddy runs.
 
-          <note><para>
+          ::: {.note}
           If left as the default value this user will automatically be created
           on system activation, otherwise the sysadmin is responsible for
           ensuring the user exists before the maddy service starts.
-          </para></note>
+          :::
         '';
       };
 
       group = mkOption {
         default = "maddy";
         type = with types; uniq string;
-        description = ''
+        description = lib.mdDoc ''
           Group account under which maddy runs.
 
-          <note><para>
+          ::: {.note}
           If left as the default value this group will automatically be created
           on system activation, otherwise the sysadmin is responsible for
           ensuring the group exists before the maddy service starts.
-          </para></note>
+          :::
         '';
       };
 
@@ -173,7 +173,7 @@ in {
         default = "localhost";
         type = with types; uniq string;
         example = ''example.com'';
-        description = ''
+        description = lib.mdDoc ''
           Hostname to use. It should be FQDN.
         '';
       };
@@ -182,7 +182,7 @@ in {
         default = "localhost";
         type = with types; uniq string;
         example = ''mail.example.com'';
-        description = ''
+        description = lib.mdDoc ''
           Primary MX domain to use. It should be FQDN.
         '';
       };
@@ -195,7 +195,7 @@ in {
           "example.com"
           "other.example.com"
         ];
-        description = ''
+        description = lib.mdDoc ''
           Define list of allowed domains.
         '';
       };
@@ -203,21 +203,22 @@ in {
       config = mkOption {
         type = with types; nullOr lines;
         default = defaultConfig;
-        description = ''
+        description = lib.mdDoc ''
           Server configuration, see
-          <link xlink:href="https://maddy.email">https://maddy.email</link> for
+          [https://maddy.email](https://maddy.email) for
           more information. The default configuration of this module will setup
           minimal maddy instance for mail transfer without TLS encryption.
-          <note><para>
+
+          ::: {.note}
           This should not be used in a production environment.
-          </para></note>
+          :::
         '';
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open the configured incoming and outgoing mail server ports.
         '';
       };
diff --git a/nixos/modules/services/mail/mail.nix b/nixos/modules/services/mail/mail.nix
index fcc7ff6db91..8e1424595b5 100644
--- a/nixos/modules/services/mail/mail.nix
+++ b/nixos/modules/services/mail/mail.nix
@@ -14,7 +14,7 @@ with lib;
         type = types.nullOr options.security.wrappers.type.nestedTypes.elemType;
         default = null;
         internal = true;
-        description = ''
+        description = lib.mdDoc ''
           Configuration for the sendmail setuid wapper.
         '';
       };
diff --git a/nixos/modules/services/mail/mailcatcher.nix b/nixos/modules/services/mail/mailcatcher.nix
index 84f06ed199d..d0f4550c192 100644
--- a/nixos/modules/services/mail/mailcatcher.nix
+++ b/nixos/modules/services/mail/mailcatcher.nix
@@ -11,37 +11,37 @@ in
   options = {
 
     services.mailcatcher = {
-      enable = mkEnableOption "MailCatcher";
+      enable = mkEnableOption (lib.mdDoc "MailCatcher");
 
       http.ip = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "The ip address of the http server.";
+        description = lib.mdDoc "The ip address of the http server.";
       };
 
       http.port = mkOption {
         type = types.port;
         default = 1080;
-        description = "The port address of the http server.";
+        description = lib.mdDoc "The port address of the http server.";
       };
 
       http.path = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "Prefix to all HTTP paths.";
+        description = lib.mdDoc "Prefix to all HTTP paths.";
         example = "/mailcatcher";
       };
 
       smtp.ip = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "The ip address of the smtp server.";
+        description = lib.mdDoc "The ip address of the smtp server.";
       };
 
       smtp.port = mkOption {
         type = types.port;
         default = 1025;
-        description = "The port address of the smtp server.";
+        description = lib.mdDoc "The port address of the smtp server.";
       };
     };
 
diff --git a/nixos/modules/services/mail/mailhog.nix b/nixos/modules/services/mail/mailhog.nix
index b113f4ff3de..7ae62de291b 100644
--- a/nixos/modules/services/mail/mailhog.nix
+++ b/nixos/modules/services/mail/mailhog.nix
@@ -27,36 +27,36 @@ in
   options = {
 
     services.mailhog = {
-      enable = mkEnableOption "MailHog";
+      enable = mkEnableOption (lib.mdDoc "MailHog");
 
       storage = mkOption {
         type = types.enum [ "maildir" "memory" ];
         default = "memory";
-        description = "Store mails on disk or in memory.";
+        description = lib.mdDoc "Store mails on disk or in memory.";
       };
 
       apiPort = mkOption {
         type = types.port;
         default = 8025;
-        description = "Port on which the API endpoint will listen.";
+        description = lib.mdDoc "Port on which the API endpoint will listen.";
       };
 
       smtpPort = mkOption {
         type = types.port;
         default = 1025;
-        description = "Port on which the SMTP endpoint will listen.";
+        description = lib.mdDoc "Port on which the SMTP endpoint will listen.";
       };
 
       uiPort = mkOption {
         type = types.port;
         default = 8025;
-        description = "Port on which the HTTP UI will listen.";
+        description = lib.mdDoc "Port on which the HTTP UI will listen.";
       };
 
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "List of additional arguments to pass to the MailHog process.";
+        description = lib.mdDoc "List of additional arguments to pass to the MailHog process.";
       };
     };
   };
diff --git a/nixos/modules/services/mail/mailman.nix b/nixos/modules/services/mail/mailman.nix
index 0c9b38b44b2..198c2f3280f 100644
--- a/nixos/modules/services/mail/mailman.nix
+++ b/nixos/modules/services/mail/mailman.nix
@@ -6,10 +6,10 @@ let
 
   cfg = config.services.mailman;
 
-  pythonEnv = pkgs.python3.withPackages (ps:
-    [ps.mailman ps.mailman-web]
-    ++ lib.optional cfg.hyperkitty.enable ps.mailman-hyperkitty
-    ++ cfg.extraPythonPackages);
+  inherit (pkgs.mailmanPackages.buildEnvs { withHyperkitty = cfg.hyperkitty.enable; withLDAP = cfg.ldap.enable; })
+    mailmanEnv webEnv;
+
+  withPostgresql = config.services.postgresql.enable;
 
   # This deliberately doesn't use recursiveUpdate so users can
   # override the defaults.
@@ -44,7 +44,13 @@ let
     transport_file_type: hash
   '';
 
-  mailmanCfg = lib.generators.toINI {} cfg.settings;
+  mailmanCfg = lib.generators.toINI {}
+    (recursiveUpdate cfg.settings
+      ((optionalAttrs (cfg.restApiPassFile != null) {
+        webservice.admin_pass = "#NIXOS_MAILMAN_REST_API_PASS_SECRET#";
+      })));
+
+  mailmanCfgFile = pkgs.writeText "mailman-raw.cfg" mailmanCfg;
 
   mailmanHyperkittyCfg = pkgs.writeText "mailman-hyperkitty.cfg" ''
     [general]
@@ -72,6 +78,9 @@ in {
       stored in the world-readable Nix store.  To continue using
       Hyperkitty, you must set services.mailman.hyperkitty.enable = true.
     '')
+    (mkRemovedOptionModule [ "services" "mailman" "package" ] ''
+      Didn't have an effect for several years.
+    '')
   ];
 
   options = {
@@ -81,22 +90,122 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable Mailman on this host. Requires an active MTA on the host (e.g. Postfix).";
+        description = lib.mdDoc "Enable Mailman on this host. Requires an active MTA on the host (e.g. Postfix).";
       };
 
-      package = mkOption {
-        type = types.package;
-        default = pkgs.mailman;
-        defaultText = literalExpression "pkgs.mailman";
-        example = literalExpression "pkgs.mailman.override { archivers = []; }";
-        description = "Mailman package to use";
+      ldap = {
+        enable = mkEnableOption (lib.mdDoc "LDAP auth");
+        serverUri = mkOption {
+          type = types.str;
+          example = "ldaps://ldap.host";
+          description = lib.mdDoc ''
+            LDAP host to connect against.
+          '';
+        };
+        bindDn = mkOption {
+          type = types.str;
+          example = "cn=root,dc=nixos,dc=org";
+          description = lib.mdDoc ''
+            Service account to bind against.
+          '';
+        };
+        bindPasswordFile = mkOption {
+          type = types.str;
+          example = "/run/secrets/ldap-bind";
+          description = lib.mdDoc ''
+            Path to the file containing the bind password of the servie account
+            defined by [](#opt-services.mailman.ldap.bindDn).
+          '';
+        };
+        superUserGroup = mkOption {
+          type = types.nullOr types.str;
+          default = null;
+          example = "cn=admin,ou=groups,dc=nixos,dc=org";
+          description = lib.mdDoc ''
+            Group where a user must be a member of to gain superuser rights.
+          '';
+        };
+        userSearch = {
+          query = mkOption {
+            type = types.str;
+            example = "(&(objectClass=inetOrgPerson)(|(uid=%(user)s)(mail=%(user)s)))";
+            description = lib.mdDoc ''
+              Query to find a user in the LDAP database.
+            '';
+          };
+          ou = mkOption {
+            type = types.str;
+            example = "ou=users,dc=nixos,dc=org";
+            description = lib.mdDoc ''
+              Organizational unit to look up a user.
+            '';
+          };
+        };
+        groupSearch = {
+          type = mkOption {
+            type = types.enum [
+              "posixGroup" "groupOfNames" "memberDNGroup" "nestedMemberDNGroup" "nestedGroupOfNames"
+              "groupOfUniqueNames" "nestedGroupOfUniqueNames" "activeDirectoryGroup" "nestedActiveDirectoryGroup"
+              "organizationalRoleGroup" "nestedOrganizationalRoleGroup"
+            ];
+            default = "posixGroup";
+            apply = v: "${toUpper (substring 0 1 v)}${substring 1 (stringLength v) v}Type";
+            description = lib.mdDoc ''
+              Type of group to perform a group search against.
+            '';
+          };
+          query = mkOption {
+            type = types.str;
+            example = "(objectClass=groupOfNames)";
+            description = lib.mdDoc ''
+              Query to find a group associated to a user in the LDAP database.
+            '';
+          };
+          ou = mkOption {
+            type = types.str;
+            example = "ou=groups,dc=nixos,dc=org";
+            description = lib.mdDoc ''
+              Organizational unit to look up a group.
+            '';
+          };
+        };
+        attrMap = {
+          username = mkOption {
+            default = "uid";
+            type = types.str;
+            description = lib.mdDoc ''
+              LDAP-attribute that corresponds to the `username`-attribute in mailman.
+            '';
+          };
+          firstName = mkOption {
+            default = "givenName";
+            type = types.str;
+            description = lib.mdDoc ''
+              LDAP-attribute that corresponds to the `firstName`-attribute in mailman.
+            '';
+          };
+          lastName = mkOption {
+            default = "sn";
+            type = types.str;
+            description = lib.mdDoc ''
+              LDAP-attribute that corresponds to the `lastName`-attribute in mailman.
+            '';
+          };
+          email = mkOption {
+            default = "mail";
+            type = types.str;
+            description = lib.mdDoc ''
+              LDAP-attribute that corresponds to the `email`-attribute in mailman.
+            '';
+          };
+        };
       };
 
       enablePostfix = mkOption {
         type = types.bool;
         default = true;
         example = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable Postfix integration. Requires an active Postfix installation.
 
           If you want to use another MTA, set this option to false and configure
@@ -109,7 +218,7 @@ in {
       siteOwner = mkOption {
         type = types.str;
         example = "postmaster@example.org";
-        description = ''
+        description = lib.mdDoc ''
           Certain messages that must be delivered to a human, but which can't
           be delivered to a list owner (e.g. a bounce from a list owner), will
           be sent to this address. It should point to a human.
@@ -119,7 +228,7 @@ in {
       webHosts = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           The list of hostnames and/or IP addresses from which the Mailman Web
           UI will accept requests. By default, "localhost" and "127.0.0.1" are
           enabled. All additional names under which your web server accepts
@@ -131,7 +240,7 @@ in {
       webUser = mkOption {
         type = types.str;
         default = "mailman-web";
-        description = ''
+        description = lib.mdDoc ''
           User to run mailman-web as
         '';
       };
@@ -139,34 +248,51 @@ in {
       webSettings = mkOption {
         type = types.attrs;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Overrides for the default mailman-web Django settings.
         '';
       };
 
+      restApiPassFile = mkOption {
+        default = null;
+        type = types.nullOr types.str;
+        description = lib.mdDoc ''
+          Path to the file containing the value for `MAILMAN_REST_API_PASS`.
+        '';
+      };
+
       serve = {
-        enable = mkEnableOption "Automatic nginx and uwsgi setup for mailman-web";
+        enable = mkEnableOption (lib.mdDoc "Automatic nginx and uwsgi setup for mailman-web");
+
+        virtualRoot = mkOption {
+          default = "/";
+          example = lib.literalExpression "/lists";
+          type = types.str;
+          description = lib.mdDoc ''
+            Path to mount the mailman-web django application on.
+          '';
+        };
       };
 
       extraPythonPackages = mkOption {
-        description = "Packages to add to the python environment used by mailman and mailman-web";
+        description = lib.mdDoc "Packages to add to the python environment used by mailman and mailman-web";
         type = types.listOf types.package;
         default = [];
       };
 
       settings = mkOption {
-        description = "Settings for mailman.cfg";
+        description = lib.mdDoc "Settings for mailman.cfg";
         type = types.attrsOf (types.attrsOf types.str);
         default = {};
       };
 
       hyperkitty = {
-        enable = mkEnableOption "the Hyperkitty archiver for Mailman";
+        enable = mkEnableOption (lib.mdDoc "the Hyperkitty archiver for Mailman");
 
         baseUrl = mkOption {
           type = types.str;
           default = "http://localhost:18507/archives/";
-          description = ''
+          description = lib.mdDoc ''
             Where can Mailman connect to Hyperkitty's internal API, preferably on
             localhost?
           '';
@@ -185,14 +311,13 @@ in {
       mailman.layout = "fhs";
 
       "paths.fhs" = {
-        bin_dir = "${pkgs.python3Packages.mailman}/bin";
+        bin_dir = "${pkgs.mailmanPackages.mailman}/bin";
         var_dir = "/var/lib/mailman";
         queue_dir = "$var_dir/queue";
         template_dir = "$var_dir/templates";
         log_dir = "/var/log/mailman";
         lock_dir = "$var_dir/lock";
         etc_dir = "/etc";
-        ext_dir = "$etc_dir/mailman.d";
         pid_file = "/run/mailman/master.pid";
       };
 
@@ -225,7 +350,14 @@ in {
               See <https://mailman.readthedocs.io/en/latest/src/mailman/docs/mta.html>.
             '';
           };
-    in (lib.optionals cfg.enablePostfix [
+    in [
+      { assertion = cfg.webHosts != [];
+        message = ''
+          services.mailman.serve.enable requires there to be at least one entry
+          in services.mailman.webHosts.
+        '';
+      }
+    ] ++ (lib.optionals cfg.enablePostfix [
       { assertion = postfix.enable;
         message = ''
           Mailman's default NixOS configuration requires Postfix to be enabled.
@@ -254,8 +386,6 @@ in {
     };
     users.groups.mailman = {};
 
-    environment.etc."mailman.cfg".text = mailmanCfg;
-
     environment.etc."mailman3/settings.py".text = ''
       import os
 
@@ -273,26 +403,61 @@ in {
 
       with open('/var/lib/mailman-web/settings_local.json') as f:
           globals().update(json.load(f))
+
+      ${optionalString (cfg.restApiPassFile != null) ''
+        with open('${cfg.restApiPassFile}') as f:
+            MAILMAN_REST_API_PASS = f.read().rstrip('\n')
+      ''}
+
+      ${optionalString (cfg.ldap.enable) ''
+        import ldap
+        from django_auth_ldap.config import LDAPSearch, ${cfg.ldap.groupSearch.type}
+        AUTH_LDAP_SERVER_URI = "${cfg.ldap.serverUri}"
+        AUTH_LDAP_BIND_DN = "${cfg.ldap.bindDn}"
+        with open("${cfg.ldap.bindPasswordFile}") as f:
+            AUTH_LDAP_BIND_PASSWORD = f.read().rstrip('\n')
+        AUTH_LDAP_USER_SEARCH = LDAPSearch("${cfg.ldap.userSearch.ou}",
+            ldap.SCOPE_SUBTREE, "${cfg.ldap.userSearch.query}")
+        AUTH_LDAP_GROUP_TYPE = ${cfg.ldap.groupSearch.type}()
+        AUTH_LDAP_GROUP_SEARCH = LDAPSearch("${cfg.ldap.groupSearch.ou}",
+            ldap.SCOPE_SUBTREE, "${cfg.ldap.groupSearch.query}")
+        AUTH_LDAP_USER_ATTR_MAP = {
+          ${concatStrings (flip mapAttrsToList cfg.ldap.attrMap (key: value: ''
+            "${key}": "${value}",
+          ''))}
+        }
+        ${optionalString (cfg.ldap.superUserGroup != null) ''
+          AUTH_LDAP_USER_FLAGS_BY_GROUP = {
+            "is_superuser": "${cfg.ldap.superUserGroup}"
+          }
+        ''}
+        AUTHENTICATION_BACKENDS = (
+            "django_auth_ldap.backend.LDAPBackend",
+            "django.contrib.auth.backends.ModelBackend"
+        )
+      ''}
     '';
 
-    services.nginx = mkIf cfg.serve.enable {
+    services.nginx = mkIf (cfg.serve.enable && cfg.webHosts != []) {
       enable = mkDefault true;
-      virtualHosts."${lib.head cfg.webHosts}" = {
-        serverAliases = cfg.webHosts;
+      virtualHosts = lib.genAttrs cfg.webHosts (webHost: {
         locations = {
-          "/".extraConfig = "uwsgi_pass unix:/run/mailman-web.socket;";
-          "/static/".alias = webSettings.STATIC_ROOT + "/";
+          ${cfg.serve.virtualRoot}.extraConfig = "uwsgi_pass unix:/run/mailman-web.socket;";
+          "${cfg.serve.virtualRoot}/static/".alias = webSettings.STATIC_ROOT + "/";
         };
-      };
+      });
     };
 
     environment.systemPackages = [ (pkgs.buildEnv {
       name = "mailman-tools";
       # We don't want to pollute the system PATH with a python
       # interpreter etc. so let's pick only the stuff we actually
-      # want from pythonEnv
+      # want from {web,mailman}Env
       pathsToLink = ["/bin"];
-      paths = [pythonEnv];
+      paths = [ mailmanEnv webEnv ];
+      # Only mailman-related stuff is installed, the rest is removed
+      # in `postBuild`.
+      ignoreCollisions = true;
       postBuild = ''
         find $out/bin/ -mindepth 1 -not -name "mailman*" -delete
       '';
@@ -313,12 +478,16 @@ in {
     systemd.services = {
       mailman = {
         description = "GNU Mailman Master Process";
-        after = [ "network.target" ];
-        restartTriggers = [ config.environment.etc."mailman.cfg".source ];
+        before = lib.optional cfg.enablePostfix "postfix.service";
+        after = [ "network.target" ]
+          ++ lib.optional cfg.enablePostfix "postfix-setup.service"
+          ++ lib.optional withPostgresql "postgresql.service";
+        restartTriggers = [ mailmanCfgFile ];
+        requires = optional withPostgresql "postgresql.service";
         wantedBy = [ "multi-user.target" ];
         serviceConfig = {
-          ExecStart = "${pythonEnv}/bin/mailman start";
-          ExecStop = "${pythonEnv}/bin/mailman stop";
+          ExecStart = "${mailmanEnv}/bin/mailman start";
+          ExecStop = "${mailmanEnv}/bin/mailman stop";
           User = "mailman";
           Group = "mailman";
           Type = "forking";
@@ -333,8 +502,18 @@ in {
         before = [ "mailman.service" "mailman-web-setup.service" "mailman-uwsgi.service" "hyperkitty.service" ];
         requiredBy = [ "mailman.service" "mailman-web-setup.service" "mailman-uwsgi.service" "hyperkitty.service" ];
         path = with pkgs; [ jq ];
+        after = optional withPostgresql "postgresql.service";
+        requires = optional withPostgresql "postgresql.service";
         serviceConfig.Type = "oneshot";
         script = ''
+          install -m0750 -o mailman -g mailman ${mailmanCfgFile} /etc/mailman.cfg
+          ${optionalString (cfg.restApiPassFile != null) ''
+            ${pkgs.replace-secret}/bin/replace-secret \
+              '#NIXOS_MAILMAN_REST_API_PASS_SECRET#' \
+              ${cfg.restApiPassFile} \
+              /etc/mailman.cfg
+          ''}
+
           mailmanDir=/var/lib/mailman
           mailmanWebDir=/var/lib/mailman-web
 
@@ -374,9 +553,9 @@ in {
         restartTriggers = [ config.environment.etc."mailman3/settings.py".source ];
         script = ''
           [[ -e "${webSettings.STATIC_ROOT}" ]] && find "${webSettings.STATIC_ROOT}/" -mindepth 1 -delete
-          ${pythonEnv}/bin/mailman-web migrate
-          ${pythonEnv}/bin/mailman-web collectstatic
-          ${pythonEnv}/bin/mailman-web compress
+          ${webEnv}/bin/mailman-web migrate
+          ${webEnv}/bin/mailman-web collectstatic
+          ${webEnv}/bin/mailman-web compress
         '';
         serviceConfig = {
           User = cfg.webUser;
@@ -390,14 +569,17 @@ in {
         uwsgiConfig.uwsgi = {
           type = "normal";
           plugins = ["python3"];
-          home = pythonEnv;
-          module = "mailman_web.wsgi";
+          home = webEnv;
+          manage-script-name = true;
+          mount = "${cfg.serve.virtualRoot}=mailman_web.wsgi:application";
           http = "127.0.0.1:18507";
         };
         uwsgiConfigFile = pkgs.writeText "uwsgi-mailman.json" (builtins.toJSON uwsgiConfig);
       in {
         wantedBy = ["multi-user.target"];
-        requires = ["mailman-uwsgi.socket" "mailman-web-setup.service"];
+        after = optional withPostgresql "postgresql.service";
+        requires = ["mailman-uwsgi.socket" "mailman-web-setup.service"]
+          ++ optional withPostgresql "postgresql.service";
         restartTriggers = [ config.environment.etc."mailman3/settings.py".source ];
         serviceConfig = {
           # Since the mailman-web settings.py obstinately creates a logs
@@ -413,9 +595,9 @@ in {
       mailman-daily = {
         description = "Trigger daily Mailman events";
         startAt = "daily";
-        restartTriggers = [ config.environment.etc."mailman.cfg".source ];
+        restartTriggers = [ mailmanCfgFile ];
         serviceConfig = {
-          ExecStart = "${pythonEnv}/bin/mailman digests --send";
+          ExecStart = "${mailmanEnv}/bin/mailman digests --send";
           User = "mailman";
           Group = "mailman";
         };
@@ -427,7 +609,7 @@ in {
         restartTriggers = [ config.environment.etc."mailman3/settings.py".source ];
         wantedBy = [ "mailman.service" "multi-user.target" ];
         serviceConfig = {
-          ExecStart = "${pythonEnv}/bin/mailman-web qcluster";
+          ExecStart = "${webEnv}/bin/mailman-web qcluster";
           User = cfg.webUser;
           Group = "mailman";
           WorkingDirectory = "/var/lib/mailman-web";
@@ -446,7 +628,7 @@ in {
         inherit startAt;
         restartTriggers = [ config.environment.etc."mailman3/settings.py".source ];
         serviceConfig = {
-          ExecStart = "${pythonEnv}/bin/mailman-web runjobs ${name}";
+          ExecStart = "${webEnv}/bin/mailman-web runjobs ${name}";
           User = cfg.webUser;
           Group = "mailman";
           WorkingDirectory = "/var/lib/mailman-web";
@@ -455,7 +637,7 @@ in {
   };
 
   meta = {
-    maintainers = with lib.maintainers; [ lheckemann qyliss ];
+    maintainers = with lib.maintainers; [ lheckemann qyliss ma27 ];
     doc = ./mailman.xml;
   };
 
diff --git a/nixos/modules/services/mail/mlmmj.nix b/nixos/modules/services/mail/mlmmj.nix
index fd74f2dc5f0..642f8b20fe3 100644
--- a/nixos/modules/services/mail/mlmmj.nix
+++ b/nixos/modules/services/mail/mlmmj.nix
@@ -56,40 +56,39 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable mlmmj";
+        description = lib.mdDoc "Enable mlmmj";
       };
 
       user = mkOption {
         type = types.str;
         default = "mlmmj";
-        description = "mailinglist local user";
+        description = lib.mdDoc "mailinglist local user";
       };
 
       group = mkOption {
         type = types.str;
         default = "mlmmj";
-        description = "mailinglist local group";
+        description = lib.mdDoc "mailinglist local group";
       };
 
       listDomain = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Set the mailing list domain";
+        description = lib.mdDoc "Set the mailing list domain";
       };
 
       mailLists = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "The collection of hosted maillists";
+        description = lib.mdDoc "The collection of hosted maillists";
       };
 
       maintInterval = mkOption {
         type = types.str;
         default = "20min";
-        description = ''
+        description = lib.mdDoc ''
           Time interval between mlmmj-maintd runs, see
-          <citerefentry><refentrytitle>systemd.time</refentrytitle>
-          <manvolnum>7</manvolnum></citerefentry> for format information.
+          {manpage}`systemd.time(7)` for format information.
         '';
       };
 
diff --git a/nixos/modules/services/mail/nullmailer.nix b/nixos/modules/services/mail/nullmailer.nix
index f9c34566997..7c72229efb2 100644
--- a/nixos/modules/services/mail/nullmailer.nix
+++ b/nixos/modules/services/mail/nullmailer.nix
@@ -10,13 +10,13 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable nullmailer daemon.";
+        description = lib.mdDoc "Whether to enable nullmailer daemon.";
       };
 
       user = mkOption {
         type = types.str;
         default = "nullmailer";
-        description = ''
+        description = lib.mdDoc ''
           User to use to run nullmailer-send.
         '';
       };
@@ -24,7 +24,7 @@ with lib;
       group = mkOption {
         type = types.str;
         default = "nullmailer";
-        description = ''
+        description = lib.mdDoc ''
           Group to use to run nullmailer-send.
         '';
       };
@@ -32,17 +32,17 @@ with lib;
       setSendmail = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to set the system sendmail to nullmailer's.";
+        description = lib.mdDoc "Whether to set the system sendmail to nullmailer's.";
       };
 
       remotesFile = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
-          Path to the <code>remotes</code> control file. This file contains a
+        description = lib.mdDoc ''
+          Path to the `remotes` control file. This file contains a
           list of remote servers to which to send each message.
 
-          See <code>man 8 nullmailer-send</code> for syntax and available
+          See `man 8 nullmailer-send` for syntax and available
           options.
         '';
       };
@@ -51,7 +51,7 @@ with lib;
         adminaddr = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             If set, all recipients to users at either "localhost" (the literal string)
             or the canonical host name (from the me control attribute) are remapped to this address.
             This is provided to allow local daemons to be able to send email to
@@ -64,7 +64,7 @@ with lib;
         allmailfrom = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             If set, content will override the envelope sender on all messages.
           '';
         };
@@ -72,7 +72,7 @@ with lib;
         defaultdomain = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
              The content of this attribute is appended to any host name that
              does not contain a period (except localhost), including defaulthost
              and idhost. Defaults to the value of the me attribute, if it exists,
@@ -83,7 +83,7 @@ with lib;
         defaulthost = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
              The content of this attribute is appended to any address that
              is missing a host name. Defaults to the value of the me control
              attribute, if it exists, otherwise the literal name defaulthost.
@@ -93,7 +93,7 @@ with lib;
         doublebounceto = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             If the original sender was empty (the original message was a
             delivery status or disposition notification), the double bounce
             is sent to the address in this attribute.
@@ -103,7 +103,7 @@ with lib;
         helohost = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Sets  the  environment variable $HELOHOST which is used by the
             SMTP protocol module to set the parameter given to the HELO command.
             Defaults to the value of the me configuration attribute.
@@ -113,7 +113,7 @@ with lib;
         idhost = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The content of this attribute is used when building the message-id
             string for the message. Defaults to the canonicalized value of defaulthost.
           '';
@@ -122,7 +122,7 @@ with lib;
         maxpause = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
              The maximum time to pause between successive queue runs, in seconds.
              Defaults to 24 hours (86400).
           '';
@@ -131,7 +131,7 @@ with lib;
         me = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
              The fully-qualifiled host name of the computer running nullmailer.
              Defaults to the literal name me.
           '';
@@ -140,7 +140,7 @@ with lib;
         pausetime = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The minimum time to pause between successive queue runs when there
             are messages in the queue, in seconds. Defaults to 1 minute (60).
             Each time this timeout is reached, the timeout is doubled to a
@@ -153,24 +153,24 @@ with lib;
         remotes = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             A list of remote servers to which to send each message. Each line
             contains a remote host name or address followed by an optional
             protocol string, separated by white space.
 
-            See <code>man 8 nullmailer-send</code> for syntax and available
+            See `man 8 nullmailer-send` for syntax and available
             options.
 
             WARNING: This is stored world-readable in the nix store. If you need
             to specify any secret credentials here, consider using the
-            <code>remotesFile</code> option instead.
+            `remotesFile` option instead.
           '';
         };
 
         sendtimeout = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The  time to wait for a remote module listed above to complete sending
             a message before killing it and trying again, in seconds.
             Defaults to 1 hour (3600).  If this is set to 0, nullmailer-send
@@ -212,6 +212,9 @@ with lib;
 
     systemd.tmpfiles.rules = [
       "d /var/spool/nullmailer - ${cfg.user} - - -"
+      "d /var/spool/nullmailer/failed 750 ${cfg.user} - - -"
+      "d /var/spool/nullmailer/queue 750 ${cfg.user} - - -"
+      "d /var/spool/nullmailer/tmp 750 ${cfg.user} - - -"
     ];
 
     systemd.services.nullmailer = {
@@ -220,7 +223,6 @@ with lib;
       after = [ "network.target" ];
 
       preStart = ''
-        mkdir -p /var/spool/nullmailer/{queue,tmp,failed}
         rm -f /var/spool/nullmailer/trigger && mkfifo -m 660 /var/spool/nullmailer/trigger
       '';
 
diff --git a/nixos/modules/services/mail/offlineimap.nix b/nixos/modules/services/mail/offlineimap.nix
index 45147758119..64fa09e8361 100644
--- a/nixos/modules/services/mail/offlineimap.nix
+++ b/nixos/modules/services/mail/offlineimap.nix
@@ -7,18 +7,18 @@ let
 in {
 
   options.services.offlineimap = {
-    enable = mkEnableOption "OfflineIMAP, a software to dispose your mailbox(es) as a local Maildir(s)";
+    enable = mkEnableOption (lib.mdDoc "OfflineIMAP, a software to dispose your mailbox(es) as a local Maildir(s)");
 
     install = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to install a user service for Offlineimap. Once
         the service is started, emails will be fetched automatically.
 
         The service must be manually started for each user with
         "systemctl --user start offlineimap" or globally through
-        <varname>services.offlineimap.enable</varname>.
+        {var}`services.offlineimap.enable`.
       '';
     };
 
@@ -26,26 +26,26 @@ in {
       type = types.package;
       default = pkgs.offlineimap;
       defaultText = literalExpression "pkgs.offlineimap";
-      description = "Offlineimap derivation to use.";
+      description = lib.mdDoc "Offlineimap derivation to use.";
     };
 
     path = mkOption {
       type = types.listOf types.path;
       default = [];
       example = literalExpression "[ pkgs.pass pkgs.bash pkgs.notmuch ]";
-      description = "List of derivations to put in Offlineimap's path.";
+      description = lib.mdDoc "List of derivations to put in Offlineimap's path.";
     };
 
     onCalendar = mkOption {
       type = types.str;
       default = "*:0/3"; # every 3 minutes
-      description = "How often is offlineimap started. Default is '*:0/3' meaning every 3 minutes. See systemd.time(7) for more information about the format.";
+      description = lib.mdDoc "How often is offlineimap started. Default is '*:0/3' meaning every 3 minutes. See systemd.time(7) for more information about the format.";
     };
 
     timeoutStartSec = mkOption {
       type = types.str;
       default = "120sec"; # Kill if still alive after 2 minutes
-      description = "How long waiting for offlineimap before killing it. Default is '120sec' meaning every 2 minutes. See systemd.time(7) for more information about the format.";
+      description = lib.mdDoc "How long waiting for offlineimap before killing it. Default is '120sec' meaning every 2 minutes. See systemd.time(7) for more information about the format.";
     };
   };
   config = mkIf (cfg.enable || cfg.install) {
diff --git a/nixos/modules/services/mail/opendkim.nix b/nixos/modules/services/mail/opendkim.nix
index f1ffc5d3aee..a377fccc7bd 100644
--- a/nixos/modules/services/mail/opendkim.nix
+++ b/nixos/modules/services/mail/opendkim.nix
@@ -31,25 +31,25 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the OpenDKIM sender authentication system.";
+        description = lib.mdDoc "Whether to enable the OpenDKIM sender authentication system.";
       };
 
       socket = mkOption {
         type = types.str;
         default = defaultSock;
-        description = "Socket which is used for communication with OpenDKIM.";
+        description = lib.mdDoc "Socket which is used for communication with OpenDKIM.";
       };
 
       user = mkOption {
         type = types.str;
         default = "opendkim";
-        description = "User for the daemon.";
+        description = lib.mdDoc "User for the daemon.";
       };
 
       group = mkOption {
         type = types.str;
         default = "opendkim";
-        description = "Group for the daemon.";
+        description = lib.mdDoc "Group for the daemon.";
       };
 
       domains = mkOption {
@@ -57,15 +57,15 @@ in {
         default = "csl:${config.networking.hostName}";
         defaultText = literalExpression ''"csl:''${config.networking.hostName}"'';
         example = "csl:example.com,mydomain.net";
-        description = ''
-          Local domains set (see <literal>opendkim(8)</literal> for more information on datasets).
+        description = lib.mdDoc ''
+          Local domains set (see `opendkim(8)` for more information on datasets).
           Messages from them are signed, not verified.
         '';
       };
 
       keyPath = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The path that opendkim should put its generated private keys into.
           The DNS settings will be found in this directory with the name selector.txt.
         '';
@@ -74,13 +74,13 @@ in {
 
       selector = mkOption {
         type = types.str;
-        description = "Selector to use when signing.";
+        description = lib.mdDoc "Selector to use when signing.";
       };
 
       configFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "Additional opendkim configuration.";
+        description = lib.mdDoc "Additional opendkim configuration.";
       };
 
     };
diff --git a/nixos/modules/services/mail/opensmtpd.nix b/nixos/modules/services/mail/opensmtpd.nix
index e7632be2804..6ad3386d2d4 100644
--- a/nixos/modules/services/mail/opensmtpd.nix
+++ b/nixos/modules/services/mail/opensmtpd.nix
@@ -28,27 +28,27 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the OpenSMTPD server.";
+        description = lib.mdDoc "Whether to enable the OpenSMTPD server.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.opensmtpd;
         defaultText = literalExpression "pkgs.opensmtpd";
-        description = "The OpenSMTPD package to use.";
+        description = lib.mdDoc "The OpenSMTPD package to use.";
       };
 
       setSendmail = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to set the system sendmail to OpenSMTPD's.";
+        description = lib.mdDoc "Whether to set the system sendmail to OpenSMTPD's.";
       };
 
       extraServerArgs = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "-v" "-P mta" ];
-        description = ''
+        description = lib.mdDoc ''
           Extra command line arguments provided when the smtpd process
           is started.
         '';
@@ -60,7 +60,7 @@ in {
           listen on lo
           accept for any deliver to lmtp localhost:24
         '';
-        description = ''
+        description = lib.mdDoc ''
           The contents of the smtpd.conf configuration file. See the
           OpenSMTPD documentation for syntax information.
         '';
@@ -69,7 +69,7 @@ in {
       procPackages = mkOption {
         type = types.listOf types.package;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Packages to search for filters, tables, queues, and schedulers.
 
           Add OpenSMTPD-extras here if you want to use the filters, etc. from
diff --git a/nixos/modules/services/mail/pfix-srsd.nix b/nixos/modules/services/mail/pfix-srsd.nix
index e3dbf2a014f..237f36945e4 100644
--- a/nixos/modules/services/mail/pfix-srsd.nix
+++ b/nixos/modules/services/mail/pfix-srsd.nix
@@ -12,20 +12,20 @@ with lib;
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = "Whether to run the postfix sender rewriting scheme daemon.";
+        description = lib.mdDoc "Whether to run the postfix sender rewriting scheme daemon.";
       };
 
       domain = mkOption {
-        description = "The domain for which to enable srs";
+        description = lib.mdDoc "The domain for which to enable srs";
         type = types.str;
         example = "example.com";
       };
 
       secretsFile = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The secret data used to encode the SRS address.
           to generate, use a command like:
-          <literal>for n in $(seq 5); do dd if=/dev/urandom count=1 bs=1024 status=none | sha256sum | sed 's/  -$//' | sed 's/^/          /'; done</literal>
+          `for n in $(seq 5); do dd if=/dev/urandom count=1 bs=1024 status=none | sha256sum | sed 's/  -$//' | sed 's/^/          /'; done`
         '';
         type = types.path;
         default = "/var/lib/pfix-srsd/secrets";
diff --git a/nixos/modules/services/mail/postfix.nix b/nixos/modules/services/mail/postfix.nix
index 23d3574ae27..5461e89a801 100644
--- a/nixos/modules/services/mail/postfix.nix
+++ b/nixos/modules/services/mail/postfix.nix
@@ -45,7 +45,7 @@ let
         type = types.str;
         default = name;
         example = "smtp";
-        description = ''
+        description = lib.mdDoc ''
           The name of the service to run. Defaults to the attribute set key.
         '';
       };
@@ -54,41 +54,41 @@ let
         type = types.enum [ "inet" "unix" "unix-dgram" "fifo" "pass" ];
         default = "unix";
         example = "inet";
-        description = "The type of the service";
+        description = lib.mdDoc "The type of the service";
       };
 
       private = mkOption {
         type = types.bool;
         example = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether the service's sockets and storage directory is restricted to
-          be only available via the mail system. If <literal>null</literal> is
-          given it uses the postfix default <literal>true</literal>.
+          be only available via the mail system. If `null` is
+          given it uses the postfix default `true`.
         '';
       };
 
       privileged = mkOption {
         type = types.bool;
         example = true;
-        description = "";
+        description = lib.mdDoc "";
       };
 
       chroot = mkOption {
         type = types.bool;
         example = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether the service is chrooted to have only access to the
-          <option>services.postfix.queueDir</option> and the closure of
-          store paths specified by the <option>program</option> option.
+          {option}`services.postfix.queueDir` and the closure of
+          store paths specified by the {option}`program` option.
         '';
       };
 
       wakeup = mkOption {
         type = types.int;
         example = 60;
-        description = ''
+        description = lib.mdDoc ''
           Automatically wake up the service after the specified number of
-          seconds. If <literal>0</literal> is given, never wake the service
+          seconds. If `0` is given, never wake the service
           up.
         '';
       };
@@ -96,22 +96,22 @@ let
       wakeupUnusedComponent = mkOption {
         type = types.bool;
         example = false;
-        description = ''
-          If set to <literal>false</literal> the component will only be woken
+        description = lib.mdDoc ''
+          If set to `false` the component will only be woken
           up if it is used. This is equivalent to postfix' notion of adding a
           question mark behind the wakeup time in
-          <filename>master.cf</filename>
+          {file}`master.cf`
         '';
       };
 
       maxproc = mkOption {
         type = types.int;
         example = 1;
-        description = ''
+        description = lib.mdDoc ''
           The maximum number of processes to spawn for this service. If the
-          value is <literal>0</literal> it doesn't have any limit. If
-          <literal>null</literal> is given it uses the postfix default of
-          <literal>100</literal>.
+          value is `0` it doesn't have any limit. If
+          `null` is given it uses the postfix default of
+          `100`.
         '';
       };
 
@@ -119,9 +119,9 @@ let
         type = types.str;
         default = name;
         example = "smtpd";
-        description = ''
+        description = lib.mdDoc ''
           A program name specifying a Postfix service/daemon process.
-          By default it's the attribute <option>name</option>.
+          By default it's the attribute {option}`name`.
         '';
       };
 
@@ -129,8 +129,8 @@ let
         type = types.listOf types.str;
         default = [];
         example = [ "-o" "smtp_helo_timeout=5" ];
-        description = ''
-          Arguments to pass to the <option>command</option>. There is no shell
+        description = lib.mdDoc ''
+          Arguments to pass to the {option}`command`. There is no shell
           processing involved and shell syntax is passed verbatim to the
           process.
         '';
@@ -140,8 +140,8 @@ let
         type = types.listOf types.str;
         default = [];
         internal = true;
-        description = ''
-          The raw configuration line for the <filename>master.cf</filename>.
+        description = lib.mdDoc ''
+          The raw configuration line for the {file}`master.cf`.
         '';
       };
     };
@@ -221,13 +221,13 @@ let
         type = types.str;
         default = "/^.*/";
         example = "/^X-Mailer:/";
-        description = "A regexp pattern matching the header";
+        description = lib.mdDoc "A regexp pattern matching the header";
       };
       action = mkOption {
         type = types.str;
         default = "DUNNO";
         example = "BCC mail@example.com";
-        description = "The action to be executed when the pattern is matched";
+        description = lib.mdDoc "The action to be executed when the pattern is matched";
       };
     };
   };
@@ -267,25 +267,25 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to run the Postfix mail server.";
+        description = lib.mdDoc "Whether to run the Postfix mail server.";
       };
 
       enableSmtp = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable smtp in master.cf.";
+        description = lib.mdDoc "Whether to enable smtp in master.cf.";
       };
 
       enableSubmission = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable smtp submission.";
+        description = lib.mdDoc "Whether to enable smtp submission.";
       };
 
       enableSubmissions = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable smtp submission via smtps.
 
           According to RFC 8314 this should be preferred
@@ -308,7 +308,7 @@ in
           smtpd_client_restrictions = "permit_sasl_authenticated,reject";
           milter_macro_daemon_name = "ORIGINATING";
         };
-        description = "Options for the submission config in master.cf";
+        description = lib.mdDoc "Options for the submission config in master.cf";
       };
 
       submissionsOptions = mkOption {
@@ -324,7 +324,7 @@ in
           smtpd_client_restrictions = "permit_sasl_authenticated,reject";
           milter_macro_daemon_name = "ORIGINATING";
         };
-        description = ''
+        description = lib.mdDoc ''
           Options for the submission config via smtps in master.cf.
 
           smtpd_tls_security_level will be set to encrypt, if it is missing
@@ -337,155 +337,155 @@ in
       setSendmail = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to set the system sendmail to postfix's.";
+        description = lib.mdDoc "Whether to set the system sendmail to postfix's.";
       };
 
       user = mkOption {
         type = types.str;
         default = "postfix";
-        description = "What to call the Postfix user (must be used only for postfix).";
+        description = lib.mdDoc "What to call the Postfix user (must be used only for postfix).";
       };
 
       group = mkOption {
         type = types.str;
         default = "postfix";
-        description = "What to call the Postfix group (must be used only for postfix).";
+        description = lib.mdDoc "What to call the Postfix group (must be used only for postfix).";
       };
 
       setgidGroup = mkOption {
         type = types.str;
         default = "postdrop";
-        description = "
+        description = lib.mdDoc ''
           How to call postfix setgid group (for postdrop). Should
           be uniquely used group.
-        ";
+        '';
       };
 
       networks = mkOption {
         type = types.nullOr (types.listOf types.str);
         default = null;
         example = ["192.168.0.1/24"];
-        description = "
+        description = lib.mdDoc ''
           Net masks for trusted - allowed to relay mail to third parties -
           hosts. Leave empty to use mynetworks_style configuration or use
           default (localhost-only).
-        ";
+        '';
       };
 
       networksStyle = mkOption {
         type = types.str;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Name of standard way of trusted network specification to use,
           leave blank if you specify it explicitly or if you want to use
           default (localhost-only).
-        ";
+        '';
       };
 
       hostname = mkOption {
         type = types.str;
         default = "";
-        description ="
+        description = lib.mdDoc ''
           Hostname to use. Leave blank to use just the hostname of machine.
           It should be FQDN.
-        ";
+        '';
       };
 
       domain = mkOption {
         type = types.str;
         default = "";
-        description ="
+        description = lib.mdDoc ''
           Domain to use. Leave blank to use hostname minus first component.
-        ";
+        '';
       };
 
       origin = mkOption {
         type = types.str;
         default = "";
-        description ="
+        description = lib.mdDoc ''
           Origin to use in outgoing e-mail. Leave blank to use hostname.
-        ";
+        '';
       };
 
       destination = mkOption {
         type = types.nullOr (types.listOf types.str);
         default = null;
         example = ["localhost"];
-        description = "
+        description = lib.mdDoc ''
           Full (!) list of domains we deliver locally. Leave blank for
           acceptable Postfix default.
-        ";
+        '';
       };
 
       relayDomains = mkOption {
         type = types.nullOr (types.listOf types.str);
         default = null;
         example = ["localdomain"];
-        description = "
+        description = lib.mdDoc ''
           List of domains we agree to relay to. Default is empty.
-        ";
+        '';
       };
 
       relayHost = mkOption {
         type = types.str;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Mail relay for outbound mail.
-        ";
+        '';
       };
 
       relayPort = mkOption {
         type = types.int;
         default = 25;
-        description = "
+        description = lib.mdDoc ''
           SMTP port for relay mail relay.
-        ";
+        '';
       };
 
       lookupMX = mkOption {
         type = types.bool;
         default = false;
-        description = "
+        description = lib.mdDoc ''
           Whether relay specified is just domain whose MX must be used.
-        ";
+        '';
       };
 
       postmasterAlias = mkOption {
         type = types.str;
         default = "root";
-        description = "
+        description = lib.mdDoc ''
           Who should receive postmaster e-mail. Multiple values can be added by
           separating values with comma.
-        ";
+        '';
       };
 
       rootAlias = mkOption {
         type = types.str;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Who should receive root e-mail. Blank for no redirection.
           Multiple values can be added by separating values with comma.
-        ";
+        '';
       };
 
       extraAliases = mkOption {
         type = types.lines;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Additional entries to put verbatim into aliases file, cf. man-page aliases(8).
-        ";
+        '';
       };
 
       aliasMapType = mkOption {
         type = with types; enum [ "hash" "regexp" "pcre" ];
         default = "hash";
         example = "regexp";
-        description = "The format the alias map should have. Use regexp if you want to use regular expressions.";
+        description = lib.mdDoc "The format the alias map should have. Use regexp if you want to use regular expressions.";
       };
 
       config = mkOption {
         type = with types; attrsOf (oneOf [ bool str (listOf str) ]);
-        description = ''
+        description = lib.mdDoc ''
           The main.cf configuration file as key value set.
         '';
         example = {
@@ -497,16 +497,16 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to the main.cf configuration file.
-        ";
+        '';
       };
 
       tlsTrustedAuthorities = mkOption {
         type = types.str;
         default = "${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt";
         defaultText = literalExpression ''"''${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"'';
-        description = ''
+        description = lib.mdDoc ''
           File containing trusted certification authorities (CA) to verify certificates of mailservers contacted for mail delivery. This basically sets smtp_tls_CAfile and enables opportunistic tls. Defaults to NixOS trusted certification authorities.
         '';
       };
@@ -514,56 +514,55 @@ in
       sslCert = mkOption {
         type = types.str;
         default = "";
-        description = "SSL certificate to use.";
+        description = lib.mdDoc "SSL certificate to use.";
       };
 
       sslKey = mkOption {
         type = types.str;
         default = "";
-        description = "SSL key to use.";
+        description = lib.mdDoc "SSL key to use.";
       };
 
       recipientDelimiter = mkOption {
         type = types.str;
         default = "";
         example = "+";
-        description = "
+        description = lib.mdDoc ''
           Delimiter for address extension: so mail to user+test can be handled by ~user/.forward+test
-        ";
+        '';
       };
 
       canonical = mkOption {
         type = types.lines;
         default = "";
-        description = ''
-          Entries for the <citerefentry><refentrytitle>canonical</refentrytitle>
-          <manvolnum>5</manvolnum></citerefentry> table.
+        description = lib.mdDoc ''
+          Entries for the {manpage}`canonical(5)` table.
         '';
       };
 
       virtual = mkOption {
         type = types.lines;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Entries for the virtual alias map, cf. man-page virtual(5).
-        ";
+        '';
       };
 
       virtualMapType = mkOption {
         type = types.enum ["hash" "regexp" "pcre"];
         default = "hash";
-        description = ''
-          What type of virtual alias map file to use. Use <literal>"regexp"</literal> for regular expressions.
+        description = lib.mdDoc ''
+          What type of virtual alias map file to use. Use `"regexp"` for regular expressions.
         '';
       };
 
       localRecipients = mkOption {
         type = with types; nullOr (listOf str);
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           List of accepted local users. Specify a bare username, an
-          <literal>"@domain.tld"</literal> wild-card, or a complete
-          <literal>"user@domain.tld"</literal> address. If set, these names end
+          `"@domain.tld"` wild-card, or a complete
+          `"user@domain.tld"` address. If set, these names end
           up in the local recipient map -- see the local(8) man-page -- and
           effectively replace the system user database lookup that's otherwise
           used by default.
@@ -573,21 +572,21 @@ in
       transport = mkOption {
         default = "";
         type = types.lines;
-        description = "
+        description = lib.mdDoc ''
           Entries for the transport map, cf. man-page transport(8).
-        ";
+        '';
       };
 
       dnsBlacklists = mkOption {
         default = [];
         type = with types; listOf str;
-        description = "dns blacklist servers to use with smtpd_client_restrictions";
+        description = lib.mdDoc "dns blacklist servers to use with smtpd_client_restrictions";
       };
 
       dnsBlacklistOverrides = mkOption {
         default = "";
         type = types.lines;
-        description = "contents of check_client_access for overriding dnsBlacklists";
+        description = lib.mdDoc "contents of check_client_access for overriding dnsBlacklists";
       };
 
       masterConfig = mkOption {
@@ -599,10 +598,10 @@ in
               args = [ "-o" "smtpd_tls_security_level=encrypt" ];
             };
           };
-        description = ''
+        description = lib.mdDoc ''
           An attribute set of service options, which correspond to the service
           definitions usually done within the Postfix
-          <filename>master.cf</filename> file.
+          {file}`master.cf` file.
         '';
       };
 
@@ -610,46 +609,46 @@ in
         type = types.lines;
         default = "";
         example = "submission inet n - n - - smtpd";
-        description = "Extra lines to append to the generated master.cf file.";
+        description = lib.mdDoc "Extra lines to append to the generated master.cf file.";
       };
 
       enableHeaderChecks = mkOption {
         type = types.bool;
         default = false;
         example = true;
-        description = "Whether to enable postfix header checks";
+        description = lib.mdDoc "Whether to enable postfix header checks";
       };
 
       headerChecks = mkOption {
         type = types.listOf (types.submodule headerCheckOptions);
         default = [];
         example = [ { pattern = "/^X-Spam-Flag:/"; action = "REDIRECT spam@example.com"; } ];
-        description = "Postfix header checks.";
+        description = lib.mdDoc "Postfix header checks.";
       };
 
       extraHeaderChecks = mkOption {
         type = types.lines;
         default = "";
         example = "/^X-Spam-Flag:/ REDIRECT spam@example.com";
-        description = "Extra lines to /etc/postfix/header_checks file.";
+        description = lib.mdDoc "Extra lines to /etc/postfix/header_checks file.";
       };
 
       aliasFiles = mkOption {
         type = types.attrsOf types.path;
         default = {};
-        description = "Aliases' tables to be compiled and placed into /var/lib/postfix/conf.";
+        description = lib.mdDoc "Aliases' tables to be compiled and placed into /var/lib/postfix/conf.";
       };
 
       mapFiles = mkOption {
         type = types.attrsOf types.path;
         default = {};
-        description = "Maps to be compiled and placed into /var/lib/postfix/conf.";
+        description = lib.mdDoc "Maps to be compiled and placed into /var/lib/postfix/conf.";
       };
 
       useSrs = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable sender rewriting scheme";
+        description = lib.mdDoc "Whether to enable sender rewriting scheme";
       };
 
     };
@@ -723,23 +722,11 @@ in
         { ${setgidGroup}.gid = config.ids.gids.postdrop;
         };
 
-      systemd.services.postfix =
-        { description = "Postfix mail server";
-
-          wantedBy = [ "multi-user.target" ];
-          after = [ "network.target" ];
-          path = [ pkgs.postfix ];
-
-          serviceConfig = {
-            Type = "forking";
-            Restart = "always";
-            PIDFile = "/var/lib/postfix/queue/pid/master.pid";
-            ExecStart = "${pkgs.postfix}/bin/postfix start";
-            ExecStop = "${pkgs.postfix}/bin/postfix stop";
-            ExecReload = "${pkgs.postfix}/bin/postfix reload";
-          };
-
-          preStart = ''
+      systemd.services.postfix-setup =
+        { description = "Setup for Postfix mail server";
+          serviceConfig.RemainAfterExit = true;
+          serviceConfig.Type = "oneshot";
+          script = ''
             # Backwards compatibility
             if [ ! -d /var/lib/postfix ] && [ -d /var/postfix ]; then
               mkdir -p /var/lib
@@ -777,6 +764,24 @@ in
           '';
         };
 
+      systemd.services.postfix =
+        { description = "Postfix mail server";
+
+          wantedBy = [ "multi-user.target" ];
+          after = [ "network.target" "postfix-setup.service" ];
+          requires = [ "postfix-setup.service" ];
+          path = [ pkgs.postfix ];
+
+          serviceConfig = {
+            Type = "forking";
+            Restart = "always";
+            PIDFile = "/var/lib/postfix/queue/pid/master.pid";
+            ExecStart = "${pkgs.postfix}/bin/postfix start";
+            ExecStop = "${pkgs.postfix}/bin/postfix stop";
+            ExecReload = "${pkgs.postfix}/bin/postfix reload";
+          };
+        };
+
       services.postfix.config = (mapAttrs (_: v: mkDefault v) {
         compatibility_level  = pkgs.postfix.version;
         mail_owner           = cfg.user;
diff --git a/nixos/modules/services/mail/postfixadmin.nix b/nixos/modules/services/mail/postfixadmin.nix
index a0846ad5290..b86428770cb 100644
--- a/nixos/modules/services/mail/postfixadmin.nix
+++ b/nixos/modules/services/mail/postfixadmin.nix
@@ -13,25 +13,25 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable postfixadmin.
 
         Also enables nginx virtual host management.
-        Further nginx configuration can be done by adapting <literal>services.nginx.virtualHosts.&lt;name&gt;</literal>.
-        See <xref linkend="opt-services.nginx.virtualHosts"/> for further information.
+        Further nginx configuration can be done by adapting `services.nginx.virtualHosts.<name>`.
+        See [](#opt-services.nginx.virtualHosts) for further information.
       '';
     };
 
     hostName = mkOption {
       type = types.str;
       example = "postfixadmin.example.com";
-      description = "Hostname to use for the nginx vhost";
+      description = lib.mdDoc "Hostname to use for the nginx vhost";
     };
 
     adminEmail = mkOption {
       type = types.str;
       example = "postmaster@example.com";
-      description = ''
+      description = lib.mdDoc ''
         Defines the Site Admin's email address.
         This will be used to send emails from to create mailboxes and
         from Send Email / Broadcast message pages.
@@ -40,9 +40,9 @@ in
 
     setupPasswordFile = mkOption {
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Password file for the admin.
-        Generate with <literal>php -r "echo password_hash('some password here', PASSWORD_DEFAULT);"</literal>
+        Generate with `php -r "echo password_hash('some password here', PASSWORD_DEFAULT);"`
       '';
     };
 
@@ -50,36 +50,36 @@ in
       username = mkOption {
         type = types.str;
         default = "postfixadmin";
-        description = ''
+        description = lib.mdDoc ''
           Username for the postgresql connection.
-          If <literal>database.host</literal> is set to <literal>localhost</literal>, a unix user and group of the same name will be created as well.
+          If `database.host` is set to `localhost`, a unix user and group of the same name will be created as well.
         '';
       };
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           Host of the postgresql server. If this is not set to
-          <literal>localhost</literal>, you have to create the
+          `localhost`, you have to create the
           postgresql user and database yourself, with appropriate
           permissions.
         '';
       };
       passwordFile = mkOption {
         type = types.path;
-        description = "Password file for the postgresql connection. Must be readable by user <literal>nginx</literal>.";
+        description = lib.mdDoc "Password file for the postgresql connection. Must be readable by user `nginx`.";
       };
       dbname = mkOption {
         type = types.str;
         default = "postfixadmin";
-        description = "Name of the postgresql database";
+        description = lib.mdDoc "Name of the postgresql database";
       };
     };
 
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = "Extra configuration for the postfixadmin instance, see postfixadmin's config.inc.php for available options.";
+      description = lib.mdDoc "Extra configuration for the postfixadmin instance, see postfixadmin's config.inc.php for available options.";
     };
   };
 
@@ -177,7 +177,7 @@ in
 
     services.phpfpm.pools.postfixadmin = {
       user = user;
-      phpPackage = pkgs.php74;
+      phpPackage = pkgs.php81;
       phpOptions = ''
         error_log = 'stderr'
         log_errors = on
diff --git a/nixos/modules/services/mail/postgrey.nix b/nixos/modules/services/mail/postgrey.nix
index 7c206e3725e..fdfa08946dd 100644
--- a/nixos/modules/services/mail/postgrey.nix
+++ b/nixos/modules/services/mail/postgrey.nix
@@ -15,12 +15,12 @@ with lib; let
         type = nullOr str;
         default = null;
         example = "127.0.0.1";
-        description = "The address to bind to. Localhost if null";
+        description = lib.mdDoc "The address to bind to. Localhost if null";
       };
       port = mkOption {
         type = natural';
         default = 10030;
-        description = "Tcp port to bind to";
+        description = lib.mdDoc "Tcp port to bind to";
       };
     };
   };
@@ -30,13 +30,13 @@ with lib; let
       path = mkOption {
         type = path;
         default = "/run/postgrey.sock";
-        description = "Path of the unix socket";
+        description = lib.mdDoc "Path of the unix socket";
       };
 
       mode = mkOption {
         type = str;
         default = "0777";
-        description = "Mode of the unix socket";
+        description = lib.mdDoc "Mode of the unix socket";
       };
     };
   };
@@ -59,7 +59,7 @@ in {
       enable = mkOption {
         type = bool;
         default = false;
-        description = "Whether to run the Postgrey daemon";
+        description = lib.mdDoc "Whether to run the Postgrey daemon";
       };
       socket = mkOption {
         type = socket;
@@ -71,73 +71,73 @@ in {
           addr = "127.0.0.1";
           port = 10030;
         };
-        description = "Socket to bind to";
+        description = lib.mdDoc "Socket to bind to";
       };
       greylistText = mkOption {
         type = str;
         default = "Greylisted for %%s seconds";
-        description = "Response status text for greylisted messages; use %%s for seconds left until greylisting is over and %%r for mail domain of recipient";
+        description = lib.mdDoc "Response status text for greylisted messages; use %%s for seconds left until greylisting is over and %%r for mail domain of recipient";
       };
       greylistAction = mkOption {
         type = str;
         default = "DEFER_IF_PERMIT";
-        description = "Response status for greylisted messages (see access(5))";
+        description = lib.mdDoc "Response status for greylisted messages (see access(5))";
       };
       greylistHeader = mkOption {
         type = str;
         default = "X-Greylist: delayed %%t seconds by postgrey-%%v at %%h; %%d";
-        description = "Prepend header to greylisted mails; use %%t for seconds delayed due to greylisting, %%v for the version of postgrey, %%d for the date, and %%h for the host";
+        description = lib.mdDoc "Prepend header to greylisted mails; use %%t for seconds delayed due to greylisting, %%v for the version of postgrey, %%d for the date, and %%h for the host";
       };
       delay = mkOption {
         type = natural;
         default = 300;
-        description = "Greylist for N seconds";
+        description = lib.mdDoc "Greylist for N seconds";
       };
       maxAge = mkOption {
         type = natural;
         default = 35;
-        description = "Delete entries from whitelist if they haven't been seen for N days";
+        description = lib.mdDoc "Delete entries from whitelist if they haven't been seen for N days";
       };
       retryWindow = mkOption {
         type = either str natural;
         default = 2;
         example = "12h";
-        description = "Allow N days for the first retry. Use string with appended 'h' to specify time in hours";
+        description = lib.mdDoc "Allow N days for the first retry. Use string with appended 'h' to specify time in hours";
       };
       lookupBySubnet = mkOption {
         type = bool;
         default = true;
-        description = "Strip the last N bits from IP addresses, determined by IPv4CIDR and IPv6CIDR";
+        description = lib.mdDoc "Strip the last N bits from IP addresses, determined by IPv4CIDR and IPv6CIDR";
       };
       IPv4CIDR = mkOption {
         type = natural;
         default = 24;
-        description = "Strip N bits from IPv4 addresses if lookupBySubnet is true";
+        description = lib.mdDoc "Strip N bits from IPv4 addresses if lookupBySubnet is true";
       };
       IPv6CIDR = mkOption {
         type = natural;
         default = 64;
-        description = "Strip N bits from IPv6 addresses if lookupBySubnet is true";
+        description = lib.mdDoc "Strip N bits from IPv6 addresses if lookupBySubnet is true";
       };
       privacy = mkOption {
         type = bool;
         default = true;
-        description = "Store data using one-way hash functions (SHA1)";
+        description = lib.mdDoc "Store data using one-way hash functions (SHA1)";
       };
       autoWhitelist = mkOption {
         type = nullOr natural';
         default = 5;
-        description = "Whitelist clients after successful delivery of N messages";
+        description = lib.mdDoc "Whitelist clients after successful delivery of N messages";
       };
       whitelistClients = mkOption {
         type = listOf path;
         default = [];
-        description = "Client address whitelist files (see postgrey(8))";
+        description = lib.mdDoc "Client address whitelist files (see postgrey(8))";
       };
       whitelistRecipients = mkOption {
         type = listOf path;
         default = [];
-        description = "Recipient address whitelist files (see postgrey(8))";
+        description = lib.mdDoc "Recipient address whitelist files (see postgrey(8))";
       };
     };
   };
diff --git a/nixos/modules/services/mail/postsrsd.nix b/nixos/modules/services/mail/postsrsd.nix
index 2ebc675ab10..41301c8697d 100644
--- a/nixos/modules/services/mail/postsrsd.nix
+++ b/nixos/modules/services/mail/postsrsd.nix
@@ -17,24 +17,24 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the postsrsd SRS server for Postfix.";
+        description = lib.mdDoc "Whether to enable the postsrsd SRS server for Postfix.";
       };
 
       secretsFile = mkOption {
         type = types.path;
         default = "/var/lib/postsrsd/postsrsd.secret";
-        description = "Secret keys used for signing and verification";
+        description = lib.mdDoc "Secret keys used for signing and verification";
       };
 
       domain = mkOption {
         type = types.str;
-        description = "Domain name for rewrite";
+        description = lib.mdDoc "Domain name for rewrite";
       };
 
       separator = mkOption {
         type = types.enum ["-" "=" "+"];
         default = "=";
-        description = "First separator character in generated addresses";
+        description = lib.mdDoc "First separator character in generated addresses";
       };
 
       # bindAddress = mkOption { # uncomment once 1.5 is released
@@ -46,37 +46,37 @@ in {
       forwardPort = mkOption {
         type = types.int;
         default = 10001;
-        description = "Port for the forward SRS lookup";
+        description = lib.mdDoc "Port for the forward SRS lookup";
       };
 
       reversePort = mkOption {
         type = types.int;
         default = 10002;
-        description = "Port for the reverse SRS lookup";
+        description = lib.mdDoc "Port for the reverse SRS lookup";
       };
 
       timeout = mkOption {
         type = types.int;
         default = 1800;
-        description = "Timeout for idle client connections in seconds";
+        description = lib.mdDoc "Timeout for idle client connections in seconds";
       };
 
       excludeDomains = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Origin domains to exclude from rewriting in addition to primary domain";
+        description = lib.mdDoc "Origin domains to exclude from rewriting in addition to primary domain";
       };
 
       user = mkOption {
         type = types.str;
         default = "postsrsd";
-        description = "User for the daemon";
+        description = lib.mdDoc "User for the daemon";
       };
 
       group = mkOption {
         type = types.str;
         default = "postsrsd";
-        description = "Group for the daemon";
+        description = lib.mdDoc "Group for the daemon";
       };
 
     };
diff --git a/nixos/modules/services/mail/public-inbox.nix b/nixos/modules/services/mail/public-inbox.nix
new file mode 100644
index 00000000000..ab7ff5f726a
--- /dev/null
+++ b/nixos/modules/services/mail/public-inbox.nix
@@ -0,0 +1,577 @@
+{ lib, pkgs, config, ... }:
+
+with lib;
+
+let
+  cfg = config.services.public-inbox;
+  stateDir = "/var/lib/public-inbox";
+
+  gitIni = pkgs.formats.gitIni { listsAsDuplicateKeys = true; };
+  iniAtom = elemAt gitIni.type/*attrsOf*/.functor.wrapped/*attrsOf*/.functor.wrapped/*either*/.functor.wrapped 0;
+
+  useSpamAssassin = cfg.settings.publicinboxmda.spamcheck == "spamc" ||
+                    cfg.settings.publicinboxwatch.spamcheck == "spamc";
+
+  publicInboxDaemonOptions = proto: defaultPort: {
+    args = mkOption {
+      type = with types; listOf str;
+      default = [];
+      description = lib.mdDoc "Command-line arguments to pass to {manpage}`public-inbox-${proto}d(1)`.";
+    };
+    port = mkOption {
+      type = with types; nullOr (either str port);
+      default = defaultPort;
+      description = lib.mdDoc ''
+        Listening port.
+        Beware that public-inbox uses well-known ports number to decide whether to enable TLS or not.
+        Set to null and use `systemd.sockets.public-inbox-${proto}d.listenStreams`
+        if you need a more advanced listening.
+      '';
+    };
+    cert = mkOption {
+      type = with types; nullOr str;
+      default = null;
+      example = "/path/to/fullchain.pem";
+      description = lib.mdDoc "Path to TLS certificate to use for connections to {manpage}`public-inbox-${proto}d(1)`.";
+    };
+    key = mkOption {
+      type = with types; nullOr str;
+      default = null;
+      example = "/path/to/key.pem";
+      description = lib.mdDoc "Path to TLS key to use for connections to {manpage}`public-inbox-${proto}d(1)`.";
+    };
+  };
+
+  serviceConfig = srv:
+    let proto = removeSuffix "d" srv;
+        needNetwork = builtins.hasAttr proto cfg && cfg.${proto}.port == null;
+    in {
+    serviceConfig = {
+      # Enable JIT-compiled C (via Inline::C)
+      Environment = [ "PERL_INLINE_DIRECTORY=/run/public-inbox-${srv}/perl-inline" ];
+      # NonBlocking is REQUIRED to avoid a race condition
+      # if running simultaneous services.
+      NonBlocking = true;
+      #LimitNOFILE = 30000;
+      User = config.users.users."public-inbox".name;
+      Group = config.users.groups."public-inbox".name;
+      RuntimeDirectory = [
+          "public-inbox-${srv}/perl-inline"
+        ];
+      RuntimeDirectoryMode = "700";
+      # This is for BindPaths= and BindReadOnlyPaths=
+      # to allow traversal of directories they create inside RootDirectory=
+      UMask = "0066";
+      StateDirectory = ["public-inbox"];
+      StateDirectoryMode = "0750";
+      WorkingDirectory = stateDir;
+      BindReadOnlyPaths = [
+          "/etc"
+          "/run/systemd"
+          "${config.i18n.glibcLocales}"
+        ] ++
+        mapAttrsToList (name: inbox: inbox.description) cfg.inboxes ++
+        # Without confinement the whole Nix store
+        # is made available to the service
+        optionals (!config.systemd.services."public-inbox-${srv}".confinement.enable) [
+          "${pkgs.dash}/bin/dash:/bin/sh"
+          builtins.storeDir
+        ];
+      # The following options are only for optimizing:
+      # systemd-analyze security public-inbox-'*'
+      AmbientCapabilities = "";
+      CapabilityBoundingSet = "";
+      # ProtectClock= adds DeviceAllow=char-rtc r
+      DeviceAllow = "";
+      LockPersonality = true;
+      MemoryDenyWriteExecute = true;
+      NoNewPrivileges = true;
+      PrivateNetwork = mkDefault (!needNetwork);
+      ProcSubset = "pid";
+      ProtectClock = true;
+      ProtectHome = mkDefault true;
+      ProtectHostname = true;
+      ProtectKernelLogs = true;
+      ProtectProc = "invisible";
+      #ProtectSystem = "strict";
+      RemoveIPC = true;
+      RestrictAddressFamilies = [ "AF_UNIX" ] ++
+        optionals needNetwork [ "AF_INET" "AF_INET6" ];
+      RestrictNamespaces = true;
+      RestrictRealtime = true;
+      RestrictSUIDSGID = true;
+      SystemCallFilter = [
+        "@system-service"
+        "~@aio" "~@chown" "~@keyring" "~@memlock" "~@resources"
+        # Not removing @setuid and @privileged because Inline::C needs them.
+        # Not removing @timer because git upload-pack needs it.
+      ];
+      SystemCallArchitectures = "native";
+
+      # The following options are redundant when confinement is enabled
+      RootDirectory = "/var/empty";
+      TemporaryFileSystem = "/";
+      PrivateMounts = true;
+      MountAPIVFS = true;
+      PrivateDevices = true;
+      PrivateTmp = true;
+      PrivateUsers = true;
+      ProtectControlGroups = true;
+      ProtectKernelModules = true;
+      ProtectKernelTunables = true;
+    };
+    confinement = {
+      # Until we agree upon doing it directly here in NixOS
+      # https://github.com/NixOS/nixpkgs/pull/104457#issuecomment-1115768447
+      # let the user choose to enable the confinement with:
+      # systemd.services.public-inbox-httpd.confinement.enable = true;
+      # systemd.services.public-inbox-imapd.confinement.enable = true;
+      # systemd.services.public-inbox-init.confinement.enable = true;
+      # systemd.services.public-inbox-nntpd.confinement.enable = true;
+      #enable = true;
+      mode = "full-apivfs";
+      # Inline::C needs a /bin/sh, and dash is enough
+      binSh = "${pkgs.dash}/bin/dash";
+      packages = [
+          pkgs.iana-etc
+          (getLib pkgs.nss)
+          pkgs.tzdata
+        ];
+    };
+  };
+in
+
+{
+  options.services.public-inbox = {
+    enable = mkEnableOption (lib.mdDoc "the public-inbox mail archiver");
+    package = mkOption {
+      type = types.package;
+      default = pkgs.public-inbox;
+      defaultText = literalExpression "pkgs.public-inbox";
+      description = lib.mdDoc "public-inbox package to use.";
+    };
+    path = mkOption {
+      type = with types; listOf package;
+      default = [];
+      example = literalExpression "with pkgs; [ spamassassin ]";
+      description = lib.mdDoc ''
+        Additional packages to place in the path of public-inbox-mda,
+        public-inbox-watch, etc.
+      '';
+    };
+    inboxes = mkOption {
+      description = lib.mdDoc ''
+        Inboxes to configure, where attribute names are inbox names.
+      '';
+      default = {};
+      type = types.attrsOf (types.submodule ({name, ...}: {
+        freeformType = types.attrsOf iniAtom;
+        options.inboxdir = mkOption {
+          type = types.str;
+          default = "${stateDir}/inboxes/${name}";
+          description = lib.mdDoc "The absolute path to the directory which hosts the public-inbox.";
+        };
+        options.address = mkOption {
+          type = with types; listOf str;
+          example = "example-discuss@example.org";
+          description = lib.mdDoc "The email addresses of the public-inbox.";
+        };
+        options.url = mkOption {
+          type = with types; nullOr str;
+          default = null;
+          example = "https://example.org/lists/example-discuss";
+          description = lib.mdDoc "URL where this inbox can be accessed over HTTP.";
+        };
+        options.description = mkOption {
+          type = types.str;
+          example = "user/dev discussion of public-inbox itself";
+          description = lib.mdDoc "User-visible description for the repository.";
+          apply = pkgs.writeText "public-inbox-description-${name}";
+        };
+        options.newsgroup = mkOption {
+          type = with types; nullOr str;
+          default = null;
+          description = lib.mdDoc "NNTP group name for the inbox.";
+        };
+        options.watch = mkOption {
+          type = with types; listOf str;
+          default = [];
+          description = lib.mdDoc "Paths for {manpage}`public-inbox-watch(1)` to monitor for new mail.";
+          example = [ "maildir:/path/to/test.example.com.git" ];
+        };
+        options.watchheader = mkOption {
+          type = with types; nullOr str;
+          default = null;
+          example = "List-Id:<test@example.com>";
+          description = lib.mdDoc ''
+            If specified, {manpage}`public-inbox-watch(1)` will only process
+            mail containing a matching header.
+          '';
+        };
+        options.coderepo = mkOption {
+          type = (types.listOf (types.enum (attrNames cfg.settings.coderepo))) // {
+            description = "list of coderepo names";
+          };
+          default = [];
+          description = lib.mdDoc "Nicknames of a 'coderepo' section associated with the inbox.";
+        };
+      }));
+    };
+    imap = {
+      enable = mkEnableOption (lib.mdDoc "the public-inbox IMAP server");
+    } // publicInboxDaemonOptions "imap" 993;
+    http = {
+      enable = mkEnableOption (lib.mdDoc "the public-inbox HTTP server");
+      mounts = mkOption {
+        type = with types; listOf str;
+        default = [ "/" ];
+        example = [ "/lists/archives" ];
+        description = lib.mdDoc ''
+          Root paths or URLs that public-inbox will be served on.
+          If domain parts are present, only requests to those
+          domains will be accepted.
+        '';
+      };
+      args = (publicInboxDaemonOptions "http" 80).args;
+      port = mkOption {
+        type = with types; nullOr (either str port);
+        default = 80;
+        example = "/run/public-inbox-httpd.sock";
+        description = lib.mdDoc ''
+          Listening port or systemd's ListenStream= entry
+          to be used as a reverse proxy, eg. in nginx:
+          `locations."/inbox".proxyPass = "http://unix:''${config.services.public-inbox.http.port}:/inbox";`
+          Set to null and use `systemd.sockets.public-inbox-httpd.listenStreams`
+          if you need a more advanced listening.
+        '';
+      };
+    };
+    mda = {
+      enable = mkEnableOption (lib.mdDoc "the public-inbox Mail Delivery Agent");
+      args = mkOption {
+        type = with types; listOf str;
+        default = [];
+        description = lib.mdDoc "Command-line arguments to pass to {manpage}`public-inbox-mda(1)`.";
+      };
+    };
+    postfix.enable = mkEnableOption (lib.mdDoc "the integration into Postfix");
+    nntp = {
+      enable = mkEnableOption (lib.mdDoc "the public-inbox NNTP server");
+    } // publicInboxDaemonOptions "nntp" 563;
+    spamAssassinRules = mkOption {
+      type = with types; nullOr path;
+      default = "${cfg.package.sa_config}/user/.spamassassin/user_prefs";
+      defaultText = literalExpression "\${cfg.package.sa_config}/user/.spamassassin/user_prefs";
+      description = lib.mdDoc "SpamAssassin configuration specific to public-inbox.";
+    };
+    settings = mkOption {
+      description = lib.mdDoc ''
+        Settings for the [public-inbox config file](https://public-inbox.org/public-inbox-config.html).
+      '';
+      default = {};
+      type = types.submodule {
+        freeformType = gitIni.type;
+        options.publicinbox = mkOption {
+          default = {};
+          description = lib.mdDoc "public inboxes";
+          type = types.submodule {
+            freeformType = with types; /*inbox name*/attrsOf (/*inbox option name*/attrsOf /*inbox option value*/iniAtom);
+            options.css = mkOption {
+              type = with types; listOf str;
+              default = [];
+              description = lib.mdDoc "The local path name of a CSS file for the PSGI web interface.";
+            };
+            options.nntpserver = mkOption {
+              type = with types; listOf str;
+              default = [];
+              example = [ "nntp://news.public-inbox.org" "nntps://news.public-inbox.org" ];
+              description = lib.mdDoc "NNTP URLs to this public-inbox instance";
+            };
+            options.wwwlisting = mkOption {
+              type = with types; enum [ "all" "404" "match=domain" ];
+              default = "404";
+              description = lib.mdDoc ''
+                Controls which lists (if any) are listed for when the root
+                public-inbox URL is accessed over HTTP.
+              '';
+            };
+          };
+        };
+        options.publicinboxmda.spamcheck = mkOption {
+          type = with types; enum [ "spamc" "none" ];
+          default = "none";
+          description = lib.mdDoc ''
+            If set to spamc, {manpage}`public-inbox-watch(1)` will filter spam
+            using SpamAssassin.
+          '';
+        };
+        options.publicinboxwatch.spamcheck = mkOption {
+          type = with types; enum [ "spamc" "none" ];
+          default = "none";
+          description = lib.mdDoc ''
+            If set to spamc, {manpage}`public-inbox-watch(1)` will filter spam
+            using SpamAssassin.
+          '';
+        };
+        options.publicinboxwatch.watchspam = mkOption {
+          type = with types; nullOr str;
+          default = null;
+          example = "maildir:/path/to/spam";
+          description = lib.mdDoc ''
+            If set, mail in this maildir will be trained as spam and
+            deleted from all watched inboxes
+          '';
+        };
+        options.coderepo = mkOption {
+          default = {};
+          description = lib.mdDoc "code repositories";
+          type = types.attrsOf (types.submodule {
+            freeformType = types.attrsOf iniAtom;
+            options.cgitUrl = mkOption {
+              type = types.str;
+              description = lib.mdDoc "URL of a cgit instance";
+            };
+            options.dir = mkOption {
+              type = types.str;
+              description = lib.mdDoc "Path to a git repository";
+            };
+          });
+        };
+      };
+    };
+    openFirewall = mkEnableOption (lib.mdDoc "opening the firewall when using a port option");
+  };
+  config = mkIf cfg.enable {
+    assertions = [
+      { assertion = config.services.spamassassin.enable || !useSpamAssassin;
+        message = ''
+          public-inbox is configured to use SpamAssassin, but
+          services.spamassassin.enable is false.  If you don't need
+          spam checking, set `services.public-inbox.settings.publicinboxmda.spamcheck' and
+          `services.public-inbox.settings.publicinboxwatch.spamcheck' to null.
+        '';
+      }
+      { assertion = cfg.path != [] || !useSpamAssassin;
+        message = ''
+          public-inbox is configured to use SpamAssassin, but there is
+          no spamc executable in services.public-inbox.path.  If you
+          don't need spam checking, set
+          `services.public-inbox.settings.publicinboxmda.spamcheck' and
+          `services.public-inbox.settings.publicinboxwatch.spamcheck' to null.
+        '';
+      }
+    ];
+    services.public-inbox.settings =
+      filterAttrsRecursive (n: v: v != null) {
+        publicinbox = mapAttrs (n: filterAttrs (n: v: n != "description")) cfg.inboxes;
+    };
+    users = {
+      users.public-inbox = {
+        home = stateDir;
+        group = "public-inbox";
+        isSystemUser = true;
+      };
+      groups.public-inbox = {};
+    };
+    networking.firewall = mkIf cfg.openFirewall
+      { allowedTCPPorts = mkMerge
+        (map (proto: (mkIf (cfg.${proto}.enable && types.port.check cfg.${proto}.port) [ cfg.${proto}.port ]))
+        ["imap" "http" "nntp"]);
+      };
+    services.postfix = mkIf (cfg.postfix.enable && cfg.mda.enable) {
+      # Not sure limiting to 1 is necessary, but better safe than sorry.
+      config.public-inbox_destination_recipient_limit = "1";
+
+      # Register the addresses as existing
+      virtual =
+        concatStringsSep "\n" (mapAttrsToList (_: inbox:
+          concatMapStringsSep "\n" (address:
+            "${address} ${address}"
+          ) inbox.address
+        ) cfg.inboxes);
+
+      # Deliver the addresses with the public-inbox transport
+      transport =
+        concatStringsSep "\n" (mapAttrsToList (_: inbox:
+          concatMapStringsSep "\n" (address:
+            "${address} public-inbox:${address}"
+          ) inbox.address
+        ) cfg.inboxes);
+
+      # The public-inbox transport
+      masterConfig.public-inbox = {
+        type = "unix";
+        privileged = true; # Required for user=
+        command = "pipe";
+        args = [
+          "flags=X" # Report as a final delivery
+          "user=${with config.users; users."public-inbox".name + ":" + groups."public-inbox".name}"
+          # Specifying a nexthop when using the transport
+          # (eg. test public-inbox:test) allows to
+          # receive mails with an extension (eg. test+foo).
+          "argv=${pkgs.writeShellScript "public-inbox-transport" ''
+            export HOME="${stateDir}"
+            export ORIGINAL_RECIPIENT="''${2:-1}"
+            export PATH="${makeBinPath cfg.path}:$PATH"
+            exec ${cfg.package}/bin/public-inbox-mda ${escapeShellArgs cfg.mda.args}
+          ''} \${original_recipient} \${nexthop}"
+        ];
+      };
+    };
+    systemd.sockets = mkMerge (map (proto:
+      mkIf (cfg.${proto}.enable && cfg.${proto}.port != null)
+        { "public-inbox-${proto}d" = {
+            listenStreams = [ (toString cfg.${proto}.port) ];
+            wantedBy = [ "sockets.target" ];
+          };
+        }
+      ) [ "imap" "http" "nntp" ]);
+    systemd.services = mkMerge [
+      (mkIf cfg.imap.enable
+        { public-inbox-imapd = mkMerge [(serviceConfig "imapd") {
+          after = [ "public-inbox-init.service" "public-inbox-watch.service" ];
+          requires = [ "public-inbox-init.service" ];
+          serviceConfig = {
+            ExecStart = escapeShellArgs (
+              [ "${cfg.package}/bin/public-inbox-imapd" ] ++
+              cfg.imap.args ++
+              optionals (cfg.imap.cert != null) [ "--cert" cfg.imap.cert ] ++
+              optionals (cfg.imap.key != null) [ "--key" cfg.imap.key ]
+            );
+          };
+        }];
+      })
+      (mkIf cfg.http.enable
+        { public-inbox-httpd = mkMerge [(serviceConfig "httpd") {
+          after = [ "public-inbox-init.service" "public-inbox-watch.service" ];
+          requires = [ "public-inbox-init.service" ];
+          serviceConfig = {
+            ExecStart = escapeShellArgs (
+              [ "${cfg.package}/bin/public-inbox-httpd" ] ++
+              cfg.http.args ++
+              # See https://public-inbox.org/public-inbox.git/tree/examples/public-inbox.psgi
+              # for upstream's example.
+              [ (pkgs.writeText "public-inbox.psgi" ''
+                #!${cfg.package.fullperl} -w
+                use strict;
+                use warnings;
+                use Plack::Builder;
+                use PublicInbox::WWW;
+
+                my $www = PublicInbox::WWW->new;
+                $www->preload;
+
+                builder {
+                  # If reached through a reverse proxy,
+                  # make it transparent by resetting some HTTP headers
+                  # used by public-inbox to generate URIs.
+                  enable 'ReverseProxy';
+
+                  # No need to send a response body if it's an HTTP HEAD requests.
+                  enable 'Head';
+
+                  # Route according to configured domains and root paths.
+                  ${concatMapStrings (path: ''
+                  mount q(${path}) => sub { $www->call(@_); };
+                  '') cfg.http.mounts}
+                }
+              '') ]
+            );
+          };
+        }];
+      })
+      (mkIf cfg.nntp.enable
+        { public-inbox-nntpd = mkMerge [(serviceConfig "nntpd") {
+          after = [ "public-inbox-init.service" "public-inbox-watch.service" ];
+          requires = [ "public-inbox-init.service" ];
+          serviceConfig = {
+            ExecStart = escapeShellArgs (
+              [ "${cfg.package}/bin/public-inbox-nntpd" ] ++
+              cfg.nntp.args ++
+              optionals (cfg.nntp.cert != null) [ "--cert" cfg.nntp.cert ] ++
+              optionals (cfg.nntp.key != null) [ "--key" cfg.nntp.key ]
+            );
+          };
+        }];
+      })
+      (mkIf (any (inbox: inbox.watch != []) (attrValues cfg.inboxes)
+        || cfg.settings.publicinboxwatch.watchspam != null)
+        { public-inbox-watch = mkMerge [(serviceConfig "watch") {
+          inherit (cfg) path;
+          wants = [ "public-inbox-init.service" ];
+          requires = [ "public-inbox-init.service" ] ++
+            optional (cfg.settings.publicinboxwatch.spamcheck == "spamc") "spamassassin.service";
+          wantedBy = [ "multi-user.target" ];
+          serviceConfig = {
+            ExecStart = "${cfg.package}/bin/public-inbox-watch";
+            ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
+          };
+        }];
+      })
+      ({ public-inbox-init = let
+          PI_CONFIG = gitIni.generate "public-inbox.ini"
+            (filterAttrsRecursive (n: v: v != null) cfg.settings);
+          in mkMerge [(serviceConfig "init") {
+          wantedBy = [ "multi-user.target" ];
+          restartIfChanged = true;
+          restartTriggers = [ PI_CONFIG ];
+          script = ''
+            set -ux
+            install -D -p ${PI_CONFIG} ${stateDir}/.public-inbox/config
+            '' + optionalString useSpamAssassin ''
+              install -m 0700 -o spamd -d ${stateDir}/.spamassassin
+              ${optionalString (cfg.spamAssassinRules != null) ''
+                ln -sf ${cfg.spamAssassinRules} ${stateDir}/.spamassassin/user_prefs
+              ''}
+            '' + concatStrings (mapAttrsToList (name: inbox: ''
+              if [ ! -e ${stateDir}/inboxes/${escapeShellArg name} ]; then
+                # public-inbox-init creates an inbox and adds it to a config file.
+                # It tries to atomically write the config file by creating
+                # another file in the same directory, and renaming it.
+                # This has the sad consequence that we can't use
+                # /dev/null, or it would try to create a file in /dev.
+                conf_dir="$(mktemp -d)"
+
+                PI_CONFIG=$conf_dir/conf \
+                ${cfg.package}/bin/public-inbox-init -V2 \
+                  ${escapeShellArgs ([ name "${stateDir}/inboxes/${name}" inbox.url ] ++ inbox.address)}
+
+                rm -rf $conf_dir
+              fi
+
+              ln -sf ${inbox.description} \
+                ${stateDir}/inboxes/${escapeShellArg name}/description
+
+              export GIT_DIR=${stateDir}/inboxes/${escapeShellArg name}/all.git
+              if test -d "$GIT_DIR"; then
+                # Config is inherited by each epoch repository,
+                # so just needs to be set for all.git.
+                ${pkgs.git}/bin/git config core.sharedRepository 0640
+              fi
+            '') cfg.inboxes
+            ) + ''
+            shopt -s nullglob
+            for inbox in ${stateDir}/inboxes/*/; do
+              # This should be idempotent, but only do it for new
+              # inboxes anyway because it's only needed once, and could
+              # be slow for large pre-existing inboxes.
+              ls -1 "$inbox" | grep -q '^xap' ||
+              ${cfg.package}/bin/public-inbox-index "$inbox"
+            done
+          '';
+          serviceConfig = {
+            Type = "oneshot";
+            RemainAfterExit = true;
+            StateDirectory = [
+              "public-inbox/.public-inbox"
+              "public-inbox/.public-inbox/emergency"
+              "public-inbox/inboxes"
+            ];
+          };
+        }];
+      })
+    ];
+    environment.systemPackages = with pkgs; [ cfg.package ];
+  };
+  meta.maintainers = with lib.maintainers; [ julm qyliss ];
+}
diff --git a/nixos/modules/services/mail/roundcube.nix b/nixos/modules/services/mail/roundcube.nix
index 1dd393da882..d8adf53e48a 100644
--- a/nixos/modules/services/mail/roundcube.nix
+++ b/nixos/modules/services/mail/roundcube.nix
@@ -14,19 +14,19 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable roundcube.
 
         Also enables nginx virtual host management.
-        Further nginx configuration can be done by adapting <literal>services.nginx.virtualHosts.&lt;name&gt;</literal>.
-        See <xref linkend="opt-services.nginx.virtualHosts"/> for further information.
+        Further nginx configuration can be done by adapting `services.nginx.virtualHosts.<name>`.
+        See [](#opt-services.nginx.virtualHosts) for further information.
       '';
     };
 
     hostName = mkOption {
       type = types.str;
       example = "webmail.example.com";
-      description = "Hostname to use for the nginx vhost";
+      description = lib.mdDoc "Hostname to use for the nginx vhost";
     };
 
     package = mkOption {
@@ -38,7 +38,7 @@ in
         roundcube.withPlugins (plugins: [ plugins.persistent_login ])
       '';
 
-      description = ''
+      description = lib.mdDoc ''
         The package which contains roundcube's sources. Can be overriden to create
         an environment which contains roundcube and third-party plugins.
       '';
@@ -48,41 +48,41 @@ in
       username = mkOption {
         type = types.str;
         default = "roundcube";
-        description = ''
+        description = lib.mdDoc ''
           Username for the postgresql connection.
-          If <literal>database.host</literal> is set to <literal>localhost</literal>, a unix user and group of the same name will be created as well.
+          If `database.host` is set to `localhost`, a unix user and group of the same name will be created as well.
         '';
       };
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           Host of the postgresql server. If this is not set to
-          <literal>localhost</literal>, you have to create the
+          `localhost`, you have to create the
           postgresql user and database yourself, with appropriate
           permissions.
         '';
       };
       password = mkOption {
         type = types.str;
-        description = "Password for the postgresql connection. Do not use: the password will be stored world readable in the store; use <literal>passwordFile</literal> instead.";
+        description = lib.mdDoc "Password for the postgresql connection. Do not use: the password will be stored world readable in the store; use `passwordFile` instead.";
         default = "";
       };
       passwordFile = mkOption {
         type = types.str;
-        description = "Password file for the postgresql connection. Must be readable by user <literal>nginx</literal>. Ignored if <literal>database.host</literal> is set to <literal>localhost</literal>, as peer authentication will be used.";
+        description = lib.mdDoc "Password file for the postgresql connection. Must be readable by user `nginx`. Ignored if `database.host` is set to `localhost`, as peer authentication will be used.";
       };
       dbname = mkOption {
         type = types.str;
         default = "roundcube";
-        description = "Name of the postgresql database";
+        description = lib.mdDoc "Name of the postgresql database";
       };
     };
 
     plugins = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         List of roundcube plugins to enable. Currently, only those directly shipped with Roundcube are supported.
       '';
     };
@@ -91,7 +91,7 @@ in
       type = types.listOf types.package;
       default = [];
       example = literalExpression "with pkgs.aspellDicts; [ en fr de ]";
-      description = ''
+      description = lib.mdDoc ''
         List of aspell dictionnaries for spell checking. If empty, spell checking is disabled.
       '';
     };
@@ -99,11 +99,11 @@ in
     maxAttachmentSize = mkOption {
       type = types.int;
       default = 18;
-      description = ''
+      description = lib.mdDoc ''
         The maximum attachment size in MB.
 
         Note: Since roundcube only uses 70% of max upload values configured in php
-        30% is added automatically to <xref linkend="opt-services.roundcube.maxAttachmentSize"/>.
+        30% is added automatically to [](#opt-services.roundcube.maxAttachmentSize).
       '';
       apply = configuredMaxAttachmentSize: "${toString (configuredMaxAttachmentSize * 1.3)}M";
     };
@@ -111,7 +111,7 @@ in
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = "Extra configuration for roundcube webmail instance";
+      description = lib.mdDoc "Extra configuration for roundcube webmail instance";
     };
   };
 
diff --git a/nixos/modules/services/mail/rspamd.nix b/nixos/modules/services/mail/rspamd.nix
index a570e137a55..f9be9024dd4 100644
--- a/nixos/modules/services/mail/rspamd.nix
+++ b/nixos/modules/services/mail/rspamd.nix
@@ -13,24 +13,24 @@ let
       socket = mkOption {
         type = types.str;
         example = "localhost:11333";
-        description = ''
+        description = lib.mdDoc ''
           Socket for this worker to listen on in a format acceptable by rspamd.
         '';
       };
       mode = mkOption {
         type = types.str;
         default = "0644";
-        description = "Mode to set on unix socket";
+        description = lib.mdDoc "Mode to set on unix socket";
       };
       owner = mkOption {
         type = types.str;
         default = "${cfg.user}";
-        description = "Owner to set on unix socket";
+        description = lib.mdDoc "Owner to set on unix socket";
       };
       group = mkOption {
         type = types.str;
         default = "${cfg.group}";
-        description = "Group to set on unix socket";
+        description = lib.mdDoc "Group to set on unix socket";
       };
       rawEntry = mkOption {
         type = types.str;
@@ -52,21 +52,21 @@ let
       enable = mkOption {
         type = types.nullOr types.bool;
         default = null;
-        description = "Whether to run the rspamd worker.";
+        description = lib.mdDoc "Whether to run the rspamd worker.";
       };
       name = mkOption {
         type = types.nullOr types.str;
         default = name;
-        description = "Name of the worker";
+        description = lib.mdDoc "Name of the worker";
       };
       type = mkOption {
         type = types.nullOr (types.enum [
           "normal" "controller" "fuzzy" "rspamd_proxy" "lua" "proxy"
         ]);
-        description = ''
-          The type of this worker. The type <literal>proxy</literal> is
+        description = lib.mdDoc ''
+          The type of this worker. The type `proxy` is
           deprecated and only kept for backwards compatibility and should be
-          replaced with <literal>rspamd_proxy</literal>.
+          replaced with `rspamd_proxy`.
         '';
         apply = let
             from = "services.rspamd.workers.\"${name}\".type";
@@ -77,7 +77,7 @@ let
       bindSockets = mkOption {
         type = types.listOf (types.either types.str (types.submodule bindSocketOpts));
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of sockets to listen, in format acceptable by rspamd
         '';
         example = [{
@@ -94,21 +94,21 @@ let
       count = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Number of worker instances to run
         '';
       };
       includes = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of files to include in configuration
         '';
       };
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Additional entries to put verbatim into worker section of rspamd config file.";
+        description = lib.mdDoc "Additional entries to put verbatim into worker section of rspamd config file.";
       };
     };
     config = mkIf (name == "normal" || name == "controller" || name == "fuzzy" || name == "rspamd_proxy") {
@@ -186,7 +186,7 @@ let
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether this file ${prefix} should be generated.  This
           option allows specific ${prefix} files to be disabled.
         '';
@@ -195,12 +195,12 @@ let
       text = mkOption {
         default = null;
         type = types.nullOr types.lines;
-        description = "Text of the file.";
+        description = lib.mdDoc "Text of the file.";
       };
 
       source = mkOption {
         type = types.path;
-        description = "Path of the source file.";
+        description = lib.mdDoc "Path of the source file.";
       };
     };
     config = {
@@ -227,19 +227,19 @@ in
 
     services.rspamd = {
 
-      enable = mkEnableOption "rspamd, the Rapid spam filtering system";
+      enable = mkEnableOption (lib.mdDoc "rspamd, the Rapid spam filtering system");
 
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to run the rspamd daemon in debug mode.";
+        description = lib.mdDoc "Whether to run the rspamd daemon in debug mode.";
       };
 
       locals = mkOption {
         type = with types; attrsOf (submodule (configFileModule "locals"));
         default = {};
-        description = ''
-          Local configuration files, written into <filename>/etc/rspamd/local.d/{name}</filename>.
+        description = lib.mdDoc ''
+          Local configuration files, written into {file}`/etc/rspamd/local.d/{name}`.
         '';
         example = literalExpression ''
           { "redis.conf".source = "/nix/store/.../etc/dir/redis.conf";
@@ -251,8 +251,8 @@ in
       overrides = mkOption {
         type = with types; attrsOf (submodule (configFileModule "overrides"));
         default = {};
-        description = ''
-          Overridden configuration files, written into <filename>/etc/rspamd/override.d/{name}</filename>.
+        description = lib.mdDoc ''
+          Overridden configuration files, written into {file}`/etc/rspamd/override.d/{name}`.
         '';
         example = literalExpression ''
           { "redis.conf".source = "/nix/store/.../etc/dir/redis.conf";
@@ -264,15 +264,15 @@ in
       localLuaRules = mkOption {
         default = null;
         type = types.nullOr types.path;
-        description = ''
-          Path of file to link to <filename>/etc/rspamd/rspamd.local.lua</filename> for local
+        description = lib.mdDoc ''
+          Path of file to link to {file}`/etc/rspamd/rspamd.local.lua` for local
           rules written in Lua
         '';
       };
 
       workers = mkOption {
         type = with types; attrsOf (submodule workerOpts);
-        description = ''
+        description = lib.mdDoc ''
           Attribute set of workers to start.
         '';
         default = {
@@ -301,7 +301,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to add at the end of the rspamd configuration
           file.
         '';
@@ -310,7 +310,7 @@ in
       user = mkOption {
         type = types.str;
         default = "rspamd";
-        description = ''
+        description = lib.mdDoc ''
           User to use when no root privileges are required.
         '';
       };
@@ -318,7 +318,7 @@ in
       group = mkOption {
         type = types.str;
         default = "rspamd";
-        description = ''
+        description = lib.mdDoc ''
           Group to use when no root privileges are required.
         '';
       };
@@ -327,12 +327,12 @@ in
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = "Add rspamd milter to postfix main.conf";
+          description = lib.mdDoc "Add rspamd milter to postfix main.conf";
         };
 
         config = mkOption {
           type = with types; attrsOf (oneOf [ bool str (listOf str) ]);
-          description = ''
+          description = lib.mdDoc ''
             Addon to postfix configuration
           '';
           default = {
diff --git a/nixos/modules/services/mail/rss2email.nix b/nixos/modules/services/mail/rss2email.nix
index 7f8d2adac64..54404c5b5f4 100644
--- a/nixos/modules/services/mail/rss2email.nix
+++ b/nixos/modules/services/mail/rss2email.nix
@@ -15,57 +15,57 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable rss2email.";
+        description = lib.mdDoc "Whether to enable rss2email.";
       };
 
       to = mkOption {
         type = types.str;
-        description = "Mail address to which to send emails";
+        description = lib.mdDoc "Mail address to which to send emails";
       };
 
       interval = mkOption {
         type = types.str;
         default = "12h";
-        description = "How often to check the feeds, in systemd interval format";
+        description = lib.mdDoc "How often to check the feeds, in systemd interval format";
       };
 
       config = mkOption {
         type = with types; attrsOf (oneOf [ str int bool ]);
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           The configuration to give rss2email.
 
-          Default will use system-wide <literal>sendmail</literal> to send the
+          Default will use system-wide `sendmail` to send the
           email. This is rss2email's default when running
-          <literal>r2e new</literal>.
+          `r2e new`.
 
           This set contains key-value associations that will be set in the
-          <literal>[DEFAULT]</literal> block along with the
-          <literal>to</literal> parameter.
+          `[DEFAULT]` block along with the
+          `to` parameter.
 
-          See <literal>man r2e</literal> for more information on which
+          See `man r2e` for more information on which
           parameters are accepted.
         '';
       };
 
       feeds = mkOption {
-        description = "The feeds to watch.";
+        description = lib.mdDoc "The feeds to watch.";
         type = types.attrsOf (types.submodule {
           options = {
             url = mkOption {
               type = types.str;
-              description = "The URL at which to fetch the feed.";
+              description = lib.mdDoc "The URL at which to fetch the feed.";
             };
 
             to = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Email address to which to send feed items.
 
-                If <literal>null</literal>, this will not be set in the
+                If `null`, this will not be set in the
                 configuration file, and rss2email will make it default to
-                <literal>rss2email.to</literal>.
+                `rss2email.to`.
               '';
             };
           };
@@ -110,7 +110,6 @@ in {
     in
     {
       preStart = ''
-        cp ${conf} /var/rss2email/conf.cfg
         if [ ! -f /var/rss2email/db.json ]; then
           echo '{"version":2,"feeds":[]}' > /var/rss2email/db.json
         fi
@@ -118,7 +117,7 @@ in {
       path = [ pkgs.system-sendmail ];
       serviceConfig = {
         ExecStart =
-          "${pkgs.rss2email}/bin/r2e -c /var/rss2email/conf.cfg -d /var/rss2email/db.json run";
+          "${pkgs.rss2email}/bin/r2e -c ${conf} -d /var/rss2email/db.json run";
         User = "rss2email";
       };
     };
diff --git a/nixos/modules/services/mail/schleuder.nix b/nixos/modules/services/mail/schleuder.nix
new file mode 100644
index 00000000000..2991418dd80
--- /dev/null
+++ b/nixos/modules/services/mail/schleuder.nix
@@ -0,0 +1,162 @@
+{ config, pkgs, lib, ... }:
+let
+  cfg = config.services.schleuder;
+  settingsFormat = pkgs.formats.yaml { };
+  postfixMap = entries: lib.concatStringsSep "\n" (lib.mapAttrsToList (name: value: "${name} ${value}") entries);
+  writePostfixMap = name: entries: pkgs.writeText name (postfixMap entries);
+  configScript = pkgs.writeScript "schleuder-cfg" ''
+    #!${pkgs.runtimeShell}
+    set -exuo pipefail
+    umask 0077
+    ${pkgs.yq}/bin/yq \
+      --slurpfile overrides <(${pkgs.yq}/bin/yq . <${lib.escapeShellArg cfg.extraSettingsFile}) \
+      < ${settingsFormat.generate "schleuder.yml" cfg.settings} \
+      '. * $overrides[0]' \
+      > /etc/schleuder/schleuder.yml
+    chown schleuder: /etc/schleuder/schleuder.yml
+  '';
+in
+{
+  options.services.schleuder = {
+    enable = lib.mkEnableOption (lib.mdDoc "Schleuder secure remailer");
+    enablePostfix = lib.mkEnableOption (lib.mdDoc "automatic postfix integration") // { default = true; };
+    lists = lib.mkOption {
+      description = lib.mdDoc ''
+        List of list addresses that should be handled by Schleuder.
+
+        Note that this is only handled by the postfix integration, and
+        the setup of the lists, their members and their keys has to be
+        performed separately via schleuder's API, using a tool such as
+        schleuder-cli.
+      '';
+      type = lib.types.listOf lib.types.str;
+      default = [ ];
+      example = [ "widget-team@example.com" "security@example.com" ];
+    };
+    /* maybe one day....
+      domains = lib.mkOption {
+      description = "Domains for which all mail should be handled by Schleuder.";
+      type = lib.types.listOf lib.types.str;
+      default = [];
+      example = ["securelists.example.com"];
+      };
+    */
+    settings = lib.mkOption {
+      description = lib.mdDoc ''
+        Settings for schleuder.yml.
+
+        Check the [example configuration](https://0xacab.org/schleuder/schleuder/blob/master/etc/schleuder.yml) for possible values.
+      '';
+      type = lib.types.submodule {
+        freeformType = settingsFormat.type;
+        options.keyserver = lib.mkOption {
+          type = lib.types.str;
+          description = lib.mdDoc ''
+            Key server from which to fetch and update keys.
+
+            Note that NixOS uses a different default from upstream, since the upstream default sks-keyservers.net is deprecated.
+          '';
+          default = "keys.openpgp.org";
+        };
+      };
+      default = { };
+    };
+    extraSettingsFile = lib.mkOption {
+      description = lib.mdDoc "YAML file to merge into the schleuder config at runtime. This can be used for secrets such as API keys.";
+      type = lib.types.nullOr lib.types.path;
+      default = null;
+    };
+    listDefaults = lib.mkOption {
+      description = lib.mdDoc ''
+        Default settings for lists (list-defaults.yml).
+
+        Check the [example configuration](https://0xacab.org/schleuder/schleuder/-/blob/master/etc/list-defaults.yml) for possible values.
+      '';
+      type = settingsFormat.type;
+      default = { };
+    };
+  };
+  config = lib.mkIf cfg.enable {
+    assertions = [
+      {
+        assertion = !(cfg.settings.api ? valid_api_keys);
+        message = ''
+          services.schleuder.settings.api.valid_api_keys is set. Defining API keys via NixOS config results in them being copied to the world-readable Nix store. Please use the extraSettingsFile option to store API keys in a non-public location.
+        '';
+      }
+      {
+        assertion = !(lib.any (db: db ? password) (lib.attrValues cfg.settings.database or {}));
+        message = ''
+          A password is defined for at least one database in services.schleuder.settings.database. Defining passwords via NixOS config results in them being copied to the world-readable Nix store. Please use the extraSettingsFile option to store database passwords in a non-public location.
+        '';
+      }
+    ];
+    users.users.schleuder.isSystemUser = true;
+    users.users.schleuder.group = "schleuder";
+    users.groups.schleuder = {};
+    environment.systemPackages = [
+      pkgs.schleuder-cli
+    ];
+    services.postfix = lib.mkIf cfg.enablePostfix {
+      extraMasterConf = ''
+        schleuder  unix  -       n       n       -       -       pipe
+          flags=DRhu user=schleuder argv=/${pkgs.schleuder}/bin/schleuder work ''${recipient}
+      '';
+      transport = lib.mkIf (cfg.lists != [ ]) (postfixMap (lib.genAttrs cfg.lists (_: "schleuder:")));
+      extraConfig = ''
+        schleuder_destination_recipient_limit = 1
+      '';
+      # review: does this make sense?
+      localRecipients = lib.mkIf (cfg.lists != [ ]) cfg.lists;
+    };
+    systemd.services = let commonServiceConfig = {
+      # We would have liked to use DynamicUser, but since the default
+      # database is SQLite and lives in StateDirectory, and that same
+      # database needs to be readable from the postfix service, this
+      # isn't trivial to do.
+      User = "schleuder";
+      StateDirectory = "schleuder";
+      StateDirectoryMode = "0700";
+    }; in
+      {
+        schleuder-init = {
+          serviceConfig = commonServiceConfig // {
+            ExecStartPre = lib.mkIf (cfg.extraSettingsFile != null) [
+              "+${configScript}"
+            ];
+            ExecStart = [ "${pkgs.schleuder}/bin/schleuder install" ];
+            Type = "oneshot";
+          };
+        };
+        schleuder-api-daemon = {
+          after = [ "local-fs.target" "network.target" "schleuder-init.service" ];
+          wantedBy = [ "multi-user.target" ];
+          requires = [ "schleuder-init.service" ];
+          serviceConfig = commonServiceConfig // {
+            ExecStart = [ "${pkgs.schleuder}/bin/schleuder-api-daemon" ];
+          };
+        };
+        schleuder-weekly-key-maintenance = {
+          after = [ "local-fs.target" "network.target" ];
+          startAt = "weekly";
+          serviceConfig = commonServiceConfig // {
+            ExecStart = [
+              "${pkgs.schleuder}/bin/schleuder refresh_keys"
+              "${pkgs.schleuder}/bin/schleuder check_keys"
+            ];
+          };
+        };
+      };
+
+    environment.etc."schleuder/schleuder.yml" = lib.mkIf (cfg.extraSettingsFile == null) {
+      source = settingsFormat.generate "schleuder.yml" cfg.settings;
+    };
+    environment.etc."schleuder/list-defaults.yml".source = settingsFormat.generate "list-defaults.yml" cfg.listDefaults;
+
+    services.schleuder = {
+      #lists_dir = "/var/lib/schleuder.lists";
+      settings.filters_dir = lib.mkDefault "/var/lib/schleuder/filters";
+      settings.keyword_handlers_dir = lib.mkDefault "/var/lib/schleuder/keyword_handlers";
+    };
+  };
+}
diff --git a/nixos/modules/services/mail/spamassassin.nix b/nixos/modules/services/mail/spamassassin.nix
index ac878222b26..49d1d931598 100644
--- a/nixos/modules/services/mail/spamassassin.nix
+++ b/nixos/modules/services/mail/spamassassin.nix
@@ -12,33 +12,36 @@ in
   options = {
 
     services.spamassassin = {
-      enable = mkEnableOption "the SpamAssassin daemon";
+      enable = mkEnableOption (lib.mdDoc "the SpamAssassin daemon");
 
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to run the SpamAssassin daemon in debug mode";
+        description = lib.mdDoc "Whether to run the SpamAssassin daemon in debug mode";
       };
 
       config = mkOption {
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           The SpamAssassin local.cf config
 
           If you are using this configuration:
-            add_header all Status _YESNO_, score=_SCORE_ required=_REQD_ tests=_TESTS_ autolearn=_AUTOLEARN_ version=_VERSION_
+
+              add_header all Status _YESNO_, score=_SCORE_ required=_REQD_ tests=_TESTS_ autolearn=_AUTOLEARN_ version=_VERSION_
 
           Then you can Use this sieve filter:
-            require ["fileinto", "reject", "envelope"];
 
-            if header :contains "X-Spam-Flag" "YES" {
-              fileinto "spam";
-            }
+              require ["fileinto", "reject", "envelope"];
+
+              if header :contains "X-Spam-Flag" "YES" {
+                fileinto "spam";
+              }
 
           Or this procmail filter:
-            :0:
-            * ^X-Spam-Flag: YES
-            /var/vpopmail/domains/lastlog.de/js/.maildir/.spam/new
+
+              :0:
+              * ^X-Spam-Flag: YES
+              /var/vpopmail/domains/lastlog.de/js/.maildir/.spam/new
 
           To filter your messages based on the additional mail headers added by spamassassin.
         '';
@@ -54,7 +57,7 @@ in
 
       initPreConf = mkOption {
         type = with types; either str path;
-        description = "The SpamAssassin init.pre config.";
+        description = lib.mdDoc "The SpamAssassin init.pre config.";
         apply = val: if builtins.isPath val then val else pkgs.writeText "init.pre" val;
         default =
         ''
@@ -135,7 +138,7 @@ in
         User = "spamd";
         Group = "spamd";
         StateDirectory = "spamassassin";
-        ExecStartPost = "+${pkgs.systemd}/bin/systemctl -q --no-block try-reload-or-restart spamd.service";
+        ExecStartPost = "+${config.systemd.package}/bin/systemctl -q --no-block try-reload-or-restart spamd.service";
       };
 
       script = ''
diff --git a/nixos/modules/services/mail/sympa.nix b/nixos/modules/services/mail/sympa.nix
index f3578bef96e..7a5047b2bea 100644
--- a/nixos/modules/services/mail/sympa.nix
+++ b/nixos/modules/services/mail/sympa.nix
@@ -80,15 +80,15 @@ in
   ###### interface
   options.services.sympa = with types; {
 
-    enable = mkEnableOption "Sympa mailing list manager";
+    enable = mkEnableOption (lib.mdDoc "Sympa mailing list manager");
 
     lang = mkOption {
       type = str;
       default = "en_US";
       example = "cs";
-      description = ''
+      description = lib.mdDoc ''
         Default Sympa language.
-        See <link xlink:href='https://github.com/sympa-community/sympa/tree/sympa-6.2/po/sympa' />
+        See <https://github.com/sympa-community/sympa/tree/sympa-6.2/po/sympa>
         for available options.
       '';
     };
@@ -96,7 +96,7 @@ in
     listMasters = mkOption {
       type = listOf str;
       example = [ "postmaster@sympa.example.org" ];
-      description = ''
+      description = lib.mdDoc ''
         The list of the email addresses of the listmasters
         (users authorized to perform global server commands).
       '';
@@ -106,9 +106,9 @@ in
       type = nullOr str;
       default = null;
       example = "lists.example.org";
-      description = ''
-        Main domain to be used in <filename>sympa.conf</filename>.
-        If <literal>null</literal>, one of the <option>services.sympa.domains</option> is chosen for you.
+      description = lib.mdDoc ''
+        Main domain to be used in {file}`sympa.conf`.
+        If `null`, one of the {option}`services.sympa.domains` is chosen for you.
       '';
     };
 
@@ -119,8 +119,8 @@ in
             type = nullOr str;
             default = null;
             example = "archive.example.org";
-            description = ''
-              Domain part of the web interface URL (no web interface for this domain if <literal>null</literal>).
+            description = lib.mdDoc ''
+              Domain part of the web interface URL (no web interface for this domain if `null`).
               DNS record of type A (or AAAA or CNAME) has to exist with this value.
             '';
           };
@@ -128,7 +128,7 @@ in
             type = str;
             default = "/";
             example = "/sympa";
-            description = "URL path part of the web interface.";
+            description = lib.mdDoc "URL path part of the web interface.";
           };
           settings = mkOption {
             type = attrsOf (oneOf [ str int bool ]);
@@ -136,9 +136,9 @@ in
             example = {
               default_max_list_members = 3;
             };
-            description = ''
-              The <filename>robot.conf</filename> configuration file as key value set.
-              See <link xlink:href='https://sympa-community.github.io/gpldoc/man/sympa.conf.5.html' />
+            description = lib.mdDoc ''
+              The {file}`robot.conf` configuration file as key value set.
+              See <https://sympa-community.github.io/gpldoc/man/sympa.conf.5.html>
               for list of configuration parameters.
             '';
           };
@@ -149,7 +149,7 @@ in
         };
       }));
 
-      description = ''
+      description = lib.mdDoc ''
         Email domains handled by this instance. There have
         to be MX records for keys of this attribute set.
       '';
@@ -172,36 +172,36 @@ in
         type = enum [ "SQLite" "PostgreSQL" "MySQL" ];
         default = "SQLite";
         example = "MySQL";
-        description = "Database engine to use.";
+        description = lib.mdDoc "Database engine to use.";
       };
 
       host = mkOption {
         type = nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Database host address.
 
-          For MySQL, use <literal>localhost</literal> to connect using Unix domain socket.
+          For MySQL, use `localhost` to connect using Unix domain socket.
 
-          For PostgreSQL, use path to directory (e.g. <filename>/run/postgresql</filename>)
+          For PostgreSQL, use path to directory (e.g. {file}`/run/postgresql`)
           to connect using Unix domain socket located in this directory.
 
-          Use <literal>null</literal> to fall back on Sympa default, or when using
-          <option>services.sympa.database.createLocally</option>.
+          Use `null` to fall back on Sympa default, or when using
+          {option}`services.sympa.database.createLocally`.
         '';
       };
 
       port = mkOption {
         type = nullOr port;
         default = null;
-        description = "Database port. Use <literal>null</literal> for default port.";
+        description = lib.mdDoc "Database port. Use `null` for default port.";
       };
 
       name = mkOption {
         type = str;
         default = if cfg.database.type == "SQLite" then "${dataDir}/sympa.sqlite" else "sympa";
         defaultText = literalExpression ''if database.type == "SQLite" then "${dataDir}/sympa.sqlite" else "sympa"'';
-        description = ''
+        description = lib.mdDoc ''
           Database name. When using SQLite this must be an absolute
           path to the database file.
         '';
@@ -210,22 +210,22 @@ in
       user = mkOption {
         type = nullOr str;
         default = user;
-        description = "Database user. The system user name is used as a default.";
+        description = lib.mdDoc "Database user. The system user name is used as a default.";
       };
 
       passwordFile = mkOption {
         type = nullOr path;
         default = null;
         example = "/run/keys/sympa-dbpassword";
-        description = ''
-          A file containing the password for <option>services.sympa.database.user</option>.
+        description = lib.mdDoc ''
+          A file containing the password for {option}`services.sympa.database.user`.
         '';
       };
 
       createLocally = mkOption {
         type = bool;
         default = true;
-        description = "Whether to create a local database automatically.";
+        description = lib.mdDoc "Whether to create a local database automatically.";
       };
     };
 
@@ -233,23 +233,23 @@ in
       enable = mkOption {
         type = bool;
         default = true;
-        description = "Whether to enable Sympa web interface.";
+        description = lib.mdDoc "Whether to enable Sympa web interface.";
       };
 
       server = mkOption {
         type = enum [ "nginx" "none" ];
         default = "nginx";
-        description = ''
+        description = lib.mdDoc ''
           The webserver used for the Sympa web interface. Set it to `none` if you want to configure it yourself.
           Further nginx configuration can be done by adapting
-          <option>services.nginx.virtualHosts.<replaceable>name</replaceable></option>.
+          {option}`services.nginx.virtualHosts.«name»`.
         '';
       };
 
       https = mkOption {
         type = bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use HTTPS. When nginx integration is enabled, this option forces SSL and enables ACME.
           Please note that Sympa web interface always uses https links even when this option is disabled.
         '';
@@ -258,7 +258,7 @@ in
       fcgiProcs = mkOption {
         type = ints.positive;
         default = 2;
-        description = "Number of FastCGI processes to fork.";
+        description = lib.mdDoc "Number of FastCGI processes to fork.";
       };
     };
 
@@ -266,12 +266,12 @@ in
       type = mkOption {
         type = enum [ "postfix" "none" ];
         default = "postfix";
-        description = ''
-          Mail transfer agent (MTA) integration. Use <literal>none</literal> if you want to configure it yourself.
+        description = lib.mdDoc ''
+          Mail transfer agent (MTA) integration. Use `none` if you want to configure it yourself.
 
-          The <literal>postfix</literal> integration sets up local Postfix instance that will pass incoming
+          The `postfix` integration sets up local Postfix instance that will pass incoming
           messages from configured domains to Sympa. You still need to configure at least outgoing message
-          handling using e.g. <option>services.postfix.relayHost</option>.
+          handling using e.g. {option}`services.postfix.relayHost`.
         '';
       };
     };
@@ -285,9 +285,9 @@ in
           viewlogs_page_size = 50;
         }
       '';
-      description = ''
-        The <filename>sympa.conf</filename> configuration file as key value set.
-        See <link xlink:href='https://sympa-community.github.io/gpldoc/man/sympa.conf.5.html' />
+      description = lib.mdDoc ''
+        The {file}`sympa.conf` configuration file as key value set.
+        See <https://sympa-community.github.io/gpldoc/man/sympa.conf.5.html>
         for list of configuration parameters.
       '';
     };
@@ -298,16 +298,16 @@ in
           enable = mkOption {
             type = bool;
             default = true;
-            description = "Whether this file should be generated. This option allows specific files to be disabled.";
+            description = lib.mdDoc "Whether this file should be generated. This option allows specific files to be disabled.";
           };
           text = mkOption {
             default = null;
             type = nullOr lines;
-            description = "Text of the file.";
+            description = lib.mdDoc "Text of the file.";
           };
           source = mkOption {
             type = path;
-            description = "Path of the source file.";
+            description = lib.mdDoc "Path of the source file.";
           };
         };
 
@@ -321,7 +321,7 @@ in
           };
         }
       '';
-      description = "Set of files to be linked in <filename>${dataDir}</filename>.";
+      description = lib.mdDoc "Set of files to be linked in {file}`${dataDir}`.";
     };
   };
 
diff --git a/nixos/modules/services/misc/matrix-appservice-discord.nix b/nixos/modules/services/matrix/appservice-discord.nix
index 8a8c7f41e3c..15f0f0cc0cd 100644
--- a/nixos/modules/services/misc/matrix-appservice-discord.nix
+++ b/nixos/modules/services/matrix/appservice-discord.nix
@@ -14,7 +14,7 @@ let
 in {
   options = {
     services.matrix-appservice-discord = {
-      enable = mkEnableOption "a bridge between Matrix and Discord";
+      enable = mkEnableOption (lib.mdDoc "a bridge between Matrix and Discord");
 
       settings = mkOption rec {
         # TODO: switch to types.config.json as prescribed by RFC42 once it's implemented
@@ -40,23 +40,16 @@ in {
             };
           }
         '';
-        description = ''
-          <filename>config.yaml</filename> configuration as a Nix attribute set.
-          </para>
+        description = lib.mdDoc ''
+          {file}`config.yaml` configuration as a Nix attribute set.
 
-          <para>
           Configuration options should match those described in
-          <link xlink:href="https://github.com/Half-Shot/matrix-appservice-discord/blob/master/config/config.sample.yaml">
-          config.sample.yaml</link>.
-          </para>
+          [config.sample.yaml](https://github.com/Half-Shot/matrix-appservice-discord/blob/master/config/config.sample.yaml).
 
-          <para>
-          <option>config.bridge.domain</option> and <option>config.bridge.homeserverUrl</option>
+          {option}`config.bridge.domain` and {option}`config.bridge.homeserverUrl`
           should be set to match the public host name of the Matrix homeserver for webhooks and avatars to work.
-          </para>
 
-          <para>
-          Secret tokens should be specified using <option>environmentFile</option>
+          Secret tokens should be specified using {option}`environmentFile`
           instead of this world-readable attribute set.
         '';
       };
@@ -64,11 +57,11 @@ in {
       environmentFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           File containing environment variables to be passed to the matrix-appservice-discord service,
           in which secret tokens can be specified securely by defining values for
-          <literal>APPSERVICE_DISCORD_AUTH_CLIENT_I_D</literal> and
-          <literal>APPSERVICE_DISCORD_AUTH_BOT_TOKEN</literal>.
+          `APPSERVICE_DISCORD_AUTH_CLIENT_I_D` and
+          `APPSERVICE_DISCORD_AUTH_BOT_TOKEN`.
         '';
       };
 
@@ -76,7 +69,7 @@ in {
         type = types.str;
         default = "http://localhost:${toString cfg.port}";
         defaultText = literalExpression ''"http://localhost:''${toString config.${opt.port}}"'';
-        description = ''
+        description = lib.mdDoc ''
           The URL where the application service is listening for HS requests.
         '';
       };
@@ -84,7 +77,7 @@ in {
       port = mkOption {
         type = types.port;
         default = 9005; # from https://github.com/Half-Shot/matrix-appservice-discord/blob/master/package.json#L11
-        description = ''
+        description = lib.mdDoc ''
           Port number on which the bridge should listen for internal communication with the Matrix homeserver.
         '';
       };
@@ -92,7 +85,7 @@ in {
       localpart = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The user_id localpart to assign to the AS.
         '';
       };
@@ -103,7 +96,7 @@ in {
         defaultText = literalExpression ''
           optional config.services.matrix-synapse.enable "matrix-synapse.service"
         '';
-        description = ''
+        description = lib.mdDoc ''
           List of Systemd services to require and wait for when starting the application service,
           such as the Matrix homeserver if it's running on the same host.
         '';
@@ -144,7 +137,7 @@ in {
         PrivateTmp = true;
         WorkingDirectory = appDir;
         StateDirectory = baseNameOf dataDir;
-        UMask = 0027;
+        UMask = "0027";
         EnvironmentFile = cfg.environmentFile;
 
         ExecStart = ''
diff --git a/nixos/modules/services/misc/matrix-appservice-irc.nix b/nixos/modules/services/matrix/appservice-irc.nix
index b041c9c82c5..388553d4182 100644
--- a/nixos/modules/services/misc/matrix-appservice-irc.nix
+++ b/nixos/modules/services/matrix/appservice-irc.nix
@@ -28,30 +28,30 @@ let
   registrationFile = "/var/lib/matrix-appservice-irc/registration.yml";
 in {
   options.services.matrix-appservice-irc = with types; {
-    enable = mkEnableOption "the Matrix/IRC bridge";
+    enable = mkEnableOption (lib.mdDoc "the Matrix/IRC bridge");
 
     port = mkOption {
       type = port;
-      description = "The port to listen on";
+      description = lib.mdDoc "The port to listen on";
       default = 8009;
     };
 
     needBindingCap = mkOption {
       type = bool;
-      description = "Whether the daemon needs to bind to ports below 1024 (e.g. for the ident service)";
+      description = lib.mdDoc "Whether the daemon needs to bind to ports below 1024 (e.g. for the ident service)";
       default = false;
     };
 
     passwordEncryptionKeyLength = mkOption {
       type = ints.unsigned;
-      description = "Length of the key to encrypt IRC passwords with";
+      description = lib.mdDoc "Length of the key to encrypt IRC passwords with";
       default = 4096;
       example = 8192;
     };
 
     registrationUrl = mkOption {
       type = str;
-      description = ''
+      description = lib.mdDoc ''
         The URL where the application service is listening for homeserver requests,
         from the Matrix homeserver perspective.
       '';
@@ -60,14 +60,14 @@ in {
 
     localpart = mkOption {
       type = str;
-      description = "The user_id localpart to assign to the appservice";
+      description = lib.mdDoc "The user_id localpart to assign to the appservice";
       default = "appservice-irc";
     };
 
     settings = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Configuration for the appservice, see
-        <link xlink:href="https://github.com/matrix-org/matrix-appservice-irc/blob/${pkgs.matrix-appservice-irc.version}/config.sample.yaml"/>
+        <https://github.com/matrix-org/matrix-appservice-irc/blob/${pkgs.matrix-appservice-irc.version}/config.sample.yaml>
         for supported values
       '';
       default = {};
@@ -76,7 +76,7 @@ in {
 
         options = {
           homeserver = mkOption {
-            description = "Homeserver configuration";
+            description = lib.mdDoc "Homeserver configuration";
             default = {};
             type = submodule {
               freeformType = jsonType;
@@ -84,12 +84,12 @@ in {
               options = {
                 url = mkOption {
                   type = str;
-                  description = "The URL to the home server for client-server API calls";
+                  description = lib.mdDoc "The URL to the home server for client-server API calls";
                 };
 
                 domain = mkOption {
                   type = str;
-                  description = ''
+                  description = lib.mdDoc ''
                     The 'domain' part for user IDs on this home server. Usually
                     (but not always) is the "domain name" part of the homeserver URL.
                   '';
@@ -100,21 +100,21 @@ in {
 
           database = mkOption {
             default = {};
-            description = "Configuration for the database";
+            description = lib.mdDoc "Configuration for the database";
             type = submodule {
               freeformType = jsonType;
 
               options = {
                 engine = mkOption {
                   type = str;
-                  description = "Which database engine to use";
+                  description = lib.mdDoc "Which database engine to use";
                   default = "nedb";
                   example = "postgres";
                 };
 
                 connectionString = mkOption {
                   type = str;
-                  description = "The database connection string";
+                  description = lib.mdDoc "The database connection string";
                   default = "nedb://var/lib/matrix-appservice-irc/data";
                   example = "postgres://username:password@host:port/databasename";
                 };
@@ -124,14 +124,14 @@ in {
 
           ircService = mkOption {
             default = {};
-            description = "IRC bridge configuration";
+            description = lib.mdDoc "IRC bridge configuration";
             type = submodule {
               freeformType = jsonType;
 
               options = {
                 passwordEncryptionKeyPath = mkOption {
                   type = str;
-                  description = ''
+                  description = lib.mdDoc ''
                     Location of the key with which IRC passwords are encrypted
                     for storage. Will be generated on first run if not present.
                   '';
@@ -140,7 +140,7 @@ in {
 
                 servers = mkOption {
                   type = submodule { freeformType = jsonType; };
-                  description = "IRC servers to connect to";
+                  description = lib.mdDoc "IRC servers to connect to";
                 };
               };
             };
@@ -153,6 +153,9 @@ in {
     systemd.services.matrix-appservice-irc = {
       description = "Matrix-IRC bridge";
       before = [ "matrix-synapse.service" ]; # So the registration can be used by Synapse
+      after = lib.optionals (cfg.settings.database.engine == "postgres") [
+        "postgresql.service"
+      ];
       wantedBy = [ "multi-user.target" ];
 
       preStart = ''
diff --git a/nixos/modules/services/misc/matrix-conduit.nix b/nixos/modules/services/matrix/conduit.nix
index 108f64de7aa..812d463e9e8 100644
--- a/nixos/modules/services/misc/matrix-conduit.nix
+++ b/nixos/modules/services/matrix/conduit.nix
@@ -11,11 +11,11 @@ in
   {
     meta.maintainers = with maintainers; [ pstn piegames ];
     options.services.matrix-conduit = {
-      enable = mkEnableOption "matrix-conduit";
+      enable = mkEnableOption (lib.mdDoc "matrix-conduit");
 
       extraEnvironment = mkOption {
         type = types.attrsOf types.str;
-        description = "Extra Environment variables to pass to the conduit server.";
+        description = lib.mdDoc "Extra Environment variables to pass to the conduit server.";
         default = {};
         example = { RUST_BACKTRACE="yes"; };
       };
@@ -25,7 +25,7 @@ in
         default = pkgs.matrix-conduit;
         defaultText = "pkgs.matrix-conduit";
         example = "pkgs.matrix-conduit";
-        description = ''
+        description = lib.mdDoc ''
           Package of the conduit matrix server to use.
         '';
       };
@@ -37,50 +37,50 @@ in
             global.server_name = mkOption {
               type = types.str;
               example = "example.com";
-              description = "The server_name is the name of this server. It is used as a suffix for user # and room ids.";
+              description = lib.mdDoc "The server_name is the name of this server. It is used as a suffix for user # and room ids.";
             };
             global.port = mkOption {
               type = types.port;
               default = 6167;
-              description = "The port Conduit will be running on. You need to set up a reverse proxy in your web server (e.g. apache or nginx), so all requests to /_matrix on port 443 and 8448 will be forwarded to the Conduit instance running on this port";
+              description = lib.mdDoc "The port Conduit will be running on. You need to set up a reverse proxy in your web server (e.g. apache or nginx), so all requests to /_matrix on port 443 and 8448 will be forwarded to the Conduit instance running on this port";
             };
             global.max_request_size = mkOption {
               type = types.ints.positive;
               default = 20000000;
-              description = "Max request size in bytes. Don't forget to also change it in the proxy.";
+              description = lib.mdDoc "Max request size in bytes. Don't forget to also change it in the proxy.";
             };
             global.allow_registration = mkOption {
               type = types.bool;
               default = false;
-              description = "Whether new users can register on this server.";
+              description = lib.mdDoc "Whether new users can register on this server.";
             };
             global.allow_encryption = mkOption {
               type = types.bool;
               default = true;
-              description = "Whether new encrypted rooms can be created. Note: existing rooms will continue to work.";
+              description = lib.mdDoc "Whether new encrypted rooms can be created. Note: existing rooms will continue to work.";
             };
             global.allow_federation = mkOption {
               type = types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Whether this server federates with other servers.
               '';
             };
             global.trusted_servers = mkOption {
               type = types.listOf types.str;
               default = [ "matrix.org" ];
-              description = "Servers trusted with signing server keys.";
+              description = lib.mdDoc "Servers trusted with signing server keys.";
             };
             global.address = mkOption {
               type = types.str;
               default = "::1";
-              description = "Address to listen on for connections by the reverse proxy/tls terminator.";
+              description = lib.mdDoc "Address to listen on for connections by the reverse proxy/tls terminator.";
             };
             global.database_path = mkOption {
               type = types.str;
               default = "/var/lib/matrix-conduit/";
               readOnly = true;
-              description = ''
+              description = lib.mdDoc ''
                 Path to the conduit database, the directory where conduit will save its data.
                 Note that due to using the DynamicUser feature of systemd, this value should not be changed
                 and is set to be read only.
@@ -90,7 +90,7 @@ in
               type = types.enum [ "sqlite" "rocksdb" ];
               default = "sqlite";
               example = "rocksdb";
-              description = ''
+              description = lib.mdDoc ''
                 The database backend for the service. Switching it on an existing
                 instance will require manual migration of data.
               '';
@@ -98,9 +98,9 @@ in
           };
         };
         default = {};
-        description = ''
+        description = lib.mdDoc ''
             Generates the conduit.toml configuration file. Refer to
-            <link xlink:href="https://gitlab.com/famedly/conduit/-/blob/master/conduit-example.toml"/>
+            <https://gitlab.com/famedly/conduit/-/blob/master/conduit-example.toml>
             for details on supported values.
             Note that database_path can not be edited because the service's reliance on systemd StateDir.
         '';
diff --git a/nixos/modules/services/misc/dendrite.nix b/nixos/modules/services/matrix/dendrite.nix
index 89bb989a09e..a5fea3da484 100644
--- a/nixos/modules/services/misc/dendrite.nix
+++ b/nixos/modules/services/matrix/dendrite.nix
@@ -7,18 +7,18 @@ let
 in
 {
   options.services.dendrite = {
-    enable = lib.mkEnableOption "matrix.org dendrite";
+    enable = lib.mkEnableOption (lib.mdDoc "matrix.org dendrite");
     httpPort = lib.mkOption {
       type = lib.types.nullOr lib.types.port;
       default = 8008;
-      description = ''
+      description = lib.mdDoc ''
         The port to listen for HTTP requests on.
       '';
     };
     httpsPort = lib.mkOption {
       type = lib.types.nullOr lib.types.port;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The port to listen for HTTPS requests on.
       '';
     };
@@ -26,52 +26,62 @@ in
       type = lib.types.nullOr lib.types.path;
       example = "/var/lib/dendrite/server.cert";
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The path to the TLS certificate.
 
-        <programlisting>
+        ```
           nix-shell -p dendrite --command "generate-keys --tls-cert server.crt --tls-key server.key"
-        </programlisting>
+        ```
       '';
     };
     tlsKey = lib.mkOption {
       type = lib.types.nullOr lib.types.path;
       example = "/var/lib/dendrite/server.key";
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The path to the TLS key.
 
-        <programlisting>
+        ```
           nix-shell -p dendrite --command "generate-keys --tls-cert server.crt --tls-key server.key"
-        </programlisting>
+        ```
       '';
     };
     environmentFile = lib.mkOption {
       type = lib.types.nullOr lib.types.path;
       example = "/var/lib/dendrite/registration_secret";
       default = null;
-      description = ''
-        Environment file as defined in <citerefentry>
-        <refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum>
-        </citerefentry>.
+      description = lib.mdDoc ''
+        Environment file as defined in {manpage}`systemd.exec(5)`.
         Secrets may be passed to the service without adding them to the world-readable
         Nix store, by specifying placeholder variables as the option value in Nix and
         setting these variables accordingly in the environment file. Currently only used
         for the registration secret to allow secure registration when
         client_api.registration_disabled is true.
 
-        <programlisting>
+        ```
           # snippet of dendrite-related config
           services.dendrite.settings.client_api.registration_shared_secret = "$REGISTRATION_SHARED_SECRET";
-        </programlisting>
+        ```
 
-        <programlisting>
+        ```
           # content of the environment file
           REGISTRATION_SHARED_SECRET=verysecretpassword
-        </programlisting>
+        ```
 
         Note that this file needs to be available on the host on which
-        <literal>dendrite</literal> is running.
+        `dendrite` is running.
+      '';
+    };
+    loadCredential = lib.mkOption {
+      type = lib.types.listOf lib.types.str;
+      default = [ ];
+      example = [ "private_key:/path/to/my_private_key" ];
+      description = lib.mdDoc ''
+        This can be used to pass secrets to the systemd service without adding them to
+        the nix store.
+        To use the example setting, see the example of
+        {option}`services.dendrite.settings.global.private_key`.
+        See the LoadCredential section of systemd.exec manual for more information.
       '';
     };
     settings = lib.mkOption {
@@ -81,29 +91,31 @@ in
           server_name = lib.mkOption {
             type = lib.types.str;
             example = "example.com";
-            description = ''
+            description = lib.mdDoc ''
               The domain name of the server, with optional explicit port.
               This is used by remote servers to connect to this server.
               This is also the last part of your UserID.
             '';
           };
           private_key = lib.mkOption {
-            type = lib.types.path;
-            example = "${workingDir}/matrix_key.pem";
-            description = ''
+            type = lib.types.either
+              lib.types.path
+              (lib.types.strMatching "^\\$CREDENTIALS_DIRECTORY/.+");
+            example = "$CREDENTIALS_DIRECTORY/private_key";
+            description = lib.mdDoc ''
               The path to the signing private key file, used to sign
               requests and events.
 
-              <programlisting>
+              ```
                 nix-shell -p dendrite --command "generate-keys --private-key matrix_key.pem"
-              </programlisting>
+              ```
             '';
           };
           trusted_third_party_id_servers = lib.mkOption {
             type = lib.types.listOf lib.types.str;
             example = [ "matrix.org" ];
             default = [ "matrix.org" "vector.im" ];
-            description = ''
+            description = lib.mdDoc ''
               Lists of domains that the server will trust as identity
               servers to verify third party identifiers such as phone
               numbers and email addresses
@@ -114,7 +126,7 @@ in
           connection_string = lib.mkOption {
             type = lib.types.str;
             default = "file:federationapi.db";
-            description = ''
+            description = lib.mdDoc ''
               Database for the Appservice API.
             '';
           };
@@ -123,7 +135,7 @@ in
           registration_disabled = lib.mkOption {
             type = lib.types.bool;
             default = true;
-            description = ''
+            description = lib.mdDoc ''
               Whether to disable user registration to the server
               without the shared secret.
             '';
@@ -133,7 +145,7 @@ in
           connection_string = lib.mkOption {
             type = lib.types.str;
             default = "file:federationapi.db";
-            description = ''
+            description = lib.mdDoc ''
               Database for the Federation API.
             '';
           };
@@ -142,7 +154,7 @@ in
           connection_string = lib.mkOption {
             type = lib.types.str;
             default = "file:keyserver.db";
-            description = ''
+            description = lib.mdDoc ''
               Database for the Key Server (for end-to-end encryption).
             '';
           };
@@ -152,7 +164,7 @@ in
             connection_string = lib.mkOption {
               type = lib.types.str;
               default = "file:mediaapi.db";
-              description = ''
+              description = lib.mdDoc ''
                 Database for the Media API.
               '';
             };
@@ -160,7 +172,7 @@ in
           base_path = lib.mkOption {
             type = lib.types.str;
             default = "${workingDir}/media_store";
-            description = ''
+            description = lib.mdDoc ''
               Storage path for uploaded media.
             '';
           };
@@ -169,7 +181,7 @@ in
           connection_string = lib.mkOption {
             type = lib.types.str;
             default = "file:roomserver.db";
-            description = ''
+            description = lib.mdDoc ''
               Database for the Room Server.
             '';
           };
@@ -178,17 +190,36 @@ in
           connection_string = lib.mkOption {
             type = lib.types.str;
             default = "file:syncserver.db";
-            description = ''
+            description = lib.mdDoc ''
               Database for the Sync API.
             '';
           };
         };
+        options.sync_api.search = {
+          enable = lib.mkEnableOption (lib.mdDoc "Dendrite's full-text search engine");
+          index_path = lib.mkOption {
+            type = lib.types.str;
+            default = "${workingDir}/searchindex";
+            description = lib.mdDoc ''
+              The path the search index will be created in.
+            '';
+          };
+          language = lib.mkOption {
+            type = lib.types.str;
+            default = "en";
+            description = lib.mdDoc ''
+              The language most likely to be used on the server - used when indexing, to
+              ensure the returned results match expectations. A full list of possible languages
+              can be found at https://github.com/blevesearch/bleve/tree/master/analysis/lang
+            '';
+          };
+        };
         options.user_api = {
           account_database = {
             connection_string = lib.mkOption {
               type = lib.types.str;
               default = "file:userapi_accounts.db";
-              description = ''
+              description = lib.mdDoc ''
                 Database for the User API, accounts.
               '';
             };
@@ -197,7 +228,7 @@ in
             connection_string = lib.mkOption {
               type = lib.types.str;
               default = "file:userapi_devices.db";
-              description = ''
+              description = lib.mdDoc ''
                 Database for the User API, devices.
               '';
             };
@@ -208,7 +239,7 @@ in
             connection_string = lib.mkOption {
               type = lib.types.str;
               default = "file:mscs.db";
-              description = ''
+              description = lib.mdDoc ''
                 Database for exerimental MSC's.
               '';
             };
@@ -216,12 +247,19 @@ in
         };
       };
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Configuration for dendrite, see:
-        <link xlink:href="https://github.com/matrix-org/dendrite/blob/master/dendrite-config.yaml"/>
+        <https://github.com/matrix-org/dendrite/blob/master/dendrite-config.yaml>
         for available options with which to populate settings.
       '';
     };
+    openRegistration = lib.mkOption {
+      type = lib.types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Allow open registration without secondary verification (reCAPTCHA).
+      '';
+    };
   };
 
   config = lib.mkIf cfg.enable {
@@ -247,7 +285,9 @@ in
         WorkingDirectory = workingDir;
         RuntimeDirectory = "dendrite";
         RuntimeDirectoryMode = "0700";
+        LimitNOFILE = 65535;
         EnvironmentFile = lib.mkIf (cfg.environmentFile != null) cfg.environmentFile;
+        LoadCredential = cfg.loadCredential;
         ExecStartPre = ''
           ${pkgs.envsubst}/bin/envsubst \
             -i ${configurationYaml} \
@@ -262,6 +302,8 @@ in
           "--https-bind-address :${builtins.toString cfg.httpsPort}"
           "--tls-cert ${cfg.tlsCert}"
           "--tls-key ${cfg.tlsKey}"
+        ] ++ lib.optionals cfg.openRegistration [
+          "--really-enable-open-registration"
         ]);
         ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
         Restart = "on-failure";
diff --git a/nixos/modules/services/misc/mautrix-facebook.nix b/nixos/modules/services/matrix/mautrix-facebook.nix
index e046c791ac0..e74f25df764 100644
--- a/nixos/modules/services/misc/mautrix-facebook.nix
+++ b/nixos/modules/services/matrix/mautrix-facebook.nix
@@ -17,7 +17,7 @@ let
 in {
   options = {
     services.mautrix-facebook = {
-      enable = mkEnableOption "Mautrix-Facebook, a Matrix-Facebook hybrid puppeting/relaybot bridge";
+      enable = mkEnableOption (lib.mdDoc "Mautrix-Facebook, a Matrix-Facebook hybrid puppeting/relaybot bridge");
 
       settings = mkOption rec {
         apply = recursiveUpdate default;
@@ -25,6 +25,7 @@ in {
         default = {
           homeserver = {
             address = "http://localhost:8008";
+            software = "standard";
           };
 
           appservice = rec {
@@ -44,6 +45,12 @@ in {
             encryption = {
               allow = true;
               default = true;
+
+              verification_levels = {
+                receive = "cross-signed-tofu";
+                send = "cross-signed-tofu";
+                share = "cross-signed-tofu";
+              };
             };
             username_template = "facebook_{userid}";
           };
@@ -75,15 +82,12 @@ in {
             };
           }
         '';
-        description = ''
-          <filename>config.yaml</filename> configuration as a Nix attribute set.
+        description = lib.mdDoc ''
+          {file}`config.yaml` configuration as a Nix attribute set.
           Configuration options should match those described in
-          <link xlink:href="https://github.com/mautrix/facebook/blob/master/mautrix_facebook/example-config.yaml">
-          example-config.yaml</link>.
-          </para>
+          [example-config.yaml](https://github.com/mautrix/facebook/blob/master/mautrix_facebook/example-config.yaml).
 
-          <para>
-          Secret tokens should be specified using <option>environmentFile</option>
+          Secret tokens should be specified using {option}`environmentFile`
           instead of this world-readable attribute set.
         '';
       };
@@ -91,34 +95,36 @@ in {
       environmentFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           File containing environment variables to be passed to the mautrix-telegram service.
 
-          Any config variable can be overridden by setting <literal>MAUTRIX_FACEBOOK_SOME_KEY</literal> to override the <literal>some.key</literal> variable.
+          Any config variable can be overridden by setting `MAUTRIX_FACEBOOK_SOME_KEY` to override the `some.key` variable.
         '';
       };
 
       configurePostgresql = mkOption {
         type = types.bool;
         default = true;
-        description = ''
-          Enable PostgreSQL and create a user and database for mautrix-facebook. The default <literal>settings</literal> reference this database, if you disable this option you must provide a database URL.
+        description = lib.mdDoc ''
+          Enable PostgreSQL and create a user and database for mautrix-facebook. The default `settings` reference this database, if you disable this option you must provide a database URL.
         '';
       };
 
       registrationData = mkOption {
         type = types.attrs;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Output data for appservice registration. Simply make any desired changes and serialize to JSON. Note that this data contains secrets so think twice before putting it into the nix store.
 
-          Currently <literal>as_token</literal> and <literal>hs_token</literal> need to be added as they are not known to this module.
+          Currently `as_token` and `hs_token` need to be added as they are not known to this module.
         '';
       };
     };
   };
 
   config = mkIf cfg.enable {
+    users.groups.mautrix-facebook = {};
+
     users.users.mautrix-facebook = {
       group = "mautrix-facebook";
       isSystemUser = true;
diff --git a/nixos/modules/services/misc/mautrix-telegram.nix b/nixos/modules/services/matrix/mautrix-telegram.nix
index 794c4dd9ddc..2d9c2dc76c2 100644
--- a/nixos/modules/services/misc/mautrix-telegram.nix
+++ b/nixos/modules/services/matrix/mautrix-telegram.nix
@@ -7,18 +7,22 @@ let
   registrationFile = "${dataDir}/telegram-registration.yaml";
   cfg = config.services.mautrix-telegram;
   settingsFormat = pkgs.formats.json {};
-  settingsFileUnsubstituted = settingsFormat.generate "mautrix-telegram-config-unsubstituted.json" cfg.settings;
-  settingsFile = "${dataDir}/config.json";
+  settingsFile =
+    settingsFormat.generate "mautrix-telegram-config.json" cfg.settings;
 
 in {
   options = {
     services.mautrix-telegram = {
-      enable = mkEnableOption "Mautrix-Telegram, a Matrix-Telegram hybrid puppeting/relaybot bridge";
+      enable = mkEnableOption (lib.mdDoc "Mautrix-Telegram, a Matrix-Telegram hybrid puppeting/relaybot bridge");
 
       settings = mkOption rec {
         apply = recursiveUpdate default;
         inherit (settingsFormat) type;
         default = {
+          homeserver = {
+            software = "standard";
+          };
+
           appservice = rec {
             database = "sqlite:///${dataDir}/mautrix-telegram.db";
             database_opts = {};
@@ -78,15 +82,12 @@ in {
             };
           }
         '';
-        description = ''
-          <filename>config.yaml</filename> configuration as a Nix attribute set.
+        description = lib.mdDoc ''
+          {file}`config.yaml` configuration as a Nix attribute set.
           Configuration options should match those described in
-          <link xlink:href="https://github.com/tulir/mautrix-telegram/blob/master/example-config.yaml">
-          example-config.yaml</link>.
-          </para>
+          [example-config.yaml](https://github.com/mautrix/telegram/blob/master/mautrix_telegram/example-config.yaml).
 
-          <para>
-          Secret tokens should be specified using <option>environmentFile</option>
+          Secret tokens should be specified using {option}`environmentFile`
           instead of this world-readable attribute set.
         '';
       };
@@ -94,14 +95,25 @@ in {
       environmentFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           File containing environment variables to be passed to the mautrix-telegram service,
-          in which secret tokens can be specified securely by defining values for
-          <literal>MAUTRIX_TELEGRAM_APPSERVICE_AS_TOKEN</literal>,
-          <literal>MAUTRIX_TELEGRAM_APPSERVICE_HS_TOKEN</literal>,
-          <literal>MAUTRIX_TELEGRAM_TELEGRAM_API_ID</literal>,
-          <literal>MAUTRIX_TELEGRAM_TELEGRAM_API_HASH</literal> and optionally
-          <literal>MAUTRIX_TELEGRAM_TELEGRAM_BOT_TOKEN</literal>.
+          in which secret tokens can be specified securely by defining values for e.g.
+          `MAUTRIX_TELEGRAM_APPSERVICE_AS_TOKEN`,
+          `MAUTRIX_TELEGRAM_APPSERVICE_HS_TOKEN`,
+          `MAUTRIX_TELEGRAM_TELEGRAM_API_ID`,
+          `MAUTRIX_TELEGRAM_TELEGRAM_API_HASH` and optionally
+          `MAUTRIX_TELEGRAM_TELEGRAM_BOT_TOKEN`.
+
+          These environment variables can also be used to set other options by
+          replacing hierachy levels by `.`, converting the name to uppercase
+          and prepending `MAUTRIX_TELEGRAM_`.
+          For example, the first value above maps to
+          {option}`settings.appservice.as_token`.
+
+          The environment variable values can be prefixed with `json::` to have
+          them be parsed as JSON. For example, `login_shared_secret_map` can be
+          set as follows:
+          `MAUTRIX_TELEGRAM_BRIDGE_LOGIN_SHARED_SECRET_MAP=json::{"example.com":"secret"}`.
         '';
       };
 
@@ -111,7 +123,7 @@ in {
         defaultText = literalExpression ''
           optional config.services.matrix-synapse.enable "matrix-synapse.service"
         '';
-        description = ''
+        description = lib.mdDoc ''
           List of Systemd services to require and wait for when starting the application service.
         '';
       };
@@ -125,18 +137,21 @@ in {
       wantedBy = [ "multi-user.target" ];
       wants = [ "network-online.target" ] ++ cfg.serviceDependencies;
       after = [ "network-online.target" ] ++ cfg.serviceDependencies;
+      path = [ pkgs.lottieconverter ];
+
+      # mautrix-telegram tries to generate a dotfile in the home directory of
+      # the running user if using a postgresql databse:
+      #
+      #  File "python3.10/site-packages/asyncpg/connect_utils.py", line 257, in _dot_postgre>
+      #    return (pathlib.Path.home() / '.postgresql' / filename).resolve()
+      #  File "python3.10/pathlib.py", line 1000, in home
+      #    return cls("~").expanduser()
+      #  File "python3.10/pathlib.py", line 1440, in expanduser
+      #    raise RuntimeError("Could not determine home directory.")
+      # RuntimeError: Could not determine home directory.
+      environment.HOME = dataDir;
 
       preStart = ''
-        # Not all secrets can be passed as environment variable (yet)
-        # https://github.com/tulir/mautrix-telegram/issues/584
-        [ -f ${settingsFile} ] && rm -f ${settingsFile}
-        old_umask=$(umask)
-        umask 0177
-        ${pkgs.envsubst}/bin/envsubst \
-          -o ${settingsFile} \
-          -i ${settingsFileUnsubstituted}
-        umask $old_umask
-
         # generate the appservice's registration file if absent
         if [ ! -f '${registrationFile}' ]; then
           ${pkgs.mautrix-telegram}/bin/mautrix-telegram \
@@ -164,7 +179,7 @@ in {
         PrivateTmp = true;
         WorkingDirectory = pkgs.mautrix-telegram; # necessary for the database migration scripts to be found
         StateDirectory = baseNameOf dataDir;
-        UMask = 0027;
+        UMask = "0027";
         EnvironmentFile = cfg.environmentFile;
 
         ExecStart = ''
@@ -172,8 +187,6 @@ in {
             --config='${settingsFile}'
         '';
       };
-
-      restartTriggers = [ settingsFileUnsubstituted ];
     };
   };
 
diff --git a/nixos/modules/services/matrix/mjolnir.nix b/nixos/modules/services/matrix/mjolnir.nix
index 278924b05cf..cbf7b93329d 100644
--- a/nixos/modules/services/matrix/mjolnir.nix
+++ b/nixos/modules/services/matrix/mjolnir.nix
@@ -65,59 +65,59 @@ let
 in
 {
   options.services.mjolnir = {
-    enable = mkEnableOption "Mjolnir, a moderation tool for Matrix";
+    enable = mkEnableOption (lib.mdDoc "Mjolnir, a moderation tool for Matrix");
 
     homeserverUrl = mkOption {
       type = types.str;
       default = "https://matrix.org";
-      description = ''
+      description = lib.mdDoc ''
         Where the homeserver is located (client-server URL).
 
-        If <literal>pantalaimon.enable</literal> is <literal>true</literal>, this option will become the homeserver to which <literal>pantalaimon</literal> connects.
-        The listen address of <literal>pantalaimon</literal> will then become the <literal>homeserverUrl</literal> of <literal>mjolnir</literal>.
+        If `pantalaimon.enable` is `true`, this option will become the homeserver to which `pantalaimon` connects.
+        The listen address of `pantalaimon` will then become the `homeserverUrl` of `mjolnir`.
       '';
     };
 
     accessTokenFile = mkOption {
       type = with types; nullOr path;
       default = null;
-      description = ''
-        File containing the matrix access token for the <literal>mjolnir</literal> user.
+      description = lib.mdDoc ''
+        File containing the matrix access token for the `mjolnir` user.
       '';
     };
 
     pantalaimon = mkOption {
-      description = ''
-        <literal>pantalaimon</literal> options (enables E2E Encryption support).
+      description = lib.mdDoc ''
+        `pantalaimon` options (enables E2E Encryption support).
 
-        This will create a <literal>pantalaimon</literal> instance with the name "mjolnir".
+        This will create a `pantalaimon` instance with the name "mjolnir".
       '';
       default = { };
       type = types.submodule {
         options = {
-          enable = mkEnableOption ''
+          enable = mkEnableOption (lib.mdDoc ''
             If true, accessToken is ignored and the username/password below will be
             used instead. The access token of the bot will be stored in the dataPath.
-          '';
+          '');
 
           username = mkOption {
             type = types.str;
-            description = "The username to login with.";
+            description = lib.mdDoc "The username to login with.";
           };
 
           passwordFile = mkOption {
             type = with types; nullOr path;
             default = null;
-            description = ''
-              File containing the matrix password for the <literal>mjolnir</literal> user.
+            description = lib.mdDoc ''
+              File containing the matrix password for the `mjolnir` user.
             '';
           };
 
           options = mkOption {
             type = types.submodule (import ./pantalaimon-options.nix);
             default = { };
-            description = ''
-              passthrough additional options to the <literal>pantalaimon</literal> service.
+            description = lib.mdDoc ''
+              passthrough additional options to the `pantalaimon` service.
             '';
           };
         };
@@ -127,7 +127,7 @@ in
     dataPath = mkOption {
       type = types.path;
       default = "/var/lib/mjolnir";
-      description = ''
+      description = lib.mdDoc ''
         The directory the bot should store various bits of information in.
       '';
     };
@@ -135,11 +135,11 @@ in
     managementRoom = mkOption {
       type = types.str;
       default = "#moderators:example.org";
-      description = ''
+      description = lib.mdDoc ''
         The room ID where people can use the bot. The bot has no access controls, so
         anyone in this room can use the bot - secure your room!
         This should be a room alias or room ID - not a matrix.to URL.
-        Note: <literal>mjolnir</literal> is fairly verbose - expect a lot of messages from it.
+        Note: `mjolnir` is fairly verbose - expect a lot of messages from it.
       '';
     };
 
@@ -152,7 +152,7 @@ in
           "https://matrix.to/#/#anotherroom:example.org"
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         A list of rooms to protect (matrix.to URLs).
       '';
     };
@@ -166,8 +166,8 @@ in
           automaticallyRedactForReasons = [ "spam" "advertising" ];
         }
       '';
-      description = ''
-        Additional settings (see <link xlink:href="https://github.com/matrix-org/mjolnir/blob/main/config/default.yaml">mjolnir default config</link> for available settings). These settings will override settings made by the module config.
+      description = lib.mdDoc ''
+        Additional settings (see [mjolnir default config](https://github.com/matrix-org/mjolnir/blob/main/config/default.yaml) for available settings). These settings will override settings made by the module config.
       '';
     };
   };
diff --git a/nixos/modules/services/matrix/pantalaimon-options.nix b/nixos/modules/services/matrix/pantalaimon-options.nix
index 035c57540d0..3945a70fc86 100644
--- a/nixos/modules/services/matrix/pantalaimon-options.nix
+++ b/nixos/modules/services/matrix/pantalaimon-options.nix
@@ -6,15 +6,15 @@ with lib;
     dataPath = mkOption {
       type = types.path;
       default = "/var/lib/pantalaimon-${name}";
-      description = ''
-        The directory where <literal>pantalaimon</literal> should store its state such as the database file.
+      description = lib.mdDoc ''
+        The directory where `pantalaimon` should store its state such as the database file.
       '';
     };
 
     logLevel = mkOption {
       type = types.enum [ "info" "warning" "error" "debug" ];
       default = "warning";
-      description = ''
+      description = lib.mdDoc ''
         Set the log level of the daemon.
       '';
     };
@@ -22,8 +22,8 @@ with lib;
     homeserver = mkOption {
       type = types.str;
       example = "https://matrix.org";
-      description = ''
-        The URI of the homeserver that the <literal>pantalaimon</literal> proxy should
+      description = lib.mdDoc ''
+        The URI of the homeserver that the `pantalaimon` proxy should
         forward requests to, without the matrix API path but including
         the http(s) schema.
       '';
@@ -32,7 +32,7 @@ with lib;
     ssl = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether or not SSL verification should be enabled for outgoing
         connections to the homeserver.
       '';
@@ -41,7 +41,7 @@ with lib;
     listenAddress = mkOption {
       type = types.str;
       default = "localhost";
-      description = ''
+      description = lib.mdDoc ''
         The address where the daemon will listen to client connections
         for this homeserver.
       '';
@@ -50,7 +50,7 @@ with lib;
     listenPort = mkOption {
       type = types.port;
       default = 8009;
-      description = ''
+      description = lib.mdDoc ''
         The port where the daemon will listen to client connections for
         this homeserver. Note that the listen address/port combination
         needs to be unique between different homeservers.
@@ -60,9 +60,9 @@ with lib;
     extraSettings = mkOption {
       type = types.attrs;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Extra configuration options. See
-        <link xlink:href="https://github.com/matrix-org/pantalaimon/blob/master/docs/man/pantalaimon.5.md">pantalaimon(5)</link>
+        [pantalaimon(5)](https://github.com/matrix-org/pantalaimon/blob/master/docs/man/pantalaimon.5.md)
         for available options.
       '';
     };
diff --git a/nixos/modules/services/matrix/pantalaimon.nix b/nixos/modules/services/matrix/pantalaimon.nix
index 63b40099ca5..591ba9a7ab5 100644
--- a/nixos/modules/services/matrix/pantalaimon.nix
+++ b/nixos/modules/services/matrix/pantalaimon.nix
@@ -51,11 +51,11 @@ in
   options.services.pantalaimon-headless.instances = mkOption {
     default = { };
     type = types.attrsOf (types.submodule (import ./pantalaimon-options.nix));
-    description = ''
+    description = lib.mdDoc ''
       Declarative instance config.
 
       Note: to use pantalaimon interactively, e.g. for a Matrix client which does not
-      support End-to-end encryption (like <literal>fractal</literal>), refer to the home-manager module.
+      support End-to-end encryption (like `fractal`), refer to the home-manager module.
     '';
   };
 
diff --git a/nixos/modules/services/matrix/matrix-synapse-log_config.yaml b/nixos/modules/services/matrix/synapse-log_config.yaml
index d85bdd1208f..d85bdd1208f 100644
--- a/nixos/modules/services/matrix/matrix-synapse-log_config.yaml
+++ b/nixos/modules/services/matrix/synapse-log_config.yaml
diff --git a/nixos/modules/services/matrix/matrix-synapse.nix b/nixos/modules/services/matrix/synapse.nix
index c4d14dbd547..86662055222 100644
--- a/nixos/modules/services/matrix/matrix-synapse.nix
+++ b/nixos/modules/services/matrix/synapse.nix
@@ -81,7 +81,7 @@ in {
     (mkRemovedOptionModule [ "services" "matrix-synapse" "verbose" ] "Use a log config instead." )
 
     # options that were moved into rfc42 style settigns
-    (mkRemovedOptionModule [ "services" "matrix-synapse" "app_service_config_files" ] "Use settings.app_service_config_Files instead" )
+    (mkRemovedOptionModule [ "services" "matrix-synapse" "app_service_config_files" ] "Use settings.app_service_config_files instead" )
     (mkRemovedOptionModule [ "services" "matrix-synapse" "database_args" ] "Use settings.database.args instead" )
     (mkRemovedOptionModule [ "services" "matrix-synapse" "database_name" ] "Use settings.database.args.database instead" )
     (mkRemovedOptionModule [ "services" "matrix-synapse" "database_type" ] "Use settings.database.name instead" )
@@ -138,12 +138,12 @@ in {
 
   options = {
     services.matrix-synapse = {
-      enable = mkEnableOption "matrix.org synapse";
+      enable = mkEnableOption (lib.mdDoc "matrix.org synapse");
 
       configFile = mkOption {
-        type = types.str;
+        type = types.path;
         readOnly = true;
-        description = ''
+        description = lib.mdDoc ''
           Path to the configuration file on the target system. Useful to configure e.g. workers
           that also need this.
         '';
@@ -153,7 +153,7 @@ in {
         type = types.package;
         default = pkgs.matrix-synapse;
         defaultText = literalExpression "pkgs.matrix-synapse";
-        description = ''
+        description = lib.mdDoc ''
           Overridable attribute of the matrix synapse server package to use.
         '';
       };
@@ -167,7 +167,7 @@ in {
             matrix-synapse-pam
           ];
         '';
-        description = ''
+        description = lib.mdDoc ''
           List of additional Matrix plugins to make available.
         '';
       };
@@ -175,7 +175,7 @@ in {
       withJemalloc = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to preload jemalloc to reduce memory fragmentation and overall usage.
         '';
       };
@@ -183,7 +183,7 @@ in {
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/matrix-synapse";
-        description = ''
+        description = lib.mdDoc ''
           The directory where matrix-synapse stores its stateful data such as
           certificates, media and uploads.
         '';
@@ -191,12 +191,12 @@ in {
 
       settings = mkOption {
         default = {};
-        description = ''
+        description = mdDoc ''
           The primary synapse configuration. See the
-          <link xlink:href="https://github.com/matrix-org/synapse/blob/v${cfg.package.version}/docs/sample_config.yaml">sample configuration</link>
+          [sample configuration](https://github.com/matrix-org/synapse/blob/v${cfg.package.version}/docs/sample_config.yaml)
           for possible values.
 
-          Secrets should be passed in by using the <literal>extraConfigFiles</literal> option.
+          Secrets should be passed in by using the `extraConfigFiles` option.
         '';
         type = with types; submodule {
           freeformType = format.type;
@@ -210,7 +210,7 @@ in {
               example = "example.com";
               default = config.networking.hostName;
               defaultText = literalExpression "config.networking.hostName";
-              description = ''
+              description = lib.mdDoc ''
                 The domain name of the server, with optional explicit port.
                 This is used by remote servers to look up the server address.
                 This is also the last part of your UserID.
@@ -222,7 +222,7 @@ in {
             enable_registration = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 Enable registration for new users.
               '';
             };
@@ -230,30 +230,30 @@ in {
             registration_shared_secret = mkOption {
               type = types.nullOr types.str;
               default = null;
-              description = ''
+              description = mdDoc ''
                 If set, allows registration by anyone who also has the shared
                 secret, even if registration is otherwise disabled.
 
-                Secrets should be passed in via <literal>extraConfigFiles</literal>!
+                Secrets should be passed in via `extraConfigFiles`!
               '';
             };
 
             macaroon_secret_key = mkOption {
               type = types.nullOr types.str;
               default = null;
-              description = ''
+              description = mdDoc ''
                 Secret key for authentication tokens. If none is specified,
                 the registration_shared_secret is used, if one is given; otherwise,
                 a secret key is derived from the signing key.
 
-                Secrets should be passed in via <literal>extraConfigFiles</literal>!
+                Secrets should be passed in via `extraConfigFiles`!
               '';
             };
 
             enable_metrics = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 Enable collection and rendering of performance metrics
               '';
             };
@@ -261,7 +261,7 @@ in {
             report_stats = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 Whether or not to report anonymized homeserver usage statistics.
               '';
             };
@@ -269,7 +269,7 @@ in {
             signing_key_path = mkOption {
               type = types.path;
               default = "${cfg.dataDir}/homeserver.signing.key";
-              description = ''
+              description = lib.mdDoc ''
                 Path to the signing key to sign messages with.
               '';
             };
@@ -278,15 +278,15 @@ in {
               type = types.path;
               default = "/run/matrix-synapse.pid";
               readOnly = true;
-              description = ''
+              description = lib.mdDoc ''
                 The file to store the PID in.
               '';
             };
 
             log_config = mkOption {
               type = types.path;
-              default = ./matrix-synapse-log_config.yaml;
-              description = ''
+              default = ./synapse-log_config.yaml;
+              description = lib.mdDoc ''
                 The file that holds the logging configuration.
               '';
             };
@@ -296,7 +296,8 @@ in {
               default = if lib.versionAtLeast config.system.stateVersion "22.05"
                 then "${cfg.dataDir}/media_store"
                 else "${cfg.dataDir}/media";
-              description = ''
+              defaultText = "${cfg.dataDir}/media_store for when system.stateVersion is at least 22.05, ${cfg.dataDir}/media when lower than 22.05";
+              description = lib.mdDoc ''
                 Directory where uploaded images and attachments are stored.
               '';
             };
@@ -305,7 +306,7 @@ in {
               type = types.nullOr types.str;
               default = null;
               example = "https://example.com:8448/";
-              description = ''
+              description = lib.mdDoc ''
                 The public-facing base URL for the client API (not including _matrix/...)
               '';
             };
@@ -314,7 +315,7 @@ in {
               type = types.nullOr types.str;
               default = null;
               example = "/var/lib/acme/example.com/fullchain.pem";
-              description = ''
+              description = lib.mdDoc ''
                 PEM encoded X509 certificate for TLS.
                 You can replace the self-signed certificate that synapse
                 autogenerates on launch with your own SSL certificate + key pair
@@ -327,7 +328,7 @@ in {
               type = types.nullOr types.str;
               default = null;
               example = "/var/lib/acme/example.com/key.pem";
-              description = ''
+              description = lib.mdDoc ''
                 PEM encoded private key for TLS. Specify null if synapse is not
                 speaking TLS directly.
               '';
@@ -337,7 +338,7 @@ in {
               type = types.bool;
               default = true;
               example = false;
-              description = ''
+              description = lib.mdDoc ''
                 Whether to enable presence tracking.
 
                 Presence tracking allows users to see the state (e.g online/offline)
@@ -351,7 +352,7 @@ in {
                   port = mkOption {
                     type = types.port;
                     example = 8448;
-                    description = ''
+                    description = lib.mdDoc ''
                       The port to listen for HTTP(S) requests on.
                     '';
                   };
@@ -368,7 +369,7 @@ in {
                       "0.0.0.0"
                     ]
                     '';
-                    description = ''
+                    description = lib.mdDoc ''
                      IP addresses to bind the listener to.
                     '';
                   };
@@ -382,7 +383,7 @@ in {
                     ];
                     default = "http";
                     example = "metrics";
-                    description = ''
+                    description = lib.mdDoc ''
                       The type of the listener, usually http.
                     '';
                   };
@@ -391,7 +392,7 @@ in {
                     type = types.bool;
                     default = true;
                     example = false;
-                    description = ''
+                    description = lib.mdDoc ''
                       Whether to enable TLS on the listener socket.
                     '';
                   };
@@ -400,7 +401,7 @@ in {
                     type = types.bool;
                     default = false;
                     example = true;
-                    description = ''
+                    description = lib.mdDoc ''
                       Use the X-Forwarded-For (XFF) header as the client IP and not the
                       actual client IP.
                     '';
@@ -421,7 +422,7 @@ in {
                             "replication"
                             "static"
                           ]);
-                          description = ''
+                          description = lib.mdDoc ''
                             List of resources to host on this listener.
                           '';
                           example = [
@@ -430,7 +431,7 @@ in {
                         };
                         compress = mkOption {
                           type = types.bool;
-                          description = ''
+                          description = lib.mdDoc ''
                             Should synapse compress HTTP responses to clients that support it?
                             This should be disabled if running synapse behind a load balancer
                             that can do automatic compression.
@@ -438,7 +439,7 @@ in {
                         };
                       };
                     });
-                    description = ''
+                    description = lib.mdDoc ''
                       List of HTTP resources to serve on this listener.
                     '';
                   };
@@ -458,7 +459,7 @@ in {
                   compress = false;
                 } ];
               } ];
-              description = ''
+              description = lib.mdDoc ''
                 List of ports that Synapse should listen on, their purpose and their configuration.
               '';
             };
@@ -476,7 +477,7 @@ in {
                 then "psycopg2"
                 else "sqlite3"
               '';
-              description = ''
+              description = lib.mdDoc ''
                 The database engine name. Can be sqlite3 or psycopg2.
               '';
             };
@@ -493,7 +494,7 @@ in {
                 psycopg2 = "matrix-synapse";
               }.''${${options.services.matrix-synapse.settings}.database.name};
               '';
-              description = ''
+              description = lib.mdDoc ''
                 Name of the database when using the psycopg2 backend,
                 path to the database location when using sqlite3.
               '';
@@ -505,7 +506,7 @@ in {
                 sqlite3 = null;
                 psycopg2 = "matrix-synapse";
               }.${cfg.settings.database.name};
-              description = ''
+              description = lib.mdDoc ''
                 Username to connect with psycopg2, set to null
                 when using sqlite3.
               '';
@@ -515,7 +516,7 @@ in {
               type = types.bool;
               default = true;
               example = false;
-              description = ''
+              description = lib.mdDoc ''
                 Is the preview URL API enabled?  If enabled, you *must* specify an
                 explicit url_preview_ip_range_blacklist of IPs that the spider is
                 denied from accessing.
@@ -545,7 +546,7 @@ in {
                 "fec0::/10"
                 "ff00::/8"
               ];
-              description = ''
+              description = lib.mdDoc ''
                 List of IP address CIDR ranges that the URL preview spider is denied
                 from accessing.
               '';
@@ -554,7 +555,7 @@ in {
             url_preview_ip_range_whitelist = mkOption {
               type = types.listOf types.str;
               default = [];
-              description = ''
+              description = lib.mdDoc ''
                 List of IP address CIDR ranges that the URL preview spider is allowed
                 to access even if they are specified in url_preview_ip_range_blacklist.
               '';
@@ -563,7 +564,7 @@ in {
             url_preview_url_blacklist = mkOption {
               type = types.listOf types.str;
               default = [];
-              description = ''
+              description = lib.mdDoc ''
                 Optional list of URL matches that the URL preview spider is
                 denied from accessing.
               '';
@@ -573,7 +574,7 @@ in {
               type = types.str;
               default = "50M";
               example = "100M";
-              description = ''
+              description = lib.mdDoc ''
                 The largest allowed upload size in bytes
               '';
             };
@@ -582,7 +583,7 @@ in {
               type = types.str;
               default = "32M";
               example = "64M";
-              description = ''
+              description = lib.mdDoc ''
                 Maximum number of pixels that will be thumbnailed
               '';
             };
@@ -591,7 +592,7 @@ in {
               type = types.bool;
               default = false;
               example = true;
-              description = ''
+              description = lib.mdDoc ''
                 Whether to generate new thumbnails on the fly to precisely match
                 the resolution requested by the client. If true then whenever
                 a new resolution is requested by the client the server will
@@ -609,7 +610,7 @@ in {
                 "turns:turn.example.com:5349?transport=udp"
                 "turns:turn.example.com:5349?transport=tcp"
               ];
-              description = ''
+              description = lib.mdDoc ''
                 The public URIs of the TURN server to give to clients
               '';
             };
@@ -619,10 +620,10 @@ in {
               example = literalExpression ''
                 config.services.coturn.static-auth-secret
               '';
-              description = ''
+              description = mdDoc ''
                 The shared secret used to compute passwords for the TURN server.
 
-                Secrets should be passed in via <literal>extraConfigFiles</literal>!
+                Secrets should be passed in via `extraConfigFiles`!
               '';
             };
 
@@ -632,7 +633,7 @@ in {
                   server_name = mkOption {
                     type = types.str;
                     example = "matrix.org";
-                    description = ''
+                    description = lib.mdDoc ''
                       Hostname of the trusted server.
                     '';
                   };
@@ -645,7 +646,7 @@ in {
                         "ed25519:auto" = "Noi6WqcDj0QmPxCNQqgezwTlBKrfqehY1u2FyWP9uYw";
                       }
                     '';
-                    description = ''
+                    description = lib.mdDoc ''
                       Attribute set from key id to base64 encoded public key.
 
                       If specified synapse will check that the response is signed
@@ -660,7 +661,7 @@ in {
                   "ed25519:auto" = "Noi6WqcDj0QmPxCNQqgezwTlBKrfqehY1u2FyWP9uYw";
                 };
               } ];
-              description = ''
+              description = lib.mdDoc ''
                 The trusted servers to download signing keys from.
               '';
             };
@@ -668,7 +669,7 @@ in {
             app_service_config_files = mkOption {
               type = types.listOf types.path;
               default = [ ];
-              description = ''
+              description = lib.mdDoc ''
                 A list of application service config file to use
               '';
             };
@@ -680,7 +681,7 @@ in {
       extraConfigFiles = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Extra config files to include.
 
           The configuration files will be included based on the command line
@@ -758,6 +759,33 @@ in {
         ExecReload = "${pkgs.util-linux}/bin/kill -HUP $MAINPID";
         Restart = "on-failure";
         UMask = "0077";
+
+        # Security Hardening
+        # Refer to systemd.exec(5) for option descriptions.
+        CapabilityBoundingSet = [ "" ];
+        LockPersonality = true;
+        NoNewPrivileges = true;
+        PrivateDevices = true;
+        PrivateTmp = true;
+        PrivateUsers = true;
+        ProcSubset = "pid";
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectProc = "invisible";
+        ProtectSystem = "strict";
+        ReadWritePaths = [ cfg.dataDir ];
+        RemoveIPC = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        RestrictSUIDSGID = true;
+        SystemCallArchitectures = "native";
+        SystemCallFilter = [ "@system-service" "~@resources" "~@privileged" ];
       };
     };
 
@@ -766,7 +794,7 @@ in {
 
   meta = {
     buildDocsInSandbox = false;
-    doc = ./matrix-synapse.xml;
+    doc = ./synapse.xml;
     maintainers = teams.matrix.members;
   };
 
diff --git a/nixos/modules/services/matrix/matrix-synapse.xml b/nixos/modules/services/matrix/synapse.xml
index cf33957d58e..40ad72173a5 100644
--- a/nixos/modules/services/matrix/matrix-synapse.xml
+++ b/nixos/modules/services/matrix/synapse.xml
@@ -30,24 +30,29 @@
    synapse server for the <literal>example.org</literal> domain, served from
    the host <literal>myhostname.example.org</literal>. For more information,
    please refer to the
-   <link xlink:href="https://github.com/matrix-org/synapse#synapse-installation">
+   <link xlink:href="https://matrix-org.github.io/synapse/latest/setup/installation.html">
    installation instructions of Synapse </link>.
 <programlisting>
-{ pkgs, lib, ... }:
+{ pkgs, lib, config, ... }:
 let
-  fqdn =
-    let
-      join = hostName: domain: hostName + lib.optionalString (domain != null) ".${domain}";
-    in join config.networking.hostName config.networking.domain;
-in {
-  networking = {
-    <link linkend="opt-networking.hostName">hostName</link> = "myhostname";
-    <link linkend="opt-networking.domain">domain</link> = "example.org";
+  fqdn = "${config.networking.hostName}.${config.networking.domain}";
+  clientConfig = {
+    "m.homeserver".base_url = "https://${fqdn}";
+    "m.identity_server" = {};
   };
-  <link linkend="opt-networking.firewall.allowedTCPPorts">networking.firewall.allowedTCPPorts</link> = [ 80 443 ];
+  serverConfig."m.server" = "${config.services.matrix-synapse.settings.server_name}:443";
+  mkWellKnown = data: ''
+    add_header Content-Type application/json;
+    add_header Access-Control-Allow-Origin *;
+    return 200 '${builtins.toJSON data}';
+  '';
+in {
+  <xref linkend="opt-networking.hostName" /> = "myhostname";
+  <xref linkend="opt-networking.domain" /> = "example.org";
+  <xref linkend="opt-networking.firewall.allowedTCPPorts" /> = [ 80 443 ];
 
-  <link linkend="opt-services.postgresql.enable">services.postgresql.enable</link> = true;
-  <link linkend="opt-services.postgresql.initialScript">services.postgresql.initialScript</link> = pkgs.writeText "synapse-init.sql" ''
+  <xref linkend="opt-services.postgresql.enable" /> = true;
+  <xref linkend="opt-services.postgresql.initialScript" /> = pkgs.writeText "synapse-init.sql" ''
     CREATE ROLE "matrix-synapse" WITH LOGIN PASSWORD 'synapse';
     CREATE DATABASE "matrix-synapse" WITH OWNER "matrix-synapse"
       TEMPLATE template0
@@ -57,78 +62,41 @@ in {
 
   services.nginx = {
     <link linkend="opt-services.nginx.enable">enable</link> = true;
-    # only recommendedProxySettings and recommendedGzipSettings are strictly required,
-    # but the rest make sense as well
     <link linkend="opt-services.nginx.recommendedTlsSettings">recommendedTlsSettings</link> = true;
     <link linkend="opt-services.nginx.recommendedOptimisation">recommendedOptimisation</link> = true;
     <link linkend="opt-services.nginx.recommendedGzipSettings">recommendedGzipSettings</link> = true;
     <link linkend="opt-services.nginx.recommendedProxySettings">recommendedProxySettings</link> = true;
-
     <link linkend="opt-services.nginx.virtualHosts">virtualHosts</link> = {
-      # This host section can be placed on a different host than the rest,
-      # i.e. to delegate from the host being accessible as ${config.networking.domain}
-      # to another host actually running the Matrix homeserver.
-      "${config.networking.domain}" = {
+      "${config.networking.domain}" = { <co xml:id='ex-matrix-synapse-dns' />
         <link linkend="opt-services.nginx.virtualHosts._name_.enableACME">enableACME</link> = true;
         <link linkend="opt-services.nginx.virtualHosts._name_.forceSSL">forceSSL</link> = true;
-
-        <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.extraConfig">locations."= /.well-known/matrix/server".extraConfig</link> =
-          let
-            # use 443 instead of the default 8448 port to unite
-            # the client-server and server-server port for simplicity
-            server = { "m.server" = "${fqdn}:443"; };
-          in ''
-            add_header Content-Type application/json;
-            return 200 '${builtins.toJSON server}';
-          '';
-        <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.extraConfig">locations."= /.well-known/matrix/client".extraConfig</link> =
-          let
-            client = {
-              "m.homeserver" =  { "base_url" = "https://${fqdn}"; };
-              "m.identity_server" =  { "base_url" = "https://vector.im"; };
-            };
-          # ACAO required to allow element-web on any URL to request this json file
-          in ''
-            add_header Content-Type application/json;
-            add_header Access-Control-Allow-Origin *;
-            return 200 '${builtins.toJSON client}';
-          '';
+        <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.extraConfig">locations."= /.well-known/matrix/server".extraConfig</link> = mkWellKnown serverConfig; <co xml:id='ex-matrix-synapse-well-known-server' />
+        <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.extraConfig">locations."= /.well-known/matrix/client".extraConfig</link> = mkWellKnown clientConfig; <co xml:id='ex-matrix-synapse-well-known-client' />
       };
-
-      # Reverse proxy for Matrix client-server and server-server communication
-      ${fqdn} = {
+      "${fqdn}" = {
         <link linkend="opt-services.nginx.virtualHosts._name_.enableACME">enableACME</link> = true;
         <link linkend="opt-services.nginx.virtualHosts._name_.forceSSL">forceSSL</link> = true;
-
-        # Or do a redirect instead of the 404, or whatever is appropriate for you.
-        # But do not put a Matrix Web client here! See the Element web section below.
-        <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.extraConfig">locations."/".extraConfig</link> = ''
+        <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.extraConfig">locations."/".extraConfig</link> = '' <co xml:id='ex-matrix-synapse-rev-default' />
           return 404;
         '';
-
-        # forward all Matrix API calls to the synapse Matrix homeserver
-        locations."/_matrix" = {
-          <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.proxyPass">proxyPass</link> = "http://[::1]:8008"; # without a trailing /
-        };
+        <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.proxyPass">locations."/_matrix".proxyPass</link> = "http://[::1]:8008"; <co xml:id='ex-matrix-synapse-rev-proxy-pass' />
+        <link linkend="opt-services.nginx.virtualHosts._name_.locations._name_.proxyPass">locations."/_synapse/client".proxyPass</link> = "http://[::1]:8008"; <co xml:id='ex-matrix-synapse-rev-client' />
       };
     };
   };
+
   services.matrix-synapse = {
     <link linkend="opt-services.matrix-synapse.enable">enable</link> = true;
-    <link linkend="opt-services.matrix-synapse.settings.server_name">server_name</link> = config.networking.domain;
-    <link linkend="opt-services.matrix-synapse.settings.listeners">listeners</link> = [
-      {
-        <link linkend="opt-services.matrix-synapse.settings.listeners._.port">port</link> = 8008;
+    <link linkend="opt-services.matrix-synapse.settings.server_name">settings.server_name</link> = config.networking.domain;
+    <link linkend="opt-services.matrix-synapse.settings.listeners">settings.listeners</link> = [
+      { <link linkend="opt-services.matrix-synapse.settings.listeners._.port">port</link> = 8008;
         <link linkend="opt-services.matrix-synapse.settings.listeners._.bind_addresses">bind_addresses</link> = [ "::1" ];
         <link linkend="opt-services.matrix-synapse.settings.listeners._.type">type</link> = "http";
         <link linkend="opt-services.matrix-synapse.settings.listeners._.tls">tls</link> = false;
         <link linkend="opt-services.matrix-synapse.settings.listeners._.x_forwarded">x_forwarded</link> = true;
         <link linkend="opt-services.matrix-synapse.settings.listeners._.resources">resources</link> = [ {
-          <link linkend="opt-services.matrix-synapse.settings.listeners._.resources._.names">names</link> = [ "client" ];
+          <link linkend="opt-services.matrix-synapse.settings.listeners._.resources._.names">names</link> = [ "client" "federation" ];
           <link linkend="opt-services.matrix-synapse.settings.listeners._.resources._.compress">compress</link> = true;
-        } {
-          <link linkend="opt-services.matrix-synapse.settings.listeners._.resources._.names">names</link> = [ "federation" ];
-          <link linkend="opt-services.matrix-synapse.settings.listeners._.resources._.compress">compress</link> = false;
         } ];
       }
     ];
@@ -136,20 +104,59 @@ in {
 }
 </programlisting>
   </para>
-
-  <para>
-   If the <code>A</code> and <code>AAAA</code> DNS records on
-   <literal>example.org</literal> do not point on the same host as the records
-   for <code>myhostname.example.org</code>, you can easily move the
-   <code>/.well-known</code> virtualHost section of the code to the host that
-   is serving <literal>example.org</literal>, while the rest stays on
-   <literal>myhostname.example.org</literal> with no other changes required.
-   This pattern also allows to seamlessly move the homeserver from
-   <literal>myhostname.example.org</literal> to
-   <literal>myotherhost.example.org</literal> by only changing the
-   <code>/.well-known</code> redirection target.
-  </para>
-
+  <calloutlist>
+   <callout arearefs='ex-matrix-synapse-dns'>
+    <para>
+     If the <code>A</code> and <code>AAAA</code> DNS records on
+     <literal>example.org</literal> do not point on the same host as the records
+     for <code>myhostname.example.org</code>, you can easily move the
+     <code>/.well-known</code> virtualHost section of the code to the host that
+     is serving <literal>example.org</literal>, while the rest stays on
+     <literal>myhostname.example.org</literal> with no other changes required.
+     This pattern also allows to seamlessly move the homeserver from
+     <literal>myhostname.example.org</literal> to
+     <literal>myotherhost.example.org</literal> by only changing the
+     <code>/.well-known</code> redirection target.
+    </para>
+   </callout>
+   <callout arearefs='ex-matrix-synapse-well-known-server'>
+    <para>
+     This section is not needed if the <link linkend="opt-services.matrix-synapse.settings.server_name">server_name</link>
+     of <package>matrix-synapse</package> is equal to the domain (i.e.
+     <literal>example.org</literal> from <literal>@foo:example.org</literal>)
+     and the federation port is 8448.
+     Further reference can be found in the <link xlink:href="https://matrix-org.github.io/synapse/latest/delegate.html">docs
+     about delegation</link>.
+    </para>
+   </callout>
+   <callout arearefs='ex-matrix-synapse-well-known-client'>
+    <para>
+     This is usually needed for homeserver discovery (from e.g. other Matrix clients).
+     Further reference can be found in the <link xlink:href="https://spec.matrix.org/latest/client-server-api/#getwell-knownmatrixclient">upstream docs</link>
+    </para>
+   </callout>
+   <callout arearefs='ex-matrix-synapse-rev-default'>
+    <para>
+     It's also possible to do a redirect here or something else, this vhost is not
+     needed for Matrix. It's recommended though to <emphasis>not put</emphasis> element
+     here, see also the <link linkend='ex-matrix-synapse-rev-default'>section about Element</link>.
+    </para>
+   </callout>
+   <callout arearefs='ex-matrix-synapse-rev-proxy-pass'>
+    <para>
+     Forward all Matrix API calls to the synapse Matrix homeserver. A trailing slash
+     <emphasis>must not</emphasis> be used here.
+    </para>
+   </callout>
+   <callout arearefs='ex-matrix-synapse-rev-client'>
+    <para>
+     Forward requests for e.g. SSO and password-resets.
+    </para>
+   </callout>
+  </calloutlist>
+ </section>
+ <section xml:id="module-services-matrix-register-users">
+  <title>Registering Matrix users</title>
   <para>
    If you want to run a server with public registration by anybody, you can
    then enable <literal><link linkend="opt-services.matrix-synapse.settings.enable_registration">services.matrix-synapse.settings.enable_registration</link> =
@@ -159,7 +166,7 @@ in {
    To create a new user or admin, run the following after you have set the secret
    and have rebuilt NixOS:
 <screen>
-<prompt>$ </prompt>nix run nixpkgs.matrix-synapse
+<prompt>$ </prompt>nix-shell -p matrix-synapse
 <prompt>$ </prompt>register_new_matrix_user -k <replaceable>your-registration-shared-secret</replaceable> http://localhost:8008
 <prompt>New user localpart: </prompt><replaceable>your-username</replaceable>
 <prompt>Password:</prompt>
@@ -168,12 +175,51 @@ in {
 Success!
 </screen>
    In the example, this would create a user with the Matrix Identifier
-   <literal>@your-username:example.org</literal>. Note that the registration
-   secret ends up in the nix store and therefore is world-readable by any user
-   on your machine, so it makes sense to only temporarily activate the
-   <link linkend="opt-services.matrix-synapse.settings.registration_shared_secret">registration_shared_secret</link>
-   option until a better solution for NixOS is in place.
+   <literal>@your-username:example.org</literal>.
+   <warning>
+    <para>
+     When using <xref linkend="opt-services.matrix-synapse.settings.registration_shared_secret" />, the secret
+     will end up in the world-readable store. Instead it's recommended to deploy the secret
+     in an additional file like this:
+     <itemizedlist>
+      <listitem>
+       <para>
+        Create a file with the following contents:
+<programlisting>registration_shared_secret: your-very-secret-secret</programlisting>
+       </para>
+      </listitem>
+      <listitem>
+       <para>
+        Deploy the file with a secret-manager such as <link xlink:href="https://nixops.readthedocs.io/en/latest/overview.html#managing-keys"><option>deployment.keys</option></link>
+        from <citerefentry><refentrytitle>nixops</refentrytitle><manvolnum>1</manvolnum></citerefentry>
+        or <link xlink:href="https://github.com/Mic92/sops-nix/">sops-nix</link> to
+        e.g. <filename>/run/secrets/matrix-shared-secret</filename> and ensure that it's readable
+        by <package>matrix-synapse</package>.
+       </para>
+      </listitem>
+      <listitem>
+       <para>
+        Include the file like this in your configuration:
+<programlisting>
+{
+  <xref linkend="opt-services.matrix-synapse.extraConfigFiles" /> = [
+    "/run/secrets/matrix-shared-secret"
+  ];
+}
+</programlisting>
+       </para>
+      </listitem>
+     </itemizedlist>
+    </para>
+   </warning>
   </para>
+  <note>
+   <para>
+    It's also possible to user alternative authentication mechanism such as
+    <link xlink:href="https://github.com/matrix-org/matrix-synapse-ldap3">LDAP (via <literal>matrix-synapse-ldap3</literal>)</link>
+    or <link xlink:href="https://matrix-org.github.io/synapse/latest/openid.html">OpenID</link>.
+   </para>
+  </note>
  </section>
  <section xml:id="module-services-matrix-element-web">
   <title>Element (formerly known as Riot) Web Client</title>
@@ -206,10 +252,7 @@ Success!
 
     <link linkend="opt-services.nginx.virtualHosts._name_.root">root</link> = pkgs.element-web.override {
       conf = {
-        default_server_config."m.homeserver" = {
-          "base_url" = "https://${fqdn}";
-          "server_name" = "${fqdn}";
-        };
+        default_server_config = clientConfig; # see `clientConfig` from the snippet above.
       };
     };
   };
@@ -217,15 +260,17 @@ Success!
 </programlisting>
   </para>
 
-  <para>
-   Note that the Element developers do not recommend running Element and your Matrix
-   homeserver on the same fully-qualified domain name for security reasons. In
-   the example, this means that you should not reuse the
-   <literal>myhostname.example.org</literal> virtualHost to also serve Element,
-   but instead serve it on a different subdomain, like
-   <literal>element.example.org</literal> in the example. See the
-   <link xlink:href="https://github.com/vector-im/riot-web#important-security-note">Element
-   Important Security Notes</link> for more information on this subject.
-  </para>
+  <note>
+   <para>
+    The Element developers do not recommend running Element and your Matrix
+    homeserver on the same fully-qualified domain name for security reasons. In
+    the example, this means that you should not reuse the
+    <literal>myhostname.example.org</literal> virtualHost to also serve Element,
+    but instead serve it on a different subdomain, like
+    <literal>element.example.org</literal> in the example. See the
+    <link xlink:href="https://github.com/vector-im/element-web/tree/v1.10.0#important-security-notes">Element
+    Important Security Notes</link> for more information on this subject.
+   </para>
+  </note>
  </section>
 </chapter>
diff --git a/nixos/modules/services/misc/airsonic.nix b/nixos/modules/services/misc/airsonic.nix
index 2b9c6d80abb..b8e9dcaf466 100644
--- a/nixos/modules/services/misc/airsonic.nix
+++ b/nixos/modules/services/misc/airsonic.nix
@@ -9,18 +9,18 @@ in {
   options = {
 
     services.airsonic = {
-      enable = mkEnableOption "Airsonic, the Free and Open Source media streaming server (fork of Subsonic and Libresonic)";
+      enable = mkEnableOption (lib.mdDoc "Airsonic, the Free and Open Source media streaming server (fork of Subsonic and Libresonic)");
 
       user = mkOption {
         type = types.str;
         default = "airsonic";
-        description = "User account under which airsonic runs.";
+        description = lib.mdDoc "User account under which airsonic runs.";
       };
 
       home = mkOption {
         type = types.path;
         default = "/var/lib/airsonic";
-        description = ''
+        description = lib.mdDoc ''
           The directory where Airsonic will create files.
           Make sure it is writable.
         '';
@@ -29,7 +29,7 @@ in {
       virtualHost = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Name of the nginx virtualhost to use and setup. If null, do not setup any virtualhost.
         '';
       };
@@ -37,7 +37,7 @@ in {
       listenAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = ''
+        description = lib.mdDoc ''
           The host name or IP address on which to bind Airsonic.
           The default value is appropriate for first launch, when the
           default credentials are easy to guess. It is also appropriate
@@ -48,9 +48,9 @@ in {
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 4040;
-        description = ''
+        description = lib.mdDoc ''
           The port on which Airsonic will listen for
           incoming HTTP traffic. Set to 0 to disable.
         '';
@@ -59,7 +59,7 @@ in {
       contextPath = mkOption {
         type = types.path;
         default = "/";
-        description = ''
+        description = lib.mdDoc ''
           The context path, i.e., the last part of the Airsonic
           URL. Typically '/' or '/airsonic'. Default '/'
         '';
@@ -68,7 +68,7 @@ in {
       maxMemory = mkOption {
         type = types.int;
         default = 100;
-        description = ''
+        description = lib.mdDoc ''
           The memory limit (max Java heap size) in megabytes.
           Default: 100
         '';
@@ -78,7 +78,7 @@ in {
         type = types.listOf types.path;
         default = [ "${pkgs.ffmpeg.bin}/bin/ffmpeg" ];
         defaultText = literalExpression ''[ "''${pkgs.ffmpeg.bin}/bin/ffmpeg" ]'';
-        description = ''
+        description = lib.mdDoc ''
           List of paths to transcoder executables that should be accessible
           from Airsonic. Symlinks will be created to each executable inside
           ''${config.${opt.home}}/transcoders.
@@ -89,7 +89,7 @@ in {
         type = types.package;
         default = pkgs.jre8;
         defaultText = literalExpression "pkgs.jre8";
-        description = ''
+        description = lib.mdDoc ''
           JRE package to use.
 
           Airsonic only supports Java 8, airsonic-advanced requires at least
@@ -101,11 +101,11 @@ in {
         type = types.path;
         default = "${pkgs.airsonic}/webapps/airsonic.war";
         defaultText = literalExpression ''"''${pkgs.airsonic}/webapps/airsonic.war"'';
-        description = "Airsonic war file to use.";
+        description = lib.mdDoc "Airsonic war file to use.";
       };
 
       jvmOptions = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Extra command line options for the JVM running AirSonic.
           Useful for sending jukebox output to non-default alsa
           devices.
diff --git a/nixos/modules/services/misc/ananicy.nix b/nixos/modules/services/misc/ananicy.nix
index 191666bc362..d2287fba6af 100644
--- a/nixos/modules/services/misc/ananicy.nix
+++ b/nixos/modules/services/misc/ananicy.nix
@@ -11,14 +11,14 @@ in
 {
   options = {
     services.ananicy = {
-      enable = mkEnableOption "Ananicy, an auto nice daemon";
+      enable = mkEnableOption (lib.mdDoc "Ananicy, an auto nice daemon");
 
       package = mkOption {
         type = types.package;
         default = pkgs.ananicy;
         defaultText = literalExpression "pkgs.ananicy";
         example = literalExpression "pkgs.ananicy-cpp";
-        description = ''
+        description = lib.mdDoc ''
           Which ananicy package to use.
         '';
       };
@@ -29,18 +29,18 @@ in
         example = {
           apply_nice = false;
         };
-        description = ''
-          See <link xlink:href="https://github.com/Nefelim4ag/Ananicy/blob/master/ananicy.d/ananicy.conf"/>
+        description = lib.mdDoc ''
+          See <https://github.com/Nefelim4ag/Ananicy/blob/master/ananicy.d/ananicy.conf>
         '';
       };
 
       extraRules = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra rules in json format on separate lines. See:
-          <link xlink:href="https://github.com/Nefelim4ag/Ananicy#configuration"/>
-          <link xlink:href="https://gitlab.com/ananicy-cpp/ananicy-cpp/#global-configuration"/>
+          <https://github.com/Nefelim4ag/Ananicy#configuration>
+          <https://gitlab.com/ananicy-cpp/ananicy-cpp/#global-configuration>
         '';
         example = literalExpression ''
           '''
diff --git a/nixos/modules/services/misc/ankisyncd.nix b/nixos/modules/services/misc/ankisyncd.nix
index 69e471f4f57..5198b824202 100644
--- a/nixos/modules/services/misc/ankisyncd.nix
+++ b/nixos/modules/services/misc/ankisyncd.nix
@@ -28,31 +28,31 @@ let
 in
   {
     options.services.ankisyncd = {
-      enable = mkEnableOption "ankisyncd";
+      enable = mkEnableOption (lib.mdDoc "ankisyncd");
 
       package = mkOption {
         type = types.package;
         default = pkgs.ankisyncd;
         defaultText = literalExpression "pkgs.ankisyncd";
-        description = "The package to use for the ankisyncd command.";
+        description = lib.mdDoc "The package to use for the ankisyncd command.";
       };
 
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = "ankisyncd host";
+        description = lib.mdDoc "ankisyncd host";
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 27701;
-        description = "ankisyncd port";
+        description = lib.mdDoc "ankisyncd port";
       };
 
       openFirewall = mkOption {
         default = false;
         type = types.bool;
-        description = "Whether to open the firewall for the specified port.";
+        description = lib.mdDoc "Whether to open the firewall for the specified port.";
       };
     };
 
diff --git a/nixos/modules/services/misc/apache-kafka.nix b/nixos/modules/services/misc/apache-kafka.nix
index d1856fff4aa..598907aaf1c 100644
--- a/nixos/modules/services/misc/apache-kafka.nix
+++ b/nixos/modules/services/misc/apache-kafka.nix
@@ -26,49 +26,49 @@ in {
 
   options.services.apache-kafka = {
     enable = mkOption {
-      description = "Whether to enable Apache Kafka.";
+      description = lib.mdDoc "Whether to enable Apache Kafka.";
       default = false;
       type = types.bool;
     };
 
     brokerId = mkOption {
-      description = "Broker ID.";
+      description = lib.mdDoc "Broker ID.";
       default = -1;
       type = types.int;
     };
 
     port = mkOption {
-      description = "Port number the broker should listen on.";
+      description = lib.mdDoc "Port number the broker should listen on.";
       default = 9092;
-      type = types.int;
+      type = types.port;
     };
 
     hostname = mkOption {
-      description = "Hostname the broker should bind to.";
+      description = lib.mdDoc "Hostname the broker should bind to.";
       default = "localhost";
       type = types.str;
     };
 
     logDirs = mkOption {
-      description = "Log file directories";
+      description = lib.mdDoc "Log file directories";
       default = [ "/tmp/kafka-logs" ];
       type = types.listOf types.path;
     };
 
     zookeeper = mkOption {
-      description = "Zookeeper connection string";
+      description = lib.mdDoc "Zookeeper connection string";
       default = "localhost:2181";
       type = types.str;
     };
 
     extraProperties = mkOption {
-      description = "Extra properties for server.properties.";
+      description = lib.mdDoc "Extra properties for server.properties.";
       type = types.nullOr types.lines;
       default = null;
     };
 
     serverProperties = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Complete server.properties content. Other server.properties config
         options will be ignored if this option is used.
       '';
@@ -77,7 +77,7 @@ in {
     };
 
     log4jProperties = mkOption {
-      description = "Kafka log4j property configuration.";
+      description = lib.mdDoc "Kafka log4j property configuration.";
       default = ''
         log4j.rootLogger=INFO, stdout
 
@@ -89,7 +89,7 @@ in {
     };
 
     jvmOptions = mkOption {
-      description = "Extra command line options for the JVM running Kafka.";
+      description = lib.mdDoc "Extra command line options for the JVM running Kafka.";
       default = [];
       type = types.listOf types.str;
       example = [
@@ -100,14 +100,14 @@ in {
     };
 
     package = mkOption {
-      description = "The kafka package to use";
+      description = lib.mdDoc "The kafka package to use";
       default = pkgs.apacheKafka;
       defaultText = literalExpression "pkgs.apacheKafka";
       type = types.package;
     };
 
     jre = mkOption {
-      description = "The JRE with which to run Kafka";
+      description = lib.mdDoc "The JRE with which to run Kafka";
       default = cfg.package.passthru.jre;
       defaultText = literalExpression "pkgs.apacheKafka.passthru.jre";
       type = types.package;
diff --git a/nixos/modules/services/misc/autofs.nix b/nixos/modules/services/misc/autofs.nix
index 5fce990afec..55ab15ff003 100644
--- a/nixos/modules/services/misc/autofs.nix
+++ b/nixos/modules/services/misc/autofs.nix
@@ -21,7 +21,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Mount filesystems on demand. Unmount them automatically.
           You may also be interested in afuse.
         '';
@@ -46,21 +46,21 @@ in
             /auto file:''${mapConf}
           '''
         '';
-        description = ''
-          Contents of <literal>/etc/auto.master</literal> file. See <command>auto.master(5)</command> and <command>autofs(5)</command>.
+        description = lib.mdDoc ''
+          Contents of `/etc/auto.master` file. See {command}`auto.master(5)` and {command}`autofs(5)`.
         '';
       };
 
       timeout = mkOption {
         type = types.int;
         default = 600;
-        description = "Set the global minimum timeout, in seconds, until directories are unmounted";
+        description = lib.mdDoc "Set the global minimum timeout, in seconds, until directories are unmounted";
       };
 
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Pass -d and -7 to automount and write log to the system journal.
         '';
       };
diff --git a/nixos/modules/services/misc/autorandr.nix b/nixos/modules/services/misc/autorandr.nix
index ef799e9ce3b..365fdd5fcc3 100644
--- a/nixos/modules/services/misc/autorandr.nix
+++ b/nixos/modules/services/misc/autorandr.nix
@@ -27,22 +27,22 @@ let
     options = {
       fingerprint = mkOption {
         type = types.attrsOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Output name to EDID mapping.
-          Use <code>autorandr --fingerprint</code> to get current setup values.
+          Use `autorandr --fingerprint` to get current setup values.
         '';
         default = { };
       };
 
       config = mkOption {
         type = types.attrsOf configModule;
-        description = "Per output profile configuration.";
+        description = lib.mdDoc "Per output profile configuration.";
         default = { };
       };
 
       hooks = mkOption {
         type = hooksModule;
-        description = "Profile hook scripts.";
+        description = lib.mdDoc "Profile hook scripts.";
         default = { };
       };
     };
@@ -52,54 +52,54 @@ let
     options = {
       enable = mkOption {
         type = types.bool;
-        description = "Whether to enable the output.";
+        description = lib.mdDoc "Whether to enable the output.";
         default = true;
       };
 
       crtc = mkOption {
         type = types.nullOr types.ints.unsigned;
-        description = "Output video display controller.";
+        description = lib.mdDoc "Output video display controller.";
         default = null;
         example = 0;
       };
 
       primary = mkOption {
         type = types.bool;
-        description = "Whether output should be marked as primary";
+        description = lib.mdDoc "Whether output should be marked as primary";
         default = false;
       };
 
       position = mkOption {
         type = types.str;
-        description = "Output position";
+        description = lib.mdDoc "Output position";
         default = "";
         example = "5760x0";
       };
 
       mode = mkOption {
         type = types.str;
-        description = "Output resolution.";
+        description = lib.mdDoc "Output resolution.";
         default = "";
         example = "3840x2160";
       };
 
       rate = mkOption {
         type = types.str;
-        description = "Output framerate.";
+        description = lib.mdDoc "Output framerate.";
         default = "";
         example = "60.00";
       };
 
       gamma = mkOption {
         type = types.str;
-        description = "Output gamma configuration.";
+        description = lib.mdDoc "Output gamma configuration.";
         default = "";
         example = "1.0:0.909:0.833";
       };
 
       rotate = mkOption {
         type = types.nullOr (types.enum [ "normal" "left" "right" "inverted" ]);
-        description = "Output rotate configuration.";
+        description = lib.mdDoc "Output rotate configuration.";
         default = null;
         example = "left";
       };
@@ -114,19 +114,16 @@ let
             [ 0.0 0.0 1.0 ]
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Refer to
-          <citerefentry>
-            <refentrytitle>xrandr</refentrytitle>
-            <manvolnum>1</manvolnum>
-          </citerefentry>
+          {manpage}`xrandr(1)`
           for the documentation of the transform matrix.
         '';
       };
 
       dpi = mkOption {
         type = types.nullOr types.ints.positive;
-        description = "Output DPI configuration.";
+        description = lib.mdDoc "Output DPI configuration.";
         default = null;
         example = 96;
       };
@@ -136,36 +133,33 @@ let
           options = {
             method = mkOption {
               type = types.enum [ "factor" "pixel" ];
-              description = "Output scaling method.";
+              description = lib.mdDoc "Output scaling method.";
               default = "factor";
               example = "pixel";
             };
 
             x = mkOption {
               type = types.either types.float types.ints.positive;
-              description = "Horizontal scaling factor/pixels.";
+              description = lib.mdDoc "Horizontal scaling factor/pixels.";
             };
 
             y = mkOption {
               type = types.either types.float types.ints.positive;
-              description = "Vertical scaling factor/pixels.";
+              description = lib.mdDoc "Vertical scaling factor/pixels.";
             };
           };
         });
-        description = ''
+        description = lib.mdDoc ''
           Output scale configuration.
-          </para><para>
+
           Either configure by pixels or a scaling factor. When using pixel method the
-          <citerefentry>
-            <refentrytitle>xrandr</refentrytitle>
-            <manvolnum>1</manvolnum>
-          </citerefentry>
+          {manpage}`xrandr(1)`
           option
-          <parameter class="command">--scale-from</parameter>
+          `--scale-from`
           will be used; when using factor method the option
-          <parameter class="command">--scale</parameter>
+          `--scale`
           will be used.
-          </para><para>
+
           This option is a shortcut version of the transform option and they are mutually
           exclusive.
         '';
@@ -184,19 +178,19 @@ let
     options = {
       postswitch = mkOption {
         type = types.attrsOf hookType;
-        description = "Postswitch hook executed after mode switch.";
+        description = lib.mdDoc "Postswitch hook executed after mode switch.";
         default = { };
       };
 
       preswitch = mkOption {
         type = types.attrsOf hookType;
-        description = "Preswitch hook executed before mode switch.";
+        description = lib.mdDoc "Preswitch hook executed before mode switch.";
         default = { };
       };
 
       predetect = mkOption {
         type = types.attrsOf hookType;
-        description = ''
+        description = lib.mdDoc ''
           Predetect hook executed before autorandr attempts to run xrandr.
         '';
         default = { };
@@ -248,12 +242,12 @@ in {
   options = {
 
     services.autorandr = {
-      enable = mkEnableOption "handling of hotplug and sleep events by autorandr";
+      enable = mkEnableOption (lib.mdDoc "handling of hotplug and sleep events by autorandr");
 
       defaultTarget = mkOption {
         default = "default";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Fallback if no monitor layout can be detected. See the docs
           (https://github.com/phillipberndt/autorandr/blob/v1.0/README.md#how-to-use)
           for further reference.
@@ -262,7 +256,7 @@ in {
 
       hooks = mkOption {
         type = hooksModule;
-        description = "Global hook scripts";
+        description = lib.mdDoc "Global hook scripts";
         default = { };
         example = ''
           {
@@ -292,7 +286,7 @@ in {
       };
       profiles = mkOption {
         type = types.attrsOf profileModule;
-        description = "Autorandr profiles specification.";
+        description = lib.mdDoc "Autorandr profiles specification.";
         default = { };
         example = literalExpression ''
           {
diff --git a/nixos/modules/services/misc/bazarr.nix b/nixos/modules/services/misc/bazarr.nix
index 99343a146a7..07c93505359 100644
--- a/nixos/modules/services/misc/bazarr.nix
+++ b/nixos/modules/services/misc/bazarr.nix
@@ -8,30 +8,30 @@ in
 {
   options = {
     services.bazarr = {
-      enable = mkEnableOption "bazarr, a subtitle manager for Sonarr and Radarr";
+      enable = mkEnableOption (lib.mdDoc "bazarr, a subtitle manager for Sonarr and Radarr");
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the bazarr web interface.";
+        description = lib.mdDoc "Open ports in the firewall for the bazarr web interface.";
       };
 
       listenPort = mkOption {
         type = types.port;
         default = 6767;
-        description = "Port on which the bazarr web interface should listen";
+        description = lib.mdDoc "Port on which the bazarr web interface should listen";
       };
 
       user = mkOption {
         type = types.str;
         default = "bazarr";
-        description = "User account under which bazarr runs.";
+        description = lib.mdDoc "User account under which bazarr runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "bazarr";
-        description = "Group under which bazarr runs.";
+        description = lib.mdDoc "Group under which bazarr runs.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/beanstalkd.nix b/nixos/modules/services/misc/beanstalkd.nix
index 1c674a5b23b..4262cae323b 100644
--- a/nixos/modules/services/misc/beanstalkd.nix
+++ b/nixos/modules/services/misc/beanstalkd.nix
@@ -12,18 +12,18 @@ in
 
   options = {
     services.beanstalkd = {
-      enable = mkEnableOption "the Beanstalk work queue";
+      enable = mkEnableOption (lib.mdDoc "the Beanstalk work queue");
 
       listen = {
         port = mkOption {
-          type = types.int;
-          description = "TCP port that will be used to accept client connections.";
+          type = types.port;
+          description = lib.mdDoc "TCP port that will be used to accept client connections.";
           default = 11300;
         };
 
         address = mkOption {
           type = types.str;
-          description = "IP address to listen on.";
+          description = lib.mdDoc "IP address to listen on.";
           default = "127.0.0.1";
           example = "0.0.0.0";
         };
@@ -32,7 +32,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to open ports in the firewall for the server.";
+        description = lib.mdDoc "Whether to open ports in the firewall for the server.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/bees.nix b/nixos/modules/services/misc/bees.nix
index fa00d7e4f55..37f90c68222 100644
--- a/nixos/modules/services/misc/bees.nix
+++ b/nixos/modules/services/misc/bees.nix
@@ -11,14 +11,13 @@ let
   fsOptions = with types; {
     options.spec = mkOption {
       type = str;
-      description = ''
+      description = lib.mdDoc ''
         Description of how to identify the filesystem to be duplicated by this
         instance of bees. Note that deduplication crosses subvolumes; one must
         not configure multiple instances for subvolumes of the same filesystem
         (or block devices which are part of the same filesystem), but only for
         completely independent btrfs filesystems.
-        </para>
-        <para>
+
         This must be in a format usable by findmnt; that could be a key=value
         pair, or a bare path to a mount point.
         Using bare paths will allow systemd to start the beesd service only
@@ -29,14 +28,12 @@ let
     options.hashTableSizeMB = mkOption {
       type = types.addCheck types.int (n: mod n 16 == 0);
       default = 1024; # 1GB; default from upstream beesd script
-      description = ''
+      description = lib.mdDoc ''
         Hash table size in MB; must be a multiple of 16.
-        </para>
-        <para>
+
         A larger ratio of index size to storage size means smaller blocks of
         duplicate content are recognized.
-        </para>
-        <para>
+
         If you have 1TB of data, a 4GB hash table (which is to say, a value of
         4096) will permit 4KB extents (the smallest possible size) to be
         recognized, whereas a value of 1024 -- creating a 1GB hash table --
@@ -47,12 +44,12 @@ let
       type = types.enum (attrNames logLevels ++ attrValues logLevels);
       apply = v: if isString v then logLevels.${v} else v;
       default = "info";
-      description = "Log verbosity (syslog keyword/level).";
+      description = lib.mdDoc "Log verbosity (syslog keyword/level).";
     };
     options.workDir = mkOption {
       type = str;
       default = ".beeshome";
-      description = ''
+      description = lib.mdDoc ''
         Name (relative to the root of the filesystem) of the subvolume where
         the hash table will be stored.
       '';
@@ -60,7 +57,7 @@ let
     options.extraOptions = mkOption {
       type = listOf str;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         Extra command-line options passed to the daemon. See upstream bees documentation.
       '';
       example = literalExpression ''
@@ -75,7 +72,7 @@ in
   options.services.beesd = {
     filesystems = mkOption {
       type = with types; attrsOf (submodule fsOptions);
-      description = "BTRFS filesystems to run block-level deduplication on.";
+      description = lib.mdDoc "BTRFS filesystems to run block-level deduplication on.";
       default = { };
       example = literalExpression ''
         {
diff --git a/nixos/modules/services/misc/bepasty.nix b/nixos/modules/services/misc/bepasty.nix
index f69832e5b2b..70d07629493 100644
--- a/nixos/modules/services/misc/bepasty.nix
+++ b/nixos/modules/services/misc/bepasty.nix
@@ -13,11 +13,11 @@ let
 in
 {
   options.services.bepasty = {
-    enable = mkEnableOption "Bepasty servers";
+    enable = mkEnableOption (lib.mdDoc "Bepasty servers");
 
     servers = mkOption {
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         configure a number of bepasty servers which will be started with
         gunicorn.
         '';
@@ -27,7 +27,7 @@ in
 
           bind = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               Bind address to be used for this server.
               '';
             example = "0.0.0.0:8000";
@@ -36,7 +36,7 @@ in
 
           dataDir = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               Path to the directory where the pastes will be saved to
               '';
             default = default_home+"/data";
@@ -44,7 +44,7 @@ in
 
           defaultPermissions = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               default permissions for all unauthenticated accesses.
               '';
             example = "read,create,delete";
@@ -53,7 +53,7 @@ in
 
           extraConfig = mkOption {
             type = types.lines;
-            description = ''
+            description = lib.mdDoc ''
               Extra configuration for bepasty server to be appended on the
               configuration.
               see https://bepasty-server.readthedocs.org/en/latest/quickstart.html#configuring-bepasty
@@ -70,13 +70,13 @@ in
 
           secretKey = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               server secret for safe session cookies, must be set.
 
               Warning: this secret is stored in the WORLD-READABLE Nix store!
 
-              It's recommended to use <option>secretKeyFile</option>
-              which takes precedence over <option>secretKey</option>.
+              It's recommended to use {option}`secretKeyFile`
+              which takes precedence over {option}`secretKey`.
               '';
             default = "";
           };
@@ -84,19 +84,19 @@ in
           secretKeyFile = mkOption {
             type = types.nullOr types.str;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               A file that contains the server secret for safe session cookies, must be set.
 
-              <option>secretKeyFile</option> takes precedence over <option>secretKey</option>.
+              {option}`secretKeyFile` takes precedence over {option}`secretKey`.
 
-              Warning: when <option>secretKey</option> is non-empty <option>secretKeyFile</option>
+              Warning: when {option}`secretKey` is non-empty {option}`secretKeyFile`
               defaults to a file in the WORLD-READABLE Nix store containing that secret.
               '';
           };
 
           workDir = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               Path to the working directory (used for config and pidfile).
               Defaults to the users home directory.
               '';
diff --git a/nixos/modules/services/misc/calibre-server.nix b/nixos/modules/services/misc/calibre-server.nix
index 2467d34b524..77c60381a31 100644
--- a/nixos/modules/services/misc/calibre-server.nix
+++ b/nixos/modules/services/misc/calibre-server.nix
@@ -23,23 +23,23 @@ in
   options = {
     services.calibre-server = {
 
-      enable = mkEnableOption "calibre-server";
+      enable = mkEnableOption (lib.mdDoc "calibre-server");
 
       libraries = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The directories of the libraries to serve. They must be readable for the user under which the server runs.
         '';
         type = types.listOf types.path;
       };
 
       user = mkOption {
-        description = "The user under which calibre-server runs.";
+        description = lib.mdDoc "The user under which calibre-server runs.";
         type = types.str;
         default = "calibre-server";
       };
 
       group = mkOption {
-        description = "The group under which calibre-server runs.";
+        description = lib.mdDoc "The group under which calibre-server runs.";
         type = types.str;
         default = "calibre-server";
       };
diff --git a/nixos/modules/services/misc/canto-daemon.nix b/nixos/modules/services/misc/canto-daemon.nix
index db51a263aab..8150e038bc1 100644
--- a/nixos/modules/services/misc/canto-daemon.nix
+++ b/nixos/modules/services/misc/canto-daemon.nix
@@ -16,7 +16,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the canto RSS daemon.";
+        description = lib.mdDoc "Whether to enable the canto RSS daemon.";
       };
     };
 
diff --git a/nixos/modules/services/misc/cfdyndns.nix b/nixos/modules/services/misc/cfdyndns.nix
index 5885617d742..9cd8b188ffa 100644
--- a/nixos/modules/services/misc/cfdyndns.nix
+++ b/nixos/modules/services/misc/cfdyndns.nix
@@ -14,11 +14,11 @@ in
 
   options = {
     services.cfdyndns = {
-      enable = mkEnableOption "Cloudflare Dynamic DNS Client";
+      enable = mkEnableOption (lib.mdDoc "Cloudflare Dynamic DNS Client");
 
       email = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The email address to use to authenticate to CloudFlare.
         '';
       };
@@ -26,7 +26,7 @@ in
       apikeyFile = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           The path to a file containing the API Key
           used to authenticate with CloudFlare.
         '';
@@ -36,7 +36,7 @@ in
         default = [];
         example = [ "host.tld" ];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The records to update in CloudFlare.
         '';
       };
diff --git a/nixos/modules/services/misc/cgminer.nix b/nixos/modules/services/misc/cgminer.nix
index 60f75530723..fced106cb32 100644
--- a/nixos/modules/services/misc/cgminer.nix
+++ b/nixos/modules/services/misc/cgminer.nix
@@ -31,25 +31,25 @@ in
 
     services.cgminer = {
 
-      enable = mkEnableOption "cgminer, an ASIC/FPGA/GPU miner for bitcoin and litecoin";
+      enable = mkEnableOption (lib.mdDoc "cgminer, an ASIC/FPGA/GPU miner for bitcoin and litecoin");
 
       package = mkOption {
         default = pkgs.cgminer;
         defaultText = literalExpression "pkgs.cgminer";
-        description = "Which cgminer derivation to use.";
+        description = lib.mdDoc "Which cgminer derivation to use.";
         type = types.package;
       };
 
       user = mkOption {
         type = types.str;
         default = "cgminer";
-        description = "User account under which cgminer runs";
+        description = lib.mdDoc "User account under which cgminer runs";
       };
 
       pools = mkOption {
         default = [];  # Run benchmark
         type = types.listOf (types.attrsOf types.str);
-        description = "List of pools where to mine";
+        description = lib.mdDoc "List of pools where to mine";
         example = [{
           url = "http://p2pool.org:9332";
           username = "17EUZxTvs9uRmPsjPZSYUU3zCz9iwstudk";
@@ -60,7 +60,7 @@ in
       hardware = mkOption {
         default = []; # Run without options
         type = types.listOf (types.attrsOf (types.either types.str types.int));
-        description= "List of config options for every GPU";
+        description= lib.mdDoc "List of config options for every GPU";
         example = [
         {
           intensity = 9;
@@ -87,7 +87,7 @@ in
       config = mkOption {
         default = {};
         type = types.attrsOf (types.either types.bool types.int);
-        description = "Additional config";
+        description = lib.mdDoc "Additional config";
         example = {
           auto-fan = true;
           auto-gpu = true;
diff --git a/nixos/modules/services/misc/clipcat.nix b/nixos/modules/services/misc/clipcat.nix
index 8b749aa7289..0129de3a9ef 100644
--- a/nixos/modules/services/misc/clipcat.nix
+++ b/nixos/modules/services/misc/clipcat.nix
@@ -7,13 +7,13 @@ let
 in {
 
   options.services.clipcat= {
-    enable = mkEnableOption "Clipcat clipboard daemon";
+    enable = mkEnableOption (lib.mdDoc "Clipcat clipboard daemon");
 
     package = mkOption {
       type = types.package;
       default = pkgs.clipcat;
       defaultText = literalExpression "pkgs.clipcat";
-      description = "clipcat derivation to use.";
+      description = lib.mdDoc "clipcat derivation to use.";
     };
   };
 
diff --git a/nixos/modules/services/misc/clipmenu.nix b/nixos/modules/services/misc/clipmenu.nix
index ef95985f8d8..1cc8c4c47f7 100644
--- a/nixos/modules/services/misc/clipmenu.nix
+++ b/nixos/modules/services/misc/clipmenu.nix
@@ -7,13 +7,13 @@ let
 in {
 
   options.services.clipmenu = {
-    enable = mkEnableOption "clipmenu, the clipboard management daemon";
+    enable = mkEnableOption (lib.mdDoc "clipmenu, the clipboard management daemon");
 
     package = mkOption {
       type = types.package;
       default = pkgs.clipmenu;
       defaultText = literalExpression "pkgs.clipmenu";
-      description = "clipmenu derivation to use.";
+      description = lib.mdDoc "clipmenu derivation to use.";
     };
   };
 
diff --git a/nixos/modules/services/misc/confd.nix b/nixos/modules/services/misc/confd.nix
index 6c66786524b..17c1be57ccb 100755
--- a/nixos/modules/services/misc/confd.nix
+++ b/nixos/modules/services/misc/confd.nix
@@ -17,52 +17,52 @@ let
 
 in {
   options.services.confd = {
-    enable = mkEnableOption "confd service";
+    enable = mkEnableOption (lib.mdDoc "confd service");
 
     backend = mkOption {
-      description = "Confd config storage backend to use.";
+      description = lib.mdDoc "Confd config storage backend to use.";
       default = "etcd";
       type = types.enum ["etcd" "consul" "redis" "zookeeper"];
     };
 
     interval = mkOption {
-      description = "Confd check interval.";
+      description = lib.mdDoc "Confd check interval.";
       default = 10;
       type = types.int;
     };
 
     nodes = mkOption {
-      description = "Confd list of nodes to connect to.";
+      description = lib.mdDoc "Confd list of nodes to connect to.";
       default = [ "http://127.0.0.1:2379" ];
       type = types.listOf types.str;
     };
 
     watch = mkOption {
-      description = "Confd, whether to watch etcd config for changes.";
+      description = lib.mdDoc "Confd, whether to watch etcd config for changes.";
       default = true;
       type = types.bool;
     };
 
     prefix = mkOption {
-      description = "The string to prefix to keys.";
+      description = lib.mdDoc "The string to prefix to keys.";
       default = "/";
       type = types.path;
     };
 
     logLevel = mkOption {
-      description = "Confd log level.";
+      description = lib.mdDoc "Confd log level.";
       default = "info";
       type = types.enum ["info" "debug"];
     };
 
     confDir = mkOption {
-      description = "The path to the confd configs.";
+      description = lib.mdDoc "The path to the confd configs.";
       default = "/etc/confd";
       type = types.path;
     };
 
     package = mkOption {
-      description = "Confd package to use.";
+      description = lib.mdDoc "Confd package to use.";
       default = pkgs.confd;
       defaultText = literalExpression "pkgs.confd";
       type = types.package;
diff --git a/nixos/modules/services/misc/cpuminer-cryptonight.nix b/nixos/modules/services/misc/cpuminer-cryptonight.nix
index 907b9d90da2..7b18c6b3cd2 100644
--- a/nixos/modules/services/misc/cpuminer-cryptonight.nix
+++ b/nixos/modules/services/misc/cpuminer-cryptonight.nix
@@ -23,27 +23,27 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the cpuminer cryptonight miner.
         '';
       };
       url = mkOption {
         type = types.str;
-        description = "URL of mining server";
+        description = lib.mdDoc "URL of mining server";
       };
       user = mkOption {
         type = types.str;
-        description = "Username for mining server";
+        description = lib.mdDoc "Username for mining server";
       };
       pass = mkOption {
         type = types.str;
         default = "x";
-        description = "Password for mining server";
+        description = lib.mdDoc "Password for mining server";
       };
       threads = mkOption {
         type = types.int;
         default = 0;
-        description = "Number of miner threads, defaults to available processors";
+        description = lib.mdDoc "Number of miner threads, defaults to available processors";
       };
     };
 
diff --git a/nixos/modules/services/misc/devmon.nix b/nixos/modules/services/misc/devmon.nix
index e4a3348646b..bd0b738b701 100644
--- a/nixos/modules/services/misc/devmon.nix
+++ b/nixos/modules/services/misc/devmon.nix
@@ -8,7 +8,7 @@ let
 in {
   options = {
     services.devmon = {
-      enable = mkEnableOption "devmon, an automatic device mounting daemon";
+      enable = mkEnableOption (lib.mdDoc "devmon, an automatic device mounting daemon");
     };
   };
 
diff --git a/nixos/modules/services/misc/dictd.nix b/nixos/modules/services/misc/dictd.nix
index 96e2a4e7c26..4b714b84f3b 100644
--- a/nixos/modules/services/misc/dictd.nix
+++ b/nixos/modules/services/misc/dictd.nix
@@ -17,7 +17,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the DICT.org dictionary server.
         '';
       };
@@ -27,7 +27,7 @@ in
         default = with pkgs.dictdDBs; [ wiktionary wordnet ];
         defaultText = literalExpression "with pkgs.dictdDBs; [ wiktionary wordnet ]";
         example = literalExpression "[ pkgs.dictdDBs.nld2eng ]";
-        description = "List of databases to make available.";
+        description = lib.mdDoc "List of databases to make available.";
       };
 
     };
@@ -45,6 +45,10 @@ in
     # get the command line client on system path to make some use of the service
     environment.systemPackages = [ pkgs.dict ];
 
+    environment.etc."dict.conf".text = ''
+      server localhost
+    '';
+
     users.users.dictd =
       { group = "dictd";
         description = "DICT.org dictd server";
diff --git a/nixos/modules/services/misc/disnix.nix b/nixos/modules/services/misc/disnix.nix
index 07c0613336a..1cdfeef57ce 100644
--- a/nixos/modules/services/misc/disnix.nix
+++ b/nixos/modules/services/misc/disnix.nix
@@ -17,29 +17,29 @@ in
 
     services.disnix = {
 
-      enable = mkEnableOption "Disnix";
+      enable = mkEnableOption (lib.mdDoc "Disnix");
 
       enableMultiUser = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to support multi-user mode by enabling the Disnix D-Bus service";
+        description = lib.mdDoc "Whether to support multi-user mode by enabling the Disnix D-Bus service";
       };
 
-      useWebServiceInterface = mkEnableOption "the DisnixWebService interface running on Apache Tomcat";
+      useWebServiceInterface = mkEnableOption (lib.mdDoc "the DisnixWebService interface running on Apache Tomcat");
 
       package = mkOption {
         type = types.path;
-        description = "The Disnix package";
+        description = lib.mdDoc "The Disnix package";
         default = pkgs.disnix;
         defaultText = literalExpression "pkgs.disnix";
       };
 
-      enableProfilePath = mkEnableOption "exposing the Disnix profiles in the system's PATH";
+      enableProfilePath = mkEnableOption (lib.mdDoc "exposing the Disnix profiles in the system's PATH");
 
       profiles = mkOption {
         type = types.listOf types.str;
         default = [ "default" ];
-        description = "Names of the Disnix profiles to expose in the system's PATH";
+        description = lib.mdDoc "Names of the Disnix profiles to expose in the system's PATH";
       };
     };
 
diff --git a/nixos/modules/services/misc/docker-registry.nix b/nixos/modules/services/misc/docker-registry.nix
index cb68a29c530..98edb413f3c 100644
--- a/nixos/modules/services/misc/docker-registry.nix
+++ b/nixos/modules/services/misc/docker-registry.nix
@@ -47,16 +47,16 @@ let
 
 in {
   options.services.dockerRegistry = {
-    enable = mkEnableOption "Docker Registry";
+    enable = mkEnableOption (lib.mdDoc "Docker Registry");
 
     listenAddress = mkOption {
-      description = "Docker registry host or ip to bind to.";
+      description = lib.mdDoc "Docker registry host or ip to bind to.";
       default = "127.0.0.1";
       type = types.str;
     };
 
     port = mkOption {
-      description = "Docker registry port to bind to.";
+      description = lib.mdDoc "Docker registry port to bind to.";
       default = 5000;
       type = types.port;
     };
@@ -64,7 +64,7 @@ in {
     storagePath = mkOption {
       type = types.nullOr types.path;
       default = "/var/lib/docker-registry";
-      description = ''
+      description = lib.mdDoc ''
         Docker registry storage path for the filesystem storage backend. Set to
         null to configure another backend via extraConfig.
       '';
@@ -73,40 +73,39 @@ in {
     enableDelete = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable delete for manifests and blobs.";
+      description = lib.mdDoc "Enable delete for manifests and blobs.";
     };
 
-    enableRedisCache = mkEnableOption "redis as blob cache";
+    enableRedisCache = mkEnableOption (lib.mdDoc "redis as blob cache");
 
     redisUrl = mkOption {
       type = types.str;
       default = "localhost:6379";
-      description = "Set redis host and port.";
+      description = lib.mdDoc "Set redis host and port.";
     };
 
     redisPassword = mkOption {
       type = types.str;
       default = "";
-      description = "Set redis password.";
+      description = lib.mdDoc "Set redis password.";
     };
 
     extraConfig = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Docker extra registry configuration via environment variables.
       '';
       default = {};
       type = types.attrs;
     };
 
-    enableGarbageCollect = mkEnableOption "garbage collect";
+    enableGarbageCollect = mkEnableOption (lib.mdDoc "garbage collect");
 
     garbageCollectDates = mkOption {
       default = "daily";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Specification (in the format described by
-        <citerefentry><refentrytitle>systemd.time</refentrytitle>
-        <manvolnum>7</manvolnum></citerefentry>) of the time at
+        {manpage}`systemd.time(7)`) of the time at
         which the garbage collect will occur.
       '';
     };
diff --git a/nixos/modules/services/misc/domoticz.nix b/nixos/modules/services/misc/domoticz.nix
index b1353d48404..fd9fcf0b78e 100644
--- a/nixos/modules/services/misc/domoticz.nix
+++ b/nixos/modules/services/misc/domoticz.nix
@@ -12,18 +12,18 @@ in {
   options = {
 
     services.domoticz = {
-      enable = mkEnableOption pkgDesc;
+      enable = mkEnableOption (lib.mdDoc pkgDesc);
 
       bind = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = "IP address to bind to.";
+        description = lib.mdDoc "IP address to bind to.";
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8080;
-        description = "Port to bind to for HTTP, set to 0 to disable HTTP.";
+        description = lib.mdDoc "Port to bind to for HTTP, set to 0 to disable HTTP.";
       };
 
     };
diff --git a/nixos/modules/services/misc/duckling.nix b/nixos/modules/services/misc/duckling.nix
index 77d2a92380b..4d06ca7fa66 100644
--- a/nixos/modules/services/misc/duckling.nix
+++ b/nixos/modules/services/misc/duckling.nix
@@ -7,12 +7,12 @@ let
 in {
   options = {
     services.duckling = {
-      enable = mkEnableOption "duckling";
+      enable = mkEnableOption (lib.mdDoc "duckling");
 
       port = mkOption {
         type = types.port;
         default = 8080;
-        description = ''
+        description = lib.mdDoc ''
           Port on which duckling will run.
         '';
       };
diff --git a/nixos/modules/services/misc/dwm-status.nix b/nixos/modules/services/misc/dwm-status.nix
index 5f591b3c5d4..de3e28c41d2 100644
--- a/nixos/modules/services/misc/dwm-status.nix
+++ b/nixos/modules/services/misc/dwm-status.nix
@@ -22,21 +22,21 @@ in
 
     services.dwm-status = {
 
-      enable = mkEnableOption "dwm-status user service";
+      enable = mkEnableOption (lib.mdDoc "dwm-status user service");
 
       package = mkOption {
         type = types.package;
         default = pkgs.dwm-status;
         defaultText = literalExpression "pkgs.dwm-status";
         example = literalExpression "pkgs.dwm-status.override { enableAlsaUtils = false; }";
-        description = ''
+        description = lib.mdDoc ''
           Which dwm-status package to use.
         '';
       };
 
       order = mkOption {
         type = types.listOf (types.enum [ "audio" "backlight" "battery" "cpu_load" "network" "time" ]);
-        description = ''
+        description = lib.mdDoc ''
           List of enabled features in order.
         '';
       };
@@ -44,7 +44,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra config in TOML format.
         '';
       };
diff --git a/nixos/modules/services/misc/dysnomia.nix b/nixos/modules/services/misc/dysnomia.nix
index 7d9c39a6973..4d748ec6eb6 100644
--- a/nixos/modules/services/misc/dysnomia.nix
+++ b/nixos/modules/services/misc/dysnomia.nix
@@ -87,52 +87,52 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable Dysnomia";
+        description = lib.mdDoc "Whether to enable Dysnomia";
       };
 
       enableAuthentication = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to publish privacy-sensitive authentication credentials";
+        description = lib.mdDoc "Whether to publish privacy-sensitive authentication credentials";
       };
 
       package = mkOption {
         type = types.path;
-        description = "The Dysnomia package";
+        description = lib.mdDoc "The Dysnomia package";
       };
 
       properties = mkOption {
-        description = "An attribute set in which each attribute represents a machine property. Optionally, these values can be shell substitutions.";
+        description = lib.mdDoc "An attribute set in which each attribute represents a machine property. Optionally, these values can be shell substitutions.";
         default = {};
         type = types.attrs;
       };
 
       containers = mkOption {
-        description = "An attribute set in which each key represents a container and each value an attribute set providing its configuration properties";
+        description = lib.mdDoc "An attribute set in which each key represents a container and each value an attribute set providing its configuration properties";
         default = {};
         type = types.attrsOf types.attrs;
       };
 
       components = mkOption {
-        description = "An atttribute set in which each key represents a container and each value an attribute set in which each key represents a component and each value a derivation constructing its initial state";
+        description = lib.mdDoc "An atttribute set in which each key represents a container and each value an attribute set in which each key represents a component and each value a derivation constructing its initial state";
         default = {};
         type = types.attrsOf types.attrs;
       };
 
       extraContainerProperties = mkOption {
-        description = "An attribute set providing additional container settings in addition to the default properties";
+        description = lib.mdDoc "An attribute set providing additional container settings in addition to the default properties";
         default = {};
         type = types.attrs;
       };
 
       extraContainerPaths = mkOption {
-        description = "A list of paths containing additional container configurations that are added to the search folders";
+        description = lib.mdDoc "A list of paths containing additional container configurations that are added to the search folders";
         default = [];
         type = types.listOf types.path;
       };
 
       extraModulePaths = mkOption {
-        description = "A list of paths containing additional modules that are added to the search folders";
+        description = lib.mdDoc "A list of paths containing additional modules that are added to the search folders";
         default = [];
         type = types.listOf types.path;
       };
@@ -140,7 +140,7 @@ in
       enableLegacyModules = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable Dysnomia legacy process and wrapper modules";
+        description = lib.mdDoc "Whether to enable Dysnomia legacy process and wrapper modules";
       };
     };
   };
@@ -186,7 +186,7 @@ in
 
     dysnomia.properties = {
       hostname = config.networking.hostName;
-      inherit (config.nixpkgs.localSystem) system;
+      inherit (pkgs.stdenv.hostPlatform) system;
 
       supportedTypes = [
         "echo"
diff --git a/nixos/modules/services/misc/errbot.nix b/nixos/modules/services/misc/errbot.nix
index b447ba5d438..a650bc5bbd9 100644
--- a/nixos/modules/services/misc/errbot.nix
+++ b/nixos/modules/services/misc/errbot.nix
@@ -27,48 +27,48 @@ in {
   options = {
     services.errbot.instances = mkOption {
       default = {};
-      description = "Errbot instance configs";
+      description = lib.mdDoc "Errbot instance configs";
       type = types.attrsOf (types.submodule {
         options = {
           dataDir = mkOption {
             type = types.nullOr types.path;
             default = null;
-            description = "Data directory for errbot instance.";
+            description = lib.mdDoc "Data directory for errbot instance.";
           };
 
           plugins = mkOption {
             type = types.listOf types.package;
             default = [];
-            description = "List of errbot plugin derivations.";
+            description = lib.mdDoc "List of errbot plugin derivations.";
           };
 
           logLevel = mkOption {
             type = types.str;
             default = "INFO";
-            description = "Errbot log level";
+            description = lib.mdDoc "Errbot log level";
           };
 
           admins = mkOption {
             type = types.listOf types.str;
             default = [];
-            description = "List of identifiers of errbot admins.";
+            description = lib.mdDoc "List of identifiers of errbot admins.";
           };
 
           backend = mkOption {
             type = types.str;
             default = "XMPP";
-            description = "Errbot backend name.";
+            description = lib.mdDoc "Errbot backend name.";
           };
 
           identity = mkOption {
             type = types.attrs;
-            description = "Errbot identity configuration";
+            description = lib.mdDoc "Errbot identity configuration";
           };
 
           extraConfig = mkOption {
             type = types.lines;
             default = "";
-            description = "String to be appended to the config verbatim";
+            description = lib.mdDoc "String to be appended to the config verbatim";
           };
         };
       });
diff --git a/nixos/modules/services/misc/etcd.nix b/nixos/modules/services/misc/etcd.nix
index 3925b7dd163..3343e94778a 100644
--- a/nixos/modules/services/misc/etcd.nix
+++ b/nixos/modules/services/misc/etcd.nix
@@ -10,124 +10,124 @@ in {
 
   options.services.etcd = {
     enable = mkOption {
-      description = "Whether to enable etcd.";
+      description = lib.mdDoc "Whether to enable etcd.";
       default = false;
       type = types.bool;
     };
 
     name = mkOption {
-      description = "Etcd unique node name.";
+      description = lib.mdDoc "Etcd unique node name.";
       default = config.networking.hostName;
       defaultText = literalExpression "config.networking.hostName";
       type = types.str;
     };
 
     advertiseClientUrls = mkOption {
-      description = "Etcd list of this member's client URLs to advertise to the rest of the cluster.";
+      description = lib.mdDoc "Etcd list of this member's client URLs to advertise to the rest of the cluster.";
       default = cfg.listenClientUrls;
       defaultText = literalExpression "config.${opt.listenClientUrls}";
       type = types.listOf types.str;
     };
 
     listenClientUrls = mkOption {
-      description = "Etcd list of URLs to listen on for client traffic.";
+      description = lib.mdDoc "Etcd list of URLs to listen on for client traffic.";
       default = ["http://127.0.0.1:2379"];
       type = types.listOf types.str;
     };
 
     listenPeerUrls = mkOption {
-      description = "Etcd list of URLs to listen on for peer traffic.";
+      description = lib.mdDoc "Etcd list of URLs to listen on for peer traffic.";
       default = ["http://127.0.0.1:2380"];
       type = types.listOf types.str;
     };
 
     initialAdvertisePeerUrls = mkOption {
-      description = "Etcd list of this member's peer URLs to advertise to rest of the cluster.";
+      description = lib.mdDoc "Etcd list of this member's peer URLs to advertise to rest of the cluster.";
       default = cfg.listenPeerUrls;
       defaultText = literalExpression "config.${opt.listenPeerUrls}";
       type = types.listOf types.str;
     };
 
     initialCluster = mkOption {
-      description = "Etcd initial cluster configuration for bootstrapping.";
+      description = lib.mdDoc "Etcd initial cluster configuration for bootstrapping.";
       default = ["${cfg.name}=http://127.0.0.1:2380"];
       defaultText = literalExpression ''["''${config.${opt.name}}=http://127.0.0.1:2380"]'';
       type = types.listOf types.str;
     };
 
     initialClusterState = mkOption {
-      description = "Etcd initial cluster configuration for bootstrapping.";
+      description = lib.mdDoc "Etcd initial cluster configuration for bootstrapping.";
       default = "new";
       type = types.enum ["new" "existing"];
     };
 
     initialClusterToken = mkOption {
-      description = "Etcd initial cluster token for etcd cluster during bootstrap.";
+      description = lib.mdDoc "Etcd initial cluster token for etcd cluster during bootstrap.";
       default = "etcd-cluster";
       type = types.str;
     };
 
     discovery = mkOption {
-      description = "Etcd discovery url";
+      description = lib.mdDoc "Etcd discovery url";
       default = "";
       type = types.str;
     };
 
     clientCertAuth = mkOption {
-      description = "Whether to use certs for client authentication";
+      description = lib.mdDoc "Whether to use certs for client authentication";
       default = false;
       type = types.bool;
     };
 
     trustedCaFile = mkOption {
-      description = "Certificate authority file to use for clients";
+      description = lib.mdDoc "Certificate authority file to use for clients";
       default = null;
       type = types.nullOr types.path;
     };
 
     certFile = mkOption {
-      description = "Cert file to use for clients";
+      description = lib.mdDoc "Cert file to use for clients";
       default = null;
       type = types.nullOr types.path;
     };
 
     keyFile = mkOption {
-      description = "Key file to use for clients";
+      description = lib.mdDoc "Key file to use for clients";
       default = null;
       type = types.nullOr types.path;
     };
 
     peerCertFile = mkOption {
-      description = "Cert file to use for peer to peer communication";
+      description = lib.mdDoc "Cert file to use for peer to peer communication";
       default = cfg.certFile;
       defaultText = literalExpression "config.${opt.certFile}";
       type = types.nullOr types.path;
     };
 
     peerKeyFile = mkOption {
-      description = "Key file to use for peer to peer communication";
+      description = lib.mdDoc "Key file to use for peer to peer communication";
       default = cfg.keyFile;
       defaultText = literalExpression "config.${opt.keyFile}";
       type = types.nullOr types.path;
     };
 
     peerTrustedCaFile = mkOption {
-      description = "Certificate authority file to use for peer to peer communication";
+      description = lib.mdDoc "Certificate authority file to use for peer to peer communication";
       default = cfg.trustedCaFile;
       defaultText = literalExpression "config.${opt.trustedCaFile}";
       type = types.nullOr types.path;
     };
 
     peerClientCertAuth = mkOption {
-      description = "Whether to check all incoming peer requests from the cluster for valid client certificates signed by the supplied CA";
+      description = lib.mdDoc "Whether to check all incoming peer requests from the cluster for valid client certificates signed by the supplied CA";
       default = false;
       type = types.bool;
     };
 
     extraConf = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Etcd extra configuration. See
-        <link xlink:href='https://github.com/coreos/etcd/blob/master/Documentation/op-guide/configuration.md#configuration-flags' />
+        <https://github.com/coreos/etcd/blob/master/Documentation/op-guide/configuration.md#configuration-flags>
       '';
       type = types.attrsOf types.str;
       default = {};
@@ -145,7 +145,7 @@ in {
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/etcd";
-      description = "Etcd data directory.";
+      description = lib.mdDoc "Etcd data directory.";
     };
   };
 
diff --git a/nixos/modules/services/misc/etebase-server.nix b/nixos/modules/services/misc/etebase-server.nix
index dd84ac37b0d..c3723d18814 100644
--- a/nixos/modules/services/misc/etebase-server.nix
+++ b/nixos/modules/services/misc/etebase-server.nix
@@ -36,12 +36,12 @@ in
         type = types.bool;
         default = false;
         example = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Etebase server.
 
           Once enabled you need to create an admin user by invoking the
-          shell command <literal>etebase-server createsuperuser</literal> with
-          the user specified by the <literal>user</literal> option or a superuser.
+          shell command `etebase-server createsuperuser` with
+          the user specified by the `user` option or a superuser.
           Then you can login and create accounts on your-etebase-server.com/admin
         '';
       };
@@ -49,19 +49,19 @@ in
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/etebase-server";
-        description = "Directory to store the Etebase server data.";
+        description = lib.mdDoc "Directory to store the Etebase server data.";
       };
 
       port = mkOption {
         type = with types; nullOr port;
         default = 8001;
-        description = "Port to listen on.";
+        description = lib.mdDoc "Port to listen on.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to open ports in the firewall for the server.
         '';
       };
@@ -69,7 +69,7 @@ in
       unixSocket = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "The path to the socket to bind to.";
+        description = lib.mdDoc "The path to the socket to bind to.";
         example = "/run/etebase-server/etebase-server.sock";
       };
 
@@ -82,14 +82,14 @@ in
               debug = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Whether to set django's DEBUG flag.
                 '';
               };
               secret_file = mkOption {
                 type = with types; nullOr str;
                 default = null;
-                description = ''
+                description = lib.mdDoc ''
                   The path to a file containing the secret
                   used as django's SECRET_KEY.
                 '';
@@ -98,13 +98,13 @@ in
                 type = types.str;
                 default = "${cfg.dataDir}/static";
                 defaultText = literalExpression ''"''${config.services.etebase-server.dataDir}/static"'';
-                description = "The directory for static files.";
+                description = lib.mdDoc "The directory for static files.";
               };
               media_root = mkOption {
                 type = types.str;
                 default = "${cfg.dataDir}/media";
                 defaultText = literalExpression ''"''${config.services.etebase-server.dataDir}/media"'';
-                description = "The media directory.";
+                description = lib.mdDoc "The media directory.";
               };
             };
             allowed_hosts = {
@@ -112,7 +112,7 @@ in
                 type = types.str;
                 default = "0.0.0.0";
                 example = "localhost";
-                description = ''
+                description = lib.mdDoc ''
                   The main host that is allowed access.
                 '';
               };
@@ -121,22 +121,22 @@ in
               engine = mkOption {
                 type = types.enum [ "django.db.backends.sqlite3" "django.db.backends.postgresql" ];
                 default = "django.db.backends.sqlite3";
-                description = "The database engine to use.";
+                description = lib.mdDoc "The database engine to use.";
               };
               name = mkOption {
                 type = types.str;
                 default = "${cfg.dataDir}/db.sqlite3";
                 defaultText = literalExpression ''"''${config.services.etebase-server.dataDir}/db.sqlite3"'';
-                description = "The database name.";
+                description = lib.mdDoc "The database name.";
               };
             };
           };
         };
         default = {};
-        description = ''
-          Configuration for <package>etebase-server</package>. Refer to
-          <link xlink:href="https://github.com/etesync/server/blob/master/etebase-server.ini.example" />
-          and <link xlink:href="https://github.com/etesync/server/wiki" />
+        description = lib.mdDoc ''
+          Configuration for `etebase-server`. Refer to
+          <https://github.com/etesync/server/blob/master/etebase-server.ini.example>
+          and <https://github.com/etesync/server/wiki>
           for details on supported values.
         '';
         example = {
@@ -153,7 +153,7 @@ in
       user = mkOption {
         type = types.str;
         default = defaultUser;
-        description = "User under which Etebase server runs.";
+        description = lib.mdDoc "User under which Etebase server runs.";
       };
     };
   };
@@ -162,11 +162,11 @@ in
 
     environment.systemPackages = with pkgs; [
       (runCommand "etebase-server" {
-        buildInputs = [ makeWrapper ];
+        nativeBuildInputs = [ makeWrapper ];
       } ''
         makeWrapper ${pythonEnv}/bin/etebase-server \
           $out/bin/etebase-server \
-          --run "cd ${cfg.dataDir}" \
+          --chdir ${escapeShellArg cfg.dataDir} \
           --prefix ETEBASE_EASY_CONFIG_PATH : "${configIni}"
       '')
     ];
diff --git a/nixos/modules/services/misc/etesync-dav.nix b/nixos/modules/services/misc/etesync-dav.nix
index 9d7cfda371b..9d99d548d95 100644
--- a/nixos/modules/services/misc/etesync-dav.nix
+++ b/nixos/modules/services/misc/etesync-dav.nix
@@ -7,37 +7,37 @@ let
 in
   {
     options.services.etesync-dav = {
-      enable = mkEnableOption "etesync-dav";
+      enable = mkEnableOption (lib.mdDoc "etesync-dav");
 
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = "The server host address.";
+        description = lib.mdDoc "The server host address.";
       };
 
       port = mkOption {
         type = types.port;
         default = 37358;
-        description = "The server host port.";
+        description = lib.mdDoc "The server host port.";
       };
 
       apiUrl = mkOption {
         type = types.str;
         default = "https://api.etesync.com/";
-        description = "The url to the etesync API.";
+        description = lib.mdDoc "The url to the etesync API.";
       };
 
       openFirewall = mkOption {
         default = false;
         type = types.bool;
-        description = "Whether to open the firewall for the specified port.";
+        description = lib.mdDoc "Whether to open the firewall for the specified port.";
       };
 
       sslCertificate = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/var/etesync.crt";
-        description = ''
+        description = lib.mdDoc ''
           Path to server SSL certificate. It will be copied into
           etesync-dav's data directory.
         '';
@@ -47,7 +47,7 @@ in
         type = types.nullOr types.path;
         default = null;
         example = "/var/etesync.key";
-        description = ''
+        description = lib.mdDoc ''
           Path to server SSL certificate key.  It will be copied into
           etesync-dav's data directory.
         '';
diff --git a/nixos/modules/services/misc/ethminer.nix b/nixos/modules/services/misc/ethminer.nix
deleted file mode 100644
index 95afb0460fb..00000000000
--- a/nixos/modules/services/misc/ethminer.nix
+++ /dev/null
@@ -1,117 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-let
-  cfg = config.services.ethminer;
-  poolUrl = escapeShellArg "stratum1+tcp://${cfg.wallet}@${cfg.pool}:${toString cfg.stratumPort}/${cfg.rig}/${cfg.registerMail}";
-in
-
-{
-
-  ###### interface
-
-  options = {
-
-    services.ethminer = {
-
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Enable ethminer ether mining.";
-      };
-
-      recheckInterval = mkOption {
-        type = types.int;
-        default = 2000;
-        description = "Interval in milliseconds between farm rechecks.";
-      };
-
-      toolkit = mkOption {
-        type = types.enum [ "cuda" "opencl" ];
-        default = "cuda";
-        description = "Cuda or opencl toolkit.";
-      };
-
-      apiPort = mkOption {
-        type = types.int;
-        default = -3333;
-        description = "Ethminer api port. minus sign puts api in read-only mode.";
-      };
-
-      wallet = mkOption {
-        type = types.str;
-        example = "0x0123456789abcdef0123456789abcdef01234567";
-        description = "Ethereum wallet address.";
-      };
-
-      pool = mkOption {
-        type = types.str;
-        example = "eth-us-east1.nanopool.org";
-        description = "Mining pool address.";
-      };
-
-      stratumPort = mkOption {
-        type = types.port;
-        default = 9999;
-        description = "Stratum protocol tcp port.";
-      };
-
-      rig = mkOption {
-        type = types.str;
-        default = "mining-rig-name";
-        description = "Mining rig name.";
-      };
-
-      registerMail = mkOption {
-        type = types.str;
-        example = "email%40example.org";
-        description = "Url encoded email address to register with pool.";
-      };
-
-      maxPower = mkOption {
-        type = types.int;
-        default = 113;
-        description = "Miner max watt usage.";
-      };
-
-    };
-
-  };
-
-
-  ###### implementation
-
-  config = mkIf cfg.enable {
-
-    systemd.services.ethminer = {
-      path = [ pkgs.cudatoolkit ];
-      description = "ethminer ethereum mining service";
-      wantedBy = [ "multi-user.target" ];
-      after = [ "network.target" ];
-
-      serviceConfig = {
-        DynamicUser = true;
-        ExecStartPre = "${pkgs.ethminer}/bin/.ethminer-wrapped --list-devices";
-        ExecStartPost = optional (cfg.toolkit == "cuda") "+${getBin config.boot.kernelPackages.nvidia_x11}/bin/nvidia-smi -pl ${toString cfg.maxPower}";
-        Restart = "always";
-      };
-
-      environment = {
-        LD_LIBRARY_PATH = "${config.boot.kernelPackages.nvidia_x11}/lib";
-      };
-
-      script = ''
-        ${pkgs.ethminer}/bin/.ethminer-wrapped \
-          --farm-recheck ${toString cfg.recheckInterval} \
-          --report-hashrate \
-          --${cfg.toolkit} \
-          --api-port ${toString cfg.apiPort} \
-          --pool ${poolUrl}
-      '';
-
-    };
-
-  };
-
-}
diff --git a/nixos/modules/services/misc/exhibitor.nix b/nixos/modules/services/misc/exhibitor.nix
index 4c935efbd84..91a87b55af5 100644
--- a/nixos/modules/services/misc/exhibitor.nix
+++ b/nixos/modules/services/misc/exhibitor.nix
@@ -68,81 +68,76 @@ in
 {
   options = {
     services.exhibitor = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = "
-          Whether to enable the exhibitor server.
-        ";
-      };
+      enable = mkEnableOption (lib.mdDoc "exhibitor server");
+
       # See https://github.com/soabase/exhibitor/wiki/Running-Exhibitor for what these mean
       # General options for any type of config
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8080;
-        description = ''
+        description = lib.mdDoc ''
           The port for exhibitor to listen on and communicate with other exhibitors.
         '';
       };
       baseDir = mkOption {
         type = types.str;
         default = "/var/exhibitor";
-        description = ''
+        description = lib.mdDoc ''
           Baseline directory for exhibitor runtime config.
         '';
       };
       configType = mkOption {
         type = types.enum [ "file" "s3" "zookeeper" "none" ];
-        description = ''
+        description = lib.mdDoc ''
           Which configuration type you want to use. Additional config will be
           required depending on which type you are using.
         '';
       };
       hostname = mkOption {
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           Hostname to use and advertise
         '';
         default = null;
       };
       nodeModification = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether the Explorer UI will allow nodes to be modified (use with caution).
         '';
         default = true;
       };
       configCheckMs = mkOption {
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Period (ms) to check for shared config updates.
         '';
         default = 30000;
       };
       headingText = mkOption {
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           Extra text to display in UI header
         '';
         default = null;
       };
       jqueryStyle = mkOption {
         type = types.enum [ "red" "black" "custom" ];
-        description = ''
+        description = lib.mdDoc ''
           Styling used for the JQuery-based UI.
         '';
         default = "red";
       };
       logLines = mkOption {
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
         Max lines of logging to keep in memory for display.
         '';
         default = 1000;
       };
       servo = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           ZooKeeper will be queried once a minute for its state via the 'mntr' four
           letter word (this requires ZooKeeper 3.4.x+). Servo will be used to publish
           this data via JMX.
@@ -151,14 +146,14 @@ in
       };
       timeout = mkOption {
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Connection timeout (ms) for ZK connections.
         '';
         default = 30000;
       };
       autoManageInstances = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Automatically manage ZooKeeper instances in the ensemble
         '';
         default = false;
@@ -167,7 +162,7 @@ in
         type = types.str;
         default = "${cfg.baseDir}/zkData";
         defaultText = literalExpression ''"''${config.${opt.baseDir}}/zkData"'';
-        description = ''
+        description = lib.mdDoc ''
           The Zookeeper data directory
         '';
       };
@@ -175,56 +170,56 @@ in
         type = types.path;
         default = "${cfg.baseDir}/zkLogs";
         defaultText = literalExpression ''"''${config.${opt.baseDir}}/zkLogs"'';
-        description = ''
+        description = lib.mdDoc ''
           The Zookeeper logs directory
         '';
       };
       extraConf = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra Exhibitor configuration to put in the ZooKeeper config file.
         '';
       };
       zkExtraCfg = mkOption {
         type = types.str;
         default = "initLimit=5&syncLimit=2&tickTime=2000";
-        description = ''
+        description = lib.mdDoc ''
           Extra options to pass into Zookeeper
         '';
       };
       zkClientPort = mkOption {
         type = types.int;
         default = 2181;
-        description = ''
+        description = lib.mdDoc ''
           Zookeeper client port
         '';
       };
       zkConnectPort = mkOption {
         type = types.int;
         default = 2888;
-        description = ''
+        description = lib.mdDoc ''
           The port to use for followers to talk to each other.
         '';
       };
       zkElectionPort = mkOption {
         type = types.int;
         default = 3888;
-        description = ''
+        description = lib.mdDoc ''
           The port for Zookeepers to use for leader election.
         '';
       };
       zkCleanupPeriod = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           How often (in milliseconds) to run the Zookeeper log cleanup task.
         '';
       };
       zkServersSpec = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Zookeeper server spec for all servers in the ensemble.
         '';
         example = [ "S:1:zk1.example.com" "S:2:zk2.example.com" "S:3:zk3.example.com" "O:4:zk-observer.example.com" ];
@@ -234,14 +229,14 @@ in
       s3Backup = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable backups to S3
         '';
       };
       fileSystemBackup = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enables file system backup of ZooKeeper log files
         '';
       };
@@ -249,21 +244,21 @@ in
       # Options for using zookeeper configType
       zkConfigConnect = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The initial connection string for ZooKeeper shared config storage
         '';
         example = ["host1:2181" "host2:2181"];
       };
       zkConfigExhibitorPath = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           If the ZooKeeper shared config is also running Exhibitor, the URI path for the REST call
         '';
         default = "/";
       };
       zkConfigExhibitorPort = mkOption {
         type = types.nullOr types.int;
-        description = ''
+        description = lib.mdDoc ''
           If the ZooKeeper shared config is also running Exhibitor, the port that
           Exhibitor is listening on. IMPORTANT: if this value is not set it implies
           that Exhibitor is not being used on the ZooKeeper shared config.
@@ -271,7 +266,7 @@ in
       };
       zkConfigPollMs = mkOption {
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           The period in ms to check for changes in the config ensemble
         '';
         default = 10000;
@@ -280,21 +275,21 @@ in
         sleepMs = mkOption {
           type = types.int;
           default = 1000;
-          description = ''
+          description = lib.mdDoc ''
             Retry sleep time connecting to the ZooKeeper config
           '';
         };
         retryQuantity = mkOption {
           type = types.int;
           default = 3;
-          description = ''
+          description = lib.mdDoc ''
             Retries connecting to the ZooKeeper config
           '';
         };
       };
       zkConfigZPath = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The base ZPath that Exhibitor should use
         '';
         example = "/exhibitor/config";
@@ -304,19 +299,19 @@ in
       s3Config = {
         bucketName = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             Bucket name to store config
           '';
         };
         objectKey = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             S3 key name to store the config
           '';
         };
         configPrefix = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             When using AWS S3 shared config files, the prefix to use for values such as locks
           '';
           default = "exhibitor-";
@@ -326,7 +321,7 @@ in
       # The next two are used for either s3backup or s3 configType
       s3Credentials = mkOption {
         type = types.nullOr types.path;
-        description = ''
+        description = lib.mdDoc ''
           Optional credentials to use for s3backup or s3config. Argument is the path
           to an AWS credential properties file with two properties:
           com.netflix.exhibitor.s3.access-key-id and com.netflix.exhibitor.s3.access-secret-key
@@ -335,7 +330,7 @@ in
       };
       s3Region = mkOption {
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           Optional region for S3 calls
         '';
         default = null;
@@ -344,7 +339,7 @@ in
       # Config options for file config type
       fsConfigDir = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Directory to store Exhibitor properties (cannot be used with s3config).
           Exhibitor uses file system locks so you can specify a shared location
           so as to enable complete ensemble management.
@@ -352,14 +347,14 @@ in
       };
       fsConfigLockPrefix = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           A prefix for a locking mechanism used in conjunction with fsconfigdir
         '';
         default = "exhibitor-lock-";
       };
       fsConfigName = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The name of the file to store config in
         '';
         default = "exhibitor.properties";
diff --git a/nixos/modules/services/misc/felix.nix b/nixos/modules/services/misc/felix.nix
index 0283de128af..306d4cf0d7c 100644
--- a/nixos/modules/services/misc/felix.nix
+++ b/nixos/modules/services/misc/felix.nix
@@ -17,25 +17,25 @@ in
 
     services.felix = {
 
-      enable = mkEnableOption "the Apache Felix OSGi service";
+      enable = mkEnableOption (lib.mdDoc "the Apache Felix OSGi service");
 
       bundles = mkOption {
         type = types.listOf types.package;
         default = [ pkgs.felix_remoteshell ];
         defaultText = literalExpression "[ pkgs.felix_remoteshell ]";
-        description = "List of bundles that should be activated on startup";
+        description = lib.mdDoc "List of bundles that should be activated on startup";
       };
 
       user = mkOption {
         type = types.str;
         default = "osgi";
-        description = "User account under which Apache Felix runs.";
+        description = lib.mdDoc "User account under which Apache Felix runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "osgi";
-        description = "Group account under which Apache Felix runs.";
+        description = lib.mdDoc "Group account under which Apache Felix runs.";
       };
 
     };
diff --git a/nixos/modules/services/misc/freeswitch.nix b/nixos/modules/services/misc/freeswitch.nix
index 472b0b73ff6..b8b81e58694 100644
--- a/nixos/modules/services/misc/freeswitch.nix
+++ b/nixos/modules/services/misc/freeswitch.nix
@@ -18,15 +18,15 @@ let
 in {
   options = {
     services.freeswitch = {
-      enable = mkEnableOption "FreeSWITCH";
+      enable = mkEnableOption (lib.mdDoc "FreeSWITCH");
       enableReload = mkOption {
         default = false;
         type = types.bool;
-        description = ''
-          Issue the <literal>reloadxml</literal> command to FreeSWITCH when configuration directory changes (instead of restart).
-          See <link xlink:href="https://freeswitch.org/confluence/display/FREESWITCH/Reloading">FreeSWITCH documentation</link> for more info.
-          The configuration directory is exposed at <filename>/etc/freeswitch</filename>.
-          See also <literal>systemd.services.*.restartIfChanged</literal>.
+        description = lib.mdDoc ''
+          Issue the `reloadxml` command to FreeSWITCH when configuration directory changes (instead of restart).
+          See [FreeSWITCH documentation](https://freeswitch.org/confluence/display/FREESWITCH/Reloading) for more info.
+          The configuration directory is exposed at {file}`/etc/freeswitch`.
+          See also `systemd.services.*.restartIfChanged`.
         '';
       };
       configTemplate = mkOption {
@@ -34,9 +34,9 @@ in {
         default = "${config.services.freeswitch.package}/share/freeswitch/conf/vanilla";
         defaultText = literalExpression ''"''${config.services.freeswitch.package}/share/freeswitch/conf/vanilla"'';
         example = literalExpression ''"''${config.services.freeswitch.package}/share/freeswitch/conf/minimal"'';
-        description = ''
+        description = lib.mdDoc ''
           Configuration template to use.
-          See available templates in <link xlink:href="https://github.com/signalwire/freeswitch/tree/master/conf">FreeSWITCH repository</link>.
+          See available templates in [FreeSWITCH repository](https://github.com/signalwire/freeswitch/tree/master/conf).
           You can also set your own configuration directory.
         '';
       };
@@ -51,18 +51,18 @@ in {
             ''';
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Override file in FreeSWITCH config template directory.
           Each top-level attribute denotes a file path in the configuration directory, its value is the file path.
-          See <link xlink:href="https://freeswitch.org/confluence/display/FREESWITCH/Default+Configuration">FreeSWITCH documentation</link> for more info.
-          Also check available templates in <link xlink:href="https://github.com/signalwire/freeswitch/tree/master/conf">FreeSWITCH repository</link>.
+          See [FreeSWITCH documentation](https://freeswitch.org/confluence/display/FREESWITCH/Default+Configuration) for more info.
+          Also check available templates in [FreeSWITCH repository](https://github.com/signalwire/freeswitch/tree/master/conf).
         '';
       };
       package = mkOption {
         type = types.package;
         default = pkgs.freeswitch;
         defaultText = literalExpression "pkgs.freeswitch";
-        description = ''
+        description = lib.mdDoc ''
           FreeSWITCH package.
         '';
       };
diff --git a/nixos/modules/services/misc/fstrim.nix b/nixos/modules/services/misc/fstrim.nix
index a9fc04b46f0..36b5f9c8cca 100644
--- a/nixos/modules/services/misc/fstrim.nix
+++ b/nixos/modules/services/misc/fstrim.nix
@@ -11,18 +11,17 @@ in {
   options = {
 
     services.fstrim = {
-      enable = mkEnableOption "periodic SSD TRIM of mounted partitions in background";
+      enable = mkEnableOption (lib.mdDoc "periodic SSD TRIM of mounted partitions in background");
 
       interval = mkOption {
         type = types.str;
         default = "weekly";
-        description = ''
+        description = lib.mdDoc ''
           How often we run fstrim. For most desktop and server systems
           a sufficient trimming frequency is once a week.
 
           The format is described in
-          <citerefentry><refentrytitle>systemd.time</refentrytitle>
-          <manvolnum>7</manvolnum></citerefentry>.
+          {manpage}`systemd.time(7)`.
         '';
       };
     };
diff --git a/nixos/modules/services/misc/gammu-smsd.nix b/nixos/modules/services/misc/gammu-smsd.nix
index d4bb58d81dd..2c7d90b28de 100644
--- a/nixos/modules/services/misc/gammu-smsd.nix
+++ b/nixos/modules/services/misc/gammu-smsd.nix
@@ -45,52 +45,52 @@ let
   initDBDir = "share/doc/gammu/examples/sql";
 
   gammuPackage = with cfg.backend; (pkgs.gammu.override {
-    dbiSupport = (service == "sql" && sql.driver == "sqlite");
-    postgresSupport = (service == "sql" && sql.driver == "native_pgsql");
+    dbiSupport = service == "sql" && sql.driver == "sqlite";
+    postgresSupport = service == "sql" && sql.driver == "native_pgsql";
   });
 
 in {
   options = {
     services.gammu-smsd = {
 
-      enable = mkEnableOption "gammu-smsd daemon";
+      enable = mkEnableOption (lib.mdDoc "gammu-smsd daemon");
 
       user = mkOption {
         type = types.str;
         default = "smsd";
-        description = "User that has access to the device";
+        description = lib.mdDoc "User that has access to the device";
       };
 
       device = {
         path = mkOption {
           type = types.path;
-          description = "Device node or address of the phone";
+          description = lib.mdDoc "Device node or address of the phone";
           example = "/dev/ttyUSB2";
         };
 
         group = mkOption {
           type = types.str;
           default = "root";
-          description = "Owner group of the device";
+          description = lib.mdDoc "Owner group of the device";
           example = "dialout";
         };
 
         connection = mkOption {
           type = types.str;
           default = "at";
-          description = "Protocol which will be used to talk to the phone";
+          description = lib.mdDoc "Protocol which will be used to talk to the phone";
         };
 
         synchronizeTime = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether to set time from computer to the phone during starting connection";
+          description = lib.mdDoc "Whether to set time from computer to the phone during starting connection";
         };
 
         pin = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = "PIN code for the simcard";
+          description = lib.mdDoc "PIN code for the simcard";
         };
       };
 
@@ -99,13 +99,13 @@ in {
         file = mkOption {
           type = types.str;
           default = "syslog";
-          description = "Path to file where information about communication will be stored";
+          description = lib.mdDoc "Path to file where information about communication will be stored";
         };
 
         format = mkOption {
           type = types.enum [ "nothing" "text" "textall" "textalldate" "errors" "errorsdate" "binary" ];
           default = "errors";
-          description = "Determines what will be logged to the LogFile";
+          description = lib.mdDoc "Determines what will be logged to the LogFile";
         };
       };
 
@@ -114,14 +114,14 @@ in {
         gammu = mkOption {
           type = types.lines;
           default = "";
-          description = "Extra config lines to be added into [gammu] section";
+          description = lib.mdDoc "Extra config lines to be added into [gammu] section";
         };
 
 
         smsd = mkOption {
           type = types.lines;
           default = "";
-          description = "Extra config lines to be added into [smsd] section";
+          description = lib.mdDoc "Extra config lines to be added into [smsd] section";
         };
       };
 
@@ -130,69 +130,69 @@ in {
         service = mkOption {
           type = types.enum [ "null" "files" "sql" ];
           default = "null";
-          description = "Service to use to store sms data.";
+          description = lib.mdDoc "Service to use to store sms data.";
         };
 
         files = {
           inboxPath = mkOption {
             type = types.path;
             default = "/var/spool/sms/inbox/";
-            description = "Where the received SMSes are stored";
+            description = lib.mdDoc "Where the received SMSes are stored";
           };
 
           outboxPath = mkOption {
             type = types.path;
             default = "/var/spool/sms/outbox/";
-            description = "Where SMSes to be sent should be placed";
+            description = lib.mdDoc "Where SMSes to be sent should be placed";
           };
 
           sentSMSPath = mkOption {
             type = types.path;
             default = "/var/spool/sms/sent/";
-            description = "Where the transmitted SMSes are placed";
+            description = lib.mdDoc "Where the transmitted SMSes are placed";
           };
 
           errorSMSPath = mkOption {
             type = types.path;
             default = "/var/spool/sms/error/";
-            description = "Where SMSes with error in transmission is placed";
+            description = lib.mdDoc "Where SMSes with error in transmission is placed";
           };
         };
 
         sql = {
           driver = mkOption {
             type = types.enum [ "native_mysql" "native_pgsql" "odbc" "dbi" ];
-            description = "DB driver to use";
+            description = lib.mdDoc "DB driver to use";
           };
 
           sqlDialect = mkOption {
             type = types.nullOr types.str;
             default = null;
-            description = "SQL dialect to use (odbc driver only)";
+            description = lib.mdDoc "SQL dialect to use (odbc driver only)";
           };
 
           database = mkOption {
             type = types.nullOr types.str;
             default = null;
-            description = "Database name to store sms data";
+            description = lib.mdDoc "Database name to store sms data";
           };
 
           host = mkOption {
             type = types.str;
             default = "localhost";
-            description = "Database server address";
+            description = lib.mdDoc "Database server address";
           };
 
           user = mkOption {
             type = types.nullOr types.str;
             default = null;
-            description = "User name used for connection to the database";
+            description = lib.mdDoc "User name used for connection to the database";
           };
 
           password = mkOption {
             type = types.nullOr types.str;
             default = null;
-            description = "User password used for connetion to the database";
+            description = lib.mdDoc "User password used for connetion to the database";
           };
         };
       };
diff --git a/nixos/modules/services/misc/geoipupdate.nix b/nixos/modules/services/misc/geoipupdate.nix
index 3211d4d88e4..27c1157e9a8 100644
--- a/nixos/modules/services/misc/geoipupdate.nix
+++ b/nixos/modules/services/misc/geoipupdate.nix
@@ -2,6 +2,7 @@
 
 let
   cfg = config.services.geoipupdate;
+  inherit (builtins) isAttrs isString isInt isList typeOf hashString;
 in
 {
   imports = [
@@ -10,28 +11,44 @@ in
 
   options = {
     services.geoipupdate = {
-      enable = lib.mkEnableOption ''
-        periodic downloading of GeoIP databases using
-        <productname>geoipupdate</productname>.
-      '';
+      enable = lib.mkEnableOption (lib.mdDoc ''
+        periodic downloading of GeoIP databases using geoipupdate.
+      '');
 
       interval = lib.mkOption {
         type = lib.types.str;
         default = "weekly";
-        description = ''
+        description = lib.mdDoc ''
           Update the GeoIP databases at this time / interval.
           The format is described in
-          <citerefentry><refentrytitle>systemd.time</refentrytitle>
-          <manvolnum>7</manvolnum></citerefentry>.
+          {manpage}`systemd.time(7)`.
         '';
       };
 
       settings = lib.mkOption {
-        description = ''
-          <productname>geoipupdate</productname> configuration
-          options. See
-          <link xlink:href="https://github.com/maxmind/geoipupdate/blob/main/doc/GeoIP.conf.md" />
+        example = lib.literalExpression ''
+          {
+            AccountID = 200001;
+            DatabaseDirectory = "/var/lib/GeoIP";
+            LicenseKey = { _secret = "/run/keys/maxmind_license_key"; };
+            Proxy = "10.0.0.10:8888";
+            ProxyUserPassword = { _secret = "/run/keys/proxy_pass"; };
+          }
+        '';
+        description = lib.mdDoc ''
+          geoipupdate configuration options. See
+          <https://github.com/maxmind/geoipupdate/blob/main/doc/GeoIP.conf.md>
           for a full list of available options.
+
+          Settings containing secret data should be set to an
+          attribute set containing the attribute
+          `_secret` - a string pointing to a file
+          containing the value the option should be set to. See the
+          example to get a better picture of this: in the resulting
+          {file}`GeoIP.conf` file, the
+          `ProxyUserPassword` key will be set to the
+          contents of the
+          {file}`/run/keys/proxy_pass` file.
         '';
         type = lib.types.submodule {
           freeformType =
@@ -45,7 +62,7 @@ in
 
             AccountID = lib.mkOption {
               type = lib.types.int;
-              description = ''
+              description = lib.mdDoc ''
                 Your MaxMind account ID.
               '';
             };
@@ -57,29 +74,34 @@ in
                 "GeoLite2-City"
                 "GeoLite2-Country"
               ];
-              description = ''
+              description = lib.mdDoc ''
                 List of database edition IDs. This includes new string
-                IDs like <literal>GeoIP2-City</literal> and old
-                numeric IDs like <literal>106</literal>.
+                IDs like `GeoIP2-City` and old
+                numeric IDs like `106`.
               '';
             };
 
             LicenseKey = lib.mkOption {
-              type = lib.types.path;
-              description = ''
-                A file containing the <productname>MaxMind</productname>
-                license key.
+              type = with lib.types; either path (attrsOf path);
+              description = lib.mdDoc ''
+                A file containing the MaxMind license key.
+
+                Always handled as a secret whether the value is
+                wrapped in a `{ _secret = ...; }`
+                attrset or not (refer to [](#opt-services.geoipupdate.settings) for
+                details).
               '';
+              apply = x: if isAttrs x then x else { _secret = x; };
             };
 
             DatabaseDirectory = lib.mkOption {
               type = lib.types.path;
               default = "/var/lib/GeoIP";
               example = "/run/GeoIP";
-              description = ''
+              description = lib.mdDoc ''
                 The directory to store the database files in. The
                 directory will be automatically created, the owner
-                changed to <literal>geoip</literal> and permissions
+                changed to `geoip` and permissions
                 set to world readable. This applies if the directory
                 already exists as well, so don't use a directory with
                 sensitive contents.
@@ -102,6 +124,9 @@ in
     systemd.services.geoipupdate-create-db-dir = {
       serviceConfig.Type = "oneshot";
       script = ''
+        set -o errexit -o pipefail -o nounset -o errtrace
+        shopt -s inherit_errexit
+
         mkdir -p ${cfg.settings.DatabaseDirectory}
         chmod 0755 ${cfg.settings.DatabaseDirectory}
       '';
@@ -115,32 +140,41 @@ in
         "network-online.target"
         "nss-lookup.target"
       ];
+      path = [ pkgs.replace-secret ];
       wants = [ "network-online.target" ];
       startAt = cfg.interval;
       serviceConfig = {
         ExecStartPre =
           let
+            isSecret = v: isAttrs v && v ? _secret && isString v._secret;
             geoipupdateKeyValue = lib.generators.toKeyValue {
               mkKeyValue = lib.flip lib.generators.mkKeyValueDefault " " rec {
-                mkValueString = v: with builtins;
+                mkValueString = v:
                   if isInt           v then toString v
                   else if isString   v then v
                   else if true  ==   v then "1"
                   else if false ==   v then "0"
                   else if isList     v then lib.concatMapStringsSep " " mkValueString v
+                  else if isSecret   v then hashString "sha256" v._secret
                   else throw "unsupported type ${typeOf v}: ${(lib.generators.toPretty {}) v}";
               };
             };
+            secretPaths = lib.catAttrs "_secret" (lib.collect isSecret cfg.settings);
+            mkSecretReplacement = file: ''
+              replace-secret ${lib.escapeShellArgs [ (hashString "sha256" file) file "/run/geoipupdate/GeoIP.conf" ]}
+            '';
+            secretReplacements = lib.concatMapStrings mkSecretReplacement secretPaths;
 
             geoipupdateConf = pkgs.writeText "geoipupdate.conf" (geoipupdateKeyValue cfg.settings);
 
             script = ''
+              set -o errexit -o pipefail -o nounset -o errtrace
+              shopt -s inherit_errexit
+
               chown geoip "${cfg.settings.DatabaseDirectory}"
 
               cp ${geoipupdateConf} /run/geoipupdate/GeoIP.conf
-              ${pkgs.replace-secret}/bin/replace-secret '${cfg.settings.LicenseKey}' \
-                                                        '${cfg.settings.LicenseKey}' \
-                                                        /run/geoipupdate/GeoIP.conf
+              ${secretReplacements}
             '';
           in
             "+${pkgs.writeShellScript "start-pre-full-privileges" script}";
@@ -149,7 +183,7 @@ in
         DynamicUser = true;
         ReadWritePaths = cfg.settings.DatabaseDirectory;
         RuntimeDirectory = "geoipupdate";
-        RuntimeDirectoryMode = 0700;
+        RuntimeDirectoryMode = "0700";
         CapabilityBoundingSet = "";
         PrivateDevices = true;
         PrivateMounts = true;
@@ -163,7 +197,7 @@ in
         ProtectKernelTunables = true;
         ProtectProc = "invisible";
         ProcSubset = "pid";
-        SystemCallFilter = [ "@system-service" "~@privileged" "~@resources" ];
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
         RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
         RestrictRealtime = true;
         RestrictNamespaces = true;
diff --git a/nixos/modules/services/misc/gitea.nix b/nixos/modules/services/misc/gitea.nix
index bc7bb663ee0..d29416eda21 100644
--- a/nixos/modules/services/misc/gitea.nix
+++ b/nixos/modules/services/misc/gitea.nix
@@ -10,6 +10,7 @@ let
   useMysql = cfg.database.type == "mysql";
   usePostgresql = cfg.database.type == "postgres";
   useSqlite = cfg.database.type == "sqlite3";
+  format = pkgs.formats.ini { };
   configFile = pkgs.writeText "app.ini" ''
     APP_NAME = ${cfg.appName}
     RUN_USER = ${cfg.user}
@@ -22,51 +23,47 @@ let
 in
 
 {
+  imports = [
+    (mkRenamedOptionModule [ "services" "gitea" "cookieSecure" ] [ "services" "gitea" "settings" "session" "COOKIE_SECURE" ])
+    (mkRenamedOptionModule [ "services" "gitea" "disableRegistration" ] [ "services" "gitea" "settings" "service" "DISABLE_REGISTRATION" ])
+    (mkRenamedOptionModule [ "services" "gitea" "log" "level" ] [ "services" "gitea" "settings" "log" "LEVEL" ])
+    (mkRenamedOptionModule [ "services" "gitea" "log" "rootPath" ] [ "services" "gitea" "settings" "log" "ROOT_PATH" ])
+    (mkRenamedOptionModule [ "services" "gitea" "ssh" "clonePort" ] [ "services" "gitea" "settings" "server" "SSH_PORT" ])
+
+    (mkRemovedOptionModule [ "services" "gitea" "ssh" "enable" ] "services.gitea.ssh.enable has been migrated into freeform setting services.gitea.settings.server.DISABLE_SSH. Keep in mind that the setting is inverted")
+  ];
+
   options = {
     services.gitea = {
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = "Enable Gitea Service.";
+        description = lib.mdDoc "Enable Gitea Service.";
       };
 
       package = mkOption {
         default = pkgs.gitea;
         type = types.package;
         defaultText = literalExpression "pkgs.gitea";
-        description = "gitea derivation to use";
+        description = lib.mdDoc "gitea derivation to use";
       };
 
       useWizard = mkOption {
         default = false;
         type = types.bool;
-        description = "Do not generate a configuration and use gitea' installation wizard instead. The first registered user will be administrator.";
+        description = lib.mdDoc "Do not generate a configuration and use gitea' installation wizard instead. The first registered user will be administrator.";
       };
 
       stateDir = mkOption {
         default = "/var/lib/gitea";
         type = types.str;
-        description = "gitea data directory.";
-      };
-
-      log = {
-        rootPath = mkOption {
-          default = "${cfg.stateDir}/log";
-          defaultText = literalExpression ''"''${config.${opt.stateDir}}/log"'';
-          type = types.str;
-          description = "Root path for log files.";
-        };
-        level = mkOption {
-          default = "Info";
-          type = types.enum [ "Trace" "Debug" "Info" "Warn" "Error" "Critical" ];
-          description = "General log level.";
-        };
+        description = lib.mdDoc "gitea data directory.";
       };
 
       user = mkOption {
         type = types.str;
         default = "gitea";
-        description = "User account under which gitea runs.";
+        description = lib.mdDoc "User account under which gitea runs.";
       };
 
       database = {
@@ -74,45 +71,45 @@ in
           type = types.enum [ "sqlite3" "mysql" "postgres" ];
           example = "mysql";
           default = "sqlite3";
-          description = "Database engine to use.";
+          description = lib.mdDoc "Database engine to use.";
         };
 
         host = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "Database host address.";
+          description = lib.mdDoc "Database host address.";
         };
 
         port = mkOption {
           type = types.port;
-          default = (if !usePostgresql then 3306 else pg.port);
+          default = if !usePostgresql then 3306 else pg.port;
           defaultText = literalExpression ''
             if config.${opt.database.type} != "postgresql"
             then 3306
             else config.${options.services.postgresql.port}
           '';
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = mkOption {
           type = types.str;
           default = "gitea";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = mkOption {
           type = types.str;
           default = "gitea";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         password = mkOption {
           type = types.str;
           default = "";
-          description = ''
-            The password corresponding to <option>database.user</option>.
+          description = lib.mdDoc ''
+            The password corresponding to {option}`database.user`.
             Warning: this is stored in cleartext in the Nix store!
-            Use <option>database.passwordFile</option> instead.
+            Use {option}`database.passwordFile` instead.
           '';
         };
 
@@ -120,9 +117,9 @@ in
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/gitea-dbpassword";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
 
@@ -131,20 +128,20 @@ in
           default = if (cfg.database.createDatabase && usePostgresql) then "/run/postgresql" else if (cfg.database.createDatabase && useMysql) then "/run/mysqld/mysqld.sock" else null;
           defaultText = literalExpression "null";
           example = "/run/mysqld/mysqld.sock";
-          description = "Path to the unix socket file to use for authentication.";
+          description = lib.mdDoc "Path to the unix socket file to use for authentication.";
         };
 
         path = mkOption {
           type = types.str;
           default = "${cfg.stateDir}/data/gitea.db";
           defaultText = literalExpression ''"''${config.${opt.stateDir}}/data/gitea.db"'';
-          description = "Path to the sqlite3 database file.";
+          description = lib.mdDoc "Path to the sqlite3 database file.";
         };
 
         createDatabase = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether to create a local database automatically.";
+          description = lib.mdDoc "Whether to create a local database automatically.";
         };
       };
 
@@ -152,7 +149,7 @@ in
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Enable a timer that runs gitea dump to generate backup-files of the
             current gitea database and repositories.
           '';
@@ -162,12 +159,11 @@ in
           type = types.str;
           default = "04:31";
           example = "hourly";
-          description = ''
+          description = lib.mdDoc ''
             Run a gitea dump at this interval. Runs by default at 04:31 every day.
 
             The format is described in
-            <citerefentry><refentrytitle>systemd.time</refentrytitle>
-            <manvolnum>7</manvolnum></citerefentry>.
+            {manpage}`systemd.time(7)`.
           '';
         };
 
@@ -175,107 +171,79 @@ in
           type = types.str;
           default = "${cfg.stateDir}/dump";
           defaultText = literalExpression ''"''${config.${opt.stateDir}}/dump"'';
-          description = "Path to the dump files.";
+          description = lib.mdDoc "Path to the dump files.";
         };
 
         type = mkOption {
           type = types.enum [ "zip" "rar" "tar" "sz" "tar.gz" "tar.xz" "tar.bz2" "tar.br" "tar.lz4" ];
           default = "zip";
-          description = "Archive format used to store the dump file.";
+          description = lib.mdDoc "Archive format used to store the dump file.";
         };
 
         file = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = "Filename to be used for the dump. If `null` a default name is choosen by gitea.";
+          description = lib.mdDoc "Filename to be used for the dump. If `null` a default name is choosen by gitea.";
           example = "gitea-dump";
         };
       };
 
-      ssh = {
-        enable = mkOption {
-          type = types.bool;
-          default = true;
-          description = "Enable external SSH feature.";
-        };
-
-        clonePort = mkOption {
-          type = types.int;
-          default = 22;
-          example = 2222;
-          description = ''
-            SSH port displayed in clone URL.
-            The option is required to configure a service when the external visible port
-            differs from the local listening port i.e. if port forwarding is used.
-          '';
-        };
-      };
-
       lfs = {
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = "Enables git-lfs support.";
+          description = lib.mdDoc "Enables git-lfs support.";
         };
 
         contentDir = mkOption {
           type = types.str;
           default = "${cfg.stateDir}/data/lfs";
           defaultText = literalExpression ''"''${config.${opt.stateDir}}/data/lfs"'';
-          description = "Where to store LFS files.";
+          description = lib.mdDoc "Where to store LFS files.";
         };
       };
 
       appName = mkOption {
         type = types.str;
         default = "gitea: Gitea Service";
-        description = "Application name.";
+        description = lib.mdDoc "Application name.";
       };
 
       repositoryRoot = mkOption {
         type = types.str;
         default = "${cfg.stateDir}/repositories";
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/repositories"'';
-        description = "Path to the git repositories.";
+        description = lib.mdDoc "Path to the git repositories.";
       };
 
       domain = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Domain name of your server.";
+        description = lib.mdDoc "Domain name of your server.";
       };
 
       rootUrl = mkOption {
         type = types.str;
         default = "http://localhost:3000/";
-        description = "Full public URL of gitea server.";
+        description = lib.mdDoc "Full public URL of gitea server.";
       };
 
       httpAddress = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = "HTTP listen address.";
+        description = lib.mdDoc "HTTP listen address.";
       };
 
       httpPort = mkOption {
-        type = types.int;
+        type = types.port;
         default = 3000;
-        description = "HTTP listen port.";
+        description = lib.mdDoc "HTTP listen port.";
       };
 
       enableUnixSocket = mkOption {
         type = types.bool;
         default = false;
-        description = "Configure Gitea to listen on a unix socket instead of the default TCP port.";
-      };
-
-      cookieSecure = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Marks session cookies as "secure" as a hint for browsers to only send
-          them via HTTPS. This option is recommend, if gitea is being served over HTTPS.
-        '';
+        description = lib.mdDoc "Configure Gitea to listen on a unix socket instead of the default TCP port.";
       };
 
       staticRootPath = mkOption {
@@ -283,33 +251,20 @@ in
         default = gitea.data;
         defaultText = literalExpression "package.data";
         example = "/var/lib/gitea/data";
-        description = "Upper level of template and static files path.";
+        description = lib.mdDoc "Upper level of template and static files path.";
       };
 
       mailerPasswordFile = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "/var/lib/secrets/gitea/mailpw";
-        description = "Path to a file containing the SMTP password.";
-      };
-
-      disableRegistration = mkEnableOption "the registration lock" // {
-        description = ''
-          By default any user can create an account on this <literal>gitea</literal> instance.
-          This can be disabled by using this option.
-
-          <emphasis>Note:</emphasis> please keep in mind that this should be added after the initial
-          deploy unless <link linkend="opt-services.gitea.useWizard">services.gitea.useWizard</link>
-          is <literal>true</literal> as the first registered user will be the administrator if
-          no install wizard is used.
-        '';
+        description = lib.mdDoc "Path to a file containing the SMTP password.";
       };
 
       settings = mkOption {
-        type = with types; attrsOf (attrsOf (oneOf [ bool int str ]));
         default = {};
-        description = ''
-          Gitea configuration. Refer to <link xlink:href="https://docs.gitea.io/en-us/config-cheat-sheet/"/>
+        description = lib.mdDoc ''
+          Gitea configuration. Refer to <https://docs.gitea.io/en-us/config-cheat-sheet/>
           for details on supported values.
         '';
         example = literalExpression ''
@@ -330,12 +285,74 @@ in
             };
           }
         '';
+        type = with types; submodule {
+          freeformType = format.type;
+          options = {
+            log = {
+              ROOT_PATH = mkOption {
+                default = "${cfg.stateDir}/log";
+                defaultText = literalExpression ''"''${config.${opt.stateDir}}/log"'';
+                type = types.str;
+                description = lib.mdDoc "Root path for log files.";
+              };
+              LEVEL = mkOption {
+                default = "Info";
+                type = types.enum [ "Trace" "Debug" "Info" "Warn" "Error" "Critical" ];
+                description = lib.mdDoc "General log level.";
+              };
+            };
+
+            server = {
+              DISABLE_SSH = mkOption {
+                type = types.bool;
+                default = false;
+                description = lib.mdDoc "Disable external SSH feature.";
+              };
+
+              SSH_PORT = mkOption {
+                type = types.port;
+                default = 22;
+                example = 2222;
+                description = lib.mdDoc ''
+                  SSH port displayed in clone URL.
+                  The option is required to configure a service when the external visible port
+                  differs from the local listening port i.e. if port forwarding is used.
+                '';
+              };
+            };
+
+            service = {
+              DISABLE_REGISTRATION = mkEnableOption (lib.mdDoc "the registration lock") // {
+                description = lib.mdDoc ''
+                  By default any user can create an account on this `gitea` instance.
+                  This can be disabled by using this option.
+
+                  *Note:* please keep in mind that this should be added after the initial
+                  deploy unless [](#opt-services.gitea.useWizard)
+                  is `true` as the first registered user will be the administrator if
+                  no install wizard is used.
+                '';
+              };
+            };
+
+            session = {
+              COOKIE_SECURE = mkOption {
+                type = types.bool;
+                default = false;
+                description = lib.mdDoc ''
+                  Marks session cookies as "secure" as a hint for browsers to only send
+                  them via HTTPS. This option is recommend, if gitea is being served over HTTPS.
+                '';
+              };
+            };
+          };
+        };
       };
 
       extraConfig = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "Configuration lines appended to the generated gitea configuration file.";
+        description = lib.mdDoc "Configuration lines appended to the generated gitea configuration file.";
       };
     };
   };
@@ -385,13 +402,6 @@ in
           HTTP_ADDR = cfg.httpAddress;
           HTTP_PORT = cfg.httpPort;
         })
-        (mkIf cfg.ssh.enable {
-          DISABLE_SSH = false;
-          SSH_PORT = cfg.ssh.clonePort;
-        })
-        (mkIf (!cfg.ssh.enable) {
-          DISABLE_SSH = true;
-        })
         (mkIf cfg.lfs.enable {
           LFS_START_SERVER = true;
           LFS_CONTENT_PATH = cfg.lfs.contentDir;
@@ -400,8 +410,7 @@ in
       ];
 
       session = {
-        COOKIE_NAME = "session";
-        COOKIE_SECURE = cfg.cookieSecure;
+        COOKIE_NAME = lib.mkDefault "session";
       };
 
       security = {
@@ -410,15 +419,6 @@ in
         INSTALL_LOCK = true;
       };
 
-      log = {
-        ROOT_PATH = cfg.log.rootPath;
-        LEVEL = cfg.log.level;
-      };
-
-      service = {
-        DISABLE_REGISTRATION = cfg.disableRegistration;
-      };
-
       mailer = mkIf (cfg.mailerPasswordFile != null) {
         PASSWD = "#mailerpass#";
       };
@@ -483,7 +483,7 @@ in
       description = "gitea";
       after = [ "network.target" ] ++ lib.optional usePostgresql "postgresql.service" ++ lib.optional useMysql "mysql.service";
       wantedBy = [ "multi-user.target" ];
-      path = [ gitea pkgs.git ];
+      path = [ gitea pkgs.git pkgs.gnupg ];
 
       # In older versions the secret naming for JWT was kind of confusing.
       # The file jwt_secret hold the value for LFS_JWT_SECRET and JWT_SECRET
@@ -499,50 +499,45 @@ in
         oldLfsJwtSecret = "${cfg.stateDir}/custom/conf/jwt_secret"; # old file for LFS_JWT_SECRET
         lfsJwtSecret = "${cfg.stateDir}/custom/conf/lfs_jwt_secret"; # new file for LFS_JWT_SECRET
         internalToken = "${cfg.stateDir}/custom/conf/internal_token";
+        replaceSecretBin = "${pkgs.replace-secret}/bin/replace-secret";
       in ''
         # copy custom configuration and generate a random secret key if needed
-        ${optionalString (cfg.useWizard == false) ''
+        ${optionalString (!cfg.useWizard) ''
           function gitea_setup {
             cp -f ${configFile} ${runConfig}
 
-            if [ ! -e ${secretKey} ]; then
+            if [ ! -s ${secretKey} ]; then
                 ${gitea}/bin/gitea generate secret SECRET_KEY > ${secretKey}
             fi
 
             # Migrate LFS_JWT_SECRET filename
-            if [[ -e ${oldLfsJwtSecret} && ! -e ${lfsJwtSecret} ]]; then
+            if [[ -s ${oldLfsJwtSecret} && ! -s ${lfsJwtSecret} ]]; then
                 mv ${oldLfsJwtSecret} ${lfsJwtSecret}
             fi
 
-            if [ ! -e ${oauth2JwtSecret} ]; then
+            if [ ! -s ${oauth2JwtSecret} ]; then
                 ${gitea}/bin/gitea generate secret JWT_SECRET > ${oauth2JwtSecret}
             fi
 
-            if [ ! -e ${lfsJwtSecret} ]; then
+            if [ ! -s ${lfsJwtSecret} ]; then
                 ${gitea}/bin/gitea generate secret LFS_JWT_SECRET > ${lfsJwtSecret}
             fi
 
-            if [ ! -e ${internalToken} ]; then
+            if [ ! -s ${internalToken} ]; then
                 ${gitea}/bin/gitea generate secret INTERNAL_TOKEN > ${internalToken}
             fi
 
-            SECRETKEY="$(head -n1 ${secretKey})"
-            DBPASS="$(head -n1 ${cfg.database.passwordFile})"
-            OAUTH2JWTSECRET="$(head -n1 ${oauth2JwtSecret})"
-            LFSJWTSECRET="$(head -n1 ${lfsJwtSecret})"
-            INTERNALTOKEN="$(head -n1 ${internalToken})"
-            ${if (cfg.mailerPasswordFile == null) then ''
-              MAILERPASSWORD="#mailerpass#"
-            '' else ''
-              MAILERPASSWORD="$(head -n1 ${cfg.mailerPasswordFile} || :)"
+            chmod u+w '${runConfig}'
+            ${replaceSecretBin} '#secretkey#' '${secretKey}' '${runConfig}'
+            ${replaceSecretBin} '#dbpass#' '${cfg.database.passwordFile}' '${runConfig}'
+            ${replaceSecretBin} '#oauth2jwtsecret#' '${oauth2JwtSecret}' '${runConfig}'
+            ${replaceSecretBin} '#lfsjwtsecret#' '${lfsJwtSecret}' '${runConfig}'
+            ${replaceSecretBin} '#internaltoken#' '${internalToken}' '${runConfig}'
+
+            ${lib.optionalString (cfg.mailerPasswordFile != null) ''
+              ${replaceSecretBin} '#mailerpass#' '${cfg.mailerPasswordFile}' '${runConfig}'
             ''}
-            sed -e "s,#secretkey#,$SECRETKEY,g" \
-                -e "s,#dbpass#,$DBPASS,g" \
-                -e "s,#oauth2jwtsecret#,$OAUTH2JWTSECRET,g" \
-                -e "s,#lfsjwtsecret#,$LFSJWTSECRET,g" \
-                -e "s,#internaltoken#,$INTERNALTOKEN,g" \
-                -e "s,#mailerpass#,$MAILERPASSWORD,g" \
-                -i ${runConfig}
+            chmod u-w '${runConfig}'
           }
           (umask 027; gitea_setup)
         ''}
@@ -597,7 +592,7 @@ in
         PrivateMounts = true;
         # System Call Filtering
         SystemCallArchitectures = "native";
-        SystemCallFilter = "~@clock @cpu-emulation @debug @keyring @memlock @module @mount @obsolete @raw-io @reboot @resources @setuid @swap";
+        SystemCallFilter = "~@clock @cpu-emulation @debug @keyring @memlock @module @mount @obsolete @raw-io @reboot @setuid @swap";
       };
 
       environment = {
@@ -627,10 +622,10 @@ in
 
     # Create database passwordFile default when password is configured.
     services.gitea.database.passwordFile =
-      (mkDefault (toString (pkgs.writeTextFile {
+      mkDefault (toString (pkgs.writeTextFile {
         name = "gitea-database-password";
         text = cfg.database.password;
-      })));
+      }));
 
     systemd.services.gitea-dump = mkIf cfg.dump.enable {
        description = "gitea dump";
diff --git a/nixos/modules/services/misc/gitit.nix b/nixos/modules/services/misc/gitit.nix
index ceb186c0f04..0fafa76b548 100644
--- a/nixos/modules/services/misc/gitit.nix
+++ b/nixos/modules/services/misc/gitit.nix
@@ -10,7 +10,7 @@ let
 
   toYesNo = b: if b then "yes" else "no";
 
-  gititShared = with cfg.haskellPackages; gitit + "/share/" + pkgs.stdenv.hostPlatform.system + "-" + ghc.name + "/" + gitit.pname + "-" + gitit.version;
+  gititShared = with cfg.haskellPackages; gitit + "/share/" + ghc.targetPrefix + ghc.haskellCompilerName + "/" + gitit.pname + "-" + gitit.version;
 
   gititWithPkgs = hsPkgs: extras: hsPkgs.ghcWithPackages (self: with self; [ gitit ] ++ (extras self));
 
@@ -31,14 +31,14 @@ let
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable the gitit service.";
+        description = lib.mdDoc "Enable the gitit service.";
       };
 
       haskellPackages = mkOption {
         default = pkgs.haskellPackages;
         defaultText = literalExpression "pkgs.haskellPackages";
         example = literalExpression "pkgs.haskell.packages.ghc784";
-        description = "haskellPackages used to build gitit and plugins.";
+        description = lib.mdDoc "haskellPackages used to build gitit and plugins.";
       };
 
       extraPackages = mkOption {
@@ -49,41 +49,41 @@ let
             haskellPackages.wreq
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra packages available to ghc when running gitit. The
           value must be a function which receives the attrset defined
-          in <varname>haskellPackages</varname> as the sole argument.
+          in {var}`haskellPackages` as the sole argument.
         '';
       };
 
       address = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = "IP address on which the web server will listen.";
+        description = lib.mdDoc "IP address on which the web server will listen.";
       };
 
       port = mkOption {
         type = types.int;
         default = 5001;
-        description = "Port on which the web server will run.";
+        description = lib.mdDoc "Port on which the web server will run.";
       };
 
       wikiTitle = mkOption {
         type = types.str;
         default = "Gitit!";
-        description = "The wiki title.";
+        description = lib.mdDoc "The wiki title.";
       };
 
       repositoryType = mkOption {
         type = types.enum ["git" "darcs" "mercurial"];
         default = "git";
-        description = "Specifies the type of repository used for wiki content.";
+        description = lib.mdDoc "Specifies the type of repository used for wiki content.";
       };
 
       repositoryPath = mkOption {
         type = types.path;
         default = homeDir + "/wiki";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the path of the repository directory. If it does not
           exist, gitit will create it on startup.
         '';
@@ -92,7 +92,7 @@ let
       requireAuthentication = mkOption {
         type = types.enum [ "none" "modify" "read" ];
         default = "modify";
-        description = ''
+        description = lib.mdDoc ''
           If 'none', login is never required, and pages can be edited
           anonymously.  If 'modify', login is required to modify the wiki
           (edit, add, delete pages, upload files).  If 'read', login is
@@ -103,7 +103,7 @@ let
       authenticationMethod = mkOption {
         type = types.enum [ "form" "http" "generic" "github" ];
         default = "form";
-        description = ''
+        description = lib.mdDoc ''
           'form' means that users will be logged in and registered using forms
           in the gitit web interface.  'http' means that gitit will assume that
           HTTP authentication is in place and take the logged in username from
@@ -121,7 +121,7 @@ let
       userFile = mkOption {
         type = types.path;
         default = homeDir + "/gitit-users";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the path of the file containing user login information.  If
           it does not exist, gitit will create it (with an empty user list).
           This file is not used if 'http' is selected for
@@ -132,7 +132,7 @@ let
       sessionTimeout = mkOption {
         type = types.int;
         default = 60;
-        description = ''
+        description = lib.mdDoc ''
           Number of minutes of inactivity before a session expires.
         '';
       };
@@ -140,7 +140,7 @@ let
       staticDir = mkOption {
         type = types.path;
         default = gititShared + "/data/static";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the path of the static directory (containing javascript,
           css, and images).  If it does not exist, gitit will create it and
           populate it with required scripts, stylesheets, and images.
@@ -150,7 +150,7 @@ let
       defaultPageType = mkOption {
         type = types.enum [ "markdown" "rst" "latex" "html" "markdown+lhs" "rst+lhs" "latex+lhs" ];
         default = "markdown";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the type of markup used to interpret pages in the wiki.
           Possible values are markdown, rst, latex, html, markdown+lhs,
           rst+lhs, and latex+lhs. (the +lhs variants treat the input as
@@ -166,7 +166,7 @@ let
       math = mkOption {
         type = types.enum [ "mathml" "raw" "mathjax" "jsmath" "google" ];
         default = "mathml";
-        description = ''
+        description = lib.mdDoc ''
           Specifies how LaTeX math is to be displayed.  Possible values are
           mathml, raw, mathjax, jsmath, and google.  If mathml is selected,
           gitit will convert LaTeX math to MathML and link in a script,
@@ -186,7 +186,7 @@ let
       mathJaxScript = mkOption {
         type = types.str;
         default = "https://d3eoax9i5htok0.cloudfront.net/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the path to MathJax rendering script.  You might want to
           use your own MathJax script to render formulas without Internet
           connection or if you want to use some special LaTeX packages.  Note:
@@ -202,7 +202,7 @@ let
       showLhsBirdTracks = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether to show Haskell code blocks in "bird style", with
           "> " at the beginning of each line.
         '';
@@ -211,7 +211,7 @@ let
       templatesDir = mkOption {
         type = types.path;
         default = gititShared + "/data/templates";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the path of the directory containing page templates.  If it
           does not exist, gitit will create it with default templates.  Users
           may wish to edit the templates to customize the appearance of their
@@ -224,7 +224,7 @@ let
       logFile = mkOption {
         type = types.path;
         default = homeDir + "/gitit.log";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the path of gitit's log file.  If it does not exist, gitit
           will create it. The log is in Apache combined log format.
         '';
@@ -233,7 +233,7 @@ let
       logLevel = mkOption {
         type = types.enum [ "DEBUG" "INFO" "NOTICE" "WARNING" "ERROR" "CRITICAL" "ALERT" "EMERGENCY" ];
         default = "ERROR";
-        description = ''
+        description = lib.mdDoc ''
           Determines how much information is logged.  Possible values (from
           most to least verbose) are DEBUG, INFO, NOTICE, WARNING, ERROR,
           CRITICAL, ALERT, EMERGENCY.
@@ -243,7 +243,7 @@ let
       frontPage = mkOption {
         type = types.str;
         default = "Front Page";
-        description = ''
+        description = lib.mdDoc ''
           Specifies which wiki page is to be used as the wiki's front page.
           Gitit creates a default front page on startup, if one does not exist
           already.
@@ -253,7 +253,7 @@ let
       noDelete = mkOption {
         type = types.str;
         default = "Front Page, Help";
-        description = ''
+        description = lib.mdDoc ''
           Specifies pages that cannot be deleted through the web interface.
           (They can still be deleted directly using git or darcs.) A
           comma-separated list of page names.  Leave blank to allow every page
@@ -264,7 +264,7 @@ let
       noEdit = mkOption {
         type = types.str;
         default = "Help";
-        description = ''
+        description = lib.mdDoc ''
           Specifies pages that cannot be edited through the web interface.
           Leave blank to allow every page to be edited.
         '';
@@ -273,7 +273,7 @@ let
       defaultSummary = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Specifies text to be used in the change description if the author
           leaves the "description" field blank.  If default-summary is blank
           (the default), the author will be required to fill in the description
@@ -284,7 +284,7 @@ let
       tableOfContents = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether to print a tables of contents (with links to
           sections) on each wiki page.
         '';
@@ -293,7 +293,7 @@ let
       plugins = mkOption {
         type = with types; listOf str;
         default = [ (gititShared + "/plugins/Dot.hs") ];
-        description = ''
+        description = lib.mdDoc ''
           Specifies a list of plugins to load. Plugins may be specified either
           by their path or by their module name. If the plugin name starts
           with Gitit.Plugin., gitit will assume that the plugin is an installed
@@ -304,7 +304,7 @@ let
       useCache = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether to cache rendered pages.  Note that if use-feed is
           selected, feeds will be cached regardless of the value of use-cache.
         '';
@@ -313,13 +313,13 @@ let
       cacheDir = mkOption {
         type = types.path;
         default = homeDir + "/cache";
-        description = "Path where rendered pages will be cached.";
+        description = lib.mdDoc "Path where rendered pages will be cached.";
       };
 
       maxUploadSize = mkOption {
         type = types.str;
         default = "1000K";
-        description = ''
+        description = lib.mdDoc ''
           Specifies an upper limit on the size (in bytes) of files uploaded
           through the wiki's web interface.  To disable uploads, set this to
           0K.  This will result in the uploads link disappearing and the
@@ -330,32 +330,32 @@ let
       maxPageSize = mkOption {
         type = types.str;
         default = "1000K";
-        description = "Specifies an upper limit on the size (in bytes) of pages.";
+        description = lib.mdDoc "Specifies an upper limit on the size (in bytes) of pages.";
       };
 
       debugMode = mkOption {
         type = types.bool;
         default = false;
-        description = "Causes debug information to be logged while gitit is running.";
+        description = lib.mdDoc "Causes debug information to be logged while gitit is running.";
       };
 
       compressResponses = mkOption {
         type = types.bool;
         default = true;
-        description = "Specifies whether HTTP responses should be compressed.";
+        description = lib.mdDoc "Specifies whether HTTP responses should be compressed.";
       };
 
       mimeTypesFile = mkOption {
         type = types.path;
         default = "/etc/mime/types.info";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the path of a file containing mime type mappings.  Each
           line of the file should contain two fields, separated by whitespace.
           The first field is the mime type, the second is a file extension.
           For example:
-<programlisting>
-video/x-ms-wmx  wmx
-</programlisting>
+          ```
+          video/x-ms-wmx  wmx
+          ```
           If the file is not found, some simple defaults will be used.
         '';
       };
@@ -363,7 +363,7 @@ video/x-ms-wmx  wmx
       useReCaptcha = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If true, causes gitit to use the reCAPTCHA service
           (http://recaptcha.net) to prevent bots from creating accounts.
         '';
@@ -372,7 +372,7 @@ video/x-ms-wmx  wmx
       reCaptchaPrivateKey = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the private key for the reCAPTCHA service.  To get
           these, you need to create an account at http://recaptcha.net.
         '';
@@ -381,7 +381,7 @@ video/x-ms-wmx  wmx
       reCaptchaPublicKey = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the public key for the reCAPTCHA service.  To get
           these, you need to create an account at http://recaptcha.net.
         '';
@@ -390,7 +390,7 @@ video/x-ms-wmx  wmx
       accessQuestion = mkOption {
         type = types.str;
         default = "What is the code given to you by Ms. X?";
-        description = ''
+        description = lib.mdDoc ''
           Specifies a question that users must answer when they attempt to
           create an account
         '';
@@ -399,7 +399,7 @@ video/x-ms-wmx  wmx
       accessQuestionAnswers = mkOption {
         type = types.str;
         default = "RED DOG, red dog";
-        description = ''
+        description = lib.mdDoc ''
           Specifies a question that users must answer when they attempt to
           create an account, along with a comma-separated list of acceptable
           answers.  This can be used to institute a rudimentary password for
@@ -413,7 +413,7 @@ video/x-ms-wmx  wmx
       rpxDomain = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the domain and key of your RPX account.  The domain is just
           the prefix of the complete RPX domain, so if your full domain is
           'https://foo.rpxnow.com/', use 'foo' as the value of rpx-domain.
@@ -423,13 +423,13 @@ video/x-ms-wmx  wmx
       rpxKey = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "RPX account access key.";
+        description = lib.mdDoc "RPX account access key.";
       };
 
       mailCommand = mkOption {
         type = types.str;
         default = "sendmail %s";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the command to use to send notification emails.  '%s' will
           be replaced by the destination email address.  The body of the
           message will be read from stdin.  If this field is left blank,
@@ -451,7 +451,7 @@ video/x-ms-wmx  wmx
           >
           > Regards
         '';
-        description = ''
+        description = lib.mdDoc ''
           Gives the text of the message that will be sent to the user should
           she want to reset her password, or change other registration info.
           The lines must be indented, and must begin with '>'.  The initial
@@ -471,7 +471,7 @@ video/x-ms-wmx  wmx
       useFeed = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether an ATOM feed should be enabled (for the site and
           for individual pages).
         '';
@@ -480,7 +480,7 @@ video/x-ms-wmx  wmx
       baseUrl = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The base URL of the wiki, to be used in constructing feed IDs and RPX
           token_urls.  Set this if useFeed is false or authentication-method
           is 'rpx'.
@@ -490,10 +490,10 @@ video/x-ms-wmx  wmx
       absoluteUrls = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Make wikilinks absolute with respect to the base-url.  So, for
           example, in a wiki served at the base URL '/wiki', on a page
-          Sub/Page, the wikilink '[Cactus]()' will produce a link to
+          Sub/Page, the wikilink `[Cactus]()` will produce a link to
           '/wiki/Cactus' if absoluteUrls is true, and a relative link to
           'Cactus' (referring to '/wiki/Sub/Cactus') if absolute-urls is 'no'.
         '';
@@ -502,19 +502,19 @@ video/x-ms-wmx  wmx
       feedDays = mkOption {
         type = types.int;
         default = 14;
-        description = "Number of days to be included in feeds.";
+        description = lib.mdDoc "Number of days to be included in feeds.";
       };
 
       feedRefreshTime = mkOption {
         type = types.int;
         default = 60;
-        description = "Number of minutes to cache feeds before refreshing.";
+        description = lib.mdDoc "Number of minutes to cache feeds before refreshing.";
       };
 
       pdfExport = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If true, PDF will appear in export options. PDF will be created using
           pdflatex, which must be installed and in the path. Note that PDF
           exports create significant additional server load.
@@ -524,7 +524,7 @@ video/x-ms-wmx  wmx
       pandocUserData = mkOption {
         type = with types; nullOr path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           If a directory is specified, this will be searched for pandoc
           customizations. These can include a templates/ directory for custom
           templates for various export formats, an S5 directory for custom S5
@@ -537,7 +537,7 @@ video/x-ms-wmx  wmx
       xssSanitize = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           If true, all HTML (including that produced by pandoc) is filtered
           through xss-sanitize.  Set to no only if you trust all of your users.
         '';
@@ -546,37 +546,37 @@ video/x-ms-wmx  wmx
       oauthClientId = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "OAuth client ID";
+        description = lib.mdDoc "OAuth client ID";
       };
 
       oauthClientSecret = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "OAuth client secret";
+        description = lib.mdDoc "OAuth client secret";
       };
 
       oauthCallback = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "OAuth callback URL";
+        description = lib.mdDoc "OAuth callback URL";
       };
 
       oauthAuthorizeEndpoint = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "OAuth authorize endpoint";
+        description = lib.mdDoc "OAuth authorize endpoint";
       };
 
       oauthAccessTokenEndpoint = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "OAuth access token endpoint";
+        description = lib.mdDoc "OAuth access token endpoint";
       };
 
       githubOrg = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = "Github organization";
+        description = lib.mdDoc "Github organization";
       };
   };
 
@@ -689,14 +689,14 @@ in
           ''
           if [ ! -d _darcs ]
           then
-            ${pkgs.darcs}/bin/darcs initialize
+            darcs initialize
             echo "${gm}" > _darcs/prefs/email
           ''
           else if repositoryType == "mercurial" then
           ''
           if [ ! -d .hg ]
           then
-            ${pkgs.mercurial}/bin/hg init
+            hg init
             cat >> .hg/hgrc <<NAMED
 [ui]
 username = gitit ${gm}
@@ -706,9 +706,9 @@ NAMED
           ''
           if [ ! -d  .git ]
           then
-            ${pkgs.git}/bin/git init
-            ${pkgs.git}/bin/git config user.email "${gm}"
-            ${pkgs.git}/bin/git config user.name "gitit"
+            git init
+            git config user.email "${gm}"
+            git config user.name "gitit"
           ''}
           chown ${uid}:${gid} -R ${repositoryPath}
           fi
diff --git a/nixos/modules/services/misc/gitlab.nix b/nixos/modules/services/misc/gitlab.nix
index e48444f7161..e206d5bb7c6 100644
--- a/nixos/modules/services/misc/gitlab.nix
+++ b/nixos/modules/services/misc/gitlab.nix
@@ -6,6 +6,9 @@ let
   cfg = config.services.gitlab;
   opt = options.services.gitlab;
 
+  toml = pkgs.formats.toml {};
+  yaml = pkgs.formats.yaml {};
+
   ruby = cfg.packages.gitlab.ruby;
 
   postgresqlPackage = if config.services.postgresql.enable then
@@ -17,8 +20,8 @@ let
   gitalySocket = "${cfg.statePath}/tmp/sockets/gitaly.socket";
   pathUrlQuote = url: replaceStrings ["/"] ["%2F"] url;
 
-  databaseConfig = {
-    production = {
+  databaseConfig = let
+    val = {
       adapter = "postgresql";
       database = cfg.databaseName;
       host = cfg.databaseHost;
@@ -26,6 +29,10 @@ let
       encoding = "utf8";
       pool = cfg.databasePool;
     } // cfg.extraDatabaseConfig;
+  in if lib.versionAtLeast (lib.getVersion cfg.packages.gitlab) "15.0" then {
+    production.main = val;
+  } else {
+    production = val;
   };
 
   # We only want to create a database if we're actually going to connect to it.
@@ -69,17 +76,18 @@ let
     repos_path = "${cfg.statePath}/repositories";
     secret_file = "${cfg.statePath}/gitlab_shell_secret";
     log_file = "${cfg.statePath}/log/gitlab-shell.log";
-    redis = {
-      bin = "${pkgs.redis}/bin/redis-cli";
-      host = "127.0.0.1";
-      port = config.services.redis.servers.gitlab.port;
-      database = 0;
-      namespace = "resque:gitlab";
-    };
   };
 
   redisConfig.production.url = cfg.redisUrl;
 
+  cableYml = yaml.generate "cable.yml" {
+    production = {
+      adapter = "redis";
+      url = cfg.redisUrl;
+      channel_prefix = "gitlab_production";
+    };
+  };
+
   pagesArgs = [
     "-pages-domain" gitlabConfig.production.pages.host
     "-pages-root" "${gitlabConfig.production.shared.path}/pages"
@@ -148,7 +156,7 @@ let
         port = cfg.registry.externalPort;
         key = cfg.registry.keyFile;
         api_url = "http://${config.services.dockerRegistry.listenAddress}:${toString config.services.dockerRegistry.port}/";
-        issuer = "gitlab-issuer";
+        issuer = cfg.registry.issuer;
       };
       extra = {};
       uploads.storage_path = cfg.statePath;
@@ -168,32 +176,43 @@ let
     MALLOC_ARENA_MAX = "2";
   } // cfg.extraEnv;
 
+  runtimeDeps = with pkgs; [
+    nodejs
+    gzip
+    git
+    gnutar
+    postgresqlPackage
+    coreutils
+    procps
+    findutils # Needed for gitlab:cleanup:orphan_job_artifact_files
+  ];
+
   gitlab-rake = pkgs.stdenv.mkDerivation {
     name = "gitlab-rake";
-    buildInputs = [ pkgs.makeWrapper ];
+    nativeBuildInputs = [ pkgs.makeWrapper ];
     dontBuild = true;
     dontUnpack = true;
     installPhase = ''
       mkdir -p $out/bin
       makeWrapper ${cfg.packages.gitlab.rubyEnv}/bin/rake $out/bin/gitlab-rake \
           ${concatStrings (mapAttrsToList (name: value: "--set ${name} '${value}' ") gitlabEnv)} \
-          --set PATH '${lib.makeBinPath [ pkgs.nodejs pkgs.gzip pkgs.git pkgs.gnutar postgresqlPackage pkgs.coreutils pkgs.procps ]}:$PATH' \
+          --set PATH '${lib.makeBinPath runtimeDeps}:$PATH' \
           --set RAKEOPT '-f ${cfg.packages.gitlab}/share/gitlab/Rakefile' \
-          --run 'cd ${cfg.packages.gitlab}/share/gitlab'
+          --chdir '${cfg.packages.gitlab}/share/gitlab'
      '';
   };
 
   gitlab-rails = pkgs.stdenv.mkDerivation {
     name = "gitlab-rails";
-    buildInputs = [ pkgs.makeWrapper ];
+    nativeBuildInputs = [ pkgs.makeWrapper ];
     dontBuild = true;
     dontUnpack = true;
     installPhase = ''
       mkdir -p $out/bin
       makeWrapper ${cfg.packages.gitlab.rubyEnv}/bin/rails $out/bin/gitlab-rails \
           ${concatStrings (mapAttrsToList (name: value: "--set ${name} '${value}' ") gitlabEnv)} \
-          --set PATH '${lib.makeBinPath [ pkgs.nodejs pkgs.gzip pkgs.git pkgs.gnutar postgresqlPackage pkgs.coreutils pkgs.procps ]}:$PATH' \
-          --run 'cd ${cfg.packages.gitlab}/share/gitlab'
+          --set PATH '${lib.makeBinPath runtimeDeps}:$PATH' \
+          --chdir '${cfg.packages.gitlab}/share/gitlab'
      '';
   };
 
@@ -225,6 +244,7 @@ in {
     (mkRenamedOptionModule [ "services" "gitlab" "stateDir" ] [ "services" "gitlab" "statePath" ])
     (mkRenamedOptionModule [ "services" "gitlab" "backupPath" ] [ "services" "gitlab" "backup" "path" ])
     (mkRemovedOptionModule [ "services" "gitlab" "satelliteDir" ] "")
+    (mkRemovedOptionModule [ "services" "gitlab" "logrotate" "extraConfig" ] "Modify services.logrotate.settings.gitlab directly instead")
   ];
 
   options = {
@@ -232,7 +252,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the gitlab service.
         '';
       };
@@ -241,7 +261,7 @@ in {
         type = types.package;
         default = pkgs.gitlab;
         defaultText = literalExpression "pkgs.gitlab";
-        description = "Reference to the gitlab package";
+        description = lib.mdDoc "Reference to the gitlab package";
         example = literalExpression "pkgs.gitlab-ee";
       };
 
@@ -249,48 +269,48 @@ in {
         type = types.package;
         default = pkgs.gitlab-shell;
         defaultText = literalExpression "pkgs.gitlab-shell";
-        description = "Reference to the gitlab-shell package";
+        description = lib.mdDoc "Reference to the gitlab-shell package";
       };
 
       packages.gitlab-workhorse = mkOption {
         type = types.package;
         default = pkgs.gitlab-workhorse;
         defaultText = literalExpression "pkgs.gitlab-workhorse";
-        description = "Reference to the gitlab-workhorse package";
+        description = lib.mdDoc "Reference to the gitlab-workhorse package";
       };
 
       packages.gitaly = mkOption {
         type = types.package;
         default = pkgs.gitaly;
         defaultText = literalExpression "pkgs.gitaly";
-        description = "Reference to the gitaly package";
+        description = lib.mdDoc "Reference to the gitaly package";
       };
 
       packages.pages = mkOption {
         type = types.package;
         default = pkgs.gitlab-pages;
         defaultText = literalExpression "pkgs.gitlab-pages";
-        description = "Reference to the gitlab-pages package";
+        description = lib.mdDoc "Reference to the gitlab-pages package";
       };
 
       statePath = mkOption {
         type = types.str;
         default = "/var/gitlab/state";
-        description = ''
+        description = lib.mdDoc ''
           GitLab state directory. Configuration, repositories and
           logs, among other things, are stored here.
 
           The directory will be created automatically if it doesn't
           exist already. Its parent directories must be owned by
-          either <literal>root</literal> or the user set in
-          <option>services.gitlab.user</option>.
+          either `root` or the user set in
+          {option}`services.gitlab.user`.
         '';
       };
 
       extraEnv = mkOption {
         type = types.attrsOf types.str;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Additional environment variables for the GitLab environment.
         '';
       };
@@ -299,11 +319,10 @@ in {
         type = with types; either str (listOf str);
         default = [];
         example = "03:00";
-        description = ''
+        description = lib.mdDoc ''
           The time(s) to run automatic backup of GitLab
           state. Specified in systemd's time format; see
-          <citerefentry><refentrytitle>systemd.time</refentrytitle>
-          <manvolnum>7</manvolnum></citerefentry>.
+          {manpage}`systemd.time(7)`.
         '';
       };
 
@@ -311,7 +330,7 @@ in {
         type = types.str;
         default = cfg.statePath + "/backup";
         defaultText = literalExpression ''config.${opt.statePath} + "/backup"'';
-        description = "GitLab path for backups.";
+        description = lib.mdDoc "GitLab path for backups.";
       };
 
       backup.keepTime = mkOption {
@@ -319,10 +338,9 @@ in {
         default = 0;
         example = 48;
         apply = x: x * 60 * 60;
-        description = ''
+        description = lib.mdDoc ''
           How long to keep the backups around, in
-          hours. <literal>0</literal> means <quote>keep
-          forever</quote>.
+          hours. `0` means “keep forever”.
         '';
       };
 
@@ -344,13 +362,13 @@ in {
         default = [];
         example = [ "artifacts" "lfs" ];
         apply = x: if isString x then x else concatStringsSep "," x;
-        description = ''
+        description = lib.mdDoc ''
           Directories to exclude from the backup. The example excludes
           CI artifacts and LFS objects from the backups. The
-          <literal>tar</literal> option skips the creation of a tar
+          `tar` option skips the creation of a tar
           file.
 
-          Refer to <link xlink:href="https://docs.gitlab.com/ee/raketasks/backup_restore.html#excluding-specific-directories-from-the-backup"/>
+          Refer to <https://docs.gitlab.com/ee/raketasks/backup_restore.html#excluding-specific-directories-from-the-backup>
           for more information.
         '';
       };
@@ -383,29 +401,29 @@ in {
             storage_class = "STANDARD";
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           GitLab automatic upload specification. Tells GitLab to
           upload the backup to a remote location when done.
 
           Attributes specified here are added under
-          <literal>production -> backup -> upload</literal> in
-          <filename>config/gitlab.yml</filename>.
+          `production -> backup -> upload` in
+          {file}`config/gitlab.yml`.
         '';
       };
 
       databaseHost = mkOption {
         type = types.str;
         default = "";
-        description = ''
-          GitLab database hostname. An empty string means <quote>use
-          local unix socket connection</quote>.
+        description = lib.mdDoc ''
+          GitLab database hostname. An empty string means
+          “use local unix socket connection”.
         '';
       };
 
       databasePasswordFile = mkOption {
         type = with types; nullOr path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           File containing the GitLab database user password.
 
           This should be a string, not a nix path, since nix paths are
@@ -416,43 +434,43 @@ in {
       databaseCreateLocally = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether a database should be automatically created on the
-          local host. Set this to <literal>false</literal> if you plan
+          local host. Set this to `false` if you plan
           on provisioning a local database yourself. This has no effect
-          if <option>services.gitlab.databaseHost</option> is customized.
+          if {option}`services.gitlab.databaseHost` is customized.
         '';
       };
 
       databaseName = mkOption {
         type = types.str;
         default = "gitlab";
-        description = "GitLab database name.";
+        description = lib.mdDoc "GitLab database name.";
       };
 
       databaseUsername = mkOption {
         type = types.str;
         default = "gitlab";
-        description = "GitLab database user.";
+        description = lib.mdDoc "GitLab database user.";
       };
 
       databasePool = mkOption {
         type = types.int;
         default = 5;
-        description = "Database connection pool size.";
+        description = lib.mdDoc "Database connection pool size.";
       };
 
       extraDatabaseConfig = mkOption {
         type = types.attrs;
         default = {};
-        description = "Extra configuration in config/database.yml.";
+        description = lib.mdDoc "Extra configuration in config/database.yml.";
       };
 
       redisUrl = mkOption {
         type = types.str;
-        default = "redis://localhost:${toString config.services.redis.servers.gitlab.port}/";
-        defaultText = literalExpression ''redis://localhost:''${toString config.services.redis.servers.gitlab.port}/'';
-        description = "Redis URL for all GitLab services except gitlab-shell";
+        default = "unix:/run/gitlab/redis.sock";
+        example = "redis://localhost:6379/";
+        description = lib.mdDoc "Redis URL for all GitLab services.";
       };
 
       extraGitlabRb = mkOption {
@@ -468,7 +486,7 @@ in {
             }
           end
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to be placed in config/extra-gitlab.rb. This can
           be used to add configuration not otherwise exposed through this module's
           options.
@@ -479,13 +497,13 @@ in {
         type = types.str;
         default = config.networking.hostName;
         defaultText = literalExpression "config.networking.hostName";
-        description = "GitLab host name. Used e.g. for copy-paste URLs.";
+        description = lib.mdDoc "GitLab host name. Used e.g. for copy-paste URLs.";
       };
 
       port = mkOption {
         type = types.port;
         default = 8080;
-        description = ''
+        description = lib.mdDoc ''
           GitLab server port for copy-paste URLs, e.g. 80 or 443 if you're
           service over https.
         '';
@@ -494,25 +512,25 @@ in {
       https = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether gitlab prints URLs with https as scheme.";
+        description = lib.mdDoc "Whether gitlab prints URLs with https as scheme.";
       };
 
       user = mkOption {
         type = types.str;
         default = "gitlab";
-        description = "User to run gitlab and all related services.";
+        description = lib.mdDoc "User to run gitlab and all related services.";
       };
 
       group = mkOption {
         type = types.str;
         default = "gitlab";
-        description = "Group to run gitlab and all related services.";
+        description = lib.mdDoc "Group to run gitlab and all related services.";
       };
 
       initialRootEmail = mkOption {
         type = types.str;
         default = "admin@local.host";
-        description = ''
+        description = lib.mdDoc ''
           Initial email address of the root account if this is a new install.
         '';
       };
@@ -520,7 +538,7 @@ in {
       initialRootPasswordFile = mkOption {
         type = with types; nullOr path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           File containing the initial password of the root account if
           this is a new install.
 
@@ -533,51 +551,51 @@ in {
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = "Enable GitLab container registry.";
+          description = lib.mdDoc "Enable GitLab container registry.";
         };
         host = mkOption {
           type = types.str;
           default = config.services.gitlab.host;
           defaultText = literalExpression "config.services.gitlab.host";
-          description = "GitLab container registry host name.";
+          description = lib.mdDoc "GitLab container registry host name.";
         };
         port = mkOption {
           type = types.int;
           default = 4567;
-          description = "GitLab container registry port.";
+          description = lib.mdDoc "GitLab container registry port.";
         };
         certFile = mkOption {
           type = types.path;
-          description = "Path to GitLab container registry certificate.";
+          description = lib.mdDoc "Path to GitLab container registry certificate.";
         };
         keyFile = mkOption {
           type = types.path;
-          description = "Path to GitLab container registry certificate-key.";
+          description = lib.mdDoc "Path to GitLab container registry certificate-key.";
         };
         defaultForProjects = mkOption {
           type = types.bool;
           default = cfg.registry.enable;
           defaultText = literalExpression "config.${opt.registry.enable}";
-          description = "If GitLab container registry should be enabled by default for projects.";
+          description = lib.mdDoc "If GitLab container registry should be enabled by default for projects.";
         };
         issuer = mkOption {
           type = types.str;
           default = "gitlab-issuer";
-          description = "GitLab container registry issuer.";
+          description = lib.mdDoc "GitLab container registry issuer.";
         };
         serviceName = mkOption {
           type = types.str;
           default = "container_registry";
-          description = "GitLab container registry service name.";
+          description = lib.mdDoc "GitLab container registry service name.";
         };
         externalAddress = mkOption {
           type = types.str;
           default = "";
-          description = "External address used to access registry from the internet";
+          description = lib.mdDoc "External address used to access registry from the internet";
         };
         externalPort = mkOption {
           type = types.int;
-          description = "External port used to access registry from the internet";
+          description = lib.mdDoc "External port used to access registry from the internet";
         };
       };
 
@@ -585,31 +603,31 @@ in {
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = "Enable gitlab mail delivery over SMTP.";
+          description = lib.mdDoc "Enable gitlab mail delivery over SMTP.";
         };
 
         address = mkOption {
           type = types.str;
           default = "localhost";
-          description = "Address of the SMTP server for GitLab.";
+          description = lib.mdDoc "Address of the SMTP server for GitLab.";
         };
 
         port = mkOption {
           type = types.int;
           default = 25;
-          description = "Port of the SMTP server for GitLab.";
+          description = lib.mdDoc "Port of the SMTP server for GitLab.";
         };
 
         username = mkOption {
           type = with types; nullOr str;
           default = null;
-          description = "Username of the SMTP server for GitLab.";
+          description = lib.mdDoc "Username of the SMTP server for GitLab.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             File containing the password of the SMTP server for GitLab.
 
             This should be a string, not a nix path, since nix paths
@@ -620,44 +638,44 @@ in {
         domain = mkOption {
           type = types.str;
           default = "localhost";
-          description = "HELO domain to use for outgoing mail.";
+          description = lib.mdDoc "HELO domain to use for outgoing mail.";
         };
 
         authentication = mkOption {
           type = with types; nullOr str;
           default = null;
-          description = "Authentication type to use, see http://api.rubyonrails.org/classes/ActionMailer/Base.html";
+          description = lib.mdDoc "Authentication type to use, see http://api.rubyonrails.org/classes/ActionMailer/Base.html";
         };
 
         enableStartTLSAuto = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether to try to use StartTLS.";
+          description = lib.mdDoc "Whether to try to use StartTLS.";
         };
 
         tls = mkOption {
           type = types.bool;
           default = false;
-          description = "Whether to use TLS wrapper-mode.";
+          description = lib.mdDoc "Whether to use TLS wrapper-mode.";
         };
 
         opensslVerifyMode = mkOption {
           type = types.str;
           default = "peer";
-          description = "How OpenSSL checks the certificate, see http://api.rubyonrails.org/classes/ActionMailer/Base.html";
+          description = lib.mdDoc "How OpenSSL checks the certificate, see http://api.rubyonrails.org/classes/ActionMailer/Base.html";
         };
       };
 
       pagesExtraArgs = mkOption {
         type = types.listOf types.str;
         default = [ "-listen-proxy" "127.0.0.1:8090" ];
-        description = "Arguments to pass to the gitlab-pages daemon";
+        description = lib.mdDoc "Arguments to pass to the gitlab-pages daemon";
       };
 
       secrets.secretFile = mkOption {
         type = with types; nullOr path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A file containing the secret used to encrypt variables in
           the DB. If you change or lose this key you will be unable to
           access variables stored in database.
@@ -673,7 +691,7 @@ in {
       secrets.dbFile = mkOption {
         type = with types; nullOr path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A file containing the secret used to encrypt variables in
           the DB. If you change or lose this key you will be unable to
           access variables stored in database.
@@ -689,7 +707,7 @@ in {
       secrets.otpFile = mkOption {
         type = with types; nullOr path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A file containing the secret used to encrypt secrets for OTP
           tokens. If you change or lose this key, users which have 2FA
           enabled for login won't be able to login anymore.
@@ -705,7 +723,7 @@ in {
       secrets.jwsFile = mkOption {
         type = with types; nullOr path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A file containing the secret used to encrypt session
           keys. If you change or lose this key, users will be
           disconnected.
@@ -723,25 +741,22 @@ in {
       extraShellConfig = mkOption {
         type = types.attrs;
         default = {};
-        description = "Extra configuration to merge into shell-config.yml";
+        description = lib.mdDoc "Extra configuration to merge into shell-config.yml";
       };
 
       puma.workers = mkOption {
         type = types.int;
         default = 2;
         apply = x: builtins.toString x;
-        description = ''
+        description = lib.mdDoc ''
           The number of worker processes Puma should spawn. This
           controls the amount of parallel Ruby code can be
-          executed. GitLab recommends <quote>Number of CPU cores -
-          1</quote>, but at least two.
-
-          <note>
-            <para>
-              Each worker consumes quite a bit of memory, so
-              be careful when increasing this.
-            </para>
-          </note>
+          executed. GitLab recommends `Number of CPU cores - 1`, but at least two.
+
+          ::: {.note}
+          Each worker consumes quite a bit of memory, so
+          be careful when increasing this.
+          :::
         '';
       };
 
@@ -749,16 +764,14 @@ in {
         type = types.int;
         default = 0;
         apply = x: builtins.toString x;
-        description = ''
+        description = lib.mdDoc ''
           The minimum number of threads Puma should use per
           worker.
 
-          <note>
-            <para>
-              Each thread consumes memory and contributes to Global VM
-              Lock contention, so be careful when increasing this.
-            </para>
-          </note>
+          ::: {.note}
+          Each thread consumes memory and contributes to Global VM
+          Lock contention, so be careful when increasing this.
+          :::
         '';
       };
 
@@ -766,31 +779,29 @@ in {
         type = types.int;
         default = 4;
         apply = x: builtins.toString x;
-        description = ''
+        description = lib.mdDoc ''
           The maximum number of threads Puma should use per
           worker. This limits how many threads Puma will automatically
           spawn in response to requests. In contrast to workers,
           threads will never be able to run Ruby code in parallel, but
           give higher IO parallelism.
 
-          <note>
-            <para>
-              Each thread consumes memory and contributes to Global VM
-              Lock contention, so be careful when increasing this.
-            </para>
-          </note>
+          ::: {.note}
+          Each thread consumes memory and contributes to Global VM
+          Lock contention, so be careful when increasing this.
+          :::
         '';
       };
 
       sidekiq.memoryKiller.enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether the Sidekiq MemoryKiller should be turned
           on. MemoryKiller kills Sidekiq when its memory consumption
           exceeds a certain limit.
 
-          See <link xlink:href="https://docs.gitlab.com/ee/administration/operations/sidekiq_memory_killer.html"/>
+          See <https://docs.gitlab.com/ee/administration/operations/sidekiq_memory_killer.html>
           for details.
         '';
       };
@@ -799,7 +810,7 @@ in {
         type = types.int;
         default = 2000;
         apply = x: builtins.toString (x * 1024);
-        description = ''
+        description = lib.mdDoc ''
           The maximum amount of memory, in MiB, a Sidekiq worker is
           allowed to consume before being killed.
         '';
@@ -809,7 +820,7 @@ in {
         type = types.int;
         default = 900;
         apply = x: builtins.toString x;
-        description = ''
+        description = lib.mdDoc ''
           The time MemoryKiller waits after noticing excessive memory
           consumption before killing Sidekiq.
         '';
@@ -819,7 +830,7 @@ in {
         type = types.int;
         default = 30;
         apply = x: builtins.toString x;
-        description = ''
+        description = lib.mdDoc ''
           The time allowed for all jobs to finish before Sidekiq is
           killed forcefully.
         '';
@@ -829,7 +840,7 @@ in {
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Enable rotation of log files.
           '';
         };
@@ -837,30 +848,51 @@ in {
         frequency = mkOption {
           type = types.str;
           default = "daily";
-          description = "How often to rotate the logs.";
+          description = lib.mdDoc "How often to rotate the logs.";
         };
 
         keep = mkOption {
           type = types.int;
           default = 30;
-          description = "How many rotations to keep.";
+          description = lib.mdDoc "How many rotations to keep.";
         };
+      };
 
-        extraConfig = mkOption {
-          type = types.lines;
-          default = ''
-            copytruncate
-            compress
-          '';
-          description = ''
-            Extra logrotate config options for this path. Refer to
-            <link xlink:href="https://linux.die.net/man/8/logrotate"/> for details.
-          '';
-        };
+      workhorse.config = mkOption {
+        type = toml.type;
+        default = {};
+        example = literalExpression ''
+          {
+            object_storage.provider = "AWS";
+            object_storage.s3 = {
+              aws_access_key_id = "AKIAXXXXXXXXXXXXXXXX";
+              aws_secret_access_key = { _secret = "/var/keys/aws_secret_access_key"; };
+            };
+          };
+        '';
+        description = lib.mdDoc ''
+          Configuration options to add to Workhorse's configuration
+          file.
+
+          See
+          <https://gitlab.com/gitlab-org/gitlab/-/blob/master/workhorse/config.toml.example>
+          and
+          <https://docs.gitlab.com/ee/development/workhorse/configuration.html>
+          for examples and option documentation.
+
+          Options containing secret data should be set to an attribute
+          set containing the attribute `_secret` - a string pointing
+          to a file containing the value the option should be set
+          to. See the example to get a better picture of this: in the
+          resulting configuration file, the
+          `object_storage.s3.aws_secret_access_key` key will be set to
+          the contents of the {file}`/var/keys/aws_secret_access_key`
+          file.
+        '';
       };
 
       extraConfig = mkOption {
-        type = types.attrs;
+        type = yaml.type;
         default = {};
         example = literalExpression ''
           {
@@ -897,21 +929,21 @@ in {
             };
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra options to be added under
-          <literal>production</literal> in
-          <filename>config/gitlab.yml</filename>, as a nix attribute
+          `production` in
+          {file}`config/gitlab.yml`, as a nix attribute
           set.
 
           Options containing secret data should be set to an attribute
-          set containing the attribute <literal>_secret</literal> - a
+          set containing the attribute `_secret` - a
           string pointing to a file containing the value the option
           should be set to. See the example to get a better picture of
           this: in the resulting
-          <filename>config/gitlab.yml</filename> file, the
-          <literal>production.omniauth.providers[0].args.client_options.secret</literal>
+          {file}`config/gitlab.yml` file, the
+          `production.omniauth.providers[0].args.client_options.secret`
           key will be set to the contents of the
-          <filename>/var/keys/gitlab_oidc_secret</filename> file.
+          {file}`/var/keys/gitlab_oidc_secret` file.
         '';
       };
     };
@@ -964,8 +996,9 @@ in {
     # Redis is required for the sidekiq queue runner.
     services.redis.servers.gitlab = {
       enable = mkDefault true;
-      port = mkDefault 31636;
-      bind = mkDefault "127.0.0.1";
+      user = mkDefault cfg.user;
+      unixSocket = mkDefault "/run/gitlab/redis.sock";
+      unixSocketPerm = mkDefault 770;
     };
 
     # We use postgres as the main data store.
@@ -977,14 +1010,14 @@ in {
     # Enable rotation of log files
     services.logrotate = {
       enable = cfg.logrotate.enable;
-      paths = {
+      settings = {
         gitlab = {
-          path = "${cfg.statePath}/log/*.log";
-          user = cfg.user;
-          group = cfg.group;
+          files = "${cfg.statePath}/log/*.log";
+          su = "${cfg.user} ${cfg.group}";
           frequency = cfg.logrotate.frequency;
-          keep = cfg.logrotate.keep;
-          extraConfig = cfg.logrotate.extraConfig;
+          rotate = cfg.logrotate.keep;
+          copytruncate = true;
+          compress = true;
         };
       };
     };
@@ -1045,7 +1078,7 @@ in {
         chown ${cfg.user}:${cfg.group} ${cfg.registry.certFile}
       '';
 
-      serviceConfig = {
+      unitConfig = {
         ConditionPathExists = "!${cfg.registry.certFile}";
       };
     };
@@ -1053,6 +1086,7 @@ in {
     # Ensure Docker Registry launches after the certificate generation job
     systemd.services.docker-registry = optionalAttrs cfg.registry.enable {
       wants = [ "gitlab-registry-cert.service" ];
+      after = [ "gitlab-registry-cert.service" ];
     };
 
     # Enable Docker Registry, if GitLab-Container Registry is enabled
@@ -1106,6 +1140,7 @@ in {
       "d ${gitlabConfig.production.shared.path}/lfs-objects 0750 ${cfg.user} ${cfg.group} -"
       "d ${gitlabConfig.production.shared.path}/packages 0750 ${cfg.user} ${cfg.group} -"
       "d ${gitlabConfig.production.shared.path}/pages 0750 ${cfg.user} ${cfg.group} -"
+      "d ${gitlabConfig.production.shared.path}/registry 0750 ${cfg.user} ${cfg.group} -"
       "d ${gitlabConfig.production.shared.path}/terraform_state 0750 ${cfg.user} ${cfg.group} -"
       "L+ /run/gitlab/config - - - - ${cfg.statePath}/config"
       "L+ /run/gitlab/log - - - - ${cfg.statePath}/log"
@@ -1159,6 +1194,7 @@ in {
           cp -rf --no-preserve=mode ${cfg.packages.gitlab}/share/gitlab/config.dist/* ${cfg.statePath}/config
           cp -rf --no-preserve=mode ${cfg.packages.gitlab}/share/gitlab/db/* ${cfg.statePath}/db
           ln -sf ${extraGitlabRb} ${cfg.statePath}/config/initializers/extra-gitlab.rb
+          ln -sf ${cableYml} ${cfg.statePath}/config/cable.yml
 
           ${cfg.packages.gitlab-shell}/bin/install
 
@@ -1186,7 +1222,7 @@ in {
                 fi
 
                 jq <${pkgs.writeText "database.yml" (builtins.toJSON databaseConfig)} \
-                   '.production.password = $ENV.db_password' \
+                   '.${if lib.versionAtLeast (lib.getVersion cfg.packages.gitlab) "15.0" then "production.main" else "production"}.password = $ENV.db_password' \
                    >'${cfg.statePath}/config/database.yml'
               ''
               else ''
@@ -1348,6 +1384,7 @@ in {
       wantedBy = [ "gitlab.target" ];
       partOf = [ "gitlab.target" ];
       path = with pkgs; [
+        remarshal
         exiftool
         git
         gnutar
@@ -1362,6 +1399,17 @@ in {
         TimeoutSec = "infinity";
         Restart = "on-failure";
         WorkingDirectory = gitlabEnv.HOME;
+        ExecStartPre = pkgs.writeShellScript "gitlab-workhorse-pre-start" ''
+          set -o errexit -o pipefail -o nounset
+          shopt -s dotglob nullglob inherit_errexit
+
+          ${utils.genJqSecretsReplacementSnippet
+              cfg.workhorse.config
+              "${cfg.statePath}/config/gitlab-workhorse.json"}
+
+          json2toml "${cfg.statePath}/config/gitlab-workhorse.json" "${cfg.statePath}/config/gitlab-workhorse.toml"
+          rm "${cfg.statePath}/config/gitlab-workhorse.json"
+        '';
         ExecStart =
           "${cfg.packages.gitlab-workhorse}/bin/workhorse "
           + "-listenUmask 0 "
@@ -1369,6 +1417,7 @@ in {
           + "-listenAddr /run/gitlab/gitlab-workhorse.socket "
           + "-authSocket ${gitlabSocket} "
           + "-documentRoot ${cfg.packages.gitlab}/share/gitlab/public "
+          + "-config ${cfg.statePath}/config/gitlab-workhorse.toml "
           + "-secretPath ${cfg.statePath}/.gitlab_workhorse_secret";
       };
     };
diff --git a/nixos/modules/services/misc/gitolite.nix b/nixos/modules/services/misc/gitolite.nix
index 810ef1f21b9..012abda2d76 100644
--- a/nixos/modules/services/misc/gitolite.nix
+++ b/nixos/modules/services/misc/gitolite.nix
@@ -14,19 +14,18 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable gitolite management under the
-          <literal>gitolite</literal> user. After
+          `gitolite` user. After
           switching to a configuration with Gitolite enabled, you can
-          then run <literal>git clone
-          gitolite@host:gitolite-admin.git</literal> to manage it further.
+          then run `git clone gitolite@host:gitolite-admin.git` to manage it further.
         '';
       };
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/gitolite";
-        description = ''
+        description = lib.mdDoc ''
           The gitolite home directory used to store all repositories. If left as the default value
           this directory will automatically be created before the gitolite server starts, otherwise
           the sysadmin is responsible for ensuring the directory exists with appropriate ownership
@@ -36,7 +35,7 @@ in
 
       adminPubkey = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Initial administrative public key for Gitolite. This should
           be an SSH Public Key. Note that this key will only be used
           once, upon the first initialization of the Gitolite user.
@@ -47,8 +46,8 @@ in
       enableGitAnnex = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          Enable git-annex support. Uses the <literal>extraGitoliteRc</literal> option
+        description = lib.mdDoc ''
+          Enable git-annex support. Uses the `extraGitoliteRc` option
           to apply the necessary configuration.
         '';
       };
@@ -56,8 +55,8 @@ in
       commonHooks = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
-          A list of custom git hooks that get copied to <literal>~/.gitolite/hooks/common</literal>.
+        description = lib.mdDoc ''
+          A list of custom git hooks that get copied to `~/.gitolite/hooks/common`.
         '';
       };
 
@@ -72,40 +71,48 @@ in
             @{$RC{ENABLE}} = grep { $_ ne 'desc' } @{$RC{ENABLE}}; # disable the command/feature
           '''
         '';
-        description = ''
-          Extra configuration to append to the default <literal>~/.gitolite.rc</literal>.
+        description = lib.mdDoc ''
+          Extra configuration to append to the default `~/.gitolite.rc`.
 
-          This should be Perl code that modifies the <literal>%RC</literal>
-          configuration variable. The default <literal>~/.gitolite.rc</literal>
-          content is generated by invoking <literal>gitolite print-default-rc</literal>,
+          This should be Perl code that modifies the `%RC`
+          configuration variable. The default `~/.gitolite.rc`
+          content is generated by invoking `gitolite print-default-rc`,
           and extra configuration from this option is appended to it. The result
-          is placed to Nix store, and the <literal>~/.gitolite.rc</literal> file
+          is placed to Nix store, and the `~/.gitolite.rc` file
           becomes a symlink to it.
 
           If you already have a customized (or otherwise changed)
-          <literal>~/.gitolite.rc</literal> file, NixOS will refuse to replace
+          `~/.gitolite.rc` file, NixOS will refuse to replace
           it with a symlink, and the `gitolite-init` initialization service
           will fail. In this situation, in order to use this option, you
           will need to take any customizations you may have in
-          <literal>~/.gitolite.rc</literal>, convert them to appropriate Perl
+          `~/.gitolite.rc`, convert them to appropriate Perl
           statements, add them to this option, and remove the file.
 
-          See also the <literal>enableGitAnnex</literal> option.
+          See also the `enableGitAnnex` option.
         '';
       };
 
       user = mkOption {
         type = types.str;
         default = "gitolite";
-        description = ''
+        description = lib.mdDoc ''
           Gitolite user account. This is the username of the gitolite endpoint.
         '';
       };
 
+      description = mkOption {
+        type = types.str;
+        default = "Gitolite user";
+        description = lib.mdDoc ''
+          Gitolite user account's description.
+        '';
+      };
+
       group = mkOption {
         type = types.str;
         default = "gitolite";
-        description = ''
+        description = lib.mdDoc ''
           Primary group of the Gitolite user account.
         '';
       };
@@ -146,7 +153,7 @@ in
     '';
 
     users.users.${cfg.user} = {
-      description     = "Gitolite user";
+      description     = cfg.description;
       home            = cfg.dataDir;
       uid             = config.ids.uids.gitolite;
       group           = cfg.group;
diff --git a/nixos/modules/services/misc/gitweb.nix b/nixos/modules/services/misc/gitweb.nix
index a1180716e36..aac0dac8a08 100644
--- a/nixos/modules/services/misc/gitweb.nix
+++ b/nixos/modules/services/misc/gitweb.nix
@@ -13,7 +13,7 @@ in
     projectroot = mkOption {
       default = "/srv/git";
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Path to git projects (bare repositories) that should be served by
         gitweb. Must not end with a slash.
       '';
@@ -22,7 +22,7 @@ in
     extraConfig = mkOption {
       default = "";
       type = types.lines;
-      description = ''
+      description = lib.mdDoc ''
         Verbatim configuration text appended to the generated gitweb.conf file.
       '';
       example = ''
@@ -35,7 +35,7 @@ in
     gitwebTheme = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Use an alternative theme for gitweb, strongly inspired by GitHub.
       '';
     };
@@ -47,7 +47,7 @@ in
         $highlight_bin = "${pkgs.highlight}/bin/highlight";
         ${cfg.extraConfig}
       '';
-      defaultText = literalDocBook "generated config file";
+      defaultText = literalMD "generated config file";
       type = types.path;
       readOnly = true;
       internal = true;
diff --git a/nixos/modules/services/misc/gogs.nix b/nixos/modules/services/misc/gogs.nix
index c7ae4f49407..fa172ed277d 100644
--- a/nixos/modules/services/misc/gogs.nix
+++ b/nixos/modules/services/misc/gogs.nix
@@ -48,31 +48,31 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = "Enable Go Git Service.";
+        description = lib.mdDoc "Enable Go Git Service.";
       };
 
       useWizard = mkOption {
         default = false;
         type = types.bool;
-        description = "Do not generate a configuration and use Gogs' installation wizard instead. The first registered user will be administrator.";
+        description = lib.mdDoc "Do not generate a configuration and use Gogs' installation wizard instead. The first registered user will be administrator.";
       };
 
       stateDir = mkOption {
         default = "/var/lib/gogs";
         type = types.str;
-        description = "Gogs data directory.";
+        description = lib.mdDoc "Gogs data directory.";
       };
 
       user = mkOption {
         type = types.str;
         default = "gogs";
-        description = "User account under which Gogs runs.";
+        description = lib.mdDoc "User account under which Gogs runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "gogs";
-        description = "Group account under which Gogs runs.";
+        description = lib.mdDoc "Group account under which Gogs runs.";
       };
 
       database = {
@@ -80,40 +80,40 @@ in
           type = types.enum [ "sqlite3" "mysql" "postgres" ];
           example = "mysql";
           default = "sqlite3";
-          description = "Database engine to use.";
+          description = lib.mdDoc "Database engine to use.";
         };
 
         host = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "Database host address.";
+          description = lib.mdDoc "Database host address.";
         };
 
         port = mkOption {
-          type = types.int;
+          type = types.port;
           default = 3306;
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = mkOption {
           type = types.str;
           default = "gogs";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = mkOption {
           type = types.str;
           default = "gogs";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         password = mkOption {
           type = types.str;
           default = "";
-          description = ''
-            The password corresponding to <option>database.user</option>.
+          description = lib.mdDoc ''
+            The password corresponding to {option}`database.user`.
             Warning: this is stored in cleartext in the Nix store!
-            Use <option>database.passwordFile</option> instead.
+            Use {option}`database.passwordFile` instead.
           '';
         };
 
@@ -121,9 +121,9 @@ in
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/gogs-dbpassword";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
 
@@ -131,51 +131,51 @@ in
           type = types.str;
           default = "${cfg.stateDir}/data/gogs.db";
           defaultText = literalExpression ''"''${config.${opt.stateDir}}/data/gogs.db"'';
-          description = "Path to the sqlite3 database file.";
+          description = lib.mdDoc "Path to the sqlite3 database file.";
         };
       };
 
       appName = mkOption {
         type = types.str;
         default = "Gogs: Go Git Service";
-        description = "Application name.";
+        description = lib.mdDoc "Application name.";
       };
 
       repositoryRoot = mkOption {
         type = types.str;
         default = "${cfg.stateDir}/repositories";
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/repositories"'';
-        description = "Path to the git repositories.";
+        description = lib.mdDoc "Path to the git repositories.";
       };
 
       domain = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Domain name of your server.";
+        description = lib.mdDoc "Domain name of your server.";
       };
 
       rootUrl = mkOption {
         type = types.str;
         default = "http://localhost:3000/";
-        description = "Full public URL of Gogs server.";
+        description = lib.mdDoc "Full public URL of Gogs server.";
       };
 
       httpAddress = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = "HTTP listen address.";
+        description = lib.mdDoc "HTTP listen address.";
       };
 
       httpPort = mkOption {
-        type = types.int;
+        type = types.port;
         default = 3000;
-        description = "HTTP listen port.";
+        description = lib.mdDoc "HTTP listen port.";
       };
 
       cookieSecure = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Marks session cookies as "secure" as a hint for browsers to only send
           them via HTTPS. This option is recommend, if Gogs is being served over HTTPS.
         '';
@@ -184,7 +184,7 @@ in
       extraConfig = mkOption {
         type = types.str;
         default = "";
-        description = "Configuration lines appended to the generated Gogs configuration file.";
+        description = lib.mdDoc "Configuration lines appended to the generated Gogs configuration file.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/gollum.nix b/nixos/modules/services/misc/gollum.nix
index cad73a871ba..4eec9610b5e 100644
--- a/nixos/modules/services/misc/gollum.nix
+++ b/nixos/modules/services/misc/gollum.nix
@@ -8,67 +8,89 @@ in
 
 {
   options.services.gollum = {
-    enable = mkOption {
-      type = types.bool;
-      default = false;
-      description = "Enable the Gollum service.";
-    };
+    enable = mkEnableOption (lib.mdDoc "Gollum service");
 
     address = mkOption {
       type = types.str;
       default = "0.0.0.0";
-      description = "IP address on which the web server will listen.";
+      description = lib.mdDoc "IP address on which the web server will listen.";
     };
 
     port = mkOption {
-      type = types.int;
+      type = types.port;
       default = 4567;
-      description = "Port on which the web server will run.";
+      description = lib.mdDoc "Port on which the web server will run.";
     };
 
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = "Content of the configuration file";
+      description = lib.mdDoc "Content of the configuration file";
     };
 
     mathjax = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable support for math rendering using MathJax";
+      description = lib.mdDoc "Enable support for math rendering using MathJax";
     };
 
     allowUploads = mkOption {
       type = types.nullOr (types.enum [ "dir" "page" ]);
       default = null;
-      description = "Enable uploads of external files";
+      description = lib.mdDoc "Enable uploads of external files";
+    };
+
+    user-icons = mkOption {
+      type = types.nullOr (types.enum [ "gravatar" "identicon" ]);
+      default = null;
+      description = lib.mdDoc "Enable specific user icons for history view";
     };
 
     emoji = mkOption {
       type = types.bool;
       default = false;
-      description = "Parse and interpret emoji tags";
+      description = lib.mdDoc "Parse and interpret emoji tags";
     };
 
     h1-title = mkOption {
       type = types.bool;
       default = false;
-      description = "Use the first h1 as page title";
+      description = lib.mdDoc "Use the first h1 as page title";
+    };
+
+    no-edit = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc "Disable editing pages";
+    };
+
+    local-time = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc "Use the browser's local timezone instead of the server's for displaying dates.";
     };
 
     branch = mkOption {
       type = types.str;
       default = "master";
       example = "develop";
-      description = "Git branch to serve";
+      description = lib.mdDoc "Git branch to serve";
     };
 
     stateDir = mkOption {
       type = types.path;
       default = "/var/lib/gollum";
-      description = "Specifies the path of the repository directory. If it does not exist, Gollum will create it on startup.";
+      description = lib.mdDoc "Specifies the path of the repository directory. If it does not exist, Gollum will create it on startup.";
     };
 
+    package = mkOption {
+      type = types.package;
+      default = pkgs.gollum;
+      defaultText = literalExpression "pkgs.gollum";
+      description = lib.mdDoc ''
+        The package used in the service
+      '';
+    };
   };
 
   config = mkIf cfg.enable {
@@ -102,7 +124,7 @@ in
         Group = config.users.groups.gollum.name;
         WorkingDirectory = cfg.stateDir;
         ExecStart = ''
-          ${pkgs.gollum}/bin/gollum \
+          ${cfg.package}/bin/gollum \
             --port ${toString cfg.port} \
             --host ${cfg.address} \
             --config ${pkgs.writeText "gollum-config.rb" cfg.extraConfig} \
@@ -110,12 +132,15 @@ in
             ${optionalString cfg.mathjax "--mathjax"} \
             ${optionalString cfg.emoji "--emoji"} \
             ${optionalString cfg.h1-title "--h1-title"} \
+            ${optionalString cfg.no-edit "--no-edit"} \
+            ${optionalString cfg.local-time "--local-time"} \
             ${optionalString (cfg.allowUploads != null) "--allow-uploads ${cfg.allowUploads}"} \
+            ${optionalString (cfg.user-icons != null) "--user-icons ${cfg.user-icons}"} \
             ${cfg.stateDir}
         '';
       };
     };
   };
 
-  meta.maintainers = with lib.maintainers; [ erictapen ];
+  meta.maintainers = with lib.maintainers; [ erictapen bbenno ];
 }
diff --git a/nixos/modules/services/misc/gpsd.nix b/nixos/modules/services/misc/gpsd.nix
index 6494578f764..1ab8d1bbe06 100644
--- a/nixos/modules/services/misc/gpsd.nix
+++ b/nixos/modules/services/misc/gpsd.nix
@@ -21,7 +21,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable `gpsd', a GPS service daemon.
         '';
       };
@@ -29,9 +29,9 @@ in
       device = mkOption {
         type = types.str;
         default = "/dev/ttyUSB0";
-        description = ''
+        description = lib.mdDoc ''
           A device may be a local serial device for GPS input, or a URL of the form:
-               <literal>[{dgpsip|ntrip}://][user:passwd@]host[:port][/stream]</literal>
+               `[{dgpsip|ntrip}://][user:passwd@]host[:port][/stream]`
           in which case it specifies an input source for DGPS or ntrip data.
         '';
       };
@@ -39,7 +39,7 @@ in
       readonly = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the broken-device-safety, otherwise
           known as read-only mode.  Some popular bluetooth and USB
           receivers lock up or become totally inaccessible when
@@ -56,7 +56,7 @@ in
       nowait = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           don't wait for client connects to poll GPS
         '';
       };
@@ -64,7 +64,7 @@ in
       port = mkOption {
         type = types.port;
         default = 2947;
-        description = ''
+        description = lib.mdDoc ''
           The port where to listen for TCP connections.
         '';
       };
@@ -72,7 +72,7 @@ in
       debugLevel = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           The debugging level.
         '';
       };
diff --git a/nixos/modules/services/misc/greenclip.nix b/nixos/modules/services/misc/greenclip.nix
index 32e8d746cb5..45847af7114 100644
--- a/nixos/modules/services/misc/greenclip.nix
+++ b/nixos/modules/services/misc/greenclip.nix
@@ -7,13 +7,13 @@ let
 in {
 
   options.services.greenclip = {
-    enable = mkEnableOption "Greenclip daemon";
+    enable = mkEnableOption (lib.mdDoc "Greenclip daemon");
 
     package = mkOption {
       type = types.package;
       default = pkgs.haskellPackages.greenclip;
       defaultText = literalExpression "pkgs.haskellPackages.greenclip";
-      description = "greenclip derivation to use.";
+      description = lib.mdDoc "greenclip derivation to use.";
     };
   };
 
diff --git a/nixos/modules/services/misc/headphones.nix b/nixos/modules/services/misc/headphones.nix
index 31bd61cb4c2..472b330fff1 100644
--- a/nixos/modules/services/misc/headphones.nix
+++ b/nixos/modules/services/misc/headphones.nix
@@ -20,38 +20,38 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the headphones server.";
+        description = lib.mdDoc "Whether to enable the headphones server.";
       };
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/${name}";
-        description = "Path where to store data files.";
+        description = lib.mdDoc "Path where to store data files.";
       };
       configFile = mkOption {
         type = types.path;
         default = "${cfg.dataDir}/config.ini";
         defaultText = literalExpression ''"''${config.${opt.dataDir}}/config.ini"'';
-        description = "Path to config file.";
+        description = lib.mdDoc "Path to config file.";
       };
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Host to listen on.";
+        description = lib.mdDoc "Host to listen on.";
       };
       port = mkOption {
         type = types.ints.u16;
         default = 8181;
-        description = "Port to bind to.";
+        description = lib.mdDoc "Port to bind to.";
       };
       user = mkOption {
         type = types.str;
         default = name;
-        description = "User to run the service as";
+        description = lib.mdDoc "User to run the service as";
       };
       group = mkOption {
         type = types.str;
         default = name;
-        description = "Group to run the service as";
+        description = lib.mdDoc "Group to run the service as";
       };
     };
   };
diff --git a/nixos/modules/services/misc/heisenbridge.nix b/nixos/modules/services/misc/heisenbridge.nix
index 7ce8a23d9af..13ba362b33d 100644
--- a/nixos/modules/services/misc/heisenbridge.nix
+++ b/nixos/modules/services/misc/heisenbridge.nix
@@ -23,27 +23,27 @@ let
 in
 {
   options.services.heisenbridge = {
-    enable = mkEnableOption "the Matrix to IRC bridge";
+    enable = mkEnableOption (lib.mdDoc "the Matrix to IRC bridge");
 
     package = mkOption {
       type = types.package;
       default = pkgs.heisenbridge;
       defaultText = "pkgs.heisenbridge";
       example = "pkgs.heisenbridge.override { … = …; }";
-      description = ''
+      description = lib.mdDoc ''
         Package of the application to run, exposed for overriding purposes.
       '';
     };
 
     homeserver = mkOption {
       type = types.str;
-      description = "The URL to the home server for client-server API calls";
+      description = lib.mdDoc "The URL to the home server for client-server API calls";
       example = "http://localhost:8008";
     };
 
     registrationUrl = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The URL where the application service is listening for HS requests, from the Matrix HS perspective.#
         The default value assumes the bridge runs on the same host as the home server, in the same network.
       '';
@@ -54,26 +54,26 @@ in
 
     address = mkOption {
       type = types.str;
-      description = "Address to listen on. IPv6 does not seem to be supported.";
+      description = lib.mdDoc "Address to listen on. IPv6 does not seem to be supported.";
       default = "127.0.0.1";
       example = "0.0.0.0";
     };
 
     port = mkOption {
       type = types.port;
-      description = "The port to listen on";
+      description = lib.mdDoc "The port to listen on";
       default = 9898;
     };
 
     debug = mkOption {
       type = types.bool;
-      description = "More verbose logging. Recommended during initial setup.";
+      description = lib.mdDoc "More verbose logging. Recommended during initial setup.";
       default = false;
     };
 
     owner = mkOption {
       type = types.nullOr types.str;
-      description = ''
+      description = lib.mdDoc ''
         Set owner MXID otherwise first talking local user will claim the bridge
       '';
       default = null;
@@ -81,7 +81,7 @@ in
     };
 
     namespaces = mkOption {
-      description = "Configure the 'namespaces' section of the registration.yml for the bridge and the server";
+      description = lib.mdDoc "Configure the 'namespaces' section of the registration.yml for the bridge and the server";
       # TODO link to Matrix documentation of the format
       type = types.submodule {
         freeformType = jsonType;
@@ -99,16 +99,16 @@ in
       };
     };
 
-    identd.enable = mkEnableOption "identd service support";
+    identd.enable = mkEnableOption (lib.mdDoc "identd service support");
     identd.port = mkOption {
       type = types.port;
-      description = "identd listen port";
+      description = lib.mdDoc "identd listen port";
       default = 113;
     };
 
     extraArgs = mkOption {
       type = types.listOf types.str;
-      description = "Heisenbridge is configured over the command line. Append extra arguments here";
+      description = lib.mdDoc "Heisenbridge is configured over the command line. Append extra arguments here";
       default = [ ];
     };
   };
@@ -204,7 +204,7 @@ in
         NoNewPrivileges = true;
         LockPersonality = true;
         RestrictRealtime = true;
-        SystemCallFilter = ["@system-service" "~@priviledged" "@chown"];
+        SystemCallFilter = ["@system-service" "~@privileged" "@chown"];
         SystemCallArchitectures = "native";
         RestrictAddressFamilies = "AF_INET AF_INET6";
       };
diff --git a/nixos/modules/services/misc/ihaskell.nix b/nixos/modules/services/misc/ihaskell.nix
index 9978e8a4653..4782053c4fb 100644
--- a/nixos/modules/services/misc/ihaskell.nix
+++ b/nixos/modules/services/misc/ihaskell.nix
@@ -17,7 +17,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Autostart an IHaskell notebook service.";
+        description = lib.mdDoc "Autostart an IHaskell notebook service.";
       };
 
       extraPackages = mkOption {
@@ -30,10 +30,10 @@ in
             haskellPackages.lens
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra packages available to ghc when running ihaskell. The
           value must be a function which receives the attrset defined
-          in <varname>haskellPackages</varname> as the sole argument.
+          in {var}`haskellPackages` as the sole argument.
         '';
       };
     };
diff --git a/nixos/modules/services/misc/input-remapper.nix b/nixos/modules/services/misc/input-remapper.nix
index f5fb2bf5308..51e1abdc98a 100644
--- a/nixos/modules/services/misc/input-remapper.nix
+++ b/nixos/modules/services/misc/input-remapper.nix
@@ -6,14 +6,14 @@ let cfg = config.services.input-remapper; in
 {
   options = {
     services.input-remapper = {
-      enable = mkEnableOption "input-remapper, an easy to use tool to change the mapping of your input device buttons.";
+      enable = mkEnableOption (lib.mdDoc "input-remapper, an easy to use tool to change the mapping of your input device buttons.");
       package = options.mkPackageOption pkgs "input-remapper" { };
-      enableUdevRules = mkEnableOption "udev rules added by input-remapper to handle hotplugged devices. Currently disabled by default due to https://github.com/sezanzeb/input-remapper/issues/140";
+      enableUdevRules = mkEnableOption (lib.mdDoc "udev rules added by input-remapper to handle hotplugged devices. Currently disabled by default due to https://github.com/sezanzeb/input-remapper/issues/140");
       serviceWantedBy = mkOption {
         default = [ "graphical.target" ];
         example = [ "multi-user.target" ];
         type = types.listOf types.str;
-        description = "Specifies the WantedBy setting for the input-remapper service.";
+        description = lib.mdDoc "Specifies the WantedBy setting for the input-remapper service.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/irkerd.nix b/nixos/modules/services/misc/irkerd.nix
index 993d77ba424..d080cc0a735 100644
--- a/nixos/modules/services/misc/irkerd.nix
+++ b/nixos/modules/services/misc/irkerd.nix
@@ -9,13 +9,13 @@ in
 {
   options.services.irkerd = {
     enable = mkOption {
-      description = "Whether to enable irker, an IRC notification daemon.";
+      description = lib.mdDoc "Whether to enable irker, an IRC notification daemon.";
       default = false;
       type = types.bool;
     };
 
     openPorts = mkOption {
-      description = "Open ports in the firewall for irkerd";
+      description = lib.mdDoc "Open ports in the firewall for irkerd";
       default = false;
       type = types.bool;
     };
@@ -24,7 +24,7 @@ in
       default = "localhost";
       example = "0.0.0.0";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Specifies the bind address on which the irker daemon listens.
         The default is localhost.
 
@@ -36,7 +36,7 @@ in
     nick = mkOption {
       default = "irker";
       type = types.str;
-      description = "Nick to use for irker";
+      description = lib.mdDoc "Nick to use for irker";
     };
   };
 
diff --git a/nixos/modules/services/misc/jackett.nix b/nixos/modules/services/misc/jackett.nix
index c2144d4a9a9..b0edf0d18da 100644
--- a/nixos/modules/services/misc/jackett.nix
+++ b/nixos/modules/services/misc/jackett.nix
@@ -9,37 +9,37 @@ in
 {
   options = {
     services.jackett = {
-      enable = mkEnableOption "Jackett";
+      enable = mkEnableOption (lib.mdDoc "Jackett");
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/jackett/.config/Jackett";
-        description = "The directory where Jackett stores its data files.";
+        description = lib.mdDoc "The directory where Jackett stores its data files.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the Jackett web interface.";
+        description = lib.mdDoc "Open ports in the firewall for the Jackett web interface.";
       };
 
       user = mkOption {
         type = types.str;
         default = "jackett";
-        description = "User account under which Jackett runs.";
+        description = lib.mdDoc "User account under which Jackett runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "jackett";
-        description = "Group under which Jackett runs.";
+        description = lib.mdDoc "Group under which Jackett runs.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.jackett;
         defaultText = literalExpression "pkgs.jackett";
-        description = "Jackett package to use.";
+        description = lib.mdDoc "Jackett package to use.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/jellyfin.nix b/nixos/modules/services/misc/jellyfin.nix
index 04cf82f8a46..f49657a0753 100644
--- a/nixos/modules/services/misc/jellyfin.nix
+++ b/nixos/modules/services/misc/jellyfin.nix
@@ -8,19 +8,19 @@ in
 {
   options = {
     services.jellyfin = {
-      enable = mkEnableOption "Jellyfin Media Server";
+      enable = mkEnableOption (lib.mdDoc "Jellyfin Media Server");
 
       user = mkOption {
         type = types.str;
         default = "jellyfin";
-        description = "User account under which Jellyfin runs.";
+        description = lib.mdDoc "User account under which Jellyfin runs.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.jellyfin;
         defaultText = literalExpression "pkgs.jellyfin";
-        description = ''
+        description = lib.mdDoc ''
           Jellyfin package to use.
         '';
       };
@@ -28,13 +28,13 @@ in
       group = mkOption {
         type = types.str;
         default = "jellyfin";
-        description = "Group under which jellyfin runs.";
+        description = lib.mdDoc "Group under which jellyfin runs.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open the default ports in the firewall for the media server. The
           HTTP/HTTPS ports can be changed in the Web UI, so this option should
           only be used if they are unchanged.
@@ -49,53 +49,61 @@ in
       after = [ "network.target" ];
       wantedBy = [ "multi-user.target" ];
 
+      # This is mostly follows: https://github.com/jellyfin/jellyfin/blob/master/fedora/jellyfin.service
+      # Upstream also disable some hardenings when running in LXC, we do the same with the isContainer option
       serviceConfig = rec {
+        Type = "simple";
         User = cfg.user;
         Group = cfg.group;
         StateDirectory = "jellyfin";
+        StateDirectoryMode = "0700";
         CacheDirectory = "jellyfin";
+        CacheDirectoryMode = "0700";
+        UMask = "0077";
+        WorkingDirectory = "/var/lib/jellyfin";
         ExecStart = "${cfg.package}/bin/jellyfin --datadir '/var/lib/${StateDirectory}' --cachedir '/var/cache/${CacheDirectory}'";
         Restart = "on-failure";
+        TimeoutSec = 15;
+        SuccessExitStatus = ["0" "143"];
 
         # Security options:
-
         NoNewPrivileges = true;
-
-        AmbientCapabilities = "";
-        CapabilityBoundingSet = "";
-
-        # ProtectClock= adds DeviceAllow=char-rtc r
-        DeviceAllow = "";
-
-        LockPersonality = true;
-
-        PrivateTmp = true;
-        # Disabled to allow Jellyfin to access hw accel devices endpoints
-        # PrivateDevices = true;
-        PrivateUsers = true;
-
-        # Disabled as it does not allow Jellyfin to interface with CUDA devices
-        # ProtectClock = true;
-        ProtectControlGroups = true;
-        ProtectHostname = true;
-        ProtectKernelLogs = true;
-        ProtectKernelModules = true;
-        ProtectKernelTunables = true;
-
-        RemoveIPC = true;
-
-        RestrictNamespaces = true;
+        SystemCallArchitectures = "native";
         # AF_NETLINK needed because Jellyfin monitors the network connection
-        RestrictAddressFamilies = [ "AF_NETLINK" "AF_INET" "AF_INET6" "AF_UNIX" ];
+        RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" "AF_NETLINK" ];
+        RestrictNamespaces = !config.boot.isContainer;
         RestrictRealtime = true;
         RestrictSUIDSGID = true;
+        ProtectControlGroups = !config.boot.isContainer;
+        ProtectHostname = true;
+        ProtectKernelLogs = !config.boot.isContainer;
+        ProtectKernelModules = !config.boot.isContainer;
+        ProtectKernelTunables = !config.boot.isContainer;
+        LockPersonality = true;
+        PrivateTmp = !config.boot.isContainer;
+        # needed for hardware accelaration
+        PrivateDevices = false;
+        PrivateUsers = true;
+        RemoveIPC = true;
 
-        SystemCallArchitectures = "native";
-        SystemCallErrorNumber = "EPERM";
         SystemCallFilter = [
-          "@system-service"
-          "~@cpu-emulation" "~@debug" "~@keyring" "~@memlock" "~@obsolete" "~@privileged" "~@setuid"
+          "~@clock"
+          "~@aio"
+          "~@chown"
+          "~@cpu-emulation"
+          "~@debug"
+          "~@keyring"
+          "~@memlock"
+          "~@module"
+          "~@mount"
+          "~@obsolete"
+          "~@privileged"
+          "~@raw-io"
+          "~@reboot"
+          "~@setuid"
+          "~@swap"
         ];
+        SystemCallErrorNumber = "EPERM";
       };
     };
 
diff --git a/nixos/modules/services/misc/klipper.nix b/nixos/modules/services/misc/klipper.nix
index 7b3780b5cc9..a2158e9461b 100644
--- a/nixos/modules/services/misc/klipper.nix
+++ b/nixos/modules/services/misc/klipper.nix
@@ -5,46 +5,70 @@ let
   format = pkgs.formats.ini {
     # https://github.com/NixOS/nixpkgs/pull/121613#issuecomment-885241996
     listToValue = l:
-      if builtins.length l == 1 then generators.mkValueStringDefault {} (head l)
+      if builtins.length l == 1 then generators.mkValueStringDefault { } (head l)
       else lib.concatMapStrings (s: "\n  ${generators.mkValueStringDefault {} s}") l;
-    mkKeyValue = generators.mkKeyValueDefault {} ":";
+    mkKeyValue = generators.mkKeyValueDefault { } ":";
   };
 in
 {
   ##### interface
   options = {
     services.klipper = {
-      enable = mkEnableOption "Klipper, the 3D printer firmware";
+      enable = mkEnableOption (lib.mdDoc "Klipper, the 3D printer firmware");
 
       package = mkOption {
         type = types.package;
         default = pkgs.klipper;
         defaultText = literalExpression "pkgs.klipper";
-        description = "The Klipper package.";
+        description = lib.mdDoc "The Klipper package.";
       };
 
       inputTTY = mkOption {
         type = types.path;
         default = "/run/klipper/tty";
-        description = "Path of the virtual printer symlink to create.";
+        description = lib.mdDoc "Path of the virtual printer symlink to create.";
       };
 
       apiSocket = mkOption {
         type = types.nullOr types.path;
         default = "/run/klipper/api";
-        description = "Path of the API socket to create.";
+        description = lib.mdDoc "Path of the API socket to create.";
+      };
+
+      mutableConfig = mkOption {
+        type = types.bool;
+        default = false;
+        example = true;
+        description = lib.mdDoc ''
+          Whether to copy the config to a mutable directory instead of using the one directly from the nix store.
+          This will only copy the config if the file at `services.klipper.mutableConfigPath` doesn't exist.
+        '';
+      };
+
+      mutableConfigFolder = mkOption {
+        type = types.path;
+        default = "/var/lib/klipper";
+        description = lib.mdDoc "Path to mutable Klipper config file.";
+      };
+
+      configFile = mkOption {
+        type = types.nullOr types.path;
+        default = null;
+        description = lib.mdDoc ''
+          Path to default Klipper config.
+        '';
       };
 
       octoprintIntegration = mkOption {
         type = types.bool;
         default = false;
-        description = "Allows Octoprint to control Klipper.";
+        description = lib.mdDoc "Allows Octoprint to control Klipper.";
       };
 
       user = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           User account under which Klipper runs.
 
           If null is specified (default), a temporary user will be created by systemd.
@@ -54,7 +78,7 @@ in
       group = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Group account under which Klipper runs.
 
           If null is specified (default), a temporary user will be created by systemd.
@@ -62,13 +86,35 @@ in
       };
 
       settings = mkOption {
-        type = format.type;
-        default = { };
-        description = ''
-          Configuration for Klipper. See the <link xlink:href="https://www.klipper3d.org/Overview.html#configuration-and-tuning-guides">documentation</link>
+        type = types.nullOr format.type;
+        default = null;
+        description = lib.mdDoc ''
+          Configuration for Klipper. See the [documentation](https://www.klipper3d.org/Overview.html#configuration-and-tuning-guides)
           for supported values.
         '';
       };
+
+      firmwares = mkOption {
+        description = lib.mdDoc "Firmwares klipper should manage";
+        default = { };
+        type = with types; attrsOf
+          (submodule {
+            options = {
+              enable = mkEnableOption (lib.mdDoc ''
+                building of firmware and addition of klipper-flash tools for manual flashing.
+                This will add `klipper-flash-$mcu` scripts to your environment which can be called to flash the firmware.
+              '');
+              serial = mkOption {
+                type = types.nullOr path;
+                description = lib.mdDoc "Path to serial port this printer is connected to. Leave `null` to derive it from `service.klipper.settings`.";
+              };
+              configFile = mkOption {
+                type = path;
+                description = lib.mdDoc "Path to firmware config which is generated using `klipper-genconf`";
+              };
+            };
+          });
+      };
     };
   };
 
@@ -77,41 +123,102 @@ in
     assertions = [
       {
         assertion = cfg.octoprintIntegration -> config.services.octoprint.enable;
-        message = "Option klipper.octoprintIntegration requires Octoprint to be enabled on this system. Please enable services.octoprint to use it.";
+        message = "Option services.klipper.octoprintIntegration requires Octoprint to be enabled on this system. Please enable services.octoprint to use it.";
       }
       {
         assertion = cfg.user != null -> cfg.group != null;
-        message = "Option klipper.group is not set when a user is specified.";
+        message = "Option services.klipper.group is not set when services.klipper.user is specified.";
+      }
+      {
+        assertion = cfg.settings != null -> foldl (a: b: a && b) true (mapAttrsToList (mcu: _: mcu != null -> (hasAttrByPath [ "${mcu}" "serial" ] cfg.settings)) cfg.firmwares);
+        message = "Option services.klipper.settings.$mcu.serial must be set when settings.klipper.firmware.$mcu is specified";
+      }
+      {
+        assertion = (cfg.configFile != null) != (cfg.settings != null);
+        message = "You need to either specify services.klipper.settings or services.klipper.defaultConfig.";
       }
     ];
 
-    environment.etc."klipper.cfg".source = format.generate "klipper.cfg" cfg.settings;
+    environment.etc = mkIf (!cfg.mutableConfig) {
+      "klipper.cfg".source = if cfg.settings != null then format.generate "klipper.cfg" cfg.settings else cfg.configFile;
+    };
 
     services.klipper = mkIf cfg.octoprintIntegration {
       user = config.services.octoprint.user;
       group = config.services.octoprint.group;
     };
 
-    systemd.services.klipper = let
-      klippyArgs = "--input-tty=${cfg.inputTTY}"
-        + optionalString (cfg.apiSocket != null) " --api-server=${cfg.apiSocket}";
-    in {
-      description = "Klipper 3D Printer Firmware";
-      wantedBy = [ "multi-user.target" ];
-      after = [ "network.target" ];
-
-      serviceConfig = {
-        ExecStart = "${cfg.package}/lib/klipper/klippy.py ${klippyArgs} /etc/klipper.cfg";
-        RuntimeDirectory = "klipper";
-        SupplementaryGroups = [ "dialout" ];
-        WorkingDirectory = "${cfg.package}/lib";
-      } // (if cfg.user != null then {
-        Group = cfg.group;
-        User = cfg.user;
-      } else {
-        DynamicUser = true;
-        User = "klipper";
-      });
-    };
+    systemd.services.klipper =
+      let
+        klippyArgs = "--input-tty=${cfg.inputTTY}"
+          + optionalString (cfg.apiSocket != null) " --api-server=${cfg.apiSocket}";
+        printerConfigPath =
+          if cfg.mutableConfig
+          then cfg.mutableConfigFolder + "/printer.cfg"
+          else "/etc/klipper.cfg";
+        printerConfigFile =
+          if cfg.settings != null
+          then format.generate "klipper.cfg" cfg.settings
+          else cfg.configFile;
+      in
+      {
+        description = "Klipper 3D Printer Firmware";
+        wantedBy = [ "multi-user.target" ];
+        after = [ "network.target" ];
+        preStart = ''
+          mkdir -p ${cfg.mutableConfigFolder}
+          ${lib.optionalString (cfg.mutableConfig) ''
+            [ -e ${printerConfigPath} ] || {
+              cp ${printerConfigFile} ${printerConfigPath}
+              chmod +w ${printerConfigPath}
+            }
+          ''}
+          mkdir -p ${cfg.mutableConfigFolder}/gcodes
+        '';
+
+        serviceConfig = {
+          ExecStart = "${cfg.package}/lib/klipper/klippy.py ${klippyArgs} ${printerConfigPath}";
+          RuntimeDirectory = "klipper";
+          StateDirectory = "klipper";
+          SupplementaryGroups = [ "dialout" ];
+          WorkingDirectory = "${cfg.package}/lib";
+          OOMScoreAdjust = "-999";
+          CPUSchedulingPolicy = "rr";
+          CPUSchedulingPriority = 99;
+          IOSchedulingClass = "realtime";
+          IOSchedulingPriority = 0;
+          UMask = "0002";
+        } // (if cfg.user != null then {
+          Group = cfg.group;
+          User = cfg.user;
+        } else {
+          DynamicUser = true;
+          User = "klipper";
+        });
+      };
+
+    environment.systemPackages =
+      with pkgs;
+      let
+        default = a: b: if a != null then a else b;
+        firmwares = filterAttrs (n: v: v!= null) (mapAttrs
+          (mcu: { enable, configFile, serial }: if enable then pkgs.klipper-firmware.override {
+            mcu = lib.strings.sanitizeDerivationName mcu;
+            firmwareConfig = configFile;
+          } else null)
+          cfg.firmwares);
+        firmwareFlasher = mapAttrsToList
+          (mcu: firmware: pkgs.klipper-flash.override {
+            mcu = lib.strings.sanitizeDerivationName mcu;
+            klipper-firmware = firmware;
+            flashDevice = default cfg.firmwares."${mcu}".serial cfg.settings."${mcu}".serial;
+            firmwareConfig = cfg.firmwares."${mcu}".configFile;
+          })
+          firmwares;
+      in
+      [ klipper-genconf ] ++ firmwareFlasher ++ attrValues firmwares;
   };
+  meta.maintainers = [
+    maintainers.cab404
+  ];
 }
diff --git a/nixos/modules/services/misc/languagetool.nix b/nixos/modules/services/misc/languagetool.nix
new file mode 100644
index 00000000000..9adf792373b
--- /dev/null
+++ b/nixos/modules/services/misc/languagetool.nix
@@ -0,0 +1,78 @@
+{ config, lib, options, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.languagetool;
+  settingsFormat = pkgs.formats.javaProperties {};
+in {
+  options.services.languagetool = {
+    enable = mkEnableOption (mdDoc "the LanguageTool server");
+
+    port = mkOption {
+      type = types.port;
+      default = 8081;
+      example = 8081;
+      description = mdDoc ''
+        Port on which LanguageTool listens.
+      '';
+    };
+
+    public = mkEnableOption (mdDoc "access from anywhere (rather than just localhost)");
+
+    allowOrigin = mkOption {
+      type = types.nullOr types.str;
+      default = null;
+      example = "https://my-website.org";
+      description = mdDoc ''
+        Set the Access-Control-Allow-Origin header in the HTTP response,
+        used for direct (non-proxy) JavaScript-based access from browsers.
+        `null` to allow access from all sites.
+      '';
+    };
+
+    settings = lib.mkOption {
+      type = types.submodule {
+        freeformType = settingsFormat.type;
+
+        options.cacheSize = mkOption {
+          type = types.ints.unsigned;
+          default = 1000;
+          apply = toString;
+          description = mdDoc "Number of sentences cached.";
+        };
+      };
+      default = {};
+      description = mdDoc ''
+        Configuration file options for LanguageTool, see
+        'languagetool-http-server --help'
+        for supported settings.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    systemd.services.languagetool =  {
+      description = "LanguageTool HTTP server";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+      serviceConfig = {
+        DynamicUser = true;
+        User = "languagetool";
+        Group = "languagetool";
+        CapabilityBoundingSet = [ "" ];
+        RestrictNamespaces = [ "" ];
+        SystemCallFilter = [ "@system-service" "~ @privileged" ];
+        ProtectHome = "yes";
+        ExecStart = ''
+          ${pkgs.languagetool}/bin/languagetool-http-server \
+            --port ${toString cfg.port} \
+            ${optionalString cfg.public "--public"} \
+            ${optionalString (cfg.allowOrigin != null) "--allow-origin ${cfg.allowOrigin}"} \
+            "--config" ${settingsFormat.generate "languagetool.conf" cfg.settings}
+          '';
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/misc/leaps.nix b/nixos/modules/services/misc/leaps.nix
index f797218522c..5522223ecc9 100644
--- a/nixos/modules/services/misc/leaps.nix
+++ b/nixos/modules/services/misc/leaps.nix
@@ -9,22 +9,22 @@ in
 {
   options = {
     services.leaps = {
-      enable = mkEnableOption "leaps";
+      enable = mkEnableOption (lib.mdDoc "leaps");
       port = mkOption {
         type = types.port;
         default = 8080;
-        description = "A port where leaps listens for incoming http requests";
+        description = lib.mdDoc "A port where leaps listens for incoming http requests";
       };
       address = mkOption {
         default = "";
         type = types.str;
         example = "127.0.0.1";
-        description = "Hostname or IP-address to listen to. By default it will listen on all interfaces.";
+        description = lib.mdDoc "Hostname or IP-address to listen to. By default it will listen on all interfaces.";
       };
       path = mkOption {
         default = "/";
         type = types.path;
-        description = "Subdirectory used for reverse proxy setups";
+        description = lib.mdDoc "Subdirectory used for reverse proxy setups";
       };
     };
   };
diff --git a/nixos/modules/services/misc/libreddit.nix b/nixos/modules/services/misc/libreddit.nix
index 77b34a85620..c961d13da47 100644
--- a/nixos/modules/services/misc/libreddit.nix
+++ b/nixos/modules/services/misc/libreddit.nix
@@ -2,44 +2,37 @@
 
 with lib;
 
-  let
-    cfg = config.services.libreddit;
-
-    args = concatStringsSep " " ([
-      "--port ${toString cfg.port}"
-      "--address ${cfg.address}"
-    ] ++ optional cfg.redirect "--redirect-https");
+let
+  cfg = config.services.libreddit;
 
+  args = concatStringsSep " " ([
+    "--port ${toString cfg.port}"
+    "--address ${cfg.address}"
+  ]);
 in
 {
   options = {
     services.libreddit = {
-      enable = mkEnableOption "Private front-end for Reddit";
+      enable = mkEnableOption (lib.mdDoc "Private front-end for Reddit");
 
       address = mkOption {
         default = "0.0.0.0";
         example = "127.0.0.1";
         type =  types.str;
-        description = "The address to listen on";
+        description = lib.mdDoc "The address to listen on";
       };
 
       port = mkOption {
         default = 8080;
         example = 8000;
         type = types.port;
-        description = "The port to listen on";
-      };
-
-      redirect = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Enable the redirecting to HTTPS";
+        description = lib.mdDoc "The port to listen on";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the libreddit web interface";
+        description = lib.mdDoc "Open ports in the firewall for the libreddit web interface";
       };
 
     };
@@ -56,6 +49,31 @@ in
           AmbientCapabilities = lib.mkIf (cfg.port < 1024) [ "CAP_NET_BIND_SERVICE" ];
           Restart = "on-failure";
           RestartSec = "2s";
+          # Hardening
+          CapabilityBoundingSet = if (cfg.port < 1024) then [ "CAP_NET_BIND_SERVICE" ] else [ "" ];
+          DeviceAllow = [ "" ];
+          LockPersonality = true;
+          MemoryDenyWriteExecute = true;
+          PrivateDevices = true;
+          # A private user cannot have process capabilities on the host's user
+          # namespace and thus CAP_NET_BIND_SERVICE has no effect.
+          PrivateUsers = (cfg.port >= 1024);
+          ProcSubset = "pid";
+          ProtectClock = true;
+          ProtectControlGroups = true;
+          ProtectHome = true;
+          ProtectHostname = true;
+          ProtectKernelLogs = true;
+          ProtectKernelModules = true;
+          ProtectKernelTunables = true;
+          ProtectProc = "invisible";
+          RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+          RestrictNamespaces = true;
+          RestrictRealtime = true;
+          RestrictSUIDSGID = true;
+          SystemCallArchitectures = "native";
+          SystemCallFilter = [ "@system-service" "~@privileged" "~@resources" ];
+          UMask = "0077";
         };
     };
 
diff --git a/nixos/modules/services/misc/lidarr.nix b/nixos/modules/services/misc/lidarr.nix
index 20153c7e61a..92b00054bdf 100644
--- a/nixos/modules/services/misc/lidarr.nix
+++ b/nixos/modules/services/misc/lidarr.nix
@@ -8,25 +8,25 @@ in
 {
   options = {
     services.lidarr = {
-      enable = mkEnableOption "Lidarr";
+      enable = mkEnableOption (lib.mdDoc "Lidarr");
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/lidarr/.config/Lidarr";
-        description = "The directory where Lidarr stores its data files.";
+        description = lib.mdDoc "The directory where Lidarr stores its data files.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.lidarr;
         defaultText = literalExpression "pkgs.lidarr";
-        description = "The Lidarr package to use";
+        description = lib.mdDoc "The Lidarr package to use";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for Lidarr
         '';
       };
@@ -34,7 +34,7 @@ in
       user = mkOption {
         type = types.str;
         default = "lidarr";
-        description = ''
+        description = lib.mdDoc ''
           User account under which Lidarr runs.
         '';
       };
@@ -42,7 +42,7 @@ in
       group = mkOption {
         type = types.str;
         default = "lidarr";
-        description = ''
+        description = lib.mdDoc ''
           Group under which Lidarr runs.
         '';
       };
diff --git a/nixos/modules/services/misc/lifecycled.nix b/nixos/modules/services/misc/lifecycled.nix
index 1c8942998d6..fb5cabb4f03 100644
--- a/nixos/modules/services/misc/lifecycled.nix
+++ b/nixos/modules/services/misc/lifecycled.nix
@@ -25,20 +25,20 @@ in
 
   options = {
     services.lifecycled = {
-      enable = mkEnableOption "lifecycled";
+      enable = mkEnableOption (lib.mdDoc "lifecycled");
 
       queueCleaner = {
-        enable = mkEnableOption "lifecycled-queue-cleaner";
+        enable = mkEnableOption (lib.mdDoc "lifecycled-queue-cleaner");
 
         frequency = mkOption {
           type = types.str;
           default = "hourly";
-          description = ''
+          description = lib.mdDoc ''
             How often to trigger the queue cleaner.
 
             NOTE: This string should be a valid value for a systemd
-            timer's <literal>OnCalendar</literal> configuration. See
-            <citerefentry><refentrytitle>systemd.timer</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+            timer's `OnCalendar` configuration. See
+            {manpage}`systemd.timer(5)`
             for more information.
           '';
         };
@@ -46,7 +46,7 @@ in
         parallel = mkOption {
           type = types.ints.unsigned;
           default = 20;
-          description = ''
+          description = lib.mdDoc ''
             The number of parallel deletes to run.
           '';
         };
@@ -55,7 +55,7 @@ in
       instanceId = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The instance ID to listen for events for.
         '';
       };
@@ -63,7 +63,7 @@ in
       snsTopic = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The SNS topic that receives events.
         '';
       };
@@ -71,14 +71,14 @@ in
       noSpot = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Disable the spot termination listener.
         '';
       };
 
       handler = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The script to invoke to handle events.
         '';
       };
@@ -86,7 +86,7 @@ in
       json = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable JSON logging.
         '';
       };
@@ -94,7 +94,7 @@ in
       cloudwatchGroup = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Write logs to a specific Cloudwatch Logs group.
         '';
       };
@@ -102,7 +102,7 @@ in
       cloudwatchStream = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Write logs to a specific Cloudwatch Logs stream. Defaults to the instance ID.
         '';
       };
@@ -110,7 +110,7 @@ in
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable debugging information.
         '';
       };
@@ -120,7 +120,7 @@ in
       awsRegion = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The region used for accessing AWS services.
         '';
       };
diff --git a/nixos/modules/services/misc/logkeys.nix b/nixos/modules/services/misc/logkeys.nix
index 0082db63a06..75d073a0c94 100644
--- a/nixos/modules/services/misc/logkeys.nix
+++ b/nixos/modules/services/misc/logkeys.nix
@@ -6,10 +6,10 @@ let
   cfg = config.services.logkeys;
 in {
   options.services.logkeys = {
-    enable = mkEnableOption "logkeys service";
+    enable = mkEnableOption (lib.mdDoc "logkeys service");
 
     device = mkOption {
-      description = "Use the given device as keyboard input event device instead of /dev/input/eventX default.";
+      description = lib.mdDoc "Use the given device as keyboard input event device instead of /dev/input/eventX default.";
       default = null;
       type = types.nullOr types.str;
       example = "/dev/input/event15";
diff --git a/nixos/modules/services/misc/mame.nix b/nixos/modules/services/misc/mame.nix
index dd6c5ef9aa0..6e9d2fd26cf 100644
--- a/nixos/modules/services/misc/mame.nix
+++ b/nixos/modules/services/misc/mame.nix
@@ -12,19 +12,19 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to setup TUN/TAP Ethernet interface for MAME emulator.
         '';
       };
       user = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User from which you run MAME binary.
         '';
       };
       hostAddr = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           IP address of the host system. Usually an address of the main network
           adapter or the adapter through which you get an internet connection.
         '';
@@ -32,9 +32,9 @@ in
       };
       emuAddr = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           IP address of the guest system. The same you set inside guest OS under
-          MAME. Should be on the same subnet as <option>services.mame.hostAddr</option>.
+          MAME. Should be on the same subnet as {option}`services.mame.hostAddr`.
         '';
         example = "192.168.31.155";
       };
diff --git a/nixos/modules/services/misc/mbpfan.nix b/nixos/modules/services/misc/mbpfan.nix
index e0a4d8a13e7..d467aa87976 100644
--- a/nixos/modules/services/misc/mbpfan.nix
+++ b/nixos/modules/services/misc/mbpfan.nix
@@ -10,13 +10,13 @@ let
 
 in {
   options.services.mbpfan = {
-    enable = mkEnableOption "mbpfan, fan controller daemon for Apple Macs and MacBooks";
+    enable = mkEnableOption (lib.mdDoc "mbpfan, fan controller daemon for Apple Macs and MacBooks");
 
     package = mkOption {
       type = types.package;
       default = pkgs.mbpfan;
       defaultText = literalExpression "pkgs.mbpfan";
-      description = ''
+      description = lib.mdDoc ''
         The package used for the mbpfan daemon.
       '';
     };
@@ -24,52 +24,46 @@ in {
     verbose = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         If true, sets the log level to verbose.
       '';
     };
 
     settings = mkOption {
       default = {};
-      description = "The INI configuration for Mbpfan.";
+      description = lib.mdDoc "INI configuration for Mbpfan.";
       type = types.submodule {
         freeformType = settingsFormat.type;
 
         options.general.min_fan1_speed = mkOption {
           type = types.nullOr types.int;
           default = 2000;
-          description = ''
-            The minimum fan speed. Setting to null enables automatic detection.
-            Check minimum fan limits with "cat /sys/devices/platform/applesmc.768/fan*_min".
-          '';
-        };
-        options.general.max_fan1_speed = mkOption {
-          type = types.nullOr types.int;
-          default = 6199;
-          description = ''
-            The maximum fan speed. Setting to null enables automatic detection.
-            Check maximum fan limits with "cat /sys/devices/platform/applesmc.768/fan*_max".
+          description = lib.mdDoc ''
+            You can check minimum and maximum fan limits with
+            `cat /sys/devices/platform/applesmc.768/fan*_min` and
+            `cat /sys/devices/platform/applesmc.768/fan*_max` respectively.
+            Setting to null implies using default value from applesmc.
           '';
         };
         options.general.low_temp = mkOption {
           type = types.int;
           default = 55;
-          description = "Temperature below which fan speed will be at minimum. Try ranges 55-63.";
+          description = lib.mdDoc "If temperature is below this, fans will run at minimum speed.";
         };
         options.general.high_temp = mkOption {
           type = types.int;
           default = 58;
-          description = "Fan will increase speed when higher than this temperature. Try ranges 58-66.";
+          description = lib.mdDoc "If temperature is above this, fan speed will gradually increase.";
         };
         options.general.max_temp = mkOption {
           type = types.int;
           default = 86;
-          description = "Fan will run at full speed above this temperature. Do not set it > 90.";
+          description = lib.mdDoc "If temperature is above this, fans will run at maximum speed.";
         };
         options.general.polling_interval = mkOption {
           type = types.int;
           default = 1;
-          description = "The polling interval.";
+          description = lib.mdDoc "The polling interval.";
         };
       };
     };
diff --git a/nixos/modules/services/misc/mediatomb.nix b/nixos/modules/services/misc/mediatomb.nix
index ee5c0ef8d27..632b7caaac4 100644
--- a/nixos/modules/services/misc/mediatomb.nix
+++ b/nixos/modules/services/misc/mediatomb.nix
@@ -15,19 +15,19 @@ let
     options = {
       path = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Absolute directory path to the media directory to index.
         '';
       };
       recursive = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether the indexation must take place recursively or not.";
+        description = lib.mdDoc "Whether the indexation must take place recursively or not.";
       };
       hidden-files = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to index the hidden files or not.";
+        description = lib.mdDoc "Whether to index the hidden files or not.";
       };
     };
   };
@@ -202,7 +202,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Gerbera/Mediatomb DLNA server.
         '';
       };
@@ -210,7 +210,7 @@ in {
       serverName = mkOption {
         type = types.str;
         default = "Gerbera (Mediatomb)";
-        description = ''
+        description = lib.mdDoc ''
           How to identify the server on the network.
         '';
       };
@@ -219,7 +219,7 @@ in {
         type = types.package;
         default = pkgs.gerbera;
         defaultText = literalExpression "pkgs.gerbera";
-        description = ''
+        description = lib.mdDoc ''
           Underlying package to be used with the module.
         '';
       };
@@ -227,7 +227,7 @@ in {
       ps3Support = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable ps3 specific tweaks.
           WARNING: incompatible with DSM 320 support.
         '';
@@ -236,7 +236,7 @@ in {
       dsmSupport = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable D-Link DSM 320 specific tweaks.
           WARNING: incompatible with ps3 support.
         '';
@@ -245,7 +245,7 @@ in {
       tg100Support = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Telegent TG100 specific tweaks.
         '';
       };
@@ -253,7 +253,7 @@ in {
       transcoding = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable transcoding.
         '';
       };
@@ -262,7 +262,7 @@ in {
         type = types.path;
         default = "/var/lib/${name}";
         defaultText = literalExpression ''"/var/lib/''${config.${opt.package}.pname}"'';
-        description = ''
+        description = lib.mdDoc ''
           The directory where Gerbera/Mediatomb stores its state, data, etc.
         '';
       };
@@ -270,7 +270,7 @@ in {
       pcDirectoryHide = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to list the top-level directory or not (from upnp client standpoint).
         '';
       };
@@ -278,19 +278,19 @@ in {
       user = mkOption {
         type = types.str;
         default = "mediatomb";
-        description = "User account under which the service runs.";
+        description = lib.mdDoc "User account under which the service runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "mediatomb";
-        description = "Group account under which the service runs.";
+        description = lib.mdDoc "Group account under which the service runs.";
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 49152;
-        description = ''
+        description = lib.mdDoc ''
           The network port to listen on.
         '';
       };
@@ -298,7 +298,7 @@ in {
       interface = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           A specific interface to bind to.
         '';
       };
@@ -306,12 +306,12 @@ in {
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If false (the default), this is up to the user to declare the firewall rules.
           If true, this opens port 1900 (tcp and udp) and the port specified by
-          <option>sercvices.mediatomb.port</option>.
+          {option}`sercvices.mediatomb.port`.
 
-          If the option <option>services.mediatomb.interface</option> is set,
+          If the option {option}`services.mediatomb.interface` is set,
           the firewall rules opened are dedicated to that interface. Otherwise,
           those rules are opened globally.
         '';
@@ -320,7 +320,7 @@ in {
       uuid = mkOption {
         type = types.str;
         default = "fdfc8a4e-a3ad-4c1d-b43d-a2eedb03a687";
-        description = ''
+        description = lib.mdDoc ''
           A unique (on your network) to identify the server by.
         '';
       };
@@ -328,7 +328,7 @@ in {
       mediaDirectories = mkOption {
         type = with types; listOf (submodule mediaDirectory);
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Declare media directories to index.
         '';
         example = [
@@ -340,12 +340,12 @@ in {
       customCfg = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          Allow the service to create and use its own config file inside the <literal>dataDir</literal> as
-          configured by <option>services.mediatomb.dataDir</option>.
+        description = lib.mdDoc ''
+          Allow the service to create and use its own config file inside the `dataDir` as
+          configured by {option}`services.mediatomb.dataDir`.
           Deactivated by default, the service then runs with the configuration generated from this module.
           Otherwise, when enabled, no service configuration is generated. Gerbera/Mediatomb then starts using
-          config.xml within the configured <literal>dataDir</literal>. It's up to the user to make a correct
+          config.xml within the configured `dataDir`. It's up to the user to make a correct
           configuration file.
         '';
       };
@@ -362,7 +362,9 @@ in {
     in mkIf cfg.enable {
     systemd.services.mediatomb = {
       description = "${cfg.serverName} media Server";
-      after = [ "network.target" ];
+      # Gerbera might fail if the network interface is not available on startup
+      # https://github.com/gerbera/gerbera/issues/1324
+      after = [ "network.target" "network-online.target" ];
       wantedBy = [ "multi-user.target" ];
       serviceConfig.ExecStart = "${binaryCommand} --port ${toString cfg.port} ${interfaceFlag} ${configFlag} --home ${cfg.dataDir}";
       serviceConfig.User = cfg.user;
diff --git a/nixos/modules/services/misc/metabase.nix b/nixos/modules/services/misc/metabase.nix
index e78100a046a..883fa0b9591 100644
--- a/nixos/modules/services/misc/metabase.nix
+++ b/nixos/modules/services/misc/metabase.nix
@@ -13,13 +13,13 @@ in {
   options = {
 
     services.metabase = {
-      enable = mkEnableOption "Metabase service";
+      enable = mkEnableOption (lib.mdDoc "Metabase service");
 
       listen = {
         ip = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = ''
+          description = lib.mdDoc ''
             IP address that Metabase should listen on.
           '';
         };
@@ -27,7 +27,7 @@ in {
         port = mkOption {
           type = types.port;
           default = 3000;
-          description = ''
+          description = lib.mdDoc ''
             Listen port for Metabase.
           '';
         };
@@ -37,7 +37,7 @@ in {
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable SSL (https) support.
           '';
         };
@@ -45,7 +45,7 @@ in {
         port = mkOption {
           type = types.port;
           default = 8443;
-          description = ''
+          description = lib.mdDoc ''
             Listen port over SSL (https) for Metabase.
           '';
         };
@@ -54,8 +54,8 @@ in {
           type = types.nullOr types.path;
           default = "${dataDir}/metabase.jks";
           example = "/etc/secrets/keystore.jks";
-          description = ''
-            <link xlink:href="https://www.digitalocean.com/community/tutorials/java-keytool-essentials-working-with-java-keystores">Java KeyStore</link> file containing the certificates.
+          description = lib.mdDoc ''
+            [Java KeyStore](https://www.digitalocean.com/community/tutorials/java-keytool-essentials-working-with-java-keystores) file containing the certificates.
           '';
         };
 
@@ -64,7 +64,7 @@ in {
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for Metabase.
         '';
       };
diff --git a/nixos/modules/services/misc/moonraker.nix b/nixos/modules/services/misc/moonraker.nix
index b75227effa0..62064b5d90f 100644
--- a/nixos/modules/services/misc/moonraker.nix
+++ b/nixos/modules/services/misc/moonraker.nix
@@ -14,26 +14,26 @@ let
 in {
   options = {
     services.moonraker = {
-      enable = mkEnableOption "Moonraker, an API web server for Klipper";
+      enable = mkEnableOption (lib.mdDoc "Moonraker, an API web server for Klipper");
 
       klipperSocket = mkOption {
         type = types.path;
         default = config.services.klipper.apiSocket;
         defaultText = literalExpression "config.services.klipper.apiSocket";
-        description = "Path to Klipper's API socket.";
+        description = lib.mdDoc "Path to Klipper's API socket.";
       };
 
       stateDir = mkOption {
         type = types.path;
         default = "/var/lib/moonraker";
-        description = "The directory containing the Moonraker databases.";
+        description = lib.mdDoc "The directory containing the Moonraker databases.";
       };
 
       configDir = mkOption {
         type = types.path;
         default = cfg.stateDir + "/config";
         defaultText = literalExpression ''config.${opt.stateDir} + "/config"'';
-        description = ''
+        description = lib.mdDoc ''
           The directory containing client-writable configuration files.
 
           Clients will be able to edit files in this directory via the API. This directory must be writable.
@@ -43,26 +43,26 @@ in {
       user = mkOption {
         type = types.str;
         default = "moonraker";
-        description = "User account under which Moonraker runs.";
+        description = lib.mdDoc "User account under which Moonraker runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "moonraker";
-        description = "Group account under which Moonraker runs.";
+        description = lib.mdDoc "Group account under which Moonraker runs.";
       };
 
       address = mkOption {
         type = types.str;
         default = "127.0.0.1";
         example = "0.0.0.0";
-        description = "The IP or host to listen on.";
+        description = lib.mdDoc "The IP or host to listen on.";
       };
 
       port = mkOption {
         type = types.ints.unsigned;
         default = 7125;
-        description = "The port to listen on.";
+        description = lib.mdDoc "The port to listen on.";
       };
 
       settings = mkOption {
@@ -74,8 +74,8 @@ in {
             cors_domains = [ "https://app.fluidd.xyz" ];
           };
         };
-        description = ''
-          Configuration for Moonraker. See the <link xlink:href="https://moonraker.readthedocs.io/en/latest/configuration/">documentation</link>
+        description = lib.mdDoc ''
+          Configuration for Moonraker. See the [documentation](https://moonraker.readthedocs.io/en/latest/configuration/)
           for supported values.
         '';
       };
@@ -83,12 +83,12 @@ in {
       allowSystemControl = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to allow Moonraker to perform system-level operations.
 
           Moonraker exposes APIs to perform system-level operations, such as
           reboot, shutdown, and management of systemd units. See the
-          <link xlink:href="https://moonraker.readthedocs.io/en/latest/web_api/#machine-commands">documentation</link>
+          [documentation](https://moonraker.readthedocs.io/en/latest/web_api/#machine-commands)
           for details on what clients are able to do.
         '';
       };
@@ -123,7 +123,11 @@ in {
           host = cfg.address;
           port = cfg.port;
           klippy_uds_address = cfg.klipperSocket;
+        };
+        file_manager = {
           config_path = cfg.configDir;
+        };
+        database = {
           database_path = "${cfg.stateDir}/database";
         };
       };
@@ -153,6 +157,7 @@ in {
 
       serviceConfig = {
         WorkingDirectory = cfg.stateDir;
+        PrivateTmp = true;
         Group = cfg.group;
         User = cfg.user;
       };
@@ -175,4 +180,9 @@ in {
       });
     '';
   };
+
+  meta.maintainers = with maintainers; [
+    cab404
+    vtuan10
+  ];
 }
diff --git a/nixos/modules/services/misc/mx-puppet-discord.nix b/nixos/modules/services/misc/mx-puppet-discord.nix
index 6214f7f7eb6..36c9f8b122e 100644
--- a/nixos/modules/services/misc/mx-puppet-discord.nix
+++ b/nixos/modules/services/misc/mx-puppet-discord.nix
@@ -12,10 +12,10 @@ let
 in {
   options = {
     services.mx-puppet-discord = {
-      enable = mkEnableOption ''
+      enable = mkEnableOption (lib.mdDoc ''
         mx-puppet-discord is a discord puppeting bridge for matrix.
         It handles bridging private and group DMs, as well as Guilds (servers)
-      '';
+      '');
 
       settings = mkOption rec {
         apply = recursiveUpdate default;
@@ -57,11 +57,11 @@ in {
             relay.whitelist = [ "@.*:example.com" ];
           }
         '';
-        description = ''
-          <filename>config.yaml</filename> configuration as a Nix attribute set.
+        description = lib.mdDoc ''
+          {file}`config.yaml` configuration as a Nix attribute set.
           Configuration options should match those described in
-          <link xlink:href="https://github.com/matrix-discord/mx-puppet-discord/blob/master/sample.config.yaml">
-          sample.config.yaml</link>.
+          [
+          sample.config.yaml](https://github.com/matrix-discord/mx-puppet-discord/blob/master/sample.config.yaml).
         '';
       };
       serviceDependencies = mkOption {
@@ -70,7 +70,7 @@ in {
         defaultText = literalExpression ''
           optional config.services.matrix-synapse.enable "matrix-synapse.service"
         '';
-        description = ''
+        description = lib.mdDoc ''
           List of Systemd services to require and wait for when starting the application service.
         '';
       };
@@ -107,7 +107,7 @@ in {
         PrivateTmp = true;
         WorkingDirectory = pkgs.mx-puppet-discord;
         StateDirectory = baseNameOf dataDir;
-        UMask = 0027;
+        UMask = "0027";
 
         ExecStart = ''
           ${pkgs.mx-puppet-discord}/bin/mx-puppet-discord \
diff --git a/nixos/modules/services/misc/n8n.nix b/nixos/modules/services/misc/n8n.nix
index 77e717eeff9..f59df471e1e 100644
--- a/nixos/modules/services/misc/n8n.nix
+++ b/nixos/modules/services/misc/n8n.nix
@@ -10,19 +10,19 @@ in
 {
   options.services.n8n = {
 
-    enable = mkEnableOption "n8n server";
+    enable = mkEnableOption (lib.mdDoc "n8n server");
 
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = "Open ports in the firewall for the n8n web interface.";
+      description = lib.mdDoc "Open ports in the firewall for the n8n web interface.";
     };
 
     settings = mkOption {
       type = format.type;
       default = {};
-      description = ''
-        Configuration for n8n, see <link xlink:href="https://docs.n8n.io/reference/configuration.html"/>
+      description = lib.mdDoc ''
+        Configuration for n8n, see <https://docs.n8n.io/reference/configuration.html>
         for supported values.
       '';
     };
diff --git a/nixos/modules/services/misc/nitter.nix b/nixos/modules/services/misc/nitter.nix
index 97005c9d914..95394d9d211 100644
--- a/nixos/modules/services/misc/nitter.nix
+++ b/nixos/modules/services/misc/nitter.nix
@@ -47,13 +47,13 @@ in
 {
   options = {
     services.nitter = {
-      enable = mkEnableOption "If enabled, start Nitter.";
+      enable = mkEnableOption (lib.mdDoc "If enabled, start Nitter.");
 
       package = mkOption {
         default = pkgs.nitter;
         type = types.package;
         defaultText = literalExpression "pkgs.nitter";
-        description = "The nitter derivation to use.";
+        description = lib.mdDoc "The nitter derivation to use.";
       };
 
       server = {
@@ -61,46 +61,46 @@ in
           type =  types.str;
           default = "0.0.0.0";
           example = "127.0.0.1";
-          description = "The address to listen on.";
+          description = lib.mdDoc "The address to listen on.";
         };
 
         port = mkOption {
           type = types.port;
           default = 8080;
           example = 8000;
-          description = "The port to listen on.";
+          description = lib.mdDoc "The port to listen on.";
         };
 
         https = mkOption {
           type = types.bool;
           default = false;
-          description = "Set secure attribute on cookies. Keep it disabled to enable cookies when not using HTTPS.";
+          description = lib.mdDoc "Set secure attribute on cookies. Keep it disabled to enable cookies when not using HTTPS.";
         };
 
         httpMaxConnections = mkOption {
           type = types.int;
           default = 100;
-          description = "Maximum number of HTTP connections.";
+          description = lib.mdDoc "Maximum number of HTTP connections.";
         };
 
         staticDir = mkOption {
           type = types.path;
           default = "${cfg.package}/share/nitter/public";
           defaultText = literalExpression ''"''${config.services.nitter.package}/share/nitter/public"'';
-          description = "Path to the static files directory.";
+          description = lib.mdDoc "Path to the static files directory.";
         };
 
         title = mkOption {
           type = types.str;
           default = "nitter";
-          description = "Title of the instance.";
+          description = lib.mdDoc "Title of the instance.";
         };
 
         hostname = mkOption {
           type = types.str;
           default = "localhost";
           example = "nitter.net";
-          description = "Hostname of the instance.";
+          description = lib.mdDoc "Hostname of the instance.";
         };
       };
 
@@ -108,37 +108,37 @@ in
         listMinutes = mkOption {
           type = types.int;
           default = 240;
-          description = "How long to cache list info (not the tweets, so keep it high).";
+          description = lib.mdDoc "How long to cache list info (not the tweets, so keep it high).";
         };
 
         rssMinutes = mkOption {
           type = types.int;
           default = 10;
-          description = "How long to cache RSS queries.";
+          description = lib.mdDoc "How long to cache RSS queries.";
         };
 
         redisHost = mkOption {
           type = types.str;
           default = "localhost";
-          description = "Redis host.";
+          description = lib.mdDoc "Redis host.";
         };
 
         redisPort = mkOption {
           type = types.port;
           default = 6379;
-          description = "Redis port.";
+          description = lib.mdDoc "Redis port.";
         };
 
         redisConnections = mkOption {
           type = types.int;
           default = 20;
-          description = "Redis connection pool size.";
+          description = lib.mdDoc "Redis connection pool size.";
         };
 
         redisMaxConnections = mkOption {
           type = types.int;
           default = 30;
-          description = ''
+          description = lib.mdDoc ''
             Maximum number of connections to Redis.
 
             New connections are opened when none are available, but if the
@@ -152,13 +152,13 @@ in
         base64Media = mkOption {
           type = types.bool;
           default = false;
-          description = "Use base64 encoding for proxied media URLs.";
+          description = lib.mdDoc "Use base64 encoding for proxied media URLs.";
         };
 
         tokenCount = mkOption {
           type = types.int;
           default = 10;
-          description = ''
+          description = lib.mdDoc ''
             Minimum amount of usable tokens.
 
             Tokens are used to authorize API requests, but they expire after
@@ -175,122 +175,122 @@ in
           type = types.str;
           default = "";
           example = "nitter.net";
-          description = "Replace Twitter links with links to this instance (blank to disable).";
+          description = lib.mdDoc "Replace Twitter links with links to this instance (blank to disable).";
         };
 
         replaceYouTube = mkOption {
           type = types.str;
           default = "";
           example = "piped.kavin.rocks";
-          description = "Replace YouTube links with links to this instance (blank to disable).";
+          description = lib.mdDoc "Replace YouTube links with links to this instance (blank to disable).";
         };
 
         replaceInstagram = mkOption {
           type = types.str;
           default = "";
-          description = "Replace Instagram links with links to this instance (blank to disable).";
+          description = lib.mdDoc "Replace Instagram links with links to this instance (blank to disable).";
         };
 
         mp4Playback = mkOption {
           type = types.bool;
           default = true;
-          description = "Enable MP4 video playback.";
+          description = lib.mdDoc "Enable MP4 video playback.";
         };
 
         hlsPlayback = mkOption {
           type = types.bool;
           default = false;
-          description = "Enable HLS video streaming (requires JavaScript).";
+          description = lib.mdDoc "Enable HLS video streaming (requires JavaScript).";
         };
 
         proxyVideos = mkOption {
           type = types.bool;
           default = true;
-          description = "Proxy video streaming through the server (might be slow).";
+          description = lib.mdDoc "Proxy video streaming through the server (might be slow).";
         };
 
         muteVideos = mkOption {
           type = types.bool;
           default = false;
-          description = "Mute videos by default.";
+          description = lib.mdDoc "Mute videos by default.";
         };
 
         autoplayGifs = mkOption {
           type = types.bool;
           default = true;
-          description = "Autoplay GIFs.";
+          description = lib.mdDoc "Autoplay GIFs.";
         };
 
         theme = mkOption {
           type = types.str;
           default = "Nitter";
-          description = "Instance theme.";
+          description = lib.mdDoc "Instance theme.";
         };
 
         infiniteScroll = mkOption {
           type = types.bool;
           default = false;
-          description = "Infinite scrolling (requires JavaScript, experimental!).";
+          description = lib.mdDoc "Infinite scrolling (requires JavaScript, experimental!).";
         };
 
         stickyProfile = mkOption {
           type = types.bool;
           default = true;
-          description = "Make profile sidebar stick to top.";
+          description = lib.mdDoc "Make profile sidebar stick to top.";
         };
 
         bidiSupport = mkOption {
           type = types.bool;
           default = false;
-          description = "Support bidirectional text (makes clicking on tweets harder).";
+          description = lib.mdDoc "Support bidirectional text (makes clicking on tweets harder).";
         };
 
         hideTweetStats = mkOption {
           type = types.bool;
           default = false;
-          description = "Hide tweet stats (replies, retweets, likes).";
+          description = lib.mdDoc "Hide tweet stats (replies, retweets, likes).";
         };
 
         hideBanner = mkOption {
           type = types.bool;
           default = false;
-          description = "Hide profile banner.";
+          description = lib.mdDoc "Hide profile banner.";
         };
 
         hidePins = mkOption {
           type = types.bool;
           default = false;
-          description = "Hide pinned tweets.";
+          description = lib.mdDoc "Hide pinned tweets.";
         };
 
         hideReplies = mkOption {
           type = types.bool;
           default = false;
-          description = "Hide tweet replies.";
+          description = lib.mdDoc "Hide tweet replies.";
         };
       };
 
       settings = mkOption {
         type = types.attrs;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Add settings here to override NixOS module generated settings.
 
           Check the official repository for the available settings:
-          https://github.com/zedeus/nitter/blob/master/nitter.conf
+          https://github.com/zedeus/nitter/blob/master/nitter.example.conf
         '';
       };
 
       redisCreateLocally = mkOption {
         type = types.bool;
         default = true;
-        description = "Configure local Redis server for Nitter.";
+        description = lib.mdDoc "Configure local Redis server for Nitter.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for Nitter web interface.";
+        description = lib.mdDoc "Open ports in the firewall for Nitter web interface.";
       };
     };
   };
@@ -347,8 +347,9 @@ in
         };
     };
 
-    services.redis = lib.mkIf (cfg.redisCreateLocally) {
+    services.redis.servers.nitter = lib.mkIf (cfg.redisCreateLocally) {
       enable = true;
+      port = cfg.cache.redisPort;
     };
 
     networking.firewall = mkIf cfg.openFirewall {
diff --git a/nixos/modules/services/misc/nix-daemon.nix b/nixos/modules/services/misc/nix-daemon.nix
index d56808c7564..c88fceb9a92 100644
--- a/nixos/modules/services/misc/nix-daemon.nix
+++ b/nixos/modules/services/misc/nix-daemon.nix
@@ -59,7 +59,7 @@ let
         ${mkKeyValuePairs cfg.settings}
         ${cfg.extraOptions}
       '';
-      checkPhase =
+      checkPhase = lib.optionalString cfg.checkConfig (
         if pkgs.stdenv.hostPlatform != pkgs.stdenv.buildPlatform then ''
           echo "Ignoring validation for cross-compilation"
         ''
@@ -72,9 +72,9 @@ let
             ${cfg.package}/bin/nix show-config ${optionalString (isNixAtLeast "2.3pre") "--no-net"} \
               ${optionalString (isNixAtLeast "2.4pre") "--option experimental-features nix-command"} \
             |& sed -e 's/^warning:/error:/' \
-            | (! grep '${if cfg.checkConfig then "^error:" else "^error: unknown setting"}')
+            | (! grep '${if cfg.checkAllErrors then "^error:" else "^error: unknown setting"}')
           set -o pipefail
-        '';
+        '');
     };
 
   legacyConfMappings = {
@@ -115,6 +115,7 @@ in
     (mkRenamedOptionModuleWith { sinceRelease = 2003; from = [ "nix" "useChroot" ]; to = [ "nix" "useSandbox" ]; })
     (mkRenamedOptionModuleWith { sinceRelease = 2003; from = [ "nix" "chrootDirs" ]; to = [ "nix" "sandboxPaths" ]; })
     (mkRenamedOptionModuleWith { sinceRelease = 2205; from = [ "nix" "daemonIONiceLevel" ]; to = [ "nix" "daemonIOSchedPriority" ]; })
+    (mkRenamedOptionModuleWith { sinceRelease = 2211; from = [ "nix" "readOnlyStore" ]; to = [ "boot" "readOnlyNixStore" ]; })
     (mkRemovedOptionModule [ "nix" "daemonNiceLevel" ] "Consider nix.daemonCPUSchedPolicy instead.")
   ] ++ mapAttrsToList (oldConf: newConf: mkRenamedOptionModuleWith { sinceRelease = 2205; from = [ "nix" oldConf ]; to = [ "nix" "settings" newConf ]; }) legacyConfMappings;
 
@@ -127,7 +128,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Nix.
           Disabling Nix makes the system hard to modify and the Nix programs and configuration will not be made available by NixOS itself.
         '';
@@ -137,7 +138,7 @@ in
         type = types.package;
         default = pkgs.nix;
         defaultText = literalExpression "pkgs.nix";
-        description = ''
+        description = lib.mdDoc ''
           This option specifies the Nix package instance to use throughout the system.
         '';
       };
@@ -145,9 +146,9 @@ in
       distributedBuilds = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to distribute builds to the machines listed in
-          <option>nix.buildMachines</option>.
+          {option}`nix.buildMachines`.
         '';
       };
 
@@ -155,30 +156,29 @@ in
         type = types.enum [ "other" "batch" "idle" ];
         default = "other";
         example = "batch";
-        description = ''
+        description = lib.mdDoc ''
           Nix daemon process CPU scheduling policy. This policy propagates to
-          build processes. <literal>other</literal> is the default scheduling
-          policy for regular tasks. The <literal>batch</literal> policy is
-          similar to <literal>other</literal>, but optimised for
-          non-interactive tasks. <literal>idle</literal> is for extremely
+          build processes. `other` is the default scheduling
+          policy for regular tasks. The `batch` policy is
+          similar to `other`, but optimised for
+          non-interactive tasks. `idle` is for extremely
           low-priority tasks that should only be run when no other task
           requires CPU time.
 
-          Please note that while using the <literal>idle</literal> policy may
+          Please note that while using the `idle` policy may
           greatly improve responsiveness of a system performing expensive
           builds, it may also slow down and potentially starve crucial
           configuration updates during load.
 
-          <literal>idle</literal> may therefore be a sensible policy for
+          `idle` may therefore be a sensible policy for
           systems that experience only intermittent phases of high CPU load,
           such as desktop or portable computers used interactively. Other
-          systems should use the <literal>other</literal> or
-          <literal>batch</literal> policy instead.
+          systems should use the `other` or
+          `batch` policy instead.
 
           For more fine-grained resource control, please refer to
-          <citerefentry><refentrytitle>systemd.resource-control
-          </refentrytitle><manvolnum>5</manvolnum></citerefentry> and adjust
-          <option>systemd.services.nix-daemon</option> directly.
+          {manpage}`systemd.resource-control(5)` and adjust
+          {option}`systemd.services.nix-daemon` directly.
       '';
       };
 
@@ -186,30 +186,30 @@ in
         type = types.enum [ "best-effort" "idle" ];
         default = "best-effort";
         example = "idle";
-        description = ''
+        description = lib.mdDoc ''
           Nix daemon process I/O scheduling class. This class propagates to
-          build processes. <literal>best-effort</literal> is the default
-          class for regular tasks. The <literal>idle</literal> class is for
+          build processes. `best-effort` is the default
+          class for regular tasks. The `idle` class is for
           extremely low-priority tasks that should only perform I/O when no
           other task does.
 
-          Please note that while using the <literal>idle</literal> scheduling
+          Please note that while using the `idle` scheduling
           class can improve responsiveness of a system performing expensive
           builds, it might also slow down or starve crucial configuration
           updates during load.
 
-          <literal>idle</literal> may therefore be a sensible class for
+          `idle` may therefore be a sensible class for
           systems that experience only intermittent phases of high I/O load,
           such as desktop or portable computers used interactively. Other
-          systems should use the <literal>best-effort</literal> class.
+          systems should use the `best-effort` class.
       '';
       };
 
       daemonIOSchedPriority = mkOption {
         type = types.int;
-        default = 0;
+        default = 4;
         example = 1;
-        description = ''
+        description = lib.mdDoc ''
           Nix daemon process I/O scheduling priority. This priority propagates
           to build processes. The supported priorities depend on the
           scheduling policy: With idle, priorities are not used in scheduling
@@ -224,18 +224,31 @@ in
             hostName = mkOption {
               type = types.str;
               example = "nixbuilder.example.org";
-              description = ''
+              description = lib.mdDoc ''
                 The hostname of the build machine.
               '';
             };
+            protocol = mkOption {
+              type = types.enum [ null "ssh" "ssh-ng" ];
+              default = "ssh";
+              example = "ssh-ng";
+              description = lib.mdDoc ''
+                The protocol used for communicating with the build machine.
+                Use `ssh-ng` if your remote builder and your
+                local Nix version support that improved protocol.
+
+                Use `null` when trying to change the special localhost builder
+                without a protocol which is for example used by hydra.
+              '';
+            };
             system = mkOption {
               type = types.nullOr types.str;
               default = null;
               example = "x86_64-linux";
-              description = ''
+              description = lib.mdDoc ''
                 The system type the build machine can execute derivations on.
-                Either this attribute or <varname>systems</varname> must be
-                present, where <varname>system</varname> takes precedence if
+                Either this attribute or {var}`systems` must be
+                present, where {var}`system` takes precedence if
                 both are set.
               '';
             };
@@ -243,10 +256,10 @@ in
               type = types.listOf types.str;
               default = [ ];
               example = [ "x86_64-linux" "aarch64-linux" ];
-              description = ''
+              description = lib.mdDoc ''
                 The system types the build machine can execute derivations on.
-                Either this attribute or <varname>system</varname> must be
-                present, where <varname>system</varname> takes precedence if
+                Either this attribute or {var}`system` must be
+                present, where {var}`system` takes precedence if
                 both are set.
               '';
             };
@@ -254,18 +267,18 @@ in
               type = types.nullOr types.str;
               default = null;
               example = "builder";
-              description = ''
+              description = lib.mdDoc ''
                 The username to log in as on the remote host. This user must be
                 able to log in and run nix commands non-interactively. It must
                 also be privileged to build derivations, so must be included in
-                <option>nix.settings.trusted-users</option>.
+                {option}`nix.settings.trusted-users`.
               '';
             };
             sshKey = mkOption {
               type = types.nullOr types.str;
               default = null;
               example = "/root/.ssh/id_buildhost_builduser";
-              description = ''
+              description = lib.mdDoc ''
                 The path to the SSH private key with which to authenticate on
                 the build machine. The private key must not have a passphrase.
                 If null, the building user (root on NixOS machines) must have an
@@ -278,7 +291,7 @@ in
             maxJobs = mkOption {
               type = types.int;
               default = 1;
-              description = ''
+              description = lib.mdDoc ''
                 The number of concurrent jobs the build machine supports. The
                 build machine will enforce its own limits, but this allows hydra
                 to schedule better since there is no work-stealing between build
@@ -288,7 +301,7 @@ in
             speedFactor = mkOption {
               type = types.int;
               default = 1;
-              description = ''
+              description = lib.mdDoc ''
                 The relative speed of this builder. This is an arbitrary integer
                 that indicates the speed of this builder, relative to other
                 builders. Higher is faster.
@@ -298,18 +311,18 @@ in
               type = types.listOf types.str;
               default = [ ];
               example = [ "big-parallel" ];
-              description = ''
+              description = lib.mdDoc ''
                 A list of features mandatory for this builder. The builder will
                 be ignored for derivations that don't require all features in
                 this list. All mandatory features are automatically included in
-                <varname>supportedFeatures</varname>.
+                {var}`supportedFeatures`.
               '';
             };
             supportedFeatures = mkOption {
               type = types.listOf types.str;
               default = [ ];
               example = [ "kvm" "big-parallel" ];
-              description = ''
+              description = lib.mdDoc ''
                 A list of features supported by this builder. The builder will
                 be ignored for derivations that require features not in this
                 list.
@@ -318,18 +331,18 @@ in
             publicHostKey = mkOption {
               type = types.nullOr types.str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The (base64-encoded) public host key of this builder. The field
-                is calculated via <command>base64 -w0 /etc/ssh/ssh_host_type_key.pub</command>.
+                is calculated via {command}`base64 -w0 /etc/ssh/ssh_host_type_key.pub`.
                 If null, SSH will use its regular known-hosts file when connecting.
               '';
             };
           };
         });
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           This option lists the machines to be used if distributed builds are
-          enabled (see <option>nix.distributedBuilds</option>).
+          enabled (see {option}`nix.distributedBuilds`).
           Nix will perform derivations on those machines via SSH by copying the
           inputs to the Nix store on the remote machine, starting the build,
           then copying the output back to the local Nix store.
@@ -341,30 +354,19 @@ in
         type = types.attrs;
         internal = true;
         default = { };
-        description = "Environment variables used by Nix.";
+        description = lib.mdDoc "Environment variables used by Nix.";
       };
 
       nrBuildUsers = mkOption {
         type = types.int;
-        description = ''
-          Number of <literal>nixbld</literal> user accounts created to
+        description = lib.mdDoc ''
+          Number of `nixbld` user accounts created to
           perform secure concurrent builds.  If you receive an error
           message saying that “all build users are currently in use”,
           you should increase this value.
         '';
       };
 
-      readOnlyStore = mkOption {
-        type = types.bool;
-        default = true;
-        description = ''
-          If set, NixOS will enforce the immutability of the Nix store
-          by making <filename>/nix/store</filename> a read-only bind
-          mount.  Nix will automatically make the store writable when
-          needed.
-        '';
-      };
-
       nixPath = mkOption {
         type = types.listOf types.str;
         default = [
@@ -372,19 +374,26 @@ in
           "nixos-config=/etc/nixos/configuration.nix"
           "/nix/var/nix/profiles/per-user/root/channels"
         ];
-        description = ''
+        description = lib.mdDoc ''
           The default Nix expression search path, used by the Nix
           evaluator to look up paths enclosed in angle brackets
-          (e.g. <literal>&lt;nixpkgs&gt;</literal>).
+          (e.g. `<nixpkgs>`).
         '';
       };
 
       checkConfig = mkOption {
         type = types.bool;
         default = true;
-        description = ''
-          If enabled (the default), checks for data type mismatches and that Nix
-          can parse the generated nix.conf.
+        description = lib.mdDoc ''
+          If enabled, checks that Nix can parse the generated nix.conf.
+        '';
+      };
+
+      checkAllErrors = mkOption {
+        type = types.bool;
+        default = true;
+        description = lib.mdDoc ''
+          If enabled, checks the nix.conf parsing for any kind of error. When disabled, checks only for unknown settings.
         '';
       };
 
@@ -395,6 +404,7 @@ in
               str
               int
               bool
+              path
               package
             ]);
           in
@@ -404,45 +414,46 @@ in
               from = mkOption {
                 type = referenceAttrs;
                 example = { type = "indirect"; id = "nixpkgs"; };
-                description = "The flake reference to be rewritten.";
+                description = lib.mdDoc "The flake reference to be rewritten.";
               };
               to = mkOption {
                 type = referenceAttrs;
                 example = { type = "github"; owner = "my-org"; repo = "my-nixpkgs"; };
-                description = "The flake reference <option>from></option> is rewritten to.";
+                description = lib.mdDoc "The flake reference {option}`from` is rewritten to.";
               };
               flake = mkOption {
                 type = types.nullOr types.attrs;
                 default = null;
                 example = literalExpression "nixpkgs";
-                description = ''
-                  The flake input <option>from></option> is rewritten to.
+                description = lib.mdDoc ''
+                  The flake input {option}`from` is rewritten to.
                 '';
               };
               exact = mkOption {
                 type = types.bool;
                 default = true;
-                description = ''
-                  Whether the <option>from</option> reference needs to match exactly. If set,
-                  a <option>from</option> reference like <literal>nixpkgs</literal> does not
-                  match with a reference like <literal>nixpkgs/nixos-20.03</literal>.
+                description = lib.mdDoc ''
+                  Whether the {option}`from` reference needs to match exactly. If set,
+                  a {option}`from` reference like `nixpkgs` does not
+                  match with a reference like `nixpkgs/nixos-20.03`.
                 '';
               };
             };
             config = {
               from = mkDefault { type = "indirect"; id = name; };
-              to = mkIf (config.flake != null) (mkDefault
+              to = mkIf (config.flake != null) (mkDefault (
                 {
                   type = "path";
                   path = config.flake.outPath;
                 } // filterAttrs
-                (n: _: n == "lastModified" || n == "rev" || n == "revCount" || n == "narHash")
-                config.flake);
+                  (n: _: n == "lastModified" || n == "rev" || n == "revCount" || n == "narHash")
+                  config.flake
+              ));
             };
           }
         ));
         default = { };
-        description = ''
+        description = lib.mdDoc ''
           A system-wide flake registry.
         '';
       };
@@ -454,7 +465,7 @@ in
           keep-outputs = true
           keep-derivations = true
         '';
-        description = "Additional text appended to <filename>nix.conf</filename>.";
+        description = lib.mdDoc "Additional text appended to {file}`nix.conf`.";
       };
 
       settings = mkOption {
@@ -466,7 +477,7 @@ in
               type = types.either types.int (types.enum [ "auto" ]);
               default = "auto";
               example = 64;
-              description = ''
+              description = lib.mdDoc ''
                 This option defines the maximum number of jobs that Nix will try to
                 build in parallel. The default is auto, which means it will use all
                 available logical cores. It is recommend to set it to the total
@@ -479,7 +490,7 @@ in
               type = types.bool;
               default = false;
               example = true;
-              description = ''
+              description = lib.mdDoc ''
                 If set to true, Nix automatically detects files in the store that have
                 identical contents, and replaces them with hard links to a single copy.
                 This saves disk space. If set to false (the default), you can still run
@@ -491,7 +502,7 @@ in
               type = types.int;
               default = 0;
               example = 64;
-              description = ''
+              description = lib.mdDoc ''
                 This option defines the maximum number of concurrent tasks during
                 one build. It affects, e.g., -j option for make.
                 The special value 0 means that the builder should use all
@@ -504,7 +515,7 @@ in
             sandbox = mkOption {
               type = types.either types.bool (types.enum [ "relaxed" ]);
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 If set, Nix will perform builds in a sandboxed environment that it
                 will set up automatically for each build. This prevents impurities
                 in builds by disallowing access to dependencies outside of the Nix
@@ -520,7 +531,7 @@ in
               type = types.listOf types.str;
               default = [ ];
               example = [ "/dev" "/proc" ];
-              description = ''
+              description = lib.mdDoc ''
                 Directories from the host filesystem to be included
                 in the sandbox.
               '';
@@ -528,7 +539,7 @@ in
 
             substituters = mkOption {
               type = types.listOf types.str;
-              description = ''
+              description = lib.mdDoc ''
                 List of binary cache URLs used to obtain pre-built binaries
                 of Nix packages.
 
@@ -540,21 +551,21 @@ in
               type = types.listOf types.str;
               default = [ ];
               example = [ "https://hydra.nixos.org/" ];
-              description = ''
+              description = lib.mdDoc ''
                 List of binary cache URLs that non-root users can use (in
                 addition to those specified using
-                <option>nix.settings.substituters</option>) by passing
-                <literal>--option binary-caches</literal> to Nix commands.
+                {option}`nix.settings.substituters`) by passing
+                `--option binary-caches` to Nix commands.
               '';
             };
 
             require-sigs = mkOption {
               type = types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 If enabled (the default), Nix will only download binaries from binary caches if
                 they are cryptographically signed with any of the keys listed in
-                <option>nix.settings.trusted-public-keys</option>. If disabled, signatures are neither
+                {option}`nix.settings.trusted-public-keys`. If disabled, signatures are neither
                 required nor checked, so it's strongly recommended that you use only
                 trustworthy caches and https to prevent man-in-the-middle attacks.
               '';
@@ -563,13 +574,13 @@ in
             trusted-public-keys = mkOption {
               type = types.listOf types.str;
               example = [ "hydra.nixos.org-1:CNHJZBh9K4tP3EKF6FkkgeVYsS3ohTl+oS0Qa8bezVs=" ];
-              description = ''
+              description = lib.mdDoc ''
                 List of public keys used to sign binary caches. If
-                <option>nix.settings.trusted-public-keys</option> is enabled,
+                {option}`nix.settings.trusted-public-keys` is enabled,
                 then Nix will use a binary from a binary cache if and only
-                if it is signed by <emphasis>any</emphasis> of the keys
+                if it is signed by *any* of the keys
                 listed here. By default, only the key for
-                <uri>cache.nixos.org</uri> is included.
+                `cache.nixos.org` is included.
               '';
             };
 
@@ -577,13 +588,13 @@ in
               type = types.listOf types.str;
               default = [ "root" ];
               example = [ "root" "alice" "@wheel" ];
-              description = ''
+              description = lib.mdDoc ''
                 A list of names of users that have additional rights when
                 connecting to the Nix daemon, such as the ability to specify
                 additional binary caches, or to import unsigned NARs. You
                 can also specify groups by prefixing them with
-                <literal>@</literal>; for instance,
-                <literal>@wheel</literal> means all users in the wheel
+                `@`; for instance,
+                `@wheel` means all users in the wheel
                 group.
               '';
             };
@@ -591,13 +602,13 @@ in
             system-features = mkOption {
               type = types.listOf types.str;
               example = [ "kvm" "big-parallel" "gccarch-skylake" ];
-              description = ''
+              description = lib.mdDoc ''
                 The set of features supported by the machine. Derivations
                 can express dependencies on system features through the
-                <literal>requiredSystemFeatures</literal> attribute.
+                `requiredSystemFeatures` attribute.
 
-                By default, pseudo-features <literal>nixos-test</literal>, <literal>benchmark</literal>,
-                and <literal>big-parallel</literal> used in Nixpkgs are set, <literal>kvm</literal>
+                By default, pseudo-features `nixos-test`, `benchmark`,
+                and `big-parallel` used in Nixpkgs are set, `kvm`
                 is also included in it is avaliable.
               '';
             };
@@ -606,13 +617,13 @@ in
               type = types.listOf types.str;
               default = [ "*" ];
               example = [ "@wheel" "@builders" "alice" "bob" ];
-              description = ''
+              description = lib.mdDoc ''
                 A list of names of users (separated by whitespace) that are
                 allowed to connect to the Nix daemon. As with
-                <option>nix.settings.trusted-users</option>, you can specify groups by
-                prefixing them with <literal>@</literal>. Also, you can
-                allow all users by specifying <literal>*</literal>. The
-                default is <literal>*</literal>. Note that trusted users are
+                {option}`nix.settings.trusted-users`, you can specify groups by
+                prefixing them with `@`. Also, you can
+                allow all users by specifying `*`. The
+                default is `*`. Note that trusted users are
                 always allowed to connect.
               '';
             };
@@ -628,22 +639,17 @@ in
             sandbox-paths = { "/bin/sh" = "''${pkgs.busybox-sandbox-shell.out}/bin/busybox"; };
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Configuration for Nix, see
-          <link xlink:href="https://nixos.org/manual/nix/stable/#sec-conf-file"/> or
-          <citerefentry>
-            <refentrytitle>nix.conf</refentrytitle>
-            <manvolnum>5</manvolnum>
-          </citerefentry> for avalaible options.
+          <https://nixos.org/manual/nix/stable/#sec-conf-file> or
+          {manpage}`nix.conf(5)` for avalaible options.
           The value declared here will be translated directly to the key-value pairs Nix expects.
-          </para>
-          <para>
-          You can use <command>nix-instantiate --eval --strict '&lt;nixpkgs/nixos&gt;' -A config.nix.settings</command>
+
+          You can use {command}`nix-instantiate --eval --strict '<nixpkgs/nixos>' -A config.nix.settings`
           to view the current value. By default it is empty.
-          </para>
-          <para>
-          Nix configurations defined under <option>nix.*</option> will be translated and applied to this
-          option. In addition, configuration specified in <option>nix.extraOptions</option> which will be appended
+
+          Nix configurations defined under {option}`nix.*` will be translated and applied to this
+          option. In addition, configuration specified in {option}`nix.extraOptions` which will be appended
           verbatim to the resulting config file.
         '';
       };
@@ -675,13 +681,15 @@ in
         concatMapStrings
           (machine:
             (concatStringsSep " " ([
-              "${optionalString (machine.sshUser != null) "${machine.sshUser}@"}${machine.hostName}"
+              "${optionalString (machine.protocol != null) "${machine.protocol}://"}${optionalString (machine.sshUser != null) "${machine.sshUser}@"}${machine.hostName}"
               (if machine.system != null then machine.system else if machine.systems != [ ] then concatStringsSep "," machine.systems else "-")
               (if machine.sshKey != null then machine.sshKey else "-")
               (toString machine.maxJobs)
               (toString machine.speedFactor)
-              (concatStringsSep "," (machine.supportedFeatures ++ machine.mandatoryFeatures))
-              (concatStringsSep "," machine.mandatoryFeatures)
+              (let res = (machine.supportedFeatures ++ machine.mandatoryFeatures);
+               in if (res == []) then "-" else (concatStringsSep "," res))
+              (let res = machine.mandatoryFeatures;
+               in if (res == []) then "-" else (concatStringsSep "," machine.mandatoryFeatures))
             ]
             ++ optional (isNixAtLeast "2.4pre") (if machine.publicHostKey != null then machine.publicHostKey else "-")))
             + "\n"
@@ -708,6 +716,14 @@ in
 
     systemd.packages = [ nixPackage ];
 
+    # Will only work once https://github.com/NixOS/nix/pull/6285 is merged
+    # systemd.tmpfiles.packages = [ nixPackage ];
+
+    # Can be dropped for Nix > https://github.com/NixOS/nix/pull/6285
+    systemd.tmpfiles.rules = [
+      "d /nix/var/nix/daemon-socket 0755 root root - -"
+    ];
+
     systemd.sockets.nix-daemon.wantedBy = [ "sockets.target" ];
 
     systemd.services.nix-daemon =
@@ -726,7 +742,7 @@ in
             CPUSchedulingPolicy = cfg.daemonCPUSchedPolicy;
             IOSchedulingClass = cfg.daemonIOSchedClass;
             IOSchedulingPriority = cfg.daemonIOSchedPriority;
-            LimitNOFILE = 4096;
+            LimitNOFILE = 1048576;
           };
 
         restartTriggers = [ nixConf ];
diff --git a/nixos/modules/services/misc/nix-gc.nix b/nixos/modules/services/misc/nix-gc.nix
index b4b4b55a6c8..97596d28cd8 100644
--- a/nixos/modules/services/misc/nix-gc.nix
+++ b/nixos/modules/services/misc/nix-gc.nix
@@ -17,20 +17,19 @@ in
       automatic = mkOption {
         default = false;
         type = types.bool;
-        description = "Automatically run the garbage collector at a specific time.";
+        description = lib.mdDoc "Automatically run the garbage collector at a specific time.";
       };
 
       dates = mkOption {
         type = types.str;
         default = "03:15";
         example = "weekly";
-        description = ''
+        description = lib.mdDoc ''
           How often or when garbage collection is performed. For most desktop and server systems
           a sufficient garbage collection is once a week.
 
           The format is described in
-          <citerefentry><refentrytitle>systemd.time</refentrytitle>
-          <manvolnum>7</manvolnum></citerefentry>.
+          {manpage}`systemd.time(7)`.
         '';
       };
 
@@ -38,12 +37,11 @@ in
         default = "0";
         type = types.str;
         example = "45min";
-        description = ''
-          Add a randomized delay before each automatic upgrade.
+        description = lib.mdDoc ''
+          Add a randomized delay before each garbage collection.
           The delay will be chosen between zero and this value.
           This value must be a time span in the format specified by
-          <citerefentry><refentrytitle>systemd.time</refentrytitle>
-          <manvolnum>7</manvolnum></citerefentry>
+          {manpage}`systemd.time(7)`
         '';
       };
 
@@ -51,7 +49,7 @@ in
         default = true;
         type = types.bool;
         example = false;
-        description = ''
+        description = lib.mdDoc ''
           Takes a boolean argument. If true, the time when the service
           unit was last triggered is stored on disk. When the timer is
           activated, the service unit is triggered immediately if it
@@ -67,8 +65,8 @@ in
         default = "";
         example = "--max-freed $((64 * 1024**3))";
         type = types.str;
-        description = ''
-          Options given to <filename>nix-collect-garbage</filename> when the
+        description = lib.mdDoc ''
+          Options given to {file}`nix-collect-garbage` when the
           garbage collector is run automatically.
         '';
       };
diff --git a/nixos/modules/services/misc/nix-optimise.nix b/nixos/modules/services/misc/nix-optimise.nix
index acf8177b146..db8148c060e 100644
--- a/nixos/modules/services/misc/nix-optimise.nix
+++ b/nixos/modules/services/misc/nix-optimise.nix
@@ -17,16 +17,15 @@ in
       automatic = mkOption {
         default = false;
         type = types.bool;
-        description = "Automatically run the nix store optimiser at a specific time.";
+        description = lib.mdDoc "Automatically run the nix store optimiser at a specific time.";
       };
 
       dates = mkOption {
         default = ["03:45"];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specification (in the format described by
-          <citerefentry><refentrytitle>systemd.time</refentrytitle>
-          <manvolnum>7</manvolnum></citerefentry>) of the time at
+          {manpage}`systemd.time(7)`) of the time at
           which the optimiser will run.
         '';
       };
diff --git a/nixos/modules/services/misc/nix-ssh-serve.nix b/nixos/modules/services/misc/nix-ssh-serve.nix
index 355fad5db46..b656692ca01 100644
--- a/nixos/modules/services/misc/nix-ssh-serve.nix
+++ b/nixos/modules/services/misc/nix-ssh-serve.nix
@@ -14,26 +14,26 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable serving the Nix store as a remote store via SSH.";
+        description = lib.mdDoc "Whether to enable serving the Nix store as a remote store via SSH.";
       };
 
       write = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable writing to the Nix store as a remote store via SSH. Note: the sshServe user is named nix-ssh and is not a trusted-user. nix-ssh should be added to the <option>nix.settings.trusted-users</option> option in most use cases, such as allowing remote building of derivations.";
+        description = lib.mdDoc "Whether to enable writing to the Nix store as a remote store via SSH. Note: the sshServe user is named nix-ssh and is not a trusted-user. nix-ssh should be added to the {option}`nix.settings.trusted-users` option in most use cases, such as allowing remote building of derivations.";
       };
 
       keys = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "ssh-dss AAAAB3NzaC1k... alice@example.org" ];
-        description = "A list of SSH public keys allowed to access the binary cache via SSH.";
+        description = lib.mdDoc "A list of SSH public keys allowed to access the binary cache via SSH.";
       };
 
       protocol = mkOption {
         type = types.enum [ "ssh" "ssh-ng" ];
         default = "ssh";
-        description = "The specific Nix-over-SSH protocol to use.";
+        description = lib.mdDoc "The specific Nix-over-SSH protocol to use.";
       };
 
     };
diff --git a/nixos/modules/services/misc/novacomd.nix b/nixos/modules/services/misc/novacomd.nix
index 7cfc68d2b67..bde8328d46f 100644
--- a/nixos/modules/services/misc/novacomd.nix
+++ b/nixos/modules/services/misc/novacomd.nix
@@ -10,7 +10,7 @@ in {
 
   options = {
     services.novacomd = {
-      enable = mkEnableOption "Novacom service for connecting to WebOS devices";
+      enable = mkEnableOption (lib.mdDoc "Novacom service for connecting to WebOS devices");
     };
   };
 
diff --git a/nixos/modules/services/misc/ntfy-sh.nix b/nixos/modules/services/misc/ntfy-sh.nix
new file mode 100644
index 00000000000..9d52fcf2536
--- /dev/null
+++ b/nixos/modules/services/misc/ntfy-sh.nix
@@ -0,0 +1,100 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.ntfy-sh;
+
+  settingsFormat = pkgs.formats.yaml { };
+in
+
+{
+  options.services.ntfy-sh = {
+    enable = mkEnableOption (mdDoc "[ntfy-sh](https://ntfy.sh), a push notification service");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.ntfy-sh;
+      defaultText = literalExpression "pkgs.ntfy-sh";
+      description = mdDoc "The ntfy.sh package to use.";
+    };
+
+    user = mkOption {
+      default = "ntfy-sh";
+      type = types.str;
+      description = lib.mdDoc "User the ntfy-sh server runs under.";
+    };
+
+    group = mkOption {
+      default = "ntfy-sh";
+      type = types.str;
+      description = lib.mdDoc "Primary group of ntfy-sh user.";
+    };
+
+    settings = mkOption {
+      type = types.submodule { freeformType = settingsFormat.type; };
+
+      default = { };
+
+      example = literalExpression ''
+        {
+          listen-http = ":8080";
+        }
+      '';
+
+      description = mdDoc ''
+        Configuration for ntfy.sh, supported values are [here](https://ntfy.sh/docs/config/#config-options).
+      '';
+    };
+  };
+
+  config =
+    let
+      configuration = settingsFormat.generate "server.yml" cfg.settings;
+    in
+    mkIf cfg.enable {
+      # to configure access control via the cli
+      environment = {
+        etc."ntfy/server.yml".source = configuration;
+        systemPackages = [ cfg.package ];
+      };
+
+      systemd.services.ntfy-sh = {
+        description = "Push notifications server";
+
+        wantedBy = [ "multi-user.target" ];
+        after = [ "network.target" ];
+
+        serviceConfig = {
+          ExecStart = "${cfg.package}/bin/ntfy serve -c ${configuration}";
+          User = cfg.user;
+
+          AmbientCapabilities = "CAP_NET_BIND_SERVICE";
+          PrivateTmp = true;
+          NoNewPrivileges = true;
+          CapabilityBoundingSet = "CAP_NET_BIND_SERVICE";
+          ProtectSystem = "full";
+          ProtectKernelTunables = true;
+          ProtectKernelModules = true;
+          ProtectKernelLogs = true;
+          ProtectControlGroups = true;
+          PrivateDevices = true;
+          RestrictSUIDSGID = true;
+          RestrictNamespaces = true;
+          RestrictRealtime = true;
+          MemoryDenyWriteExecute = true;
+        };
+      };
+
+      users.groups = optionalAttrs (cfg.group == "ntfy-sh") {
+        ntfy-sh = { };
+      };
+
+      users.users = optionalAttrs (cfg.user == "ntfy-sh") {
+        ntfy-sh = {
+          isSystemUser = true;
+          group = cfg.group;
+        };
+      };
+    };
+}
diff --git a/nixos/modules/services/misc/nzbget.nix b/nixos/modules/services/misc/nzbget.nix
index 27c5f2e395f..d02fda62fa4 100644
--- a/nixos/modules/services/misc/nzbget.nix
+++ b/nixos/modules/services/misc/nzbget.nix
@@ -25,26 +25,26 @@ in
 
   options = {
     services.nzbget = {
-      enable = mkEnableOption "NZBGet";
+      enable = mkEnableOption (lib.mdDoc "NZBGet");
 
       user = mkOption {
         type = types.str;
         default = "nzbget";
-        description = "User account under which NZBGet runs";
+        description = lib.mdDoc "User account under which NZBGet runs";
       };
 
       group = mkOption {
         type = types.str;
         default = "nzbget";
-        description = "Group under which NZBGet runs";
+        description = lib.mdDoc "Group under which NZBGet runs";
       };
 
       settings = mkOption {
         type = with types; attrsOf (oneOf [ bool int str ]);
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           NZBGet configuration, passed via command line using switch -o. Refer to
-          <link xlink:href="https://github.com/nzbget/nzbget/blob/master/nzbget.conf"/>
+          <https://github.com/nzbget/nzbget/blob/master/nzbget.conf>
           for details on supported values.
         '';
         example = {
diff --git a/nixos/modules/services/misc/nzbhydra2.nix b/nixos/modules/services/misc/nzbhydra2.nix
index 500c40f117d..47d08135f57 100644
--- a/nixos/modules/services/misc/nzbhydra2.nix
+++ b/nixos/modules/services/misc/nzbhydra2.nix
@@ -7,26 +7,26 @@ let cfg = config.services.nzbhydra2;
 in {
   options = {
     services.nzbhydra2 = {
-      enable = mkEnableOption "NZBHydra2";
+      enable = mkEnableOption (lib.mdDoc "NZBHydra2");
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/nzbhydra2";
-        description = "The directory where NZBHydra2 stores its data files.";
+        description = lib.mdDoc "The directory where NZBHydra2 stores its data files.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
         description =
-          "Open ports in the firewall for the NZBHydra2 web interface.";
+          lib.mdDoc "Open ports in the firewall for the NZBHydra2 web interface.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.nzbhydra2;
         defaultText = literalExpression "pkgs.nzbhydra2";
-        description = "NZBHydra2 package to use.";
+        description = lib.mdDoc "NZBHydra2 package to use.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/octoprint.nix b/nixos/modules/services/misc/octoprint.nix
index cd846d3f268..c216c6fa2b7 100644
--- a/nixos/modules/services/misc/octoprint.nix
+++ b/nixos/modules/services/misc/octoprint.nix
@@ -17,7 +17,7 @@ let
 
   cfgUpdate = pkgs.writeText "octoprint-config.yaml" (builtins.toJSON fullConfig);
 
-  pluginsEnv = package.python.withPackages (ps: [ps.octoprint] ++ (cfg.plugins ps));
+  pluginsEnv = package.python.withPackages (ps: [ ps.octoprint ] ++ (cfg.plugins ps));
 
   package = pkgs.octoprint;
 
@@ -29,12 +29,12 @@ in
 
     services.octoprint = {
 
-      enable = mkEnableOption "OctoPrint, web interface for 3D printers";
+      enable = mkEnableOption (lib.mdDoc "OctoPrint, web interface for 3D printers");
 
       host = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           Host to bind OctoPrint to.
         '';
       };
@@ -42,41 +42,47 @@ in
       port = mkOption {
         type = types.port;
         default = 5000;
-        description = ''
+        description = lib.mdDoc ''
           Port to bind OctoPrint to.
         '';
       };
 
+      openFirewall = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc "Open ports in the firewall for OctoPrint.";
+      };
+
       user = mkOption {
         type = types.str;
         default = "octoprint";
-        description = "User for the daemon.";
+        description = lib.mdDoc "User for the daemon.";
       };
 
       group = mkOption {
         type = types.str;
         default = "octoprint";
-        description = "Group for the daemon.";
+        description = lib.mdDoc "Group for the daemon.";
       };
 
       stateDir = mkOption {
         type = types.path;
         default = "/var/lib/octoprint";
-        description = "State directory of the daemon.";
+        description = lib.mdDoc "State directory of the daemon.";
       };
 
       plugins = mkOption {
         type = types.functionTo (types.listOf types.package);
-        default = plugins: [];
+        default = plugins: [ ];
         defaultText = literalExpression "plugins: []";
         example = literalExpression "plugins: with plugins; [ themeify stlviewer ]";
-        description = "Additional plugins to be used. Available plugins are passed through the plugins input.";
+        description = lib.mdDoc "Additional plugins to be used. Available plugins are passed through the plugins input.";
       };
 
       extraConfig = mkOption {
         type = types.attrs;
-        default = {};
-        description = "Extra options which are added to OctoPrint's YAML configuration file.";
+        default = { };
+        description = lib.mdDoc "Extra options which are added to OctoPrint's YAML configuration file.";
       };
 
     };
@@ -128,6 +134,6 @@ in
       };
     };
 
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ];
   };
-
 }
diff --git a/nixos/modules/services/misc/ombi.nix b/nixos/modules/services/misc/ombi.nix
index b5882168e51..8bf6a9b116e 100644
--- a/nixos/modules/services/misc/ombi.nix
+++ b/nixos/modules/services/misc/ombi.nix
@@ -7,40 +7,40 @@ let cfg = config.services.ombi;
 in {
   options = {
     services.ombi = {
-      enable = mkEnableOption ''
+      enable = mkEnableOption (lib.mdDoc ''
         Ombi.
-        Optionally see <link xlink:href="https://docs.ombi.app/info/reverse-proxy"/>
+        Optionally see <https://docs.ombi.app/info/reverse-proxy>
         on how to set up a reverse proxy
-      '';
+      '');
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/ombi";
-        description = "The directory where Ombi stores its data files.";
+        description = lib.mdDoc "The directory where Ombi stores its data files.";
       };
 
       port = mkOption {
         type = types.port;
         default = 5000;
-        description = "The port for the Ombi web interface.";
+        description = lib.mdDoc "The port for the Ombi web interface.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the Ombi web interface.";
+        description = lib.mdDoc "Open ports in the firewall for the Ombi web interface.";
       };
 
       user = mkOption {
         type = types.str;
         default = "ombi";
-        description = "User account under which Ombi runs.";
+        description = lib.mdDoc "User account under which Ombi runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "ombi";
-        description = "Group under which Ombi runs.";
+        description = lib.mdDoc "Group under which Ombi runs.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/osrm.nix b/nixos/modules/services/misc/osrm.nix
index 79c347ab7e0..12c908a761e 100644
--- a/nixos/modules/services/misc/osrm.nix
+++ b/nixos/modules/services/misc/osrm.nix
@@ -11,44 +11,44 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable the OSRM service.";
+      description = lib.mdDoc "Enable the OSRM service.";
     };
 
     address = mkOption {
       type = types.str;
       default = "0.0.0.0";
-      description = "IP address on which the web server will listen.";
+      description = lib.mdDoc "IP address on which the web server will listen.";
     };
 
     port = mkOption {
-      type = types.int;
+      type = types.port;
       default = 5000;
-      description = "Port on which the web server will run.";
+      description = lib.mdDoc "Port on which the web server will run.";
     };
 
     threads = mkOption {
       type = types.int;
       default = 4;
-      description = "Number of threads to use.";
+      description = lib.mdDoc "Number of threads to use.";
     };
 
     algorithm = mkOption {
       type = types.enum [ "CH" "CoreCH" "MLD" ];
       default = "MLD";
-      description = "Algorithm to use for the data. Must be one of CH, CoreCH, MLD";
+      description = lib.mdDoc "Algorithm to use for the data. Must be one of CH, CoreCH, MLD";
     };
 
     extraFlags = mkOption {
       type = types.listOf types.str;
       default = [];
       example = [ "--max-table-size 1000" "--max-matching-size 1000" ];
-      description = "Extra command line arguments passed to osrm-routed";
+      description = lib.mdDoc "Extra command line arguments passed to osrm-routed";
     };
 
     dataFile = mkOption {
       type = types.path;
       example = "/var/lib/osrm/berlin-latest.osrm";
-      description = "Data file location";
+      description = lib.mdDoc "Data file location";
     };
 
   };
diff --git a/nixos/modules/services/misc/owncast.nix b/nixos/modules/services/misc/owncast.nix
index 0852335238f..01fe34cf50f 100644
--- a/nixos/modules/services/misc/owncast.nix
+++ b/nixos/modules/services/misc/owncast.nix
@@ -5,12 +5,12 @@ in {
 
   options.services.owncast = {
 
-    enable = mkEnableOption "owncast";
+    enable = mkEnableOption (lib.mdDoc "owncast");
 
     dataDir = mkOption {
       type = types.str;
       default = "/var/lib/owncast";
-      description = ''
+      description = lib.mdDoc ''
         The directory where owncast stores its data files. If left as the default value this directory will automatically be created before the owncast server starts, otherwise the sysadmin is responsible for ensuring the directory exists with appropriate ownership and permissions.
       '';
     };
@@ -18,7 +18,7 @@ in {
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Open the appropriate ports in the firewall for owncast.
       '';
     };
@@ -26,26 +26,26 @@ in {
     user = mkOption {
       type = types.str;
       default = "owncast";
-      description = "User account under which owncast runs.";
+      description = lib.mdDoc "User account under which owncast runs.";
     };
 
     group = mkOption {
       type = types.str;
       default = "owncast";
-      description = "Group under which owncast runs.";
+      description = lib.mdDoc "Group under which owncast runs.";
     };
 
     listen = mkOption {
       type = types.str;
       default = "127.0.0.1";
       example = "0.0.0.0";
-      description = "The IP address to bind the owncast web server to.";
+      description = lib.mdDoc "The IP address to bind the owncast web server to.";
     };
 
     port = mkOption {
       type = types.port;
       default = 8080;
-      description = ''
+      description = lib.mdDoc ''
         TCP port where owncast web-gui listens.
       '';
     };
@@ -53,7 +53,7 @@ in {
     rtmp-port = mkOption {
       type = types.port;
       default = 1935;
-      description = ''
+      description = lib.mdDoc ''
         TCP port where owncast rtmp service listens.
       '';
     };
diff --git a/nixos/modules/services/misc/packagekit.nix b/nixos/modules/services/misc/packagekit.nix
index 9191078ef9c..f3e6bf50e9b 100644
--- a/nixos/modules/services/misc/packagekit.nix
+++ b/nixos/modules/services/misc/packagekit.nix
@@ -39,22 +39,22 @@ in
   ];
 
   options.services.packagekit = {
-    enable = mkEnableOption ''
+    enable = mkEnableOption (lib.mdDoc ''
       PackageKit provides a cross-platform D-Bus abstraction layer for
       installing software. Software utilizing PackageKit can install
       software regardless of the package manager.
-    '';
+    '');
 
     settings = mkOption {
       type = iniFmt.type;
       default = { };
-      description = "Additional settings passed straight through to PackageKit.conf";
+      description = lib.mdDoc "Additional settings passed straight through to PackageKit.conf";
     };
 
     vendorSettings = mkOption {
       type = iniFmt.type;
       default = { };
-      description = "Additional settings passed straight through to Vendor.conf";
+      description = lib.mdDoc "Additional settings passed straight through to Vendor.conf";
     };
   };
 
diff --git a/nixos/modules/services/misc/paperless-ng.nix b/nixos/modules/services/misc/paperless.nix
index 11e44f5ece5..6a98d5cb686 100644
--- a/nixos/modules/services/misc/paperless-ng.nix
+++ b/nixos/modules/services/misc/paperless.nix
@@ -2,28 +2,33 @@
 
 with lib;
 let
-  cfg = config.services.paperless-ng;
+  cfg = config.services.paperless;
+  pkg = cfg.package;
 
   defaultUser = "paperless";
 
-  hasCustomRedis = hasAttr "PAPERLESS_REDIS" cfg.extraConfig;
+  # Don't start a redis instance if the user sets a custom redis connection
+  enableRedis = !hasAttr "PAPERLESS_REDIS" cfg.extraConfig;
+  redisServer = config.services.redis.servers.paperless;
 
   env = {
     PAPERLESS_DATA_DIR = cfg.dataDir;
     PAPERLESS_MEDIA_ROOT = cfg.mediaDir;
     PAPERLESS_CONSUMPTION_DIR = cfg.consumptionDir;
     GUNICORN_CMD_ARGS = "--bind=${cfg.address}:${toString cfg.port}";
+  } // optionalAttrs (config.time.timeZone != null) {
+    PAPERLESS_TIME_ZONE = config.time.timeZone;
+  } // optionalAttrs enableRedis {
+    PAPERLESS_REDIS = "unix://${redisServer.unixSocket}";
   } // (
     lib.mapAttrs (_: toString) cfg.extraConfig
-  ) // (optionalAttrs (!hasCustomRedis) {
-    PAPERLESS_REDIS = "unix://${config.services.redis.servers.paperless-ng.unixSocket}";
-  });
+  );
 
   manage = let
     setupEnv = lib.concatStringsSep "\n" (mapAttrsToList (name: val: "export ${name}=\"${val}\"") env);
   in pkgs.writeShellScript "manage" ''
     ${setupEnv}
-    exec ${cfg.package}/bin/paperless-ng "$@"
+    exec ${pkg}/bin/paperless-ngx "$@"
   '';
 
   # Secure the services
@@ -36,7 +41,7 @@ let
       "-/etc/hosts"
       "-/etc/localtime"
       "-/run/postgresql"
-    ] ++ (optional (!hasCustomRedis) config.services.redis.servers.paperless-ng.unixSocket);
+    ] ++ (optional enableRedis redisServer.unixSocket);
     BindPaths = [
       cfg.consumptionDir
       cfg.dataDir
@@ -53,7 +58,6 @@ let
     PrivateNetwork = true;
     PrivateTmp = true;
     PrivateUsers = true;
-    ProcSubset = "pid";
     ProtectClock = true;
     # Breaks if the home dir of the user is in /home
     # Also does not add much value in combination with the TemporaryFileSystem.
@@ -66,88 +70,88 @@ let
     ProtectKernelModules = true;
     ProtectKernelTunables = true;
     ProtectProc = "invisible";
+    # Don't restrict ProcSubset because django-q requires read access to /proc/stat
+    # to query CPU and memory information.
+    # Note that /proc only contains processes of user `paperless`, so this is safe.
+    # ProcSubset = "pid";
     RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
     RestrictNamespaces = true;
     RestrictRealtime = true;
     RestrictSUIDSGID = true;
-    SupplementaryGroups = optional (!hasCustomRedis) config.services.redis.servers.paperless-ng.user;
+    SupplementaryGroups = optional enableRedis redisServer.user;
     SystemCallArchitectures = "native";
-    SystemCallFilter = [ "@system-service" "~@privileged @resources @setuid @keyring" ];
+    SystemCallFilter = [ "@system-service" "~@privileged @setuid @keyring" ];
     # Does not work well with the temporary root
     #UMask = "0066";
   };
 in
 {
-  meta.maintainers = with maintainers; [ earvstedt Flakebi ];
+  meta.maintainers = with maintainers; [ erikarvstedt Flakebi ];
 
   imports = [
-    (mkRemovedOptionModule [ "services" "paperless"] ''
-      The paperless module has been removed as the upstream project died.
-      Users should migrate to the paperless-ng module (services.paperless-ng).
-      More information can be found in the NixOS 21.11 release notes.
-    '')
+    (mkRenamedOptionModule [ "services" "paperless-ng" ] [ "services" "paperless" ])
   ];
 
-  options.services.paperless-ng = {
+  options.services.paperless = {
     enable = mkOption {
       type = lib.types.bool;
       default = false;
-      description = ''
-        Enable Paperless-ng.
+      description = lib.mdDoc ''
+        Enable Paperless.
 
         When started, the Paperless database is automatically created if it doesn't
         exist and updated if the Paperless package has changed.
         Both tasks are achieved by running a Django migration.
 
         A script to manage the Paperless instance (by wrapping Django's manage.py) is linked to
-        <literal>''${dataDir}/paperless-ng-manage</literal>.
+        `''${dataDir}/paperless-manage`.
       '';
     };
 
     dataDir = mkOption {
       type = types.str;
       default = "/var/lib/paperless";
-      description = "Directory to store the Paperless data.";
+      description = lib.mdDoc "Directory to store the Paperless data.";
     };
 
     mediaDir = mkOption {
       type = types.str;
       default = "${cfg.dataDir}/media";
       defaultText = literalExpression ''"''${dataDir}/media"'';
-      description = "Directory to store the Paperless documents.";
+      description = lib.mdDoc "Directory to store the Paperless documents.";
     };
 
     consumptionDir = mkOption {
       type = types.str;
       default = "${cfg.dataDir}/consume";
       defaultText = literalExpression ''"''${dataDir}/consume"'';
-      description = "Directory from which new documents are imported.";
+      description = lib.mdDoc "Directory from which new documents are imported.";
     };
 
     consumptionDirIsPublic = mkOption {
       type = types.bool;
       default = false;
-      description = "Whether all users can write to the consumption dir.";
+      description = lib.mdDoc "Whether all users can write to the consumption dir.";
     };
 
     passwordFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      example = "/run/keys/paperless-ng-password";
-      description = ''
+      example = "/run/keys/paperless-password";
+      description = lib.mdDoc ''
         A file containing the superuser password.
 
         A superuser is required to access the web interface.
         If unset, you can create a superuser manually by running
-        <literal>''${dataDir}/paperless-ng-manage createsuperuser</literal>.
+        `''${dataDir}/paperless-manage createsuperuser`.
 
-        The default superuser name is <literal>admin</literal>. To change it, set
-        option <option>extraConfig.PAPERLESS_ADMIN_USER</option>.
+        The default superuser name is `admin`. To change it, set
+        option {option}`extraConfig.PAPERLESS_ADMIN_USER`.
         WARNING: When changing the superuser name after the initial setup, the old superuser
         will continue to exist.
 
         To disable login for the web interface, set the following:
-        <literal>extraConfig.PAPERLESS_AUTO_LOGIN_USERNAME = "admin";</literal>.
+        `extraConfig.PAPERLESS_AUTO_LOGIN_USERNAME = "admin";`.
         WARNING: Only use this on a trusted system without internet access to Paperless.
       '';
     };
@@ -155,48 +159,46 @@ in
     address = mkOption {
       type = types.str;
       default = "localhost";
-      description = "Web interface address.";
+      description = lib.mdDoc "Web interface address.";
     };
 
     port = mkOption {
       type = types.port;
       default = 28981;
-      description = "Web interface port.";
+      description = lib.mdDoc "Web interface port.";
     };
 
     extraConfig = mkOption {
       type = types.attrs;
       default = {};
-      description = ''
-        Extra paperless-ng config options.
+      description = lib.mdDoc ''
+        Extra paperless config options.
 
-        See <link xlink:href="https://paperless-ng.readthedocs.io/en/latest/configuration.html">the documentation</link>
+        See [the documentation](https://paperless-ngx.readthedocs.io/en/latest/configuration.html)
         for available options.
       '';
-      example = literalExpression ''
-        {
-          PAPERLESS_OCR_LANGUAGE = "deu+eng";
-        }
-      '';
+      example = {
+        PAPERLESS_OCR_LANGUAGE = "deu+eng";
+        PAPERLESS_DBHOST = "/run/postgresql";
+      };
     };
 
     user = mkOption {
       type = types.str;
       default = defaultUser;
-      description = "User under which Paperless runs.";
+      description = lib.mdDoc "User under which Paperless runs.";
     };
 
     package = mkOption {
       type = types.package;
-      default = pkgs.paperless-ng;
-      defaultText = literalExpression "pkgs.paperless-ng";
-      description = "The Paperless package to use.";
+      default = pkgs.paperless-ngx;
+      defaultText = literalExpression "pkgs.paperless-ngx";
+      description = lib.mdDoc "The Paperless package to use.";
     };
   };
 
   config = mkIf cfg.enable {
-    # Enable redis if no special url is set
-    services.redis.servers.paperless-ng.enable = mkIf (!hasCustomRedis) true;
+    services.redis.servers.paperless.enable = mkIf enableRedis true;
 
     systemd.tmpfiles.rules = [
       "d '${cfg.dataDir}' - ${cfg.user} ${config.users.users.${cfg.user}.group} - -"
@@ -208,27 +210,29 @@ in
       )
     ];
 
-    systemd.services.paperless-ng-server = {
-      description = "Paperless document server";
+    systemd.services.paperless-scheduler = {
+      description = "Paperless scheduler";
       serviceConfig = defaultServiceConfig // {
         User = cfg.user;
-        ExecStart = "${cfg.package}/bin/paperless-ng qcluster";
+        ExecStart = "${pkg}/bin/paperless-ngx qcluster";
         Restart = "on-failure";
         # The `mbind` syscall is needed for running the classifier.
         SystemCallFilter = defaultServiceConfig.SystemCallFilter ++ [ "mbind" ];
+        # Needs to talk to mail server for automated import rules
+        PrivateNetwork = false;
       };
       environment = env;
       wantedBy = [ "multi-user.target" ];
-      wants = [ "paperless-ng-consumer.service" "paperless-ng-web.service" ];
+      wants = [ "paperless-consumer.service" "paperless-web.service" ];
 
       preStart = ''
-        ln -sf ${manage} ${cfg.dataDir}/paperless-ng-manage
+        ln -sf ${manage} ${cfg.dataDir}/paperless-manage
 
         # Auto-migrate on first run or if the package has changed
         versionFile="${cfg.dataDir}/src-version"
-        if [[ $(cat "$versionFile" 2>/dev/null) != ${cfg.package} ]]; then
-          ${cfg.package}/bin/paperless-ng migrate
-          echo ${cfg.package} > "$versionFile"
+        if [[ $(cat "$versionFile" 2>/dev/null) != ${pkg} ]]; then
+          ${pkg}/bin/paperless-ngx migrate
+          echo ${pkg} > "$versionFile"
         fi
       ''
       + optionalString (cfg.passwordFile != null) ''
@@ -238,73 +242,70 @@ in
         superuserStateFile="${cfg.dataDir}/superuser-state"
 
         if [[ $(cat "$superuserStateFile" 2>/dev/null) != $superuserState ]]; then
-          ${cfg.package}/bin/paperless-ng manage_superuser
+          ${pkg}/bin/paperless-ngx manage_superuser
           echo "$superuserState" > "$superuserStateFile"
         fi
       '';
-    } // optionalAttrs (!hasCustomRedis) {
-      after = [ "redis-paperless-ng.service" ];
+    } // optionalAttrs enableRedis {
+      after = [ "redis-paperless.service" ];
     };
 
-    # Password copying can't be implemented as a privileged preStart script
-    # in 'paperless-ng-server' because 'defaultServiceConfig' limits the filesystem
-    # paths accessible by the service.
-    systemd.services.paperless-ng-copy-password = mkIf (cfg.passwordFile != null) {
-      requiredBy = [ "paperless-ng-server.service" ];
-      before = [ "paperless-ng-server.service" ];
+    # Reading the user-provided password file requires root access
+    systemd.services.paperless-copy-password = mkIf (cfg.passwordFile != null) {
+      requiredBy = [ "paperless-scheduler.service" ];
+      before = [ "paperless-scheduler.service" ];
       serviceConfig = {
         ExecStart = ''
           ${pkgs.coreutils}/bin/install --mode 600 --owner '${cfg.user}' --compare \
             '${cfg.passwordFile}' '${cfg.dataDir}/superuser-password'
         '';
         Type = "oneshot";
-        # Needs to talk to mail server for automated import rules
-        PrivateNetwork = false;
       };
     };
 
-    systemd.services.paperless-ng-consumer = {
+    systemd.services.paperless-consumer = {
       description = "Paperless document consumer";
       serviceConfig = defaultServiceConfig // {
         User = cfg.user;
-        ExecStart = "${cfg.package}/bin/paperless-ng document_consumer";
+        ExecStart = "${pkg}/bin/paperless-ngx document_consumer";
         Restart = "on-failure";
       };
       environment = env;
-      # Bind to `paperless-ng-server` so that the consumer never runs
+      # Bind to `paperless-scheduler` so that the consumer never runs
       # during migrations
-      bindsTo = [ "paperless-ng-server.service" ];
-      after = [ "paperless-ng-server.service" ];
+      bindsTo = [ "paperless-scheduler.service" ];
+      after = [ "paperless-scheduler.service" ];
     };
 
-    systemd.services.paperless-ng-web = {
+    systemd.services.paperless-web = {
       description = "Paperless web server";
       serviceConfig = defaultServiceConfig // {
         User = cfg.user;
         ExecStart = ''
-          ${pkgs.python3Packages.gunicorn}/bin/gunicorn \
-            -c ${cfg.package}/lib/paperless-ng/gunicorn.conf.py paperless.asgi:application
+          ${pkg.python.pkgs.gunicorn}/bin/gunicorn \
+            -c ${pkg}/lib/paperless-ngx/gunicorn.conf.py paperless.asgi:application
         '';
         Restart = "on-failure";
 
-        AmbientCapabilities = "CAP_NET_BIND_SERVICE";
-        CapabilityBoundingSet = "CAP_NET_BIND_SERVICE";
-        # gunicorn needs setuid
-        SystemCallFilter = defaultServiceConfig.SystemCallFilter ++ [ "@setuid" ];
+        # gunicorn needs setuid, liblapack needs mbind
+        SystemCallFilter = defaultServiceConfig.SystemCallFilter ++ [ "@setuid mbind" ];
         # Needs to serve web page
         PrivateNetwork = false;
+      } // lib.optionalAttrs (cfg.port < 1024) {
+        AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
+        CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
       };
       environment = env // {
-        PATH = mkForce cfg.package.path;
-        PYTHONPATH = "${cfg.package.pythonPath}:${cfg.package}/lib/paperless-ng/src";
+        PATH = mkForce pkg.path;
+        PYTHONPATH = "${pkg.python.pkgs.makePythonPath pkg.propagatedBuildInputs}:${pkg}/lib/paperless-ngx/src";
       };
       # Allow the web interface to access the private /tmp directory of the server.
       # This is required to support uploading files via the web interface.
-      unitConfig.JoinsNamespaceOf = "paperless-ng-server.service";
-      # Bind to `paperless-ng-server` so that the web server never runs
+      unitConfig.JoinsNamespaceOf = "paperless-scheduler.service";
+      # Bind to `paperless-scheduler` so that the web server never runs
       # during migrations
-      bindsTo = [ "paperless-ng-server.service" ];
-      after = [ "paperless-ng-server.service" ];
+      bindsTo = [ "paperless-scheduler.service" ];
+      after = [ "paperless-scheduler.service" ];
     };
 
     users = optionalAttrs (cfg.user == defaultUser) {
diff --git a/nixos/modules/services/misc/parsoid.nix b/nixos/modules/services/misc/parsoid.nix
index 09b7f977bfb..6f4a340c8a1 100644
--- a/nixos/modules/services/misc/parsoid.nix
+++ b/nixos/modules/services/misc/parsoid.nix
@@ -39,7 +39,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Parsoid -- bidirectional
           wikitext parser.
         '';
@@ -48,7 +48,7 @@ in
       wikis = mkOption {
         type = types.listOf (types.either types.str types.attrs);
         example = [ "http://localhost/api.php" ];
-        description = ''
+        description = lib.mdDoc ''
           Used MediaWiki API endpoints.
         '';
       };
@@ -56,7 +56,7 @@ in
       workers = mkOption {
         type = types.int;
         default = 2;
-        description = ''
+        description = lib.mdDoc ''
           Number of Parsoid workers.
         '';
       };
@@ -64,15 +64,15 @@ in
       interface = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = ''
+        description = lib.mdDoc ''
           Interface to listen on.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8000;
-        description = ''
+        description = lib.mdDoc ''
           Port to listen on.
         '';
       };
@@ -80,7 +80,7 @@ in
       extraConfig = mkOption {
         type = types.attrs;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to add to parsoid configuration.
         '';
       };
diff --git a/nixos/modules/services/misc/persistent-evdev.nix b/nixos/modules/services/misc/persistent-evdev.nix
new file mode 100644
index 00000000000..b1f367fec7f
--- /dev/null
+++ b/nixos/modules/services/misc/persistent-evdev.nix
@@ -0,0 +1,60 @@
+{ config, lib, pkgs, ... }:
+
+let
+  cfg = config.services.persistent-evdev;
+  settingsFormat = pkgs.formats.json {};
+
+  configFile = settingsFormat.generate "persistent-evdev-config" {
+    cache = "/var/cache/persistent-evdev";
+    devices = lib.mapAttrs (virt: phys: "/dev/input/by-id/${phys}") cfg.devices;
+  };
+in
+{
+  options.services.persistent-evdev = {
+    enable = lib.mkEnableOption (lib.mdDoc "virtual input devices that persist even if the backing device is hotplugged");
+
+    devices = lib.mkOption {
+      default = {};
+      type = with lib.types; attrsOf str;
+      description = lib.mdDoc ''
+        A set of virtual proxy device labels with backing physical device ids.
+
+        Physical devices should already exist in {file}`/dev/input/by-id/`.
+        Proxy devices will be automatically given a `uinput-` prefix.
+
+        See the [project page](https://github.com/aiberia/persistent-evdev#example-usage-with-libvirt)
+        for example configuration of virtual devices with libvirt
+        and remember to add `uinput-*` devices to the qemu
+        `cgroup_device_acl` list (see [](#opt-virtualisation.libvirtd.qemu.verbatimConfig)).
+      '';
+      example = lib.literalExpression ''
+        {
+          persist-mouse0 = "usb-Logitech_G403_Prodigy_Gaming_Mouse_078738533531-event-if01";
+          persist-mouse1 = "usb-Logitech_G403_Prodigy_Gaming_Mouse_078738533531-event-mouse";
+          persist-mouse2 = "usb-Logitech_G403_Prodigy_Gaming_Mouse_078738533531-if01-event-kbd";
+          persist-keyboard0 = "usb-Microsoft_Natural®_Ergonomic_Keyboard_4000-event-kbd";
+          persist-keyboard1 = "usb-Microsoft_Natural®_Ergonomic_Keyboard_4000-if01-event-kbd";
+        }
+      '';
+    };
+  };
+
+  config = lib.mkIf cfg.enable {
+
+    systemd.services.persistent-evdev = {
+      documentation = [ "https://github.com/aiberia/persistent-evdev/blob/master/README.md" ];
+      description = "Persistent evdev proxy";
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = {
+        Restart = "on-failure";
+        ExecStart = "${pkgs.persistent-evdev}/bin/persistent-evdev.py ${configFile}";
+        CacheDirectory = "persistent-evdev";
+      };
+    };
+
+    services.udev.packages = [ pkgs.persistent-evdev ];
+  };
+
+  meta.maintainers = with lib.maintainers; [ lodi ];
+}
diff --git a/nixos/modules/services/misc/pinnwand.nix b/nixos/modules/services/misc/pinnwand.nix
index cbc796c9a7c..5fca9f4125a 100644
--- a/nixos/modules/services/misc/pinnwand.nix
+++ b/nixos/modules/services/misc/pinnwand.nix
@@ -10,38 +10,75 @@ let
 in
 {
   options.services.pinnwand = {
-    enable = mkEnableOption "Pinnwand";
+    enable = mkEnableOption (lib.mdDoc "Pinnwand");
 
     port = mkOption {
       type = types.port;
-      description = "The port to listen on.";
+      description = lib.mdDoc "The port to listen on.";
       default = 8000;
     };
 
     settings = mkOption {
-      type = format.type;
-      description = ''
-        Your <filename>pinnwand.toml</filename> as a Nix attribute set. Look up
-        possible options in the <link xlink:href="https://github.com/supakeen/pinnwand/blob/master/pinnwand.toml-example">pinnwand.toml-example</link>.
-      '';
       default = {};
+      description = lib.mdDoc ''
+        Your {file}`pinnwand.toml` as a Nix attribute set. Look up
+        possible options in the [documentation](https://pinnwand.readthedocs.io/en/v${pkgs.pinnwand.version}/configuration.html).
+      '';
+      type = types.submodule {
+        freeformType = format.type;
+        options = {
+          database_uri = mkOption {
+            type = types.str;
+            default = "sqlite:////var/lib/pinnwand/pinnwand.db";
+            example = "sqlite:///:memory";
+            description = lib.mdDoc ''
+              Database URI compatible with [SQLAlchemyhttps://docs.sqlalchemy.org/en/14/core/engines.html#database-urls].
+
+              Additional packages may need to be introduced into the environment for certain databases.
+            '';
+          };
+
+          paste_size = mkOption {
+            type = types.ints.positive;
+            default = 262144;
+            example = 524288;
+            description = lib.mdDoc ''
+              Maximum size of a paste in bytes.
+            '';
+          };
+          paste_help = mkOption {
+            type = types.str;
+            default = ''
+              <p>Welcome to pinnwand, this site is a pastebin. It allows you to share code with others. If you write code in the text area below and press the paste button you will be given a link you can share with others so they can view your code as well.</p><p>People with the link can view your pasted code, only you can remove your paste and it expires automatically. Note that anyone could guess the URI to your paste so don't rely on it being private.</p>
+              '';
+            description = lib.mdDoc ''
+              Raw HTML help text shown in the header area.
+            '';
+          };
+          footer = mkOption {
+            type = types.str;
+            default = ''
+              View <a href="//github.com/supakeen/pinnwand" target="_BLANK">source code</a>, the <a href="/removal">removal</a> or <a href="/expiry">expiry</a> stories, or read the <a href="/about">about</a> page.
+            '';
+            description = lib.mdDoc ''
+              The footer in raw HTML.
+            '';
+          };
+        };
+      };
     };
   };
 
   config = mkIf cfg.enable {
-    services.pinnwand.settings = {
-      database_uri = mkDefault "sqlite:////var/lib/pinnwand/pinnwand.db";
-      paste_size = mkDefault 262144;
-      paste_help = mkDefault ''
-        <p>Welcome to pinnwand, this site is a pastebin. It allows you to share code with others. If you write code in the text area below and press the paste button you will be given a link you can share with others so they can view your code as well.</p><p>People with the link can view your pasted code, only you can remove your paste and it expires automatically. Note that anyone could guess the URI to your paste so don't rely on it being private.</p>
-      '';
-      footer = mkDefault ''
-        View <a href="//github.com/supakeen/pinnwand" target="_BLANK">source code</a>, the <a href="/removal">removal</a> or <a href="/expiry">expiry</a> stories, or read the <a href="/about">about</a> page.
-      '';
-    };
+    systemd.services.pinnwand = {
+      description = "Pinnwannd HTTP Server";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+
+      unitConfig.Documentation = "https://pinnwand.readthedocs.io/en/latest/";
 
-    systemd.services = let
-      hardeningOptions = {
+      serviceConfig = {
+        ExecStart = "${pkgs.pinnwand}/bin/pinnwand --configuration-path ${configFile} http --port ${toString cfg.port}";
         User = "pinnwand";
         DynamicUser = true;
 
@@ -72,32 +109,14 @@ in
         RestrictNamespaces = true;
         RestrictRealtime = true;
         SystemCallArchitectures = "native";
-        SystemCallFilter = "@system-service";
+        SystemCallFilter = [
+          "@system-service"
+          "~@privileged"
+        ];
         UMask = "0077";
       };
-
-      command = "${pkgs.pinnwand}/bin/pinnwand --configuration-path ${configFile}";
-    in {
-      pinnwand = {
-        description = "Pinnwannd HTTP Server";
-        after = [ "network.target" ];
-        wantedBy = [ "multi-user.target" ];
-
-        unitConfig.Documentation = "https://pinnwand.readthedocs.io/en/latest/";
-
-        serviceConfig = {
-          ExecStart = "${command} http --port ${toString(cfg.port)}";
-        } // hardeningOptions;
-      };
-
-      pinnwand-reaper = {
-        description = "Pinnwand Reaper";
-        startAt = "daily";
-
-        serviceConfig = {
-          ExecStart = "${command} -vvvv reap";  # verbosity increased to show number of deleted pastes
-        } // hardeningOptions;
-      };
     };
   };
+
+  meta.buildDocsInSandbox = false;
 }
diff --git a/nixos/modules/services/misc/plex.nix b/nixos/modules/services/misc/plex.nix
index 1cd8da768f4..7fc76028c02 100644
--- a/nixos/modules/services/misc/plex.nix
+++ b/nixos/modules/services/misc/plex.nix
@@ -12,12 +12,12 @@ in
 
   options = {
     services.plex = {
-      enable = mkEnableOption "Plex Media Server";
+      enable = mkEnableOption (lib.mdDoc "Plex Media Server");
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/plex";
-        description = ''
+        description = lib.mdDoc ''
           The directory where Plex stores its data files.
         '';
       };
@@ -25,7 +25,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for the media server.
         '';
       };
@@ -33,7 +33,7 @@ in
       user = mkOption {
         type = types.str;
         default = "plex";
-        description = ''
+        description = lib.mdDoc ''
           User account under which Plex runs.
         '';
       };
@@ -41,7 +41,7 @@ in
       group = mkOption {
         type = types.str;
         default = "plex";
-        description = ''
+        description = lib.mdDoc ''
           Group under which Plex runs.
         '';
       };
@@ -49,7 +49,7 @@ in
       extraPlugins = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of paths to extra plugin bundles to install in Plex's plugin
           directory. Every time the systemd unit for Plex starts up, all of the
           symlinks in Plex's plugin directory will be cleared and this module
@@ -73,7 +73,7 @@ in
       extraScanners = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of paths to extra scanners to install in Plex's scanners
           directory.
 
@@ -97,7 +97,7 @@ in
         type = types.package;
         default = pkgs.plex;
         defaultText = literalExpression "pkgs.plex";
-        description = ''
+        description = lib.mdDoc ''
           The Plex package to use. Plex subscribers may wish to use their own
           package here, pointing to subscriber-only server versions.
         '';
@@ -134,6 +134,7 @@ in
 
         ExecStart = "${cfg.package}/bin/plexmediaserver";
         KillSignal = "SIGQUIT";
+        PIDFile = "${cfg.dataDir}/Plex Media Server/plexmediaserver.pid";
         Restart = "on-failure";
       };
 
diff --git a/nixos/modules/services/misc/plikd.nix b/nixos/modules/services/misc/plikd.nix
index a62dbef1d2a..9b0825bf40c 100644
--- a/nixos/modules/services/misc/plikd.nix
+++ b/nixos/modules/services/misc/plikd.nix
@@ -11,19 +11,19 @@ in
 {
   options = {
     services.plikd = {
-      enable = mkEnableOption "the plikd server";
+      enable = mkEnableOption (lib.mdDoc "the plikd server");
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the plikd.";
+        description = lib.mdDoc "Open ports in the firewall for the plikd.";
       };
 
       settings = mkOption {
         type = format.type;
         default = {};
-        description = ''
-          Configuration for plikd, see <link xlink:href="https://github.com/root-gg/plik/blob/master/server/plikd.cfg"/>
+        description = lib.mdDoc ''
+          Configuration for plikd, see <https://github.com/root-gg/plik/blob/master/server/plikd.cfg>
           for supported values.
         '';
       };
diff --git a/nixos/modules/services/misc/podgrab.nix b/nixos/modules/services/misc/podgrab.nix
index 7077408b794..c0a12471850 100644
--- a/nixos/modules/services/misc/podgrab.nix
+++ b/nixos/modules/services/misc/podgrab.nix
@@ -4,13 +4,13 @@ let
 in
 {
   options.services.podgrab = with lib; {
-    enable = mkEnableOption "Podgrab, a self-hosted podcast manager";
+    enable = mkEnableOption (lib.mdDoc "Podgrab, a self-hosted podcast manager");
 
     passwordFile = mkOption {
       type = with types; nullOr str;
       default = null;
       example = "/run/secrets/password.env";
-      description = ''
+      description = lib.mdDoc ''
         The path to a file containing the PASSWORD environment variable
         definition for Podgrab's authentification.
       '';
@@ -20,7 +20,7 @@ in
       type = types.port;
       default = 8080;
       example = 4242;
-      description = "The port on which Podgrab will listen for incoming HTTP traffic.";
+      description = lib.mdDoc "The port on which Podgrab will listen for incoming HTTP traffic.";
     };
   };
 
@@ -36,7 +36,7 @@ in
       };
       serviceConfig = {
         DynamicUser = true;
-        EnvironmentFile = lib.optional (cfg.passwordFile != null) [
+        EnvironmentFile = lib.optionals (cfg.passwordFile != null) [
           cfg.passwordFile
         ];
         ExecStart = "${pkgs.podgrab}/bin/podgrab";
diff --git a/nixos/modules/services/misc/polaris.nix b/nixos/modules/services/misc/polaris.nix
new file mode 100644
index 00000000000..83da486083b
--- /dev/null
+++ b/nixos/modules/services/misc/polaris.nix
@@ -0,0 +1,151 @@
+{ config
+, pkgs
+, lib
+, ...}:
+
+with lib;
+let
+  cfg = config.services.polaris;
+  settingsFormat = pkgs.formats.toml {};
+in
+{
+  options = {
+    services.polaris = {
+      enable = mkEnableOption (lib.mdDoc "Polaris Music Server");
+
+      package = mkPackageOption pkgs "polaris" { };
+
+      user = mkOption {
+        type = types.str;
+        default = "polaris";
+        description = lib.mdDoc "User account under which Polaris runs.";
+      };
+
+      group = mkOption {
+        type = types.str;
+        default = "polaris";
+        description = lib.mdDoc "Group under which Polaris is run.";
+      };
+
+      extraGroups = mkOption {
+        type = types.listOf types.str;
+        default = [];
+        description = lib.mdDoc "Polaris' auxiliary groups.";
+        example = literalExpression ''["media" "music"]'';
+      };
+
+      port = mkOption {
+        type = types.port;
+        default = 5050;
+        description = lib.mdDoc ''
+          The port which the Polaris REST api and web UI should listen to.
+          Note: polaris is hardcoded to listen to the hostname "0.0.0.0".
+        '';
+      };
+
+      settings = mkOption {
+        type = settingsFormat.type;
+        default = {};
+        description = lib.mdDoc ''
+          Contents for the TOML Polaris config, applied each start.
+          Although poorly documented, an example may be found here:
+          [test-config.toml](https://github.com/agersant/polaris/blob/374d0ca56fc0a466d797a4b252e2078607476797/test-data/config.toml)
+        '';
+        example = literalExpression ''
+          {
+            settings.reindex_every_n_seconds = 7*24*60*60; # weekly, default is 1800
+            settings.album_art_pattern =
+              "(cover|front|folder)\.(jpeg|jpg|png|bmp|gif)";
+            mount_dirs = [
+              {
+                name = "NAS";
+                source = "/mnt/nas/music";
+              }
+              {
+                name = "Local";
+                source = "/home/my_user/Music";
+              }
+            ];
+          }
+        '';
+      };
+
+      openFirewall = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Open the configured port in the firewall.
+        '';
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.polaris = {
+      description = "Polaris Music Server";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = rec {
+        User = cfg.user;
+        Group = cfg.group;
+        DynamicUser = true;
+        SupplementaryGroups = cfg.extraGroups;
+        StateDirectory = "polaris";
+        CacheDirectory = "polaris";
+        ExecStart = escapeShellArgs ([
+          "${cfg.package}/bin/polaris"
+          "--foreground"
+          "--port" cfg.port
+          "--database" "/var/lib/${StateDirectory}/db.sqlite"
+          "--cache" "/var/cache/${CacheDirectory}"
+        ] ++ optionals (cfg.settings != {}) [
+          "--config" (settingsFormat.generate "polaris-config.toml" cfg.settings)
+        ]);
+        Restart = "on-failure";
+
+        # Security options:
+
+        #NoNewPrivileges = true; # implied by DynamicUser
+        #RemoveIPC = true; # implied by DynamicUser
+
+        AmbientCapabilities = "";
+        CapabilityBoundingSet = "";
+
+        DeviceAllow = "";
+
+        LockPersonality = true;
+
+        #PrivateTmp = true; # implied by DynamicUser
+        PrivateDevices = true;
+        PrivateUsers = true;
+
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+
+        RestrictNamespaces = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+        RestrictRealtime = true;
+        #RestrictSUIDSGID = true; # implied by DynamicUser
+
+        SystemCallArchitectures = "native";
+        SystemCallErrorNumber = "EPERM";
+        SystemCallFilter = [
+          "@system-service"
+          "~@cpu-emulation" "~@debug" "~@keyring" "~@memlock" "~@obsolete" "~@privileged" "~@setuid"
+        ];
+      };
+    };
+
+    networking.firewall = mkIf cfg.openFirewall {
+      allowedTCPPorts = [ cfg.port ];
+    };
+
+  };
+
+  meta.maintainers = with maintainers; [ pbsds ];
+}
diff --git a/nixos/modules/services/misc/portunus.nix b/nixos/modules/services/misc/portunus.nix
new file mode 100644
index 00000000000..0b283ea27d8
--- /dev/null
+++ b/nixos/modules/services/misc/portunus.nix
@@ -0,0 +1,288 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.portunus;
+
+in
+{
+  options.services.portunus = {
+    enable = mkEnableOption (lib.mdDoc "Portunus, a self-contained user/group management and authentication service for LDAP");
+
+    domain = mkOption {
+      type = types.str;
+      example = "sso.example.com";
+      description = lib.mdDoc "Subdomain which gets reverse proxied to Portunus webserver.";
+    };
+
+    port = mkOption {
+      type = types.port;
+      default = 8080;
+      description = lib.mdDoc ''
+        Port where the Portunus webserver should listen on.
+
+        This must be put behind a TLS-capable reverse proxy because Portunus only listens on localhost.
+      '';
+    };
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.portunus;
+      defaultText = "pkgs.portunus";
+      description = lib.mdDoc "The Portunus package to use.";
+    };
+
+    seedPath = mkOption {
+      type = types.nullOr types.path;
+      default = null;
+      description = lib.mdDoc ''
+        Path to a portunus seed file in json format.
+        See <https://github.com/majewsky/portunus#seeding-users-and-groups-from-static-configuration> for available options.
+      '';
+    };
+
+    stateDir = mkOption {
+      type = types.path;
+      default = "/var/lib/portunus";
+      description = lib.mdDoc "Path where Portunus stores its state.";
+    };
+
+    user = mkOption {
+      type = types.str;
+      default = "portunus";
+      description = lib.mdDoc "User account under which Portunus runs its webserver.";
+    };
+
+    group = mkOption {
+      type = types.str;
+      default = "portunus";
+      description = lib.mdDoc "Group account under which Portunus runs its webserver.";
+    };
+
+    dex = {
+      enable = mkEnableOption (lib.mdDoc ''
+        Dex ldap connector.
+
+        To activate dex, first a search user must be created in the Portunus web ui
+        and then the password must to be set as the `DEX_SEARCH_USER_PASSWORD` environment variable
+        in the [](#opt-services.dex.environmentFile) setting.
+      '');
+
+      oidcClients = mkOption {
+        type = types.listOf (types.submodule {
+          options = {
+            callbackURL = mkOption {
+              type = types.str;
+              description = lib.mdDoc "URL where the OIDC client should redirect";
+            };
+            id = mkOption {
+              type = types.str;
+              description = lib.mdDoc "ID of the OIDC client";
+            };
+          };
+        });
+        default = [ ];
+        example = [
+          {
+            callbackURL = "https://example.com/client/oidc/callback";
+            id = "service";
+          }
+        ];
+        description = lib.mdDoc ''
+          List of OIDC clients.
+
+          The OIDC secret must be set as the `DEX_CLIENT_''${id}` environment variable
+          in the [](#opt-services.dex.environmentFile) setting.
+        '';
+      };
+
+      port = mkOption {
+        type = types.port;
+        default = 5556;
+        description = lib.mdDoc "Port where dex should listen on.";
+      };
+    };
+
+    ldap = {
+      package = mkOption {
+        type = types.package;
+        default = pkgs.openldap;
+        defaultText = "pkgs.openldap";
+        description = lib.mdDoc "The OpenLDAP package to use.";
+      };
+
+      searchUserName = mkOption {
+        type = types.str;
+        default = "";
+        example = "admin";
+        description = lib.mdDoc ''
+          The login name of the search user.
+          This user account must be configured in Portunus either manually or via seeding.
+        '';
+      };
+
+      suffix = mkOption {
+        type = types.str;
+        example = "dc=example,dc=org";
+        description = lib.mdDoc ''
+          The DN of the topmost entry in your LDAP directory.
+          Please refer to the Portunus documentation for more information on how this impacts the structure of the LDAP directory.
+        '';
+      };
+
+      tls = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Wether to enable LDAPS protocol.
+          This also adds two entries to the `/etc/hosts` file to point [](#opt-services.portunus.domain) to localhost,
+          so that CLIs and programs can use ldaps protocol and verify the certificate without opening the firewall port for the protocol.
+
+          This requires a TLS certificate for [](#opt-services.portunus.domain) to be configured via [](#opt-security.acme.certs).
+        '';
+      };
+
+      user = mkOption {
+        type = types.str;
+        default = "openldap";
+        description = lib.mdDoc "User account under which Portunus runs its LDAP server.";
+      };
+
+      group = mkOption {
+        type = types.str;
+        default = "openldap";
+        description = lib.mdDoc "Group account under which Portunus runs its LDAP server.";
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    assertions = [
+      {
+        assertion = cfg.dex.enable -> cfg.ldap.searchUserName != "";
+        message = "services.portunus.dex.enable requires services.portunus.ldap.searchUserName to be set.";
+      }
+    ];
+
+    # add ldapsearch(1) etc. to interactive shells
+    environment.systemPackages = [ cfg.ldap.package ];
+
+    # allow connecting via ldaps /w certificate without opening ports
+    networking.hosts = mkIf cfg.ldap.tls {
+      "::1" = [ cfg.domain ];
+      "127.0.0.1" = [ cfg.domain ];
+    };
+
+    services.dex = mkIf cfg.dex.enable {
+      enable = true;
+      settings = {
+        issuer = "https://${cfg.domain}/dex";
+        web.http = "127.0.0.1:${toString cfg.dex.port}";
+        storage = {
+          type = "sqlite3";
+          config.file = "/var/lib/dex/dex.db";
+        };
+        enablePasswordDB = false;
+        connectors = [{
+          type = "ldap";
+          id = "ldap";
+          name = "LDAP";
+          config = {
+            host = "${cfg.domain}:636";
+            bindDN = "uid=${cfg.ldap.searchUserName},ou=users,${cfg.ldap.suffix}";
+            bindPW = "$DEX_SEARCH_USER_PASSWORD";
+            userSearch = {
+              baseDN = "ou=users,${cfg.ldap.suffix}";
+              filter = "(objectclass=person)";
+              username = "uid";
+              idAttr = "uid";
+              emailAttr = "mail";
+              nameAttr = "cn";
+              preferredUsernameAttr = "uid";
+            };
+            groupSearch = {
+              baseDN = "ou=groups,${cfg.ldap.suffix}";
+              filter = "(objectclass=groupOfNames)";
+              nameAttr = "cn";
+              userMatchers = [{ userAttr = "DN"; groupAttr = "member"; }];
+            };
+          };
+        }];
+
+        staticClients = forEach cfg.dex.oidcClients (client: {
+          inherit (client) id;
+          redirectURIs = [ client.callbackURL ];
+          name = "OIDC for ${client.id}";
+          secretEnv = "DEX_CLIENT_${client.id}";
+        });
+      };
+    };
+
+    systemd.services = {
+      dex.serviceConfig = mkIf cfg.dex.enable {
+        # `dex.service` is super locked down out of the box, but we need some
+        # place to write the SQLite database. This creates $STATE_DIRECTORY below
+        # /var/lib/private because DynamicUser=true, but it gets symlinked into
+        # /var/lib/dex inside the unit
+        StateDirectory = "dex";
+      };
+
+      portunus = {
+        description = "Self-contained authentication service";
+        wantedBy = [ "multi-user.target" ];
+        after = [ "network.target" ];
+        serviceConfig.ExecStart = "${cfg.package.out}/bin/portunus-orchestrator";
+        environment = {
+          PORTUNUS_LDAP_SUFFIX = cfg.ldap.suffix;
+          PORTUNUS_SERVER_BINARY = "${cfg.package}/bin/portunus-server";
+          PORTUNUS_SERVER_GROUP = cfg.group;
+          PORTUNUS_SERVER_USER = cfg.user;
+          PORTUNUS_SERVER_HTTP_LISTEN = "[::]:${toString cfg.port}";
+          PORTUNUS_SERVER_STATE_DIR = cfg.stateDir;
+          PORTUNUS_SLAPD_BINARY = "${cfg.ldap.package}/libexec/slapd";
+          PORTUNUS_SLAPD_GROUP = cfg.ldap.group;
+          PORTUNUS_SLAPD_USER = cfg.ldap.user;
+          PORTUNUS_SLAPD_SCHEMA_DIR = "${cfg.ldap.package}/etc/schema";
+        } // (optionalAttrs (cfg.seedPath != null) ({
+          PORTUNUS_SEED_PATH = cfg.seedPath;
+        })) // (optionalAttrs cfg.ldap.tls (
+          let
+            acmeDirectory = config.security.acme.certs."${cfg.domain}".directory;
+          in
+          {
+            PORTUNUS_SLAPD_TLS_CA_CERTIFICATE = "/etc/ssl/certs/ca-certificates.crt";
+            PORTUNUS_SLAPD_TLS_CERTIFICATE = "${acmeDirectory}/cert.pem";
+            PORTUNUS_SLAPD_TLS_DOMAIN_NAME = cfg.domain;
+            PORTUNUS_SLAPD_TLS_PRIVATE_KEY = "${acmeDirectory}/key.pem";
+          }));
+      };
+    };
+
+    users.users = mkMerge [
+      (mkIf (cfg.ldap.user == "openldap") {
+        openldap = {
+          group = cfg.ldap.group;
+          isSystemUser = true;
+        };
+      })
+      (mkIf (cfg.user == "portunus") {
+        portunus = {
+          group = cfg.group;
+          isSystemUser = true;
+        };
+      })
+    ];
+
+    users.groups = mkMerge [
+      (mkIf (cfg.ldap.user == "openldap") {
+        openldap = { };
+      })
+      (mkIf (cfg.user == "portunus") {
+        portunus = { };
+      })
+    ];
+  };
+
+  meta.maintainers = [ maintainers.majewsky ] ++ teams.c3d2.members;
+}
diff --git a/nixos/modules/services/misc/prowlarr.nix b/nixos/modules/services/misc/prowlarr.nix
index ef820b4022d..77b8ec98947 100644
--- a/nixos/modules/services/misc/prowlarr.nix
+++ b/nixos/modules/services/misc/prowlarr.nix
@@ -9,12 +9,12 @@ in
 {
   options = {
     services.prowlarr = {
-      enable = mkEnableOption "Prowlarr";
+      enable = mkEnableOption (lib.mdDoc "Prowlarr");
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the Prowlarr web interface.";
+        description = lib.mdDoc "Open ports in the firewall for the Prowlarr web interface.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/pykms.nix b/nixos/modules/services/misc/pykms.nix
index 2f752bcc7ed..314388e0152 100644
--- a/nixos/modules/services/misc/pykms.nix
+++ b/nixos/modules/services/misc/pykms.nix
@@ -18,43 +18,43 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the PyKMS service.";
+        description = lib.mdDoc "Whether to enable the PyKMS service.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = "The IP address on which to listen.";
+        description = lib.mdDoc "The IP address on which to listen.";
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 1688;
-        description = "The port on which to listen.";
+        description = lib.mdDoc "The port on which to listen.";
       };
 
       openFirewallPort = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether the listening port should be opened automatically.";
+        description = lib.mdDoc "Whether the listening port should be opened automatically.";
       };
 
       memoryLimit = mkOption {
         type = types.str;
         default = "64M";
-        description = "How much memory to use at most.";
+        description = lib.mdDoc "How much memory to use at most.";
       };
 
       logLevel = mkOption {
         type = types.enum [ "CRITICAL" "ERROR" "WARNING" "INFO" "DEBUG" "MININFO" ];
         default = "INFO";
-        description = "How much to log";
+        description = lib.mdDoc "How much to log";
       };
 
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = "Additional arguments";
+        description = lib.mdDoc "Additional arguments";
       };
     };
   };
diff --git a/nixos/modules/services/misc/radarr.nix b/nixos/modules/services/misc/radarr.nix
index 74444e24043..834b092c0d1 100644
--- a/nixos/modules/services/misc/radarr.nix
+++ b/nixos/modules/services/misc/radarr.nix
@@ -9,30 +9,38 @@ in
 {
   options = {
     services.radarr = {
-      enable = mkEnableOption "Radarr";
+      enable = mkEnableOption (lib.mdDoc "Radarr");
+
+      package = mkOption {
+        description = lib.mdDoc "Radarr package to use";
+        default = pkgs.radarr;
+        defaultText = literalExpression "pkgs.radarr";
+        example = literalExpression "pkgs.radarr";
+        type = types.package;
+      };
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/radarr/.config/Radarr";
-        description = "The directory where Radarr stores its data files.";
+        description = lib.mdDoc "The directory where Radarr stores its data files.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the Radarr web interface.";
+        description = lib.mdDoc "Open ports in the firewall for the Radarr web interface.";
       };
 
       user = mkOption {
         type = types.str;
         default = "radarr";
-        description = "User account under which Radarr runs.";
+        description = lib.mdDoc "User account under which Radarr runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "radarr";
-        description = "Group under which Radarr runs.";
+        description = lib.mdDoc "Group under which Radarr runs.";
       };
     };
   };
@@ -51,7 +59,7 @@ in
         Type = "simple";
         User = cfg.user;
         Group = cfg.group;
-        ExecStart = "${pkgs.radarr}/bin/Radarr -nobrowser -data='${cfg.dataDir}'";
+        ExecStart = "${cfg.package}/bin/Radarr -nobrowser -data='${cfg.dataDir}'";
         Restart = "on-failure";
       };
     };
diff --git a/nixos/modules/services/misc/redmine.nix b/nixos/modules/services/misc/redmine.nix
index 696b8d1a25d..58a595b5c76 100644
--- a/nixos/modules/services/misc/redmine.nix
+++ b/nixos/modules/services/misc/redmine.nix
@@ -49,46 +49,46 @@ in
   # interface
   options = {
     services.redmine = {
-      enable = mkEnableOption "Redmine";
+      enable = mkEnableOption (lib.mdDoc "Redmine");
 
       package = mkOption {
         type = types.package;
         default = pkgs.redmine;
         defaultText = literalExpression "pkgs.redmine";
-        description = "Which Redmine package to use.";
+        description = lib.mdDoc "Which Redmine package to use.";
         example = literalExpression "pkgs.redmine.override { ruby = pkgs.ruby_2_7; }";
       };
 
       user = mkOption {
         type = types.str;
         default = "redmine";
-        description = "User under which Redmine is ran.";
+        description = lib.mdDoc "User under which Redmine is ran.";
       };
 
       group = mkOption {
         type = types.str;
         default = "redmine";
-        description = "Group under which Redmine is ran.";
+        description = lib.mdDoc "Group under which Redmine is ran.";
       };
 
       port = mkOption {
         type = types.port;
         default = 3000;
-        description = "Port on which Redmine is ran.";
+        description = lib.mdDoc "Port on which Redmine is ran.";
       };
 
       stateDir = mkOption {
         type = types.str;
         default = "/var/lib/redmine";
-        description = "The state directory, logs and plugins are stored here.";
+        description = lib.mdDoc "The state directory, logs and plugins are stored here.";
       };
 
       settings = mkOption {
         type = format.type;
         default = {};
-        description = ''
-          Redmine configuration (<filename>configuration.yml</filename>). Refer to
-          <link xlink:href="https://guides.rubyonrails.org/action_mailer_basics.html#action-mailer-configuration"/>
+        description = lib.mdDoc ''
+          Redmine configuration ({file}`configuration.yml`). Refer to
+          <https://guides.rubyonrails.org/action_mailer_basics.html#action-mailer-configuration>
           for details.
         '';
         example = literalExpression ''
@@ -107,10 +107,10 @@ in
       extraEnv = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration in additional_environment.rb.
 
-          See <link xlink:href="https://svn.redmine.org/redmine/trunk/config/additional_environment.rb.example"/>
+          See <https://svn.redmine.org/redmine/trunk/config/additional_environment.rb.example>
           for details.
         '';
         example = ''
@@ -121,7 +121,7 @@ in
       themes = mkOption {
         type = types.attrsOf types.path;
         default = {};
-        description = "Set of themes.";
+        description = lib.mdDoc "Set of themes.";
         example = literalExpression ''
           {
             dkuk-redmine_alex_skin = builtins.fetchurl {
@@ -135,7 +135,7 @@ in
       plugins = mkOption {
         type = types.attrsOf types.path;
         default = {};
-        description = "Set of plugins.";
+        description = lib.mdDoc "Set of plugins.";
         example = literalExpression ''
           {
             redmine_env_auth = builtins.fetchurl {
@@ -151,41 +151,41 @@ in
           type = types.enum [ "mysql2" "postgresql" ];
           example = "postgresql";
           default = "mysql2";
-          description = "Database engine to use.";
+          description = lib.mdDoc "Database engine to use.";
         };
 
         host = mkOption {
           type = types.str;
           default = "localhost";
-          description = "Database host address.";
+          description = lib.mdDoc "Database host address.";
         };
 
         port = mkOption {
-          type = types.int;
+          type = types.port;
           default = if cfg.database.type == "postgresql" then 5432 else 3306;
           defaultText = literalExpression "3306";
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = mkOption {
           type = types.str;
           default = "redmine";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = mkOption {
           type = types.str;
           default = "redmine";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/redmine-dbpassword";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
 
@@ -197,13 +197,64 @@ in
             else null;
           defaultText = literalExpression "/run/mysqld/mysqld.sock";
           example = "/run/mysqld/mysqld.sock";
-          description = "Path to the unix socket file to use for authentication.";
+          description = lib.mdDoc "Path to the unix socket file to use for authentication.";
         };
 
         createLocally = mkOption {
           type = types.bool;
           default = true;
-          description = "Create the database and database user locally.";
+          description = lib.mdDoc "Create the database and database user locally.";
+        };
+      };
+
+      components = {
+        subversion = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc "Subversion integration.";
+        };
+
+        mercurial = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc "Mercurial integration.";
+        };
+
+        git = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc "git integration.";
+        };
+
+        cvs = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc "cvs integration.";
+        };
+
+        breezy = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc "bazaar integration.";
+        };
+
+        imagemagick = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc "Allows exporting Gant diagrams as PNG.";
+        };
+
+        ghostscript = mkOption {
+          type = types.bool;
+          default = false;
+          description = lib.mdDoc "Allows exporting Gant diagrams as PDF.";
+        };
+
+        minimagick_font_path = mkOption {
+          type = types.str;
+          default = "";
+          description = lib.mdDoc "MiniMagick font path";
+          example = "/run/current-system/sw/share/X11/fonts/LiberationSans-Regular.ttf";
         };
       };
     };
@@ -225,16 +276,21 @@ in
       { assertion = cfg.database.createLocally -> cfg.database.host == "localhost";
         message = "services.redmine.database.host must be set to localhost if services.redmine.database.createLocally is set to true";
       }
+      { assertion = cfg.components.imagemagick -> cfg.components.minimagick_font_path != "";
+        message = "services.redmine.components.minimagick_font_path must be configured with a path to a font file if services.redmine.components.imagemagick is set to true.";
+      }
     ];
 
     services.redmine.settings = {
       production = {
-        scm_subversion_command = "${pkgs.subversion}/bin/svn";
-        scm_mercurial_command = "${pkgs.mercurial}/bin/hg";
-        scm_git_command = "${pkgs.git}/bin/git";
-        scm_cvs_command = "${pkgs.cvs}/bin/cvs";
-        scm_bazaar_command = "${pkgs.breezy}/bin/bzr";
-        scm_darcs_command = "${pkgs.darcs}/bin/darcs";
+        scm_subversion_command = if cfg.components.subversion then "${pkgs.subversion}/bin/svn" else "";
+        scm_mercurial_command = if cfg.components.mercurial then "${pkgs.mercurial}/bin/hg" else "";
+        scm_git_command = if cfg.components.git then "${pkgs.git}/bin/git" else "";
+        scm_cvs_command = if cfg.components.cvs then "${pkgs.cvs}/bin/cvs" else "";
+        scm_bazaar_command = if cfg.components.breezy then "${pkgs.breezy}/bin/bzr" else "";
+        imagemagick_convert_command = if cfg.components.imagemagick then "${pkgs.imagemagick}/bin/convert" else "";
+        gs_command = if cfg.components.ghostscript then "${pkgs.ghostscript}/bin/gs" else "";
+        minimagick_font_path = "${cfg.components.minimagick_font_path}";
       };
     };
 
@@ -296,14 +352,15 @@ in
       environment.REDMINE_LANG = "en";
       environment.SCHEMA = "${cfg.stateDir}/cache/schema.db";
       path = with pkgs; [
-        imagemagick
-        breezy
-        cvs
-        darcs
-        git
-        mercurial
-        subversion
-      ];
+      ]
+      ++ optional cfg.components.subversion subversion
+      ++ optional cfg.components.mercurial mercurial
+      ++ optional cfg.components.git git
+      ++ optional cfg.components.cvs cvs
+      ++ optional cfg.components.breezy breezy
+      ++ optional cfg.components.imagemagick imagemagick
+      ++ optional cfg.components.ghostscript ghostscript;
+
       preStart = ''
         rm -rf "${cfg.stateDir}/plugins/"*
         rm -rf "${cfg.stateDir}/public/themes/"*
diff --git a/nixos/modules/services/misc/ripple-data-api.nix b/nixos/modules/services/misc/ripple-data-api.nix
index 93eba98b7d3..2663d734980 100644
--- a/nixos/modules/services/misc/ripple-data-api.nix
+++ b/nixos/modules/services/misc/ripple-data-api.nix
@@ -35,47 +35,47 @@ let
 in {
   options = {
     services.rippleDataApi = {
-      enable = mkEnableOption "ripple data api";
+      enable = mkEnableOption (lib.mdDoc "ripple data api");
 
       port = mkOption {
-        description = "Ripple data api port";
+        description = lib.mdDoc "Ripple data api port";
         default = 5993;
         type = types.int;
       };
 
       importMode = mkOption {
-        description = "Ripple data api import mode.";
+        description = lib.mdDoc "Ripple data api import mode.";
         default = "liveOnly";
         type = types.enum ["live" "liveOnly"];
       };
 
       minLedger = mkOption {
-        description = "Ripple data api minimal ledger to fetch.";
+        description = lib.mdDoc "Ripple data api minimal ledger to fetch.";
         default = null;
         type = types.nullOr types.int;
       };
 
       maxLedger = mkOption {
-        description = "Ripple data api maximal ledger to fetch.";
+        description = lib.mdDoc "Ripple data api maximal ledger to fetch.";
         default = null;
         type = types.nullOr types.int;
       };
 
       redis = {
         enable = mkOption {
-          description = "Whether to enable caching of ripple data to redis.";
+          description = lib.mdDoc "Whether to enable caching of ripple data to redis.";
           default = true;
           type = types.bool;
         };
 
         host = mkOption {
-          description = "Ripple data api redis host.";
+          description = lib.mdDoc "Ripple data api redis host.";
           default = "localhost";
           type = types.str;
         };
 
         port = mkOption {
-          description = "Ripple data api redis port.";
+          description = lib.mdDoc "Ripple data api redis port.";
           default = 5984;
           type = types.int;
         };
@@ -83,44 +83,44 @@ in {
 
       couchdb = {
         host = mkOption {
-          description = "Ripple data api couchdb host.";
+          description = lib.mdDoc "Ripple data api couchdb host.";
           default = "localhost";
           type = types.str;
         };
 
         port = mkOption {
-          description = "Ripple data api couchdb port.";
+          description = lib.mdDoc "Ripple data api couchdb port.";
           default = 5984;
           type = types.int;
         };
 
         db = mkOption {
-          description = "Ripple data api couchdb database.";
+          description = lib.mdDoc "Ripple data api couchdb database.";
           default = "rippled";
           type = types.str;
         };
 
         user = mkOption {
-          description = "Ripple data api couchdb username.";
+          description = lib.mdDoc "Ripple data api couchdb username.";
           default = "rippled";
           type = types.str;
         };
 
         pass = mkOption {
-          description = "Ripple data api couchdb password.";
+          description = lib.mdDoc "Ripple data api couchdb password.";
           default = "";
           type = types.str;
         };
 
         create = mkOption {
-          description = "Whether to create couchdb database needed by ripple data api.";
+          description = lib.mdDoc "Whether to create couchdb database needed by ripple data api.";
           type = types.bool;
           default = true;
         };
       };
 
       rippleds = mkOption {
-        description = "List of rippleds to be used by ripple data api.";
+        description = lib.mdDoc "List of rippleds to be used by ripple data api.";
         default = [
           "http://s_east.ripple.com:51234"
           "http://s_west.ripple.com:51234"
diff --git a/nixos/modules/services/misc/rippled.nix b/nixos/modules/services/misc/rippled.nix
index f6ec0677774..d14b6421b74 100644
--- a/nixos/modules/services/misc/rippled.nix
+++ b/nixos/modules/services/misc/rippled.nix
@@ -92,41 +92,41 @@ let
 
       ip = mkOption {
         default = "127.0.0.1";
-        description = "Ip where rippled listens.";
+        description = lib.mdDoc "Ip where rippled listens.";
         type = types.str;
       };
 
       port = mkOption {
-        description = "Port where rippled listens.";
-        type = types.int;
+        description = lib.mdDoc "Port where rippled listens.";
+        type = types.port;
       };
 
       protocol = mkOption {
-        description = "Protocols expose by rippled.";
+        description = lib.mdDoc "Protocols expose by rippled.";
         type = types.listOf (types.enum ["http" "https" "ws" "wss" "peer"]);
       };
 
       user = mkOption {
-        description = "When set, these credentials will be required on HTTP/S requests.";
+        description = lib.mdDoc "When set, these credentials will be required on HTTP/S requests.";
         type = types.str;
         default = "";
       };
 
       password = mkOption {
-        description = "When set, these credentials will be required on HTTP/S requests.";
+        description = lib.mdDoc "When set, these credentials will be required on HTTP/S requests.";
         type = types.str;
         default = "";
       };
 
       admin = mkOption {
-        description = "A comma-separated list of admin IP addresses.";
+        description = lib.mdDoc "A comma-separated list of admin IP addresses.";
         type = types.listOf types.str;
         default = ["127.0.0.1"];
       };
 
       ssl = {
         key = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Specifies the filename holding the SSL key in PEM format.
           '';
           default = null;
@@ -134,7 +134,7 @@ let
         };
 
         cert = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Specifies the path to the SSL certificate file in PEM format.
             This is not needed if the chain includes it.
           '';
@@ -143,7 +143,7 @@ let
         };
 
         chain = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             If you need a certificate chain, specify the path to the
             certificate chain here. The chain may include the end certificate.
           '';
@@ -157,33 +157,33 @@ let
   dbOptions = {
     options = {
       type = mkOption {
-        description = "Rippled database type.";
+        description = lib.mdDoc "Rippled database type.";
         type = types.enum ["rocksdb" "nudb"];
         default = "rocksdb";
       };
 
       path = mkOption {
-        description = "Location to store the database.";
+        description = lib.mdDoc "Location to store the database.";
         type = types.path;
         default = cfg.databasePath;
         defaultText = literalExpression "config.${opt.databasePath}";
       };
 
       compression = mkOption {
-        description = "Whether to enable snappy compression.";
+        description = lib.mdDoc "Whether to enable snappy compression.";
         type = types.nullOr types.bool;
         default = null;
       };
 
       onlineDelete = mkOption {
-        description = "Enable automatic purging of older ledger information.";
+        description = lib.mdDoc "Enable automatic purging of older ledger information.";
         type = types.nullOr (types.addCheck types.int (v: v > 256));
         default = cfg.ledgerHistory;
         defaultText = literalExpression "config.${opt.ledgerHistory}";
       };
 
       advisoryDelete = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           If set, then require administrative RPC call "can_delete"
           to enable online deletion of ledger records.
         '';
@@ -192,7 +192,7 @@ let
       };
 
       extraOpts = mkOption {
-        description = "Extra database options.";
+        description = lib.mdDoc "Extra database options.";
         type = types.lines;
         default = "";
       };
@@ -207,17 +207,17 @@ in
 
   options = {
     services.rippled = {
-      enable = mkEnableOption "rippled";
+      enable = mkEnableOption (lib.mdDoc "rippled");
 
       package = mkOption {
-        description = "Which rippled package to use.";
+        description = lib.mdDoc "Which rippled package to use.";
         type = types.package;
         default = pkgs.rippled;
         defaultText = literalExpression "pkgs.rippled";
       };
 
       ports = mkOption {
-        description = "Ports exposed by rippled";
+        description = lib.mdDoc "Ports exposed by rippled";
         type = with types; attrsOf (submodule portOptions);
         default = {
           rpc = {
@@ -241,7 +241,7 @@ in
       };
 
       nodeDb = mkOption {
-        description = "Rippled main database options.";
+        description = lib.mdDoc "Rippled main database options.";
         type = with types; nullOr (submodule dbOptions);
         default = {
           type = "rocksdb";
@@ -256,19 +256,19 @@ in
       };
 
       tempDb = mkOption {
-        description = "Rippled temporary database options.";
+        description = lib.mdDoc "Rippled temporary database options.";
         type = with types; nullOr (submodule dbOptions);
         default = null;
       };
 
       importDb = mkOption {
-        description = "Settings for performing a one-time import.";
+        description = lib.mdDoc "Settings for performing a one-time import.";
         type = with types; nullOr (submodule dbOptions);
         default = null;
       };
 
       nodeSize = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Rippled size of the node you are running.
           "tiny", "small", "medium", "large", and "huge"
         '';
@@ -277,7 +277,7 @@ in
       };
 
       ips = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           List of hostnames or ips where the Ripple protocol is served.
           For a starter list, you can either copy entries from:
           https://ripple.com/ripple.txt or if you prefer you can let it
@@ -292,7 +292,7 @@ in
       };
 
       ipsFixed = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           List of IP addresses or hostnames to which rippled should always
           attempt to maintain peer connections with. This is useful for
           manually forming private networks, for example to configure a
@@ -306,7 +306,7 @@ in
       };
 
       validators = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           List of nodes to always accept as validators. Nodes are specified by domain
           or public key.
         '';
@@ -321,7 +321,7 @@ in
       };
 
       databasePath = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Path to the ripple database.
         '';
         type = types.path;
@@ -329,7 +329,7 @@ in
       };
 
       validationQuorum = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The minimum number of trusted validations a ledger must have before
           the server considers it fully validated.
         '';
@@ -338,7 +338,7 @@ in
       };
 
       ledgerHistory = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The number of past ledgers to acquire on server startup and the minimum
           to maintain while running.
         '';
@@ -347,7 +347,7 @@ in
       };
 
       fetchDepth = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The number of past ledgers to serve to other peers that request historical
           ledger data (or "full" for no limit).
         '';
@@ -356,7 +356,7 @@ in
       };
 
       sntpServers = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           IP address or domain of NTP servers to use for time synchronization.;
         '';
         type = types.listOf types.str;
@@ -369,22 +369,22 @@ in
       };
 
       logLevel = mkOption {
-        description = "Logging verbosity.";
+        description = lib.mdDoc "Logging verbosity.";
         type = types.enum ["debug" "error" "info"];
         default = "error";
       };
 
       statsd = {
-        enable = mkEnableOption "statsd monitoring for rippled";
+        enable = mkEnableOption (lib.mdDoc "statsd monitoring for rippled");
 
         address = mkOption {
-          description = "The UDP address and port of the listening StatsD server.";
+          description = lib.mdDoc "The UDP address and port of the listening StatsD server.";
           default = "127.0.0.1:8125";
           type = types.str;
         };
 
         prefix = mkOption {
-          description = "A string prepended to each collected metric.";
+          description = lib.mdDoc "A string prepended to each collected metric.";
           default = "";
           type = types.str;
         };
@@ -393,7 +393,7 @@ in
       extraConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to the rippled.cfg configuration file.
         '';
       };
@@ -401,7 +401,7 @@ in
       config = mkOption {
         internal = true;
         default = pkgs.writeText "rippled.conf" rippledCfg;
-        defaultText = literalDocBook "generated config file";
+        defaultText = literalMD "generated config file";
       };
     };
   };
diff --git a/nixos/modules/services/misc/rmfakecloud.nix b/nixos/modules/services/misc/rmfakecloud.nix
index fe522653c21..1cdfdeceabc 100644
--- a/nixos/modules/services/misc/rmfakecloud.nix
+++ b/nixos/modules/services/misc/rmfakecloud.nix
@@ -9,13 +9,13 @@ let
 in {
   options = {
     services.rmfakecloud = {
-      enable = mkEnableOption "rmfakecloud remarkable self-hosted cloud";
+      enable = mkEnableOption (lib.mdDoc "rmfakecloud remarkable self-hosted cloud");
 
       package = mkOption {
         type = types.package;
         default = pkgs.rmfakecloud;
         defaultText = literalExpression "pkgs.rmfakecloud";
-        description = ''
+        description = lib.mdDoc ''
           rmfakecloud package to use.
 
           The default does not include the web user interface.
@@ -25,7 +25,7 @@ in {
       storageUrl = mkOption {
         type = types.str;
         example = "https://local.appspot.com";
-        description = ''
+        description = lib.mdDoc ''
           URL used by the tablet to access the rmfakecloud service.
         '';
       };
@@ -33,7 +33,7 @@ in {
       port = mkOption {
         type = types.port;
         default = 3000;
-        description = ''
+        description = lib.mdDoc ''
           Listening port number.
         '';
       };
@@ -41,7 +41,7 @@ in {
       logLevel = mkOption {
         type = types.enum [ "info" "debug" "warn" "error" ];
         default = "info";
-        description = ''
+        description = lib.mdDoc ''
           Logging level.
         '';
       };
@@ -50,7 +50,7 @@ in {
         type = with types; attrsOf str;
         default = { };
         example = { DATADIR = "/custom/path/for/rmfakecloud/data"; };
-        description = ''
+        description = lib.mdDoc ''
           Extra settings in the form of a set of key-value pairs.
           For tokens and secrets, use `environmentFile` instead.
 
@@ -63,7 +63,7 @@ in {
         type = with types; nullOr path;
         default = null;
         example = "/etc/secrets/rmfakecloud.env";
-        description = ''
+        description = lib.mdDoc ''
           Path to an environment file loaded for the rmfakecloud service.
 
           This can be used to securely store tokens and secrets outside of the
@@ -138,7 +138,7 @@ in {
         SystemCallArchitectures = "native";
         WorkingDirectory = serviceDataDir;
         StateDirectory = baseNameOf serviceDataDir;
-        UMask = 0027;
+        UMask = "0027";
       };
     };
   };
diff --git a/nixos/modules/services/misc/safeeyes.nix b/nixos/modules/services/misc/safeeyes.nix
index 638218d8bb0..9dfa2001bcb 100644
--- a/nixos/modules/services/misc/safeeyes.nix
+++ b/nixos/modules/services/misc/safeeyes.nix
@@ -16,7 +16,7 @@ in
 
     services.safeeyes = {
 
-      enable = mkEnableOption "the safeeyes OSGi service";
+      enable = mkEnableOption (lib.mdDoc "the safeeyes OSGi service");
 
     };
 
@@ -34,8 +34,6 @@ in
       wantedBy = [ "graphical-session.target" ];
       partOf   = [ "graphical-session.target" ];
 
-      path = [ pkgs.alsa-utils ];
-
       startLimitIntervalSec = 350;
       startLimitBurst = 10;
       serviceConfig = {
diff --git a/nixos/modules/services/misc/sdrplay.nix b/nixos/modules/services/misc/sdrplay.nix
index 2801108f082..2d5333e3885 100644
--- a/nixos/modules/services/misc/sdrplay.nix
+++ b/nixos/modules/services/misc/sdrplay.nix
@@ -5,13 +5,13 @@ with lib;
     enable = mkOption {
       default = false;
       example = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable the SDRplay API service and udev rules.
 
-        <note><para>
-          To enable integration with SoapySDR and GUI applications like gqrx create an overlay containing
-          <literal>soapysdr-with-plugins = super.soapysdr.override { extraPackages = [ super.soapysdrplay ]; };</literal>
-        </para></note>
+        ::: {.note}
+        To enable integration with SoapySDR and GUI applications like gqrx create an overlay containing
+        `soapysdr-with-plugins = super.soapysdr.override { extraPackages = [ super.soapysdrplay ]; };`
+        :::
       '';
       type = lib.types.bool;
     };
diff --git a/nixos/modules/services/misc/serviio.nix b/nixos/modules/services/misc/serviio.nix
index 0ead6a81691..57efebb2c03 100644
--- a/nixos/modules/services/misc/serviio.nix
+++ b/nixos/modules/services/misc/serviio.nix
@@ -31,7 +31,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Serviio Media Server.
         '';
       };
@@ -39,7 +39,7 @@ in {
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/serviio";
-        description = ''
+        description = lib.mdDoc ''
           The directory where serviio stores its state, data, etc.
         '';
       };
diff --git a/nixos/modules/services/misc/sickbeard.nix b/nixos/modules/services/misc/sickbeard.nix
index a3db9928634..bd8d8d8fa7c 100644
--- a/nixos/modules/services/misc/sickbeard.nix
+++ b/nixos/modules/services/misc/sickbeard.nix
@@ -20,43 +20,43 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the sickbeard server.";
+        description = lib.mdDoc "Whether to enable the sickbeard server.";
       };
       package = mkOption {
         type = types.package;
         default = pkgs.sickbeard;
         defaultText = literalExpression "pkgs.sickbeard";
         example = literalExpression "pkgs.sickrage";
-        description =''
-          Enable <literal>pkgs.sickrage</literal> or <literal>pkgs.sickgear</literal>
+        description =lib.mdDoc ''
+          Enable `pkgs.sickrage` or `pkgs.sickgear`
           as an alternative to SickBeard
         '';
       };
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/${name}";
-        description = "Path where to store data files.";
+        description = lib.mdDoc "Path where to store data files.";
       };
       configFile = mkOption {
         type = types.path;
         default = "${cfg.dataDir}/config.ini";
         defaultText = literalExpression ''"''${config.${opt.dataDir}}/config.ini"'';
-        description = "Path to config file.";
+        description = lib.mdDoc "Path to config file.";
       };
       port = mkOption {
         type = types.ints.u16;
         default = 8081;
-        description = "Port to bind to.";
+        description = lib.mdDoc "Port to bind to.";
       };
       user = mkOption {
         type = types.str;
         default = name;
-        description = "User to run the service as";
+        description = lib.mdDoc "User to run the service as";
       };
       group = mkOption {
         type = types.str;
         default = name;
-        description = "Group to run the service as";
+        description = lib.mdDoc "Group to run the service as";
       };
     };
   };
diff --git a/nixos/modules/services/misc/signald.nix b/nixos/modules/services/misc/signald.nix
index 4cd34e4326d..32ba154506c 100644
--- a/nixos/modules/services/misc/signald.nix
+++ b/nixos/modules/services/misc/signald.nix
@@ -8,24 +8,24 @@ let
 in
 {
   options.services.signald = {
-    enable = mkEnableOption "the signald service";
+    enable = mkEnableOption (lib.mdDoc "the signald service");
 
     user = mkOption {
       type = types.str;
       default = defaultUser;
-      description = "User under which signald runs.";
+      description = lib.mdDoc "User under which signald runs.";
     };
 
     group = mkOption {
       type = types.str;
       default = defaultUser;
-      description = "Group under which signald runs.";
+      description = lib.mdDoc "Group under which signald runs.";
     };
 
     socketPath = mkOption {
       type = types.str;
       default = "/run/signald/signald.sock";
-      description = "Path to the signald socket";
+      description = lib.mdDoc "Path to the signald socket";
     };
   };
 
diff --git a/nixos/modules/services/misc/siproxd.nix b/nixos/modules/services/misc/siproxd.nix
index 20fe0793b84..f1a1ed4d29b 100644
--- a/nixos/modules/services/misc/siproxd.nix
+++ b/nixos/modules/services/misc/siproxd.nix
@@ -37,7 +37,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Siproxd SIP
           proxy/masquerading daemon.
         '';
@@ -46,20 +46,20 @@ in
       ifInbound = mkOption {
         type = types.str;
         example = "eth0";
-        description = "Local network interface";
+        description = lib.mdDoc "Local network interface";
       };
 
       ifOutbound = mkOption {
         type = types.str;
         example = "ppp0";
-        description = "Public network interface";
+        description = lib.mdDoc "Public network interface";
       };
 
       hostsAllowReg = mkOption {
         type = types.listOf types.str;
         default = [ ];
         example = [ "192.168.1.0/24" "192.168.2.0/24" ];
-        description = ''
+        description = lib.mdDoc ''
           Acess control list for incoming SIP registrations.
         '';
       };
@@ -68,7 +68,7 @@ in
         type = types.listOf types.str;
         default = [ ];
         example = [ "123.45.0.0/16" "123.46.0.0/16" ];
-        description = ''
+        description = lib.mdDoc ''
           Acess control list for incoming SIP traffic.
         '';
       };
@@ -77,7 +77,7 @@ in
         type = types.listOf types.str;
         default = [ ];
         example = [ "10.0.0.0/8" "11.0.0.0/8" ];
-        description = ''
+        description = lib.mdDoc ''
           Acess control list for denying incoming
           SIP registrations and traffic.
         '';
@@ -86,7 +86,7 @@ in
       sipListenPort = mkOption {
         type = types.int;
         default = 5060;
-        description = ''
+        description = lib.mdDoc ''
           Port to listen for incoming SIP messages.
         '';
       };
@@ -94,7 +94,7 @@ in
       rtpPortLow = mkOption {
         type = types.int;
         default = 7070;
-        description = ''
+        description = lib.mdDoc ''
          Bottom of UDP port range for incoming and outgoing RTP traffic
         '';
       };
@@ -102,7 +102,7 @@ in
       rtpPortHigh = mkOption {
         type = types.int;
         default = 7089;
-        description = ''
+        description = lib.mdDoc ''
          Top of UDP port range for incoming and outgoing RTP traffic
         '';
       };
@@ -110,7 +110,7 @@ in
       rtpTimeout = mkOption {
         type = types.int;
         default = 300;
-        description = ''
+        description = lib.mdDoc ''
           Timeout for an RTP stream. If for the specified
           number of seconds no data is relayed on an active
           stream, it is considered dead and will be killed.
@@ -120,7 +120,7 @@ in
       rtpDscp = mkOption {
         type = types.int;
         default = 46;
-        description = ''
+        description = lib.mdDoc ''
           DSCP (differentiated services) value to be assigned
           to RTP packets. Allows QOS aware routers to handle
           different types traffic with different priorities.
@@ -130,7 +130,7 @@ in
       sipDscp = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           DSCP (differentiated services) value to be assigned
           to SIP packets. Allows QOS aware routers to handle
           different types traffic with different priorities.
@@ -140,7 +140,7 @@ in
       passwordFile = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Path to per-user password file.
         '';
       };
@@ -148,7 +148,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to add to siproxd configuration.
         '';
       };
diff --git a/nixos/modules/services/misc/snapper.nix b/nixos/modules/services/misc/snapper.nix
index 3c3f6c4d641..cfdfa2830ce 100644
--- a/nixos/modules/services/misc/snapper.nix
+++ b/nixos/modules/services/misc/snapper.nix
@@ -12,7 +12,7 @@ in
     snapshotRootOnBoot = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to snapshot root on boot
       '';
     };
@@ -20,31 +20,29 @@ in
     snapshotInterval = mkOption {
       type = types.str;
       default = "hourly";
-      description = ''
+      description = lib.mdDoc ''
         Snapshot interval.
 
         The format is described in
-        <citerefentry><refentrytitle>systemd.time</refentrytitle>
-        <manvolnum>7</manvolnum></citerefentry>.
+        {manpage}`systemd.time(7)`.
       '';
     };
 
     cleanupInterval = mkOption {
       type = types.str;
       default = "1d";
-      description = ''
+      description = lib.mdDoc ''
         Cleanup interval.
 
         The format is described in
-        <citerefentry><refentrytitle>systemd.time</refentrytitle>
-        <manvolnum>7</manvolnum></citerefentry>.
+        {manpage}`systemd.time(7)`.
       '';
     };
 
     filters = mkOption {
       type = types.nullOr types.lines;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Global display difference filter. See man:snapper(8) for more details.
       '';
     };
@@ -64,7 +62,7 @@ in
         }
       '';
 
-      description = ''
+      description = lib.mdDoc ''
         Subvolume configuration
       '';
 
@@ -72,7 +70,7 @@ in
         options = {
           subvolume = mkOption {
             type = types.path;
-            description = ''
+            description = lib.mdDoc ''
               Path of the subvolume or mount point.
               This path is a subvolume and has to contain a subvolume named
               .snapshots.
@@ -83,7 +81,7 @@ in
           fstype = mkOption {
             type = types.enum [ "btrfs" ];
             default = "btrfs";
-            description = ''
+            description = lib.mdDoc ''
               Filesystem type. Only btrfs is stable and tested.
             '';
           };
@@ -91,7 +89,7 @@ in
           extraConfig = mkOption {
             type = types.lines;
             default = "";
-            description = ''
+            description = lib.mdDoc ''
               Additional configuration next to SUBVOLUME and FSTYPE.
               See man:snapper-configs(5).
             '';
diff --git a/nixos/modules/services/misc/sonarr.nix b/nixos/modules/services/misc/sonarr.nix
index 77c7f0582d0..65c51d9677d 100644
--- a/nixos/modules/services/misc/sonarr.nix
+++ b/nixos/modules/services/misc/sonarr.nix
@@ -8,18 +8,18 @@ in
 {
   options = {
     services.sonarr = {
-      enable = mkEnableOption "Sonarr";
+      enable = mkEnableOption (lib.mdDoc "Sonarr");
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/sonarr/.config/NzbDrone";
-        description = "The directory where Sonarr stores its data files.";
+        description = lib.mdDoc "The directory where Sonarr stores its data files.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for the Sonarr web interface
         '';
       };
@@ -27,13 +27,22 @@ in
       user = mkOption {
         type = types.str;
         default = "sonarr";
-        description = "User account under which Sonaar runs.";
+        description = lib.mdDoc "User account under which Sonaar runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "sonarr";
-        description = "Group under which Sonaar runs.";
+        description = lib.mdDoc "Group under which Sonaar runs.";
+      };
+
+      package = mkOption {
+        type = types.package;
+        default = pkgs.sonarr;
+        defaultText = literalExpression "pkgs.sonarr";
+        description = lib.mdDoc ''
+          Sonarr package to use.
+        '';
       };
     };
   };
@@ -52,7 +61,7 @@ in
         Type = "simple";
         User = cfg.user;
         Group = cfg.group;
-        ExecStart = "${pkgs.sonarr}/bin/NzbDrone -nobrowser -data='${cfg.dataDir}'";
+        ExecStart = "${cfg.package}/bin/NzbDrone -nobrowser -data='${cfg.dataDir}'";
         Restart = "on-failure";
       };
     };
diff --git a/nixos/modules/services/misc/sourcehut/builds.nix b/nixos/modules/services/misc/sourcehut/builds.nix
deleted file mode 100644
index 685a132d350..00000000000
--- a/nixos/modules/services/misc/sourcehut/builds.nix
+++ /dev/null
@@ -1,236 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  scfg = cfg.builds;
-  rcfg = config.services.redis;
-  iniKey = "builds.sr.ht";
-
-  drv = pkgs.sourcehut.buildsrht;
-in
-{
-  options.services.sourcehut.builds = {
-    user = mkOption {
-      type = types.str;
-      default = "buildsrht";
-      description = ''
-        User for builds.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5002;
-      description = ''
-        Port on which the "builds" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "builds.sr.ht";
-      description = ''
-        PostgreSQL database name for builds.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/buildsrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/buildsrht"'';
-      description = ''
-        State path for builds.sr.ht.
-      '';
-    };
-
-    enableWorker = mkOption {
-      type = types.bool;
-      default = false;
-      description = ''
-        Run workers for builds.sr.ht.
-      '';
-    };
-
-    images = mkOption {
-      type = types.attrsOf (types.attrsOf (types.attrsOf types.package));
-      default = { };
-      example = lib.literalExpression ''(let
-          # Pinning unstable to allow usage with flakes and limit rebuilds.
-          pkgs_unstable = builtins.fetchGit {
-              url = "https://github.com/NixOS/nixpkgs";
-              rev = "ff96a0fa5635770390b184ae74debea75c3fd534";
-              ref = "nixos-unstable";
-          };
-          image_from_nixpkgs = pkgs_unstable: (import ("''${pkgs.sourcehut.buildsrht}/lib/images/nixos/image.nix") {
-            pkgs = (import pkgs_unstable {});
-          });
-        in
-        {
-          nixos.unstable.x86_64 = image_from_nixpkgs pkgs_unstable;
-        }
-      )'';
-      description = ''
-        Images for builds.sr.ht. Each package should be distro.release.arch and point to a /nix/store/package/root.img.qcow2.
-      '';
-    };
-
-  };
-
-  config = with scfg; let
-    image_dirs = lib.lists.flatten (
-      lib.attrsets.mapAttrsToList
-        (distro: revs:
-          lib.attrsets.mapAttrsToList
-            (rev: archs:
-              lib.attrsets.mapAttrsToList
-                (arch: image:
-                  pkgs.runCommand "buildsrht-images" { } ''
-                    mkdir -p $out/${distro}/${rev}/${arch}
-                    ln -s ${image}/*.qcow2 $out/${distro}/${rev}/${arch}/root.img.qcow2
-                  '')
-                archs)
-            revs)
-        scfg.images);
-    image_dir_pre = pkgs.symlinkJoin {
-      name = "builds.sr.ht-worker-images-pre";
-      paths = image_dirs ++ [
-        "${pkgs.sourcehut.buildsrht}/lib/images"
-      ];
-    };
-    image_dir = pkgs.runCommand "builds.sr.ht-worker-images" { } ''
-      mkdir -p $out/images
-      cp -Lr ${image_dir_pre}/* $out/images
-    '';
-  in
-  lib.mkIf (cfg.enable && elem "builds" cfg.services) {
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          extraGroups = lib.optionals cfg.builds.enableWorker [ "docker" ];
-          description = "builds.sr.ht user";
-        };
-      };
-
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services.postgresql = {
-      authentication = ''
-        local ${database} ${user} trust
-      '';
-      ensureDatabases = [ database ];
-      ensureUsers = [
-        {
-          name = user;
-          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-        }
-      ];
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        "d ${statePath} 0755 ${user} ${user} -"
-      ] ++ (lib.optionals cfg.builds.enableWorker
-        [ "d ${statePath}/logs 0775 ${user} ${user} - -" ]
-      );
-
-      services = {
-        buildsrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey
-          {
-            after = [ "postgresql.service" "network.target" ];
-            requires = [ "postgresql.service" ];
-            wantedBy = [ "multi-user.target" ];
-
-            description = "builds.sr.ht website service";
-
-            serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-
-            # Hack to bypass this hack: https://git.sr.ht/~sircmpwn/core.sr.ht/tree/master/item/srht-update-profiles#L6
-          } // { preStart = " "; };
-
-        buildsrht-worker = {
-          enable = scfg.enableWorker;
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-          partOf = [ "buildsrht.service" ];
-          description = "builds.sr.ht worker service";
-          path = [ pkgs.openssh pkgs.docker ];
-          preStart = let qemuPackage = pkgs.qemu_kvm;
-          in ''
-            if [[ "$(docker images -q qemu:latest 2> /dev/null)" == "" || "$(cat ${statePath}/docker-image-qemu 2> /dev/null || true)" != "${qemuPackage.version}" ]]; then
-              # Create and import qemu:latest image for docker
-              ${
-                pkgs.dockerTools.streamLayeredImage {
-                  name = "qemu";
-                  tag = "latest";
-                  contents = [ qemuPackage ];
-                }
-              } | docker load
-              # Mark down current package version
-              printf "%s" "${qemuPackage.version}" > ${statePath}/docker-image-qemu
-            fi
-          '';
-          serviceConfig = {
-            Type = "simple";
-            User = user;
-            Group = "nginx";
-            Restart = "always";
-          };
-          serviceConfig.ExecStart = "${pkgs.sourcehut.buildsrht}/bin/builds.sr.ht-worker";
-        };
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL builds.sr.ht is being served at (protocol://domain)
-      "builds.sr.ht".origin = mkDefault "http://builds.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "builds.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "builds.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "builds.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "builds.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # builds.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "builds.sr.ht".oauth-client-id = mkDefault null;
-      "builds.sr.ht".oauth-client-secret = mkDefault null;
-      # The redis connection used for the celery worker
-      "builds.sr.ht".redis = mkDefault "redis://${rcfg.bind}:${toString rcfg.port}/3";
-      # The shell used for ssh
-      "builds.sr.ht".shell = mkDefault "runner-shell";
-      # Register the builds.sr.ht dispatcher
-      "git.sr.ht::dispatch".${builtins.unsafeDiscardStringContext "${pkgs.sourcehut.buildsrht}/bin/buildsrht-keys"} = mkDefault "${user}:${user}";
-
-      # Location for build logs, images, and control command
-    } // lib.attrsets.optionalAttrs scfg.enableWorker {
-      # Default worker stores logs that are accessible via this address:port
-      "builds.sr.ht::worker".name = mkDefault "127.0.0.1:5020";
-      "builds.sr.ht::worker".buildlogs = mkDefault "${scfg.statePath}/logs";
-      "builds.sr.ht::worker".images = mkDefault "${image_dir}/images";
-      "builds.sr.ht::worker".controlcmd = mkDefault "${image_dir}/images/control";
-      "builds.sr.ht::worker".timeout = mkDefault "3m";
-    };
-
-    services.nginx.virtualHosts."logs.${cfg.originBase}" =
-      if scfg.enableWorker then {
-        listen = with builtins; let address = split ":" cfg.settings."builds.sr.ht::worker".name;
-        in [{ addr = elemAt address 0; port = lib.toInt (elemAt address 2); }];
-        locations."/logs".root = "${scfg.statePath}";
-      } else { };
-
-    services.nginx.virtualHosts."builds.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.buildsrht}/${pkgs.sourcehut.python.sitePackages}/buildsrht";
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/default.nix b/nixos/modules/services/misc/sourcehut/default.nix
index 21551d7d5f0..aaa7bb05754 100644
--- a/nixos/modules/services/misc/sourcehut/default.nix
+++ b/nixos/modules/services/misc/sourcehut/default.nix
@@ -47,33 +47,33 @@ let
     })));
   commonServiceSettings = srv: {
     origin = mkOption {
-      description = "URL ${srv}.sr.ht is being served at (protocol://domain)";
+      description = lib.mdDoc "URL ${srv}.sr.ht is being served at (protocol://domain)";
       type = types.str;
       default = "https://${srv}.${domain}";
       defaultText = "https://${srv}.example.com";
     };
     debug-host = mkOption {
-      description = "Address to bind the debug server to.";
+      description = lib.mdDoc "Address to bind the debug server to.";
       type = with types; nullOr str;
       default = null;
     };
     debug-port = mkOption {
-      description = "Port to bind the debug server to.";
+      description = lib.mdDoc "Port to bind the debug server to.";
       type = with types; nullOr str;
       default = null;
     };
     connection-string = mkOption {
-      description = "SQLAlchemy connection string for the database.";
+      description = lib.mdDoc "SQLAlchemy connection string for the database.";
       type = types.str;
       default = "postgresql:///localhost?user=${srv}srht&host=/run/postgresql";
     };
-    migrate-on-upgrade = mkEnableOption "automatic migrations on package upgrade" // { default = true; };
+    migrate-on-upgrade = mkEnableOption (lib.mdDoc "automatic migrations on package upgrade") // { default = true; };
     oauth-client-id = mkOption {
-      description = "${srv}.sr.ht's OAuth client id for meta.sr.ht.";
+      description = lib.mdDoc "${srv}.sr.ht's OAuth client id for meta.sr.ht.";
       type = types.str;
     };
     oauth-client-secret = mkOption {
-      description = "${srv}.sr.ht's OAuth client secret for meta.sr.ht.";
+      description = lib.mdDoc "${srv}.sr.ht's OAuth client secret for meta.sr.ht.";
       type = types.path;
       apply = s: "<" + toString s;
     };
@@ -83,12 +83,11 @@ let
   python = pkgs.sourcehut.python.withPackages (ps: with ps; [
     gunicorn
     eventlet
-    # For monitoring Celery: sudo -u listssrht celery --app listssrht.process -b redis+socket:///run/redis-sourcehut/redis.sock?virtual_host=5 flower
+    # For monitoring Celery: sudo -u listssrht celery --app listssrht.process -b redis+socket:///run/redis-sourcehut/redis.sock?virtual_host=1 flower
     flower
     # Sourcehut services
     srht
     buildsrht
-    dispatchsrht
     gitsrht
     hgsrht
     hubsrht
@@ -101,23 +100,23 @@ let
     todosrht
   ]);
   mkOptionNullOrStr = description: mkOption {
-    inherit description;
+    description = lib.mdDoc description;
     type = with types; nullOr str;
     default = null;
   };
 in
 {
   options.services.sourcehut = {
-    enable = mkEnableOption ''
-      sourcehut - git hosting, continuous integration, mailing list, ticket tracking,
-      task dispatching, wiki and account management services
-    '';
+    enable = mkEnableOption (lib.mdDoc ''
+      sourcehut - git hosting, continuous integration, mailing list, ticket tracking, wiki
+      and account management services
+    '');
 
     services = mkOption {
       type = with types; listOf (enum
-        [ "builds" "dispatch" "git" "hg" "hub" "lists" "man" "meta" "pages" "paste" "todo" ]);
+        [ "builds" "git" "hg" "hub" "lists" "man" "meta" "pages" "paste" "todo" ]);
       defaultText = "locally enabled services";
-      description = ''
+      description = lib.mdDoc ''
         Services that may be displayed as links in the title bar of the Web interface.
       '';
     };
@@ -125,42 +124,42 @@ in
     listenAddress = mkOption {
       type = types.str;
       default = "localhost";
-      description = "Address to bind to.";
+      description = lib.mdDoc "Address to bind to.";
     };
 
     python = mkOption {
       internal = true;
       type = types.package;
       default = python;
-      description = ''
+      description = lib.mdDoc ''
         The python package to use. It should contain references to the *srht modules and also
         gunicorn.
       '';
     };
 
     minio = {
-      enable = mkEnableOption ''local minio integration'';
+      enable = mkEnableOption (lib.mdDoc ''local minio integration'');
     };
 
     nginx = {
-      enable = mkEnableOption ''local nginx integration'';
+      enable = mkEnableOption (lib.mdDoc ''local nginx integration'');
       virtualHost = mkOption {
         type = types.attrs;
         default = {};
-        description = "Virtual-host configuration merged with all Sourcehut's virtual-hosts.";
+        description = lib.mdDoc "Virtual-host configuration merged with all Sourcehut's virtual-hosts.";
       };
     };
 
     postfix = {
-      enable = mkEnableOption ''local postfix integration'';
+      enable = mkEnableOption (lib.mdDoc ''local postfix integration'');
     };
 
     postgresql = {
-      enable = mkEnableOption ''local postgresql integration'';
+      enable = mkEnableOption (lib.mdDoc ''local postgresql integration'');
     };
 
     redis = {
-      enable = mkEnableOption ''local redis integration in a dedicated redis-server'';
+      enable = mkEnableOption (lib.mdDoc ''local redis integration in a dedicated redis-server'');
     };
 
     settings = mkOption {
@@ -168,48 +167,48 @@ in
         freeformType = settingsFormat.type;
         options."sr.ht" = {
           global-domain = mkOption {
-            description = "Global domain name.";
+            description = lib.mdDoc "Global domain name.";
             type = types.str;
             example = "example.com";
           };
           environment = mkOption {
-            description = "Values other than \"production\" adds a banner to each page.";
+            description = lib.mdDoc "Values other than \"production\" adds a banner to each page.";
             type = types.enum [ "development" "production" ];
             default = "development";
           };
           network-key = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               An absolute file path (which should be outside the Nix-store)
-              to a secret key to encrypt internal messages with. Use <code>srht-keygen network</code> to
+              to a secret key to encrypt internal messages with. Use `srht-keygen network` to
               generate this key. It must be consistent between all services and nodes.
             '';
             type = types.path;
             apply = s: "<" + toString s;
           };
           owner-email = mkOption {
-            description = "Owner's email.";
+            description = lib.mdDoc "Owner's email.";
             type = types.str;
             default = "contact@example.com";
           };
           owner-name = mkOption {
-            description = "Owner's name.";
+            description = lib.mdDoc "Owner's name.";
             type = types.str;
             default = "John Doe";
           };
           site-blurb = mkOption {
-            description = "Blurb for your site.";
+            description = lib.mdDoc "Blurb for your site.";
             type = types.str;
             default = "the hacker's forge";
           };
           site-info = mkOption {
-            description = "The top-level info page for your site.";
+            description = lib.mdDoc "The top-level info page for your site.";
             type = types.str;
             default = "https://sourcehut.org";
           };
           service-key = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               An absolute file path (which should be outside the Nix-store)
-              to a key used for encrypting session cookies. Use <code>srht-keygen service</code> to
+              to a key used for encrypting session cookies. Use `srht-keygen service` to
               generate the service key. This must be shared between each node of the same
               service (e.g. git1.sr.ht and git2.sr.ht), but different services may use
               different keys. If you configure all of your services with the same
@@ -219,12 +218,12 @@ in
             apply = s: "<" + toString s;
           };
           site-name = mkOption {
-            description = "The name of your network of sr.ht-based sites.";
+            description = lib.mdDoc "The name of your network of sr.ht-based sites.";
             type = types.str;
             default = "sourcehut";
           };
           source-url = mkOption {
-            description = "The source code for your fork of sr.ht.";
+            description = lib.mdDoc "The source code for your fork of sr.ht.";
             type = types.str;
             default = "https://git.sr.ht/~sircmpwn/srht";
           };
@@ -232,40 +231,52 @@ in
         options.mail = {
           smtp-host = mkOptionNullOrStr "Outgoing SMTP host.";
           smtp-port = mkOption {
-            description = "Outgoing SMTP port.";
+            description = lib.mdDoc "Outgoing SMTP port.";
             type = with types; nullOr port;
             default = null;
           };
           smtp-user = mkOptionNullOrStr "Outgoing SMTP user.";
           smtp-password = mkOptionNullOrStr "Outgoing SMTP password.";
-          smtp-from = mkOptionNullOrStr "Outgoing SMTP FROM.";
+          smtp-from = mkOption {
+            type = types.str;
+            description = lib.mdDoc "Outgoing SMTP FROM.";
+          };
           error-to = mkOptionNullOrStr "Address receiving application exceptions";
           error-from = mkOptionNullOrStr "Address sending application exceptions";
-          pgp-privkey = mkOptionNullOrStr ''
-            An absolute file path (which should be outside the Nix-store)
-            to an OpenPGP private key.
+          pgp-privkey = mkOption {
+            type = types.str;
+            description = lib.mdDoc ''
+              An absolute file path (which should be outside the Nix-store)
+              to an OpenPGP private key.
 
-            Your PGP key information (DO NOT mix up pub and priv here)
-            You must remove the password from your secret key, if present.
-            You can do this with <code>gpg --edit-key [key-id]</code>,
-            then use the <code>passwd</code> command and do not enter a new password.
-          '';
-          pgp-pubkey = mkOptionNullOrStr "OpenPGP public key.";
-          pgp-key-id = mkOptionNullOrStr "OpenPGP key identifier.";
+              Your PGP key information (DO NOT mix up pub and priv here)
+              You must remove the password from your secret key, if present.
+              You can do this with `gpg --edit-key [key-id]`,
+              then use the `passwd` command and do not enter a new password.
+            '';
+          };
+          pgp-pubkey = mkOption {
+            type = with types; either path str;
+            description = lib.mdDoc "OpenPGP public key.";
+          };
+          pgp-key-id = mkOption {
+            type = types.str;
+            description = lib.mdDoc "OpenPGP key identifier.";
+          };
         };
         options.objects = {
           s3-upstream = mkOption {
-            description = "Configure the S3-compatible object storage service.";
+            description = lib.mdDoc "Configure the S3-compatible object storage service.";
             type = with types; nullOr str;
             default = null;
           };
           s3-access-key = mkOption {
-            description = "Access key to the S3-compatible object storage service";
+            description = lib.mdDoc "Access key to the S3-compatible object storage service";
             type = with types; nullOr str;
             default = null;
           };
           s3-secret-key = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               An absolute file path (which should be outside the Nix-store)
               to the secret key of the S3-compatible object storage service.
             '';
@@ -276,59 +287,33 @@ in
         };
         options.webhooks = {
           private-key = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               An absolute file path (which should be outside the Nix-store)
               to a base64-encoded Ed25519 key for signing webhook payloads.
               This should be consistent for all *.sr.ht sites,
               as this key will be used to verify signatures
               from other sites in your network.
-              Use the <code>srht-keygen webhook</code> command to generate a key.
+              Use the `srht-keygen webhook` command to generate a key.
             '';
             type = types.path;
             apply = s: "<" + toString s;
           };
         };
 
-        options."dispatch.sr.ht" = commonServiceSettings "dispatch" // {
-        };
-        options."dispatch.sr.ht::github" = {
-          oauth-client-id = mkOptionNullOrStr "OAuth client id.";
-          oauth-client-secret = mkOptionNullOrStr "OAuth client secret.";
-        };
-        options."dispatch.sr.ht::gitlab" = {
-          enabled = mkEnableOption "GitLab integration";
-          canonical-upstream = mkOption {
-            type = types.str;
-            description = "Canonical upstream.";
-            default = "gitlab.com";
-          };
-          repo-cache = mkOption {
-            type = types.str;
-            description = "Repository cache directory.";
-            default = "./repo-cache";
-          };
-          "gitlab.com" = mkOption {
-            type = with types; nullOr str;
-            description = "GitLab id and secret.";
-            default = null;
-            example = "GitLab:application id:secret";
-          };
-        };
-
         options."builds.sr.ht" = commonServiceSettings "builds" // {
-          allow-free = mkEnableOption "nonpaying users to submit builds";
+          allow-free = mkEnableOption (lib.mdDoc "nonpaying users to submit builds");
           redis = mkOption {
-            description = "The Redis connection used for the Celery worker.";
+            description = lib.mdDoc "The Redis connection used for the Celery worker.";
             type = types.str;
             default = "redis+socket:///run/redis-sourcehut-buildsrht/redis.sock?virtual_host=2";
           };
           shell = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Scripts used to launch on SSH connection.
-              <literal>/usr/bin/master-shell</literal> on master,
-              <literal>/usr/bin/runner-shell</literal> on runner.
+              `/usr/bin/master-shell` on master,
+              `/usr/bin/runner-shell` on runner.
               If master and worker are on the same system
-              set to <literal>/usr/bin/runner-shell</literal>.
+              set to `/usr/bin/runner-shell`.
             '';
             type = types.enum ["/usr/bin/master-shell" "/usr/bin/runner-shell"];
             default = "/usr/bin/master-shell";
@@ -336,19 +321,19 @@ in
         };
         options."builds.sr.ht::worker" = {
           bind-address = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               HTTP bind address for serving local build information/monitoring.
             '';
             type = types.str;
             default = "localhost:8080";
           };
           buildlogs = mkOption {
-            description = "Path to write build logs.";
+            description = lib.mdDoc "Path to write build logs.";
             type = types.str;
             default = "/var/log/sourcehut/buildsrht-worker";
           };
           name = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Listening address and listening port
               of the build runner (with HTTP port if not 80).
             '';
@@ -356,9 +341,9 @@ in
             default = "localhost:5020";
           };
           timeout = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Max build duration.
-              See <link xlink:href="https://golang.org/pkg/time/#ParseDuration"/>.
+              See <https://golang.org/pkg/time/#ParseDuration>.
             '';
             type = types.str;
             default = "3m";
@@ -367,12 +352,12 @@ in
 
         options."git.sr.ht" = commonServiceSettings "git" // {
           outgoing-domain = mkOption {
-            description = "Outgoing domain.";
+            description = lib.mdDoc "Outgoing domain.";
             type = types.str;
             default = "https://git.localhost.localdomain";
           };
           post-update-script = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               A post-update script which is installed in every git repo.
               This setting is propagated to newer and existing repositories.
             '';
@@ -381,7 +366,7 @@ in
             defaultText = "\${pkgs.sourcehut.gitsrht}/bin/gitsrht-update-hook";
           };
           repos = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Path to git repositories on disk.
               If changing the default, you must ensure that
               the gitsrht's user as read and write access to it.
@@ -390,18 +375,18 @@ in
             default = "/var/lib/sourcehut/gitsrht/repos";
           };
           webhooks = mkOption {
-            description = "The Redis connection used for the webhooks worker.";
+            description = lib.mdDoc "The Redis connection used for the webhooks worker.";
             type = types.str;
             default = "redis+socket:///run/redis-sourcehut-gitsrht/redis.sock?virtual_host=1";
           };
         };
         options."git.sr.ht::api" = {
           internal-ipnet = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Set of IP subnets which are permitted to utilize internal API
               authentication. This should be limited to the subnets
               from which your *.sr.ht services are running.
-              See <xref linkend="opt-services.sourcehut.listenAddress"/>.
+              See [](#opt-services.sourcehut.listenAddress).
             '';
             type = with types; listOf str;
             default = [ "127.0.0.0/8" "::1/128" ];
@@ -410,7 +395,7 @@ in
 
         options."hg.sr.ht" = commonServiceSettings "hg" // {
           changegroup-script = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               A changegroup script which is installed in every mercurial repo.
               This setting is propagated to newer and existing repositories.
             '';
@@ -419,7 +404,7 @@ in
             defaultText = "\${cfg.python}/bin/hgsrht-hook-changegroup";
           };
           repos = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Path to mercurial repositories on disk.
               If changing the default, you must ensure that
               the hgsrht's user as read and write access to it.
@@ -432,18 +417,18 @@ in
             (defaults to where the hgsrht code is)
           '';
           clone_bundle_threshold = mkOption {
-            description = ".hg/store size (in MB) past which the nightly job generates clone bundles.";
+            description = lib.mdDoc ".hg/store size (in MB) past which the nightly job generates clone bundles.";
             type = types.ints.unsigned;
             default = 50;
           };
           hg_ssh = mkOption {
-            description = "Path to hg-ssh (if not in $PATH).";
+            description = lib.mdDoc "Path to hg-ssh (if not in $PATH).";
             type = types.str;
             default = "${pkgs.mercurial}/bin/hg-ssh";
             defaultText = "\${pkgs.mercurial}/bin/hg-ssh";
           };
           webhooks = mkOption {
-            description = "The Redis connection used for the webhooks worker.";
+            description = lib.mdDoc "The Redis connection used for the webhooks worker.";
             type = types.str;
             default = "redis+socket:///run/redis-sourcehut-hgsrht/redis.sock?virtual_host=1";
           };
@@ -453,31 +438,31 @@ in
         };
 
         options."lists.sr.ht" = commonServiceSettings "lists" // {
-          allow-new-lists = mkEnableOption "Allow creation of new lists.";
+          allow-new-lists = mkEnableOption (lib.mdDoc "Allow creation of new lists.");
           notify-from = mkOption {
-            description = "Outgoing email for notifications generated by users.";
+            description = lib.mdDoc "Outgoing email for notifications generated by users.";
             type = types.str;
             default = "lists-notify@localhost.localdomain";
           };
           posting-domain = mkOption {
-            description = "Posting domain.";
+            description = lib.mdDoc "Posting domain.";
             type = types.str;
             default = "lists.localhost.localdomain";
           };
           redis = mkOption {
-            description = "The Redis connection used for the Celery worker.";
+            description = lib.mdDoc "The Redis connection used for the Celery worker.";
             type = types.str;
             default = "redis+socket:///run/redis-sourcehut-listssrht/redis.sock?virtual_host=2";
           };
           webhooks = mkOption {
-            description = "The Redis connection used for the webhooks worker.";
+            description = lib.mdDoc "The Redis connection used for the webhooks worker.";
             type = types.str;
             default = "redis+socket:///run/redis-sourcehut-listssrht/redis.sock?virtual_host=1";
           };
         };
         options."lists.sr.ht::worker" = {
           reject-mimetypes = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Comma-delimited list of Content-Types to reject. Messages with Content-Types
               included in this list are rejected. Multipart messages are always supported,
               and each part is checked against this list.
@@ -488,12 +473,12 @@ in
             default = ["text/html"];
           };
           reject-url = mkOption {
-            description = "Reject URL.";
+            description = lib.mdDoc "Reject URL.";
             type = types.str;
             default = "https://man.sr.ht/lists.sr.ht/etiquette.md";
           };
           sock = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Path for the lmtp daemon's unix socket. Direct incoming mail to this socket.
               Alternatively, specify IP:PORT and an SMTP server will be run instead.
             '';
@@ -501,7 +486,7 @@ in
             default = "/tmp/lists.sr.ht-lmtp.sock";
           };
           sock-group = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               The lmtp daemon will make the unix socket group-read/write
               for users in this group.
             '';
@@ -517,38 +502,38 @@ in
           removeAttrs (commonServiceSettings "meta")
             ["oauth-client-id" "oauth-client-secret"] // {
           api-origin = mkOption {
-            description = "Origin URL for API, 100 more than web.";
+            description = lib.mdDoc "Origin URL for API, 100 more than web.";
             type = types.str;
             default = "http://${cfg.listenAddress}:${toString (cfg.meta.port + 100)}";
             defaultText = ''http://<xref linkend="opt-services.sourcehut.listenAddress"/>:''${toString (<xref linkend="opt-services.sourcehut.meta.port"/> + 100)}'';
           };
           webhooks = mkOption {
-            description = "The Redis connection used for the webhooks worker.";
+            description = lib.mdDoc "The Redis connection used for the webhooks worker.";
             type = types.str;
             default = "redis+socket:///run/redis-sourcehut-metasrht/redis.sock?virtual_host=1";
           };
-          welcome-emails = mkEnableOption "sending stock sourcehut welcome emails after signup";
+          welcome-emails = mkEnableOption (lib.mdDoc "sending stock sourcehut welcome emails after signup");
         };
         options."meta.sr.ht::api" = {
           internal-ipnet = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Set of IP subnets which are permitted to utilize internal API
               authentication. This should be limited to the subnets
               from which your *.sr.ht services are running.
-              See <xref linkend="opt-services.sourcehut.listenAddress"/>.
+              See [](#opt-services.sourcehut.listenAddress).
             '';
             type = with types; listOf str;
             default = [ "127.0.0.0/8" "::1/128" ];
           };
         };
         options."meta.sr.ht::aliases" = mkOption {
-          description = "Aliases for the client IDs of commonly used OAuth clients.";
+          description = lib.mdDoc "Aliases for the client IDs of commonly used OAuth clients.";
           type = with types; attrsOf int;
           default = {};
           example = { "git.sr.ht" = 12345; };
         };
         options."meta.sr.ht::billing" = {
-          enabled = mkEnableOption "the billing system";
+          enabled = mkEnableOption (lib.mdDoc "the billing system");
           stripe-public-key = mkOptionNullOrStr "Public key for Stripe. Get your keys at https://dashboard.stripe.com/account/apikeys";
           stripe-secret-key = mkOptionNullOrStr ''
             An absolute file path (which should be outside the Nix-store)
@@ -558,14 +543,14 @@ in
           };
         };
         options."meta.sr.ht::settings" = {
-          registration = mkEnableOption "public registration";
+          registration = mkEnableOption (lib.mdDoc "public registration");
           onboarding-redirect = mkOption {
-            description = "Where to redirect new users upon registration.";
+            description = lib.mdDoc "Where to redirect new users upon registration.";
             type = types.str;
             default = "https://meta.localhost.localdomain";
           };
           user-invites = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               How many invites each user is issued upon registration
               (only applicable if open registration is disabled).
             '';
@@ -576,7 +561,7 @@ in
 
         options."pages.sr.ht" = commonServiceSettings "pages" // {
           gemini-certs = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               An absolute file path (which should be outside the Nix-store)
               to Gemini certificates.
             '';
@@ -584,14 +569,14 @@ in
             default = null;
           };
           max-site-size = mkOption {
-            description = "Maximum size of any given site (post-gunzip), in MiB.";
+            description = lib.mdDoc "Maximum size of any given site (post-gunzip), in MiB.";
             type = types.int;
             default = 1024;
           };
           user-domain = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Configures the user domain, if enabled.
-              All users are given &lt;username&gt;.this.domain.
+              All users are given \<username\>.this.domain.
             '';
             type = with types; nullOr str;
             default = null;
@@ -599,11 +584,11 @@ in
         };
         options."pages.sr.ht::api" = {
           internal-ipnet = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Set of IP subnets which are permitted to utilize internal API
               authentication. This should be limited to the subnets
               from which your *.sr.ht services are running.
-              See <xref linkend="opt-services.sourcehut.listenAddress"/>.
+              See [](#opt-services.sourcehut.listenAddress).
             '';
             type = with types; listOf str;
             default = [ "127.0.0.0/8" "::1/128" ];
@@ -615,24 +600,24 @@ in
 
         options."todo.sr.ht" = commonServiceSettings "todo" // {
           notify-from = mkOption {
-            description = "Outgoing email for notifications generated by users.";
+            description = lib.mdDoc "Outgoing email for notifications generated by users.";
             type = types.str;
             default = "todo-notify@localhost.localdomain";
           };
           webhooks = mkOption {
-            description = "The Redis connection used for the webhooks worker.";
+            description = lib.mdDoc "The Redis connection used for the webhooks worker.";
             type = types.str;
             default = "redis+socket:///run/redis-sourcehut-todosrht/redis.sock?virtual_host=1";
           };
         };
         options."todo.sr.ht::mail" = {
           posting-domain = mkOption {
-            description = "Posting domain.";
+            description = lib.mdDoc "Posting domain.";
             type = types.str;
             default = "todo.localhost.localdomain";
           };
           sock = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               Path for the lmtp daemon's unix socket. Direct incoming mail to this socket.
               Alternatively, specify IP:PORT and an SMTP server will be run instead.
             '';
@@ -640,7 +625,7 @@ in
             default = "/tmp/todo.sr.ht-lmtp.sock";
           };
           sock-group = mkOption {
-            description = ''
+            description = lib.mdDoc ''
               The lmtp daemon will make the unix socket group-read/write
               for users in this group.
             '';
@@ -650,23 +635,23 @@ in
         };
       };
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         The configuration for the sourcehut network.
       '';
     };
 
     builds = {
-      enableWorker = mkEnableOption ''
+      enableWorker = mkEnableOption (lib.mdDoc ''
         worker for builds.sr.ht
 
-        <warning><para>
+        ::: {.warning}
         For smaller deployments, job runners can be installed alongside the master server
         but even if you only build your own software, integration with other services
         may cause you to run untrusted builds
         (e.g. automatic testing of patches via listssrht).
-        See <link xlink:href="https://man.sr.ht/builds.sr.ht/configuration.md#security-model"/>.
-        </para></warning>
-      '';
+        See <https://man.sr.ht/builds.sr.ht/configuration.md#security-model>.
+        :::
+      '');
 
       images = mkOption {
         type = with types; attrsOf (attrsOf (attrsOf package));
@@ -686,7 +671,7 @@ in
             nixos.unstable.x86_64 = image_from_nixpkgs;
           }
         )'';
-        description = ''
+        description = lib.mdDoc ''
           Images for builds.sr.ht. Each package should be distro.release.arch and point to a /nix/store/package/root.img.qcow2.
         '';
       };
@@ -698,12 +683,12 @@ in
         default = pkgs.git;
         defaultText = literalExpression "pkgs.git";
         example = literalExpression "pkgs.gitFull";
-        description = ''
+        description = lib.mdDoc ''
           Git package for git.sr.ht. This can help silence collisions.
         '';
       };
       fcgiwrap.preforkProcess = mkOption {
-        description = "Number of fcgiwrap processes to prefork.";
+        description = lib.mdDoc "Number of fcgiwrap processes to prefork.";
         type = types.int;
         default = 4;
       };
@@ -714,14 +699,14 @@ in
         type = types.package;
         default = pkgs.mercurial;
         defaultText = literalExpression "pkgs.mercurial";
-        description = ''
+        description = lib.mdDoc ''
           Mercurial package for hg.sr.ht. This can help silence collisions.
         '';
       };
       cloneBundles = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Generate clonebundles (which require more disk space but dramatically speed up cloning large repositories).
         '';
       };
@@ -732,12 +717,12 @@ in
         extraArgs = mkOption {
           type = with types; listOf str;
           default = [ "--loglevel DEBUG" "--pool eventlet" "--without-heartbeat" ];
-          description = "Extra arguments passed to the Celery responsible for processing mails.";
+          description = lib.mdDoc "Extra arguments passed to the Celery responsible for processing mails.";
         };
         celeryConfig = mkOption {
           type = types.lines;
           default = "";
-          description = "Content of the <literal>celeryconfig.py</literal> used by the Celery of <literal>listssrht-process</literal>.";
+          description = lib.mdDoc "Content of the `celeryconfig.py` used by the Celery of `listssrht-process`.";
         };
       };
     };
@@ -905,6 +890,11 @@ in
       inherit configIniOfService;
       srvsrht = "buildsrht";
       port = 5002;
+      extraServices.buildsrht-api = {
+        serviceConfig.Restart = "always";
+        serviceConfig.RestartSec = "5s";
+        serviceConfig.ExecStart = "${pkgs.sourcehut.buildsrht}/bin/buildsrht-api -b ${cfg.listenAddress}:${toString (cfg.builds.port + 100)}";
+      };
       # TODO: a celery worker on the master and worker are apparently needed
       extraServices.buildsrht-worker = let
         qemuPackage = pkgs.qemu_kvm;
@@ -928,13 +918,13 @@ in
           fi
         '';
         serviceConfig = {
-          ExecStart = "${pkgs.sourcehut.buildsrht}/bin/builds.sr.ht-worker";
+          ExecStart = "${pkgs.sourcehut.buildsrht}/bin/buildsrht-worker";
           BindPaths = [ cfg.settings."builds.sr.ht::worker".buildlogs ];
           LogsDirectory = [ "sourcehut/${serviceName}" ];
           RuntimeDirectory = [ "sourcehut/${serviceName}/subdir" ];
           StateDirectory = [ "sourcehut/${serviceName}" ];
           TimeoutStartSec = "1800s";
-          # builds.sr.ht-worker looks up ../config.ini
+          # buildsrht-worker looks up ../config.ini
           WorkingDirectory = "-"+"/run/sourcehut/${serviceName}/subdir";
         };
       };
@@ -952,12 +942,12 @@ in
           ) cfg.builds.images
         );
         image_dir_pre = pkgs.symlinkJoin {
-          name = "builds.sr.ht-worker-images-pre";
+          name = "buildsrht-worker-images-pre";
           paths = image_dirs;
             # FIXME: not working, apparently because ubuntu/latest is a broken link
             # ++ [ "${pkgs.sourcehut.buildsrht}/lib/images" ];
         };
-        image_dir = pkgs.runCommand "builds.sr.ht-worker-images" { } ''
+        image_dir = pkgs.runCommand "buildsrht-worker-images" { } ''
           mkdir -p $out/images
           cp -Lr ${image_dir_pre}/* $out/images
         '';
@@ -1004,11 +994,6 @@ in
       ];
     })
 
-    (import ./service.nix "dispatch" {
-      inherit configIniOfService;
-      port = 5005;
-    })
-
     (import ./service.nix "git" (let
       baseService = {
         path = [ cfg.git.package ];
@@ -1018,7 +1003,7 @@ in
       inherit configIniOfService;
       mainService = mkMerge [ baseService {
         serviceConfig.StateDirectory = [ "sourcehut/gitsrht" "sourcehut/gitsrht/repos" ];
-        preStart = mkIf (!versionAtLeast config.system.stateVersion "22.05") (mkBefore ''
+        preStart = mkIf (versionOlder config.system.stateVersion "22.05") (mkBefore ''
           # Fix Git hooks of repositories pre-dating https://github.com/NixOS/nixpkgs/pull/133984
           (
           set +f
@@ -1081,6 +1066,11 @@ in
           };
         })
       ];
+      extraServices.gitsrht-api = {
+        serviceConfig.Restart = "always";
+        serviceConfig.RestartSec = "5s";
+        serviceConfig.ExecStart = "${pkgs.sourcehut.gitsrht}/bin/gitsrht-api -b ${cfg.listenAddress}:${toString (cfg.git.port + 100)}";
+      };
       extraServices.gitsrht-fcgiwrap = mkIf cfg.nginx.enable {
         serviceConfig = {
           # Socket is passed by gitsrht-fcgiwrap.socket
@@ -1124,6 +1114,11 @@ in
         timerConfig.OnCalendar = ["daily"];
         timerConfig.AccuracySec = "1h";
       };
+      extraServices.hgsrht-api = {
+        serviceConfig.Restart = "always";
+        serviceConfig.RestartSec = "5s";
+        serviceConfig.ExecStart = "${pkgs.sourcehut.hgsrht}/bin/hgsrht-api -b ${cfg.listenAddress}:${toString (cfg.hg.port + 100)}";
+      };
       extraConfig = mkMerge [
         {
           users.users.${cfg.hg.user}.shell = pkgs.bash;
@@ -1184,6 +1179,11 @@ in
       inherit configIniOfService;
       port = 5006;
       webhooks = true;
+      extraServices.listssrht-api = {
+        serviceConfig.Restart = "always";
+        serviceConfig.RestartSec = "5s";
+        serviceConfig.ExecStart = "${pkgs.sourcehut.listssrht}/bin/listssrht-api -b ${cfg.listenAddress}:${toString (cfg.lists.port + 100)}";
+      };
       # Receive the mail from Postfix and enqueue them into Redis and PostgreSQL
       extraServices.listssrht-lmtp = {
         wants = [ "postfix.service" ];
@@ -1232,9 +1232,13 @@ in
       inherit configIniOfService;
       port = 5000;
       webhooks = true;
+      extraTimers.metasrht-daily.timerConfig = {
+        OnCalendar = ["daily"];
+        AccuracySec = "1h";
+      };
       extraServices.metasrht-api = {
         serviceConfig.Restart = "always";
-        serviceConfig.RestartSec = "2s";
+        serviceConfig.RestartSec = "5s";
         preStart = "set -x\n" + concatStringsSep "\n\n" (attrValues (mapAttrs (k: s:
           let srvMatch = builtins.match "^([a-z]*)\\.sr\\.ht$" k;
               srv = head srvMatch;
@@ -1248,10 +1252,6 @@ in
           ) cfg.settings));
         serviceConfig.ExecStart = "${pkgs.sourcehut.metasrht}/bin/metasrht-api -b ${cfg.listenAddress}:${toString (cfg.meta.port + 100)}";
       };
-      extraTimers.metasrht-daily.timerConfig = {
-        OnCalendar = ["daily"];
-        AccuracySec = "1h";
-      };
       extraConfig = mkMerge [
         {
           assertions = [
@@ -1348,6 +1348,11 @@ in
       inherit configIniOfService;
       port = 5003;
       webhooks = true;
+      extraServices.todosrht-api = {
+        serviceConfig.Restart = "always";
+        serviceConfig.RestartSec = "5s";
+        serviceConfig.ExecStart = "${pkgs.sourcehut.todosrht}/bin/todosrht-api -b ${cfg.listenAddress}:${toString (cfg.todo.port + 100)}";
+      };
       extraServices.todosrht-lmtp = {
         wants = [ "postfix.service" ];
         unitConfig.JoinsNamespaceOf = optional cfg.postfix.enable "postfix.service";
@@ -1379,8 +1384,12 @@ in
     (mkRenamedOptionModule [ "services" "sourcehut" "address" ]
                            [ "services" "sourcehut" "listenAddress" ])
 
+    (mkRemovedOptionModule [ "services" "sourcehut" "dispatch" ] ''
+        dispatch is deprecated. See https://sourcehut.org/blog/2022-08-01-dispatch-deprecation-plans/
+        for more information.
+    '')
   ];
 
   meta.doc = ./sourcehut.xml;
-  meta.maintainers = with maintainers; [ julm tomberek ];
+  meta.maintainers = with maintainers; [ tomberek ];
 }
diff --git a/nixos/modules/services/misc/sourcehut/dispatch.nix b/nixos/modules/services/misc/sourcehut/dispatch.nix
deleted file mode 100644
index 292a51d3e1c..00000000000
--- a/nixos/modules/services/misc/sourcehut/dispatch.nix
+++ /dev/null
@@ -1,127 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  cfgIni = cfg.settings;
-  scfg = cfg.dispatch;
-  iniKey = "dispatch.sr.ht";
-
-  drv = pkgs.sourcehut.dispatchsrht;
-in
-{
-  options.services.sourcehut.dispatch = {
-    user = mkOption {
-      type = types.str;
-      default = "dispatchsrht";
-      description = ''
-        User for dispatch.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5005;
-      description = ''
-        Port on which the "dispatch" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "dispatch.sr.ht";
-      description = ''
-        PostgreSQL database name for dispatch.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/dispatchsrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/dispatchsrht"'';
-      description = ''
-        State path for dispatch.sr.ht.
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "dispatch" cfg.services) {
-
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          description = "dispatch.sr.ht user";
-        };
-      };
-
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services.postgresql = {
-      authentication = ''
-        local ${database} ${user} trust
-      '';
-      ensureDatabases = [ database ];
-      ensureUsers = [
-        {
-          name = user;
-          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-        }
-      ];
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        "d ${statePath} 0750 ${user} ${user} -"
-      ];
-
-      services.dispatchsrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-        after = [ "postgresql.service" "network.target" ];
-        requires = [ "postgresql.service" ];
-        wantedBy = [ "multi-user.target" ];
-
-        description = "dispatch.sr.ht website service";
-
-        serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL dispatch.sr.ht is being served at (protocol://domain)
-      "dispatch.sr.ht".origin = mkDefault "http://dispatch.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "dispatch.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "dispatch.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "dispatch.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "dispatch.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # dispatch.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "dispatch.sr.ht".oauth-client-id = mkDefault null;
-      "dispatch.sr.ht".oauth-client-secret = mkDefault null;
-
-      # Github Integration
-      "dispatch.sr.ht::github".oauth-client-id = mkDefault null;
-      "dispatch.sr.ht::github".oauth-client-secret = mkDefault null;
-
-      # Gitlab Integration
-      "dispatch.sr.ht::gitlab".enabled = mkDefault null;
-      "dispatch.sr.ht::gitlab".canonical-upstream = mkDefault "gitlab.com";
-      "dispatch.sr.ht::gitlab".repo-cache = mkDefault "./repo-cache";
-      # "dispatch.sr.ht::gitlab"."gitlab.com" = mkDefault "GitLab:application id:secret";
-    };
-
-    services.nginx.virtualHosts."dispatch.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.dispatchsrht}/${pkgs.sourcehut.python.sitePackages}/dispatchsrht";
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/git.nix b/nixos/modules/services/misc/sourcehut/git.nix
deleted file mode 100644
index ff110905d18..00000000000
--- a/nixos/modules/services/misc/sourcehut/git.nix
+++ /dev/null
@@ -1,217 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  scfg = cfg.git;
-  iniKey = "git.sr.ht";
-
-  rcfg = config.services.redis;
-  drv = pkgs.sourcehut.gitsrht;
-in
-{
-  options.services.sourcehut.git = {
-    user = mkOption {
-      type = types.str;
-      visible = false;
-      internal = true;
-      readOnly = true;
-      default = "git";
-      description = ''
-        User for git.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5001;
-      description = ''
-        Port on which the "git" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "git.sr.ht";
-      description = ''
-        PostgreSQL database name for git.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/gitsrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/gitsrht"'';
-      description = ''
-        State path for git.sr.ht.
-      '';
-    };
-
-    package = mkOption {
-      type = types.package;
-      default = pkgs.git;
-      defaultText = literalExpression "pkgs.git";
-      example = literalExpression "pkgs.gitFull";
-      description = ''
-        Git package for git.sr.ht. This can help silence collisions.
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "git" cfg.services) {
-    # sshd refuses to run with `Unsafe AuthorizedKeysCommand ... bad ownership or modes for directory /nix/store`
-    environment.etc."ssh/gitsrht-dispatch" = {
-      mode = "0755";
-      text = ''
-        #! ${pkgs.stdenv.shell}
-        ${cfg.python}/bin/gitsrht-dispatch "$@"
-      '';
-    };
-
-    # Needs this in the $PATH when sshing into the server
-    environment.systemPackages = [ cfg.git.package ];
-
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          # https://stackoverflow.com/questions/22314298/git-push-results-in-fatal-protocol-error-bad-line-length-character-this
-          # Probably could use gitsrht-shell if output is restricted to just parameters...
-          shell = pkgs.bash;
-          description = "git.sr.ht user";
-        };
-      };
-
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services = {
-      cron.systemCronJobs = [ "*/20 * * * * ${cfg.python}/bin/gitsrht-periodic" ];
-      fcgiwrap.enable = true;
-
-      openssh.authorizedKeysCommand = ''/etc/ssh/gitsrht-dispatch "%u" "%h" "%t" "%k"'';
-      openssh.authorizedKeysCommandUser = "root";
-      openssh.extraConfig = ''
-        PermitUserEnvironment SRHT_*
-      '';
-
-      postgresql = {
-        authentication = ''
-          local ${database} ${user} trust
-        '';
-        ensureDatabases = [ database ];
-        ensureUsers = [
-          {
-            name = user;
-            ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-          }
-        ];
-      };
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        # /var/log is owned by root
-        "f /var/log/git-srht-shell 0644 ${user} ${user} -"
-
-        "d ${statePath} 0750 ${user} ${user} -"
-        "d ${cfg.settings."${iniKey}".repos} 2755 ${user} ${user} -"
-      ];
-
-      services = {
-        gitsrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-          after = [ "redis.service" "postgresql.service" "network.target" ];
-          requires = [ "redis.service" "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          # Needs internally to create repos at the very least
-          path = [ pkgs.git ];
-          description = "git.sr.ht website service";
-
-          serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-        };
-
-        gitsrht-webhooks = {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "git.sr.ht webhooks service";
-          serviceConfig = {
-            Type = "simple";
-            User = user;
-            Restart = "always";
-          };
-
-          serviceConfig.ExecStart = "${cfg.python}/bin/celery -A ${drv.pname}.webhooks worker --loglevel=info";
-        };
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL git.sr.ht is being served at (protocol://domain)
-      "git.sr.ht".origin = mkDefault "http://git.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "git.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "git.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "git.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "git.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # The redis connection used for the webhooks worker
-      "git.sr.ht".webhooks = mkDefault "redis://${rcfg.bind}:${toString rcfg.port}/1";
-
-      # A post-update script which is installed in every git repo.
-      "git.sr.ht".post-update-script = mkDefault "${pkgs.sourcehut.gitsrht}/bin/gitsrht-update-hook";
-
-      # git.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "git.sr.ht".oauth-client-id = mkDefault null;
-      "git.sr.ht".oauth-client-secret = mkDefault null;
-      # Path to git repositories on disk
-      "git.sr.ht".repos = mkDefault "/var/lib/git";
-
-      "git.sr.ht".outgoing-domain = mkDefault "http://git.${cfg.originBase}";
-
-      # The authorized keys hook uses this to dispatch to various handlers
-      # The format is a program to exec into as the key, and the user to match as the
-      # value. When someone tries to log in as this user, this program is executed
-      # and is expected to omit an AuthorizedKeys file.
-      #
-      # Discard of the string context is in order to allow derivation-derived strings.
-      # This is safe if the relevant package is installed which will be the case if the setting is utilized.
-      "git.sr.ht::dispatch".${builtins.unsafeDiscardStringContext "${pkgs.sourcehut.gitsrht}/bin/gitsrht-keys"} = mkDefault "${user}:${user}";
-    };
-
-    services.nginx.virtualHosts."git.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.gitsrht}/${pkgs.sourcehut.python.sitePackages}/gitsrht";
-      extraConfig = ''
-            location = /authorize {
-            proxy_pass http://${cfg.address}:${toString port};
-            proxy_pass_request_body off;
-            proxy_set_header Content-Length "";
-            proxy_set_header X-Original-URI $request_uri;
-        }
-            location ~ ^/([^/]+)/([^/]+)/(HEAD|info/refs|objects/info/.*|git-upload-pack).*$ {
-                auth_request /authorize;
-                root /var/lib/git;
-                fastcgi_pass unix:/run/fcgiwrap.sock;
-                fastcgi_param SCRIPT_FILENAME ${pkgs.git}/bin/git-http-backend;
-                fastcgi_param PATH_INFO $uri;
-                fastcgi_param GIT_PROJECT_ROOT $document_root;
-                fastcgi_read_timeout 500s;
-                include ${config.services.nginx.package}/conf/fastcgi_params;
-                gzip off;
-            }
-      '';
-
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/hg.nix b/nixos/modules/services/misc/sourcehut/hg.nix
deleted file mode 100644
index 6ba1df8b6dd..00000000000
--- a/nixos/modules/services/misc/sourcehut/hg.nix
+++ /dev/null
@@ -1,175 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  scfg = cfg.hg;
-  iniKey = "hg.sr.ht";
-
-  rcfg = config.services.redis;
-  drv = pkgs.sourcehut.hgsrht;
-in
-{
-  options.services.sourcehut.hg = {
-    user = mkOption {
-      type = types.str;
-      internal = true;
-      readOnly = true;
-      default = "hg";
-      description = ''
-        User for hg.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5010;
-      description = ''
-        Port on which the "hg" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "hg.sr.ht";
-      description = ''
-        PostgreSQL database name for hg.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/hgsrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/hgsrht"'';
-      description = ''
-        State path for hg.sr.ht.
-      '';
-    };
-
-    cloneBundles = mkOption {
-      type = types.bool;
-      default = false;
-      description = ''
-        Generate clonebundles (which require more disk space but dramatically speed up cloning large repositories).
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "hg" cfg.services) {
-    # In case it ever comes into being
-    environment.etc."ssh/hgsrht-dispatch" = {
-      mode = "0755";
-      text = ''
-        #! ${pkgs.stdenv.shell}
-        ${cfg.python}/bin/gitsrht-dispatch $@
-      '';
-    };
-
-    environment.systemPackages = [ pkgs.mercurial ];
-
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          # Assuming hg.sr.ht needs this too
-          shell = pkgs.bash;
-          description = "hg.sr.ht user";
-        };
-      };
-
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services = {
-      cron.systemCronJobs = [ "*/20 * * * * ${cfg.python}/bin/hgsrht-periodic" ]
-        ++ optional cloneBundles "0 * * * * ${cfg.python}/bin/hgsrht-clonebundles";
-
-      openssh.authorizedKeysCommand = ''/etc/ssh/hgsrht-dispatch "%u" "%h" "%t" "%k"'';
-      openssh.authorizedKeysCommandUser = "root";
-      openssh.extraConfig = ''
-        PermitUserEnvironment SRHT_*
-      '';
-
-      postgresql = {
-        authentication = ''
-          local ${database} ${user} trust
-        '';
-        ensureDatabases = [ database ];
-        ensureUsers = [
-          {
-            name = user;
-            ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-          }
-        ];
-      };
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        # /var/log is owned by root
-        "f /var/log/hg-srht-shell 0644 ${user} ${user} -"
-
-        "d ${statePath} 0750 ${user} ${user} -"
-        "d ${cfg.settings."${iniKey}".repos} 2755 ${user} ${user} -"
-      ];
-
-      services.hgsrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-        after = [ "redis.service" "postgresql.service" "network.target" ];
-        requires = [ "redis.service" "postgresql.service" ];
-        wantedBy = [ "multi-user.target" ];
-
-        path = [ pkgs.mercurial ];
-        description = "hg.sr.ht website service";
-
-        serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL hg.sr.ht is being served at (protocol://domain)
-      "hg.sr.ht".origin = mkDefault "http://hg.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "hg.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "hg.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "hg.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # The redis connection used for the webhooks worker
-      "hg.sr.ht".webhooks = mkDefault "redis://${rcfg.bind}:${toString rcfg.port}/1";
-      # A post-update script which is installed in every mercurial repo.
-      "hg.sr.ht".changegroup-script = mkDefault "${cfg.python}/bin/hgsrht-hook-changegroup";
-      # hg.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "hg.sr.ht".oauth-client-id = mkDefault null;
-      "hg.sr.ht".oauth-client-secret = mkDefault null;
-      # Path to mercurial repositories on disk
-      "hg.sr.ht".repos = mkDefault "/var/lib/hg";
-      # Path to the srht mercurial extension
-      # (defaults to where the hgsrht code is)
-      # "hg.sr.ht".srhtext = mkDefault null;
-      # .hg/store size (in MB) past which the nightly job generates clone bundles.
-      # "hg.sr.ht".clone_bundle_threshold = mkDefault 50;
-      # Path to hg-ssh (if not in $PATH)
-      # "hg.sr.ht".hg_ssh = mkDefault /path/to/hg-ssh;
-
-      # The authorized keys hook uses this to dispatch to various handlers
-      # The format is a program to exec into as the key, and the user to match as the
-      # value. When someone tries to log in as this user, this program is executed
-      # and is expected to omit an AuthorizedKeys file.
-      #
-      # Uncomment the relevant lines to enable the various sr.ht dispatchers.
-      "hg.sr.ht::dispatch"."/run/current-system/sw/bin/hgsrht-keys" = mkDefault "${user}:${user}";
-    };
-
-    # TODO: requires testing and addition of hg-specific requirements
-    services.nginx.virtualHosts."hg.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.hgsrht}/${pkgs.sourcehut.python.sitePackages}/hgsrht";
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/hub.nix b/nixos/modules/services/misc/sourcehut/hub.nix
deleted file mode 100644
index 7d137a76505..00000000000
--- a/nixos/modules/services/misc/sourcehut/hub.nix
+++ /dev/null
@@ -1,120 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  cfgIni = cfg.settings;
-  scfg = cfg.hub;
-  iniKey = "hub.sr.ht";
-
-  drv = pkgs.sourcehut.hubsrht;
-in
-{
-  options.services.sourcehut.hub = {
-    user = mkOption {
-      type = types.str;
-      default = "hubsrht";
-      description = ''
-        User for hub.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5014;
-      description = ''
-        Port on which the "hub" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "hub.sr.ht";
-      description = ''
-        PostgreSQL database name for hub.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/hubsrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/hubsrht"'';
-      description = ''
-        State path for hub.sr.ht.
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "hub" cfg.services) {
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          description = "hub.sr.ht user";
-        };
-      };
-
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services.postgresql = {
-      authentication = ''
-        local ${database} ${user} trust
-      '';
-      ensureDatabases = [ database ];
-      ensureUsers = [
-        {
-          name = user;
-          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-        }
-      ];
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        "d ${statePath} 0750 ${user} ${user} -"
-      ];
-
-      services.hubsrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-        after = [ "postgresql.service" "network.target" ];
-        requires = [ "postgresql.service" ];
-        wantedBy = [ "multi-user.target" ];
-
-        description = "hub.sr.ht website service";
-
-        serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL hub.sr.ht is being served at (protocol://domain)
-      "hub.sr.ht".origin = mkDefault "http://hub.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "hub.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "hub.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "hub.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "hub.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # hub.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "hub.sr.ht".oauth-client-id = mkDefault null;
-      "hub.sr.ht".oauth-client-secret = mkDefault null;
-    };
-
-    services.nginx.virtualHosts."${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.hubsrht}/${pkgs.sourcehut.python.sitePackages}/hubsrht";
-    };
-    services.nginx.virtualHosts."hub.${cfg.originBase}" = {
-      globalRedirect = "${cfg.originBase}";
-      forceSSL = true;
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/lists.nix b/nixos/modules/services/misc/sourcehut/lists.nix
deleted file mode 100644
index 76f155caa05..00000000000
--- a/nixos/modules/services/misc/sourcehut/lists.nix
+++ /dev/null
@@ -1,187 +0,0 @@
-# Email setup is fairly involved, useful references:
-# https://drewdevault.com/2018/08/05/Local-mail-server.html
-
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  cfgIni = cfg.settings;
-  scfg = cfg.lists;
-  iniKey = "lists.sr.ht";
-
-  rcfg = config.services.redis;
-  drv = pkgs.sourcehut.listssrht;
-in
-{
-  options.services.sourcehut.lists = {
-    user = mkOption {
-      type = types.str;
-      default = "listssrht";
-      description = ''
-        User for lists.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5006;
-      description = ''
-        Port on which the "lists" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "lists.sr.ht";
-      description = ''
-        PostgreSQL database name for lists.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/listssrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/listssrht"'';
-      description = ''
-        State path for lists.sr.ht.
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "lists" cfg.services) {
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          extraGroups = [ "postfix" ];
-          description = "lists.sr.ht user";
-        };
-      };
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services.postgresql = {
-      authentication = ''
-        local ${database} ${user} trust
-      '';
-      ensureDatabases = [ database ];
-      ensureUsers = [
-        {
-          name = user;
-          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-        }
-      ];
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        "d ${statePath} 0750 ${user} ${user} -"
-      ];
-
-      services = {
-        listssrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "lists.sr.ht website service";
-
-          serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-        };
-
-        listssrht-process = {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "lists.sr.ht process service";
-          serviceConfig = {
-            Type = "simple";
-            User = user;
-            Restart = "always";
-            ExecStart = "${cfg.python}/bin/celery -A ${drv.pname}.process worker --loglevel=info";
-          };
-        };
-
-        listssrht-lmtp = {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "lists.sr.ht process service";
-          serviceConfig = {
-            Type = "simple";
-            User = user;
-            Restart = "always";
-            ExecStart = "${cfg.python}/bin/listssrht-lmtp";
-          };
-        };
-
-
-        listssrht-webhooks = {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "lists.sr.ht webhooks service";
-          serviceConfig = {
-            Type = "simple";
-            User = user;
-            Restart = "always";
-            ExecStart = "${cfg.python}/bin/celery -A ${drv.pname}.webhooks worker --loglevel=info";
-          };
-        };
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL lists.sr.ht is being served at (protocol://domain)
-      "lists.sr.ht".origin = mkDefault "http://lists.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "lists.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "lists.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "lists.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "lists.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # lists.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "lists.sr.ht".oauth-client-id = mkDefault null;
-      "lists.sr.ht".oauth-client-secret = mkDefault null;
-      # Outgoing email for notifications generated by users
-      "lists.sr.ht".notify-from = mkDefault "CHANGEME@example.org";
-      # The redis connection used for the webhooks worker
-      "lists.sr.ht".webhooks = mkDefault "redis://${rcfg.bind}:${toString rcfg.port}/2";
-      # The redis connection used for the celery worker
-      "lists.sr.ht".redis = mkDefault "redis://${rcfg.bind}:${toString rcfg.port}/4";
-      # Network-key
-      "lists.sr.ht".network-key = mkDefault null;
-      # Allow creation
-      "lists.sr.ht".allow-new-lists = mkDefault "no";
-      # Posting Domain
-      "lists.sr.ht".posting-domain = mkDefault "lists.${cfg.originBase}";
-
-      # Path for the lmtp daemon's unix socket. Direct incoming mail to this socket.
-      # Alternatively, specify IP:PORT and an SMTP server will be run instead.
-      "lists.sr.ht::worker".sock = mkDefault "/tmp/lists.sr.ht-lmtp.sock";
-      # The lmtp daemon will make the unix socket group-read/write for users in this
-      # group.
-      "lists.sr.ht::worker".sock-group = mkDefault "postfix";
-      "lists.sr.ht::worker".reject-url = mkDefault "https://man.sr.ht/lists.sr.ht/etiquette.md";
-      "lists.sr.ht::worker".reject-mimetypes = mkDefault "text/html";
-
-    };
-
-    services.nginx.virtualHosts."lists.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.listssrht}/${pkgs.sourcehut.python.sitePackages}/listssrht";
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/man.nix b/nixos/modules/services/misc/sourcehut/man.nix
deleted file mode 100644
index 8ca271c32ee..00000000000
--- a/nixos/modules/services/misc/sourcehut/man.nix
+++ /dev/null
@@ -1,124 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  cfgIni = cfg.settings;
-  scfg = cfg.man;
-  iniKey = "man.sr.ht";
-
-  drv = pkgs.sourcehut.mansrht;
-in
-{
-  options.services.sourcehut.man = {
-    user = mkOption {
-      type = types.str;
-      default = "mansrht";
-      description = ''
-        User for man.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5004;
-      description = ''
-        Port on which the "man" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "man.sr.ht";
-      description = ''
-        PostgreSQL database name for man.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/mansrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/mansrht"'';
-      description = ''
-        State path for man.sr.ht.
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "man" cfg.services) {
-    assertions =
-      [
-        {
-          assertion = hasAttrByPath [ "git.sr.ht" "oauth-client-id" ] cfgIni;
-          message = "man.sr.ht needs access to git.sr.ht.";
-        }
-      ];
-
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          description = "man.sr.ht user";
-        };
-      };
-
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services.postgresql = {
-      authentication = ''
-        local ${database} ${user} trust
-      '';
-      ensureDatabases = [ database ];
-      ensureUsers = [
-        {
-          name = user;
-          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-        }
-      ];
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        "d ${statePath} 0750 ${user} ${user} -"
-      ];
-
-      services.mansrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-        after = [ "postgresql.service" "network.target" ];
-        requires = [ "postgresql.service" ];
-        wantedBy = [ "multi-user.target" ];
-
-        description = "man.sr.ht website service";
-
-        serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL man.sr.ht is being served at (protocol://domain)
-      "man.sr.ht".origin = mkDefault "http://man.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "man.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "man.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "man.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "man.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # man.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "man.sr.ht".oauth-client-id = mkDefault null;
-      "man.sr.ht".oauth-client-secret = mkDefault null;
-    };
-
-    services.nginx.virtualHosts."man.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.mansrht}/${pkgs.sourcehut.python.sitePackages}/mansrht";
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/meta.nix b/nixos/modules/services/misc/sourcehut/meta.nix
deleted file mode 100644
index 33e4f2332b5..00000000000
--- a/nixos/modules/services/misc/sourcehut/meta.nix
+++ /dev/null
@@ -1,213 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  cfgIni = cfg.settings;
-  scfg = cfg.meta;
-  iniKey = "meta.sr.ht";
-
-  rcfg = config.services.redis;
-  drv = pkgs.sourcehut.metasrht;
-in
-{
-  options.services.sourcehut.meta = {
-    user = mkOption {
-      type = types.str;
-      default = "metasrht";
-      description = ''
-        User for meta.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5000;
-      description = ''
-        Port on which the "meta" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "meta.sr.ht";
-      description = ''
-        PostgreSQL database name for meta.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/metasrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/metasrht"'';
-      description = ''
-        State path for meta.sr.ht.
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "meta" cfg.services) {
-    assertions =
-      [
-        {
-          assertion = with cfgIni."meta.sr.ht::billing"; enabled == "yes" -> (stripe-public-key != null && stripe-secret-key != null);
-          message = "If meta.sr.ht::billing is enabled, the keys should be defined.";
-        }
-      ];
-
-    users = {
-      users = {
-        ${user} = {
-          isSystemUser = true;
-          group = user;
-          description = "meta.sr.ht user";
-        };
-      };
-
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services.cron.systemCronJobs = [ "0 0 * * * ${cfg.python}/bin/metasrht-daily" ];
-    services.postgresql = {
-      authentication = ''
-        local ${database} ${user} trust
-      '';
-      ensureDatabases = [ database ];
-      ensureUsers = [
-        {
-          name = user;
-          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-        }
-      ];
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        "d ${statePath} 0750 ${user} ${user} -"
-      ];
-
-      services = {
-        metasrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "meta.sr.ht website service";
-
-          preStart = ''
-            # Configure client(s) as "preauthorized"
-            ${concatMapStringsSep "\n\n"
-              (attr: ''
-                if ! test -e "${statePath}/${attr}.oauth" || [ "$(cat ${statePath}/${attr}.oauth)" != "${cfgIni."${attr}".oauth-client-id}" ]; then
-                  # Configure ${attr}'s OAuth client as "preauthorized"
-                  psql ${database} \
-                    -c "UPDATE oauthclient SET preauthorized = true WHERE client_id = '${cfgIni."${attr}".oauth-client-id}'"
-
-                  printf "%s" "${cfgIni."${attr}".oauth-client-id}" > "${statePath}/${attr}.oauth"
-                fi
-              '')
-              (builtins.attrNames (filterAttrs
-                (k: v: !(hasInfix "::" k) && builtins.hasAttr "oauth-client-id" v && v.oauth-client-id != null)
-                cfg.settings))}
-          '';
-
-          serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-        };
-
-        metasrht-api = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "meta.sr.ht api service";
-
-          preStart = ''
-            # Configure client(s) as "preauthorized"
-            ${concatMapStringsSep "\n\n"
-              (attr: ''
-                if ! test -e "${statePath}/${attr}.oauth" || [ "$(cat ${statePath}/${attr}.oauth)" != "${cfgIni."${attr}".oauth-client-id}" ]; then
-                  # Configure ${attr}'s OAuth client as "preauthorized"
-                  psql ${database} \
-                    -c "UPDATE oauthclient SET preauthorized = true WHERE client_id = '${cfgIni."${attr}".oauth-client-id}'"
-
-                  printf "%s" "${cfgIni."${attr}".oauth-client-id}" > "${statePath}/${attr}.oauth"
-                fi
-              '')
-              (builtins.attrNames (filterAttrs
-                (k: v: !(hasInfix "::" k) && builtins.hasAttr "oauth-client-id" v && v.oauth-client-id != null)
-                cfg.settings))}
-          '';
-
-          serviceConfig.ExecStart = "${pkgs.sourcehut.metasrht}/bin/metasrht-api -b :${toString (port + 100)}";
-        };
-
-        metasrht-webhooks = {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "meta.sr.ht webhooks service";
-          serviceConfig = {
-            Type = "simple";
-            User = user;
-            Restart = "always";
-            ExecStart = "${cfg.python}/bin/celery -A ${drv.pname}.webhooks worker --loglevel=info";
-          };
-
-        };
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL meta.sr.ht is being served at (protocol://domain)
-      "meta.sr.ht".origin = mkDefault "https://meta.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "meta.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "meta.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "meta.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "meta.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # If "yes", the user will be sent the stock sourcehut welcome emails after
-      # signup (requires cron to be configured properly). These are specific to the
-      # sr.ht instance so you probably want to patch these before enabling this.
-      "meta.sr.ht".welcome-emails = mkDefault "no";
-
-      # The redis connection used for the webhooks worker
-      "meta.sr.ht".webhooks = mkDefault "redis://${rcfg.bind}:${toString rcfg.port}/6";
-
-      # If "no", public registration will not be permitted.
-      "meta.sr.ht::settings".registration = mkDefault "no";
-      # Where to redirect new users upon registration
-      "meta.sr.ht::settings".onboarding-redirect = mkDefault "https://meta.${cfg.originBase}";
-      # How many invites each user is issued upon registration (only applicable if
-      # open registration is disabled)
-      "meta.sr.ht::settings".user-invites = mkDefault 5;
-
-      # Origin URL for API, 100 more than web
-      "meta.sr.ht".api-origin = mkDefault "http://localhost:5100";
-
-      # You can add aliases for the client IDs of commonly used OAuth clients here.
-      #
-      # Example:
-      "meta.sr.ht::aliases" = mkDefault { };
-      # "meta.sr.ht::aliases"."git.sr.ht" = 12345;
-
-      # "yes" to enable the billing system
-      "meta.sr.ht::billing".enabled = mkDefault "no";
-      # Get your keys at https://dashboard.stripe.com/account/apikeys
-      "meta.sr.ht::billing".stripe-public-key = mkDefault null;
-      "meta.sr.ht::billing".stripe-secret-key = mkDefault null;
-    };
-
-    services.nginx.virtualHosts."meta.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.metasrht}/${pkgs.sourcehut.python.sitePackages}/metasrht";
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/paste.nix b/nixos/modules/services/misc/sourcehut/paste.nix
deleted file mode 100644
index b481ebaf891..00000000000
--- a/nixos/modules/services/misc/sourcehut/paste.nix
+++ /dev/null
@@ -1,135 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  cfgIni = cfg.settings;
-  scfg = cfg.paste;
-  iniKey = "paste.sr.ht";
-
-  rcfg = config.services.redis;
-  drv = pkgs.sourcehut.pastesrht;
-in
-{
-  options.services.sourcehut.paste = {
-    user = mkOption {
-      type = types.str;
-      default = "pastesrht";
-      description = ''
-        User for paste.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5011;
-      description = ''
-        Port on which the "paste" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "paste.sr.ht";
-      description = ''
-        PostgreSQL database name for paste.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/pastesrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/pastesrht"'';
-      description = ''
-        State path for pastesrht.sr.ht.
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "paste" cfg.services) {
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          description = "paste.sr.ht user";
-        };
-      };
-
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services.postgresql = {
-      authentication = ''
-        local ${database} ${user} trust
-      '';
-      ensureDatabases = [ database ];
-      ensureUsers = [
-        {
-          name = user;
-          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-        }
-      ];
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        "d ${statePath} 0750 ${user} ${user} -"
-      ];
-
-      services = {
-        pastesrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "paste.sr.ht website service";
-
-          serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-        };
-
-        pastesrht-webhooks = {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "paste.sr.ht webhooks service";
-          serviceConfig = {
-            Type = "simple";
-            User = user;
-            Restart = "always";
-            ExecStart = "${cfg.python}/bin/celery -A ${drv.pname}.webhooks worker --loglevel=info";
-          };
-
-        };
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL paste.sr.ht is being served at (protocol://domain)
-      "paste.sr.ht".origin = mkDefault "http://paste.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "paste.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "paste.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "paste.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "paste.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # paste.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "paste.sr.ht".oauth-client-id = mkDefault null;
-      "paste.sr.ht".oauth-client-secret = mkDefault null;
-      "paste.sr.ht".webhooks = mkDefault "redis://${rcfg.bind}:${toString rcfg.port}/5";
-    };
-
-    services.nginx.virtualHosts."paste.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.pastesrht}/${pkgs.sourcehut.python.sitePackages}/pastesrht";
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/sourcehut/service.nix b/nixos/modules/services/misc/sourcehut/service.nix
index f1706ad0a6a..37a439ee352 100644
--- a/nixos/modules/services/misc/sourcehut/service.nix
+++ b/nixos/modules/services/misc/sourcehut/service.nix
@@ -117,12 +117,12 @@ let
 in
 {
   options.services.sourcehut.${srv} = {
-    enable = mkEnableOption "${srv} service";
+    enable = mkEnableOption (lib.mdDoc "${srv} service");
 
     user = mkOption {
       type = types.str;
       default = srvsrht;
-      description = ''
+      description = lib.mdDoc ''
         User for ${srv}.sr.ht.
       '';
     };
@@ -130,7 +130,7 @@ in
     group = mkOption {
       type = types.str;
       default = srvsrht;
-      description = ''
+      description = lib.mdDoc ''
         Group for ${srv}.sr.ht.
         Membership grants access to the Git/Mercurial repositories by default,
         but not to the config.ini file (where secrets are).
@@ -140,7 +140,7 @@ in
     port = mkOption {
       type = types.port;
       default = port;
-      description = ''
+      description = lib.mdDoc ''
         Port on which the "${srv}" backend should listen.
       '';
     };
@@ -148,9 +148,9 @@ in
     redis = {
       host = mkOption {
         type = types.str;
-        default = "unix:/run/redis-sourcehut-${srvsrht}/redis.sock?db=0";
+        default = "unix:///run/redis-sourcehut-${srvsrht}/redis.sock?db=0";
         example = "redis://shared.wireguard:6379/0";
-        description = ''
+        description = lib.mdDoc ''
           The redis host URL. This is used for caching and temporary storage, and must
           be shared between nodes (e.g. git1.sr.ht and git2.sr.ht), but need not be
           shared between services. It may be shared between services, however, with no
@@ -163,9 +163,9 @@ in
       database = mkOption {
         type = types.str;
         default = "${srv}.sr.ht";
-        description = ''
+        description = lib.mdDoc ''
           PostgreSQL database name for the ${srv}.sr.ht service,
-          used if <xref linkend="opt-services.sourcehut.postgresql.enable"/> is <literal>true</literal>.
+          used if [](#opt-services.sourcehut.postgresql.enable) is `true`.
         '';
       };
     };
@@ -174,7 +174,7 @@ in
       extraArgs = mkOption {
         type = with types; listOf str;
         default = ["--timeout 120" "--workers 1" "--log-level=info"];
-        description = "Extra arguments passed to Gunicorn.";
+        description = lib.mdDoc "Extra arguments passed to Gunicorn.";
       };
     };
   } // optionalAttrs webhooks {
@@ -182,12 +182,12 @@ in
       extraArgs = mkOption {
         type = with types; listOf str;
         default = ["--loglevel DEBUG" "--pool eventlet" "--without-heartbeat"];
-        description = "Extra arguments passed to the Celery responsible for webhooks.";
+        description = lib.mdDoc "Extra arguments passed to the Celery responsible for webhooks.";
       };
       celeryConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Content of the <literal>celeryconfig.py</literal> used by the Celery responsible for webhooks.";
+        description = lib.mdDoc "Content of the `celeryconfig.py` used by the Celery responsible for webhooks.";
       };
     };
   };
diff --git a/nixos/modules/services/misc/sourcehut/todo.nix b/nixos/modules/services/misc/sourcehut/todo.nix
deleted file mode 100644
index 262fa48f59d..00000000000
--- a/nixos/modules/services/misc/sourcehut/todo.nix
+++ /dev/null
@@ -1,163 +0,0 @@
-{ config, lib, options, pkgs, ... }:
-
-with lib;
-let
-  cfg = config.services.sourcehut;
-  opt = options.services.sourcehut;
-  cfgIni = cfg.settings;
-  scfg = cfg.todo;
-  iniKey = "todo.sr.ht";
-
-  rcfg = config.services.redis;
-  drv = pkgs.sourcehut.todosrht;
-in
-{
-  options.services.sourcehut.todo = {
-    user = mkOption {
-      type = types.str;
-      default = "todosrht";
-      description = ''
-        User for todo.sr.ht.
-      '';
-    };
-
-    port = mkOption {
-      type = types.port;
-      default = 5003;
-      description = ''
-        Port on which the "todo" module should listen.
-      '';
-    };
-
-    database = mkOption {
-      type = types.str;
-      default = "todo.sr.ht";
-      description = ''
-        PostgreSQL database name for todo.sr.ht.
-      '';
-    };
-
-    statePath = mkOption {
-      type = types.path;
-      default = "${cfg.statePath}/todosrht";
-      defaultText = literalExpression ''"''${config.${opt.statePath}}/todosrht"'';
-      description = ''
-        State path for todo.sr.ht.
-      '';
-    };
-  };
-
-  config = with scfg; lib.mkIf (cfg.enable && elem "todo" cfg.services) {
-    users = {
-      users = {
-        "${user}" = {
-          isSystemUser = true;
-          group = user;
-          extraGroups = [ "postfix" ];
-          description = "todo.sr.ht user";
-        };
-      };
-      groups = {
-        "${user}" = { };
-      };
-    };
-
-    services.postgresql = {
-      authentication = ''
-        local ${database} ${user} trust
-      '';
-      ensureDatabases = [ database ];
-      ensureUsers = [
-        {
-          name = user;
-          ensurePermissions = { "DATABASE \"${database}\"" = "ALL PRIVILEGES"; };
-        }
-      ];
-    };
-
-    systemd = {
-      tmpfiles.rules = [
-        "d ${statePath} 0750 ${user} ${user} -"
-      ];
-
-      services = {
-        todosrht = import ./service.nix { inherit config pkgs lib; } scfg drv iniKey {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "todo.sr.ht website service";
-
-          serviceConfig.ExecStart = "${cfg.python}/bin/gunicorn ${drv.pname}.app:app -b ${cfg.address}:${toString port}";
-        };
-
-       todosrht-lmtp = {
-         after = [ "postgresql.service" "network.target" ];
-         bindsTo = [ "postgresql.service" ];
-         wantedBy = [ "multi-user.target" ];
-
-         description = "todo.sr.ht process service";
-         serviceConfig = {
-           Type = "simple";
-           User = user;
-           Restart = "always";
-           ExecStart = "${cfg.python}/bin/todosrht-lmtp";
-         };
-       };
-
-        todosrht-webhooks = {
-          after = [ "postgresql.service" "network.target" ];
-          requires = [ "postgresql.service" ];
-          wantedBy = [ "multi-user.target" ];
-
-          description = "todo.sr.ht webhooks service";
-          serviceConfig = {
-            Type = "simple";
-            User = user;
-            Restart = "always";
-            ExecStart = "${cfg.python}/bin/celery -A ${drv.pname}.webhooks worker --loglevel=info";
-          };
-
-        };
-      };
-    };
-
-    services.sourcehut.settings = {
-      # URL todo.sr.ht is being served at (protocol://domain)
-      "todo.sr.ht".origin = mkDefault "http://todo.${cfg.originBase}";
-      # Address and port to bind the debug server to
-      "todo.sr.ht".debug-host = mkDefault "0.0.0.0";
-      "todo.sr.ht".debug-port = mkDefault port;
-      # Configures the SQLAlchemy connection string for the database.
-      "todo.sr.ht".connection-string = mkDefault "postgresql:///${database}?user=${user}&host=/var/run/postgresql";
-      # Set to "yes" to automatically run migrations on package upgrade.
-      "todo.sr.ht".migrate-on-upgrade = mkDefault "yes";
-      # todo.sr.ht's OAuth client ID and secret for meta.sr.ht
-      # Register your client at meta.example.org/oauth
-      "todo.sr.ht".oauth-client-id = mkDefault null;
-      "todo.sr.ht".oauth-client-secret = mkDefault null;
-      # Outgoing email for notifications generated by users
-      "todo.sr.ht".notify-from = mkDefault "CHANGEME@example.org";
-      # The redis connection used for the webhooks worker
-      "todo.sr.ht".webhooks = mkDefault "redis://${rcfg.bind}:${toString rcfg.port}/1";
-      # Network-key
-      "todo.sr.ht".network-key = mkDefault null;
-
-      # Path for the lmtp daemon's unix socket. Direct incoming mail to this socket.
-      # Alternatively, specify IP:PORT and an SMTP server will be run instead.
-      "todo.sr.ht::mail".sock = mkDefault "/tmp/todo.sr.ht-lmtp.sock";
-      # The lmtp daemon will make the unix socket group-read/write for users in this
-      # group.
-      "todo.sr.ht::mail".sock-group = mkDefault "postfix";
-
-      "todo.sr.ht::mail".posting-domain = mkDefault "todo.${cfg.originBase}";
-    };
-
-    services.nginx.virtualHosts."todo.${cfg.originBase}" = {
-      forceSSL = true;
-      locations."/".proxyPass = "http://${cfg.address}:${toString port}";
-      locations."/query".proxyPass = "http://${cfg.address}:${toString (port + 100)}";
-      locations."/static".root = "${pkgs.sourcehut.todosrht}/${pkgs.sourcehut.python.sitePackages}/todosrht";
-    };
-  };
-}
diff --git a/nixos/modules/services/misc/spice-vdagentd.nix b/nixos/modules/services/misc/spice-vdagentd.nix
index 2dd9fcf68ab..bde64847d89 100644
--- a/nixos/modules/services/misc/spice-vdagentd.nix
+++ b/nixos/modules/services/misc/spice-vdagentd.nix
@@ -7,7 +7,7 @@ in
 {
   options = {
     services.spice-vdagentd = {
-      enable = mkEnableOption "Spice guest vdagent daemon";
+      enable = mkEnableOption (lib.mdDoc "Spice guest vdagent daemon");
     };
   };
 
diff --git a/nixos/modules/services/misc/spice-webdavd.nix b/nixos/modules/services/misc/spice-webdavd.nix
new file mode 100644
index 00000000000..6c817e429ac
--- /dev/null
+++ b/nixos/modules/services/misc/spice-webdavd.nix
@@ -0,0 +1,38 @@
+{ config, pkgs, lib, ... }:
+
+with lib;
+let
+  cfg = config.services.spice-webdavd;
+in
+{
+  options = {
+    services.spice-webdavd = {
+      enable = mkEnableOption (lib.mdDoc "the spice guest webdav proxy daemon");
+
+      package = mkOption {
+        default = pkgs.phodav;
+        defaultText = literalExpression "pkgs.phodav";
+        type = types.package;
+        description = lib.mdDoc "spice-webdavd provider package to use.";
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    # ensure the webdav fs this exposes can actually be mounted
+    services.davfs2.enable = true;
+
+    # add the udev rule which starts the proxy when the spice socket is present
+    services.udev.packages = [ cfg.package ];
+
+    systemd.services.spice-webdavd = {
+      description = "spice-webdav proxy daemon";
+
+      serviceConfig = {
+        Type = "simple";
+        ExecStart = "${cfg.package}/bin/spice-webdavd -p 9843";
+        Restart = "on-success";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/misc/ssm-agent.nix b/nixos/modules/services/misc/ssm-agent.nix
index 4ae596ade17..d1f371c2bd6 100644
--- a/nixos/modules/services/misc/ssm-agent.nix
+++ b/nixos/modules/services/misc/ssm-agent.nix
@@ -17,11 +17,11 @@ let
   '';
 in {
   options.services.ssm-agent = {
-    enable = mkEnableOption "AWS SSM agent";
+    enable = mkEnableOption (lib.mdDoc "AWS SSM agent");
 
     package = mkOption {
       type = types.path;
-      description = "The SSM agent package to use";
+      description = lib.mdDoc "The SSM agent package to use";
       default = pkgs.ssm-agent.override { overrideEtc = false; };
       defaultText = literalExpression "pkgs.ssm-agent.override { overrideEtc = false; }";
     };
diff --git a/nixos/modules/services/misc/sssd.nix b/nixos/modules/services/misc/sssd.nix
index 386281e2b7c..edd5750a4a4 100644
--- a/nixos/modules/services/misc/sssd.nix
+++ b/nixos/modules/services/misc/sssd.nix
@@ -3,14 +3,18 @@ with lib;
 let
   cfg = config.services.sssd;
   nscd = config.services.nscd;
+
+  dataDir = "/var/lib/sssd";
+  settingsFile = "${dataDir}/sssd.conf";
+  settingsFileUnsubstituted = pkgs.writeText "${dataDir}/sssd-unsubstituted.conf" cfg.config;
 in {
   options = {
     services.sssd = {
-      enable = mkEnableOption "the System Security Services Daemon";
+      enable = mkEnableOption (lib.mdDoc "the System Security Services Daemon");
 
       config = mkOption {
         type = types.lines;
-        description = "Contents of <filename>sssd.conf</filename>.";
+        description = lib.mdDoc "Contents of {file}`sssd.conf`.";
         default = ''
           [sssd]
           config_file_version = 2
@@ -33,9 +37,40 @@ in {
       sshAuthorizedKeysIntegration = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to make sshd look up authorized keys from SSS.
-          For this to work, the <literal>ssh</literal> SSS service must be enabled in the sssd configuration.
+          For this to work, the `ssh` SSS service must be enabled in the sssd configuration.
+        '';
+      };
+
+      kcm = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to use SSS as a Kerberos Cache Manager (KCM).
+          Kerberos will be configured to cache credentials in SSS.
+        '';
+      };
+      environmentFile = mkOption {
+        type = types.nullOr types.path;
+        default = null;
+        description = lib.mdDoc ''
+          Environment file as defined in {manpage}`systemd.exec(5)`.
+
+          Secrets may be passed to the service without adding them to the world-readable
+          Nix store, by specifying placeholder variables as the option value in Nix and
+          setting these variables accordingly in the environment file.
+
+          ```
+            # snippet of sssd-related config
+            [domain/LDAP]
+            ldap_default_authtok = $SSSD_LDAP_DEFAULT_AUTHTOK
+          ```
+
+          ```
+            # contents of the environment file
+            SSSD_LDAP_DEFAULT_AUTHTOK=verysecretpassword
+          ```
         '';
       };
     };
@@ -51,22 +86,29 @@ in {
         wants = [ "nss-user-lookup.target" ];
         restartTriggers = [
           config.environment.etc."nscd.conf".source
-          config.environment.etc."sssd/sssd.conf".source
+          settingsFileUnsubstituted
         ];
         script = ''
           export LDB_MODULES_PATH+="''${LDB_MODULES_PATH+:}${pkgs.ldb}/modules/ldb:${pkgs.sssd}/modules/ldb"
           mkdir -p /var/lib/sss/{pubconf,db,mc,pipes,gpo_cache,secrets} /var/lib/sss/pipes/private /var/lib/sss/pubconf/krb5.include.d
-          ${pkgs.sssd}/bin/sssd -D
+          ${pkgs.sssd}/bin/sssd -D -c ${settingsFile}
         '';
         serviceConfig = {
           Type = "forking";
           PIDFile = "/run/sssd.pid";
+          StateDirectory = baseNameOf dataDir;
+          # We cannot use LoadCredential here because it's not available in ExecStartPre
+          EnvironmentFile = lib.mkIf (cfg.environmentFile != null) cfg.environmentFile;
         };
-      };
-
-      environment.etc."sssd/sssd.conf" = {
-        text = cfg.config;
-        mode = "0400";
+        preStart = ''
+          [ -f ${settingsFile} ] && rm -f ${settingsFile}
+          old_umask=$(umask)
+          umask 0177
+          ${pkgs.envsubst}/bin/envsubst \
+            -o ${settingsFile} \
+            -i ${settingsFileUnsubstituted}
+          umask $old_umask
+        '';
       };
 
       system.nssModules = [ pkgs.sssd ];
@@ -79,6 +121,28 @@ in {
       services.dbus.packages = [ pkgs.sssd ];
     })
 
+    (mkIf cfg.kcm {
+      systemd.services.sssd-kcm = {
+        description = "SSSD Kerberos Cache Manager";
+        requires = [ "sssd-kcm.socket" ];
+        serviceConfig = {
+          ExecStartPre = "-${pkgs.sssd}/bin/sssd --genconf-section=kcm";
+          ExecStart = "${pkgs.sssd}/libexec/sssd/sssd_kcm --uid 0 --gid 0";
+        };
+        restartTriggers = [
+          config.environment.etc."sssd/sssd.conf".source
+        ];
+      };
+      systemd.sockets.sssd-kcm = {
+        description = "SSSD Kerberos Cache Manager responder socket";
+        wantedBy = [ "sockets.target" ];
+        # Matches the default in MIT krb5 and Heimdal:
+        # https://github.com/krb5/krb5/blob/krb5-1.19.3-final/src/include/kcm.h#L43
+        listenStreams = [ "/var/run/.heim_org.h5l.kcm-socket" ];
+      };
+      krb5.libdefaults.default_ccache_name = "KCM:";
+    })
+
     (mkIf cfg.sshAuthorizedKeysIntegration {
     # Ugly: sshd refuses to start if a store path is given because /nix/store is group-writable.
     # So indirect by a symlink.
diff --git a/nixos/modules/services/misc/subsonic.nix b/nixos/modules/services/misc/subsonic.nix
index 2dda8970dd3..0862d578259 100644
--- a/nixos/modules/services/misc/subsonic.nix
+++ b/nixos/modules/services/misc/subsonic.nix
@@ -8,12 +8,12 @@ let
 in {
   options = {
     services.subsonic = {
-      enable = mkEnableOption "Subsonic daemon";
+      enable = mkEnableOption (lib.mdDoc "Subsonic daemon");
 
       home = mkOption {
         type = types.path;
         default = "/var/lib/subsonic";
-        description = ''
+        description = lib.mdDoc ''
           The directory where Subsonic will create files.
           Make sure it is writable.
         '';
@@ -22,7 +22,7 @@ in {
       listenAddress = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           The host name or IP address on which to bind Subsonic.
           Only relevant if you have multiple network interfaces and want
           to make Subsonic available on only one of them. The default value
@@ -33,7 +33,7 @@ in {
       port = mkOption {
         type = types.port;
         default = 4040;
-        description = ''
+        description = lib.mdDoc ''
           The port on which Subsonic will listen for
           incoming HTTP traffic. Set to 0 to disable.
         '';
@@ -42,7 +42,7 @@ in {
       httpsPort = mkOption {
         type = types.port;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           The port on which Subsonic will listen for
           incoming HTTPS traffic. Set to 0 to disable.
         '';
@@ -51,7 +51,7 @@ in {
       contextPath = mkOption {
         type = types.path;
         default = "/";
-        description = ''
+        description = lib.mdDoc ''
           The context path, i.e., the last part of the Subsonic
           URL. Typically '/' or '/subsonic'. Default '/'
         '';
@@ -60,7 +60,7 @@ in {
       maxMemory = mkOption {
         type = types.int;
         default = 100;
-        description = ''
+        description = lib.mdDoc ''
           The memory limit (max Java heap size) in megabytes.
           Default: 100
         '';
@@ -69,7 +69,7 @@ in {
       defaultMusicFolder = mkOption {
         type = types.path;
         default = "/var/music";
-        description = ''
+        description = lib.mdDoc ''
           Configure Subsonic to use this folder for music.  This option
           only has effect the first time Subsonic is started.
         '';
@@ -78,7 +78,7 @@ in {
       defaultPodcastFolder = mkOption {
         type = types.path;
         default = "/var/music/Podcast";
-        description = ''
+        description = lib.mdDoc ''
           Configure Subsonic to use this folder for Podcasts.  This option
           only has effect the first time Subsonic is started.
         '';
@@ -87,7 +87,7 @@ in {
       defaultPlaylistFolder = mkOption {
         type = types.path;
         default = "/var/playlists";
-        description = ''
+        description = lib.mdDoc ''
           Configure Subsonic to use this folder for playlists.  This option
           only has effect the first time Subsonic is started.
         '';
@@ -97,7 +97,7 @@ in {
         type = types.listOf types.path;
         default = [ "${pkgs.ffmpeg.bin}/bin/ffmpeg" ];
         defaultText = literalExpression ''[ "''${pkgs.ffmpeg.bin}/bin/ffmpeg" ]'';
-        description = ''
+        description = lib.mdDoc ''
           List of paths to transcoder executables that should be accessible
           from Subsonic. Symlinks will be created to each executable inside
           ''${config.${opt.home}}/transcoders.
diff --git a/nixos/modules/services/misc/sundtek.nix b/nixos/modules/services/misc/sundtek.nix
index e3234518c94..e85d7c5b92b 100644
--- a/nixos/modules/services/misc/sundtek.nix
+++ b/nixos/modules/services/misc/sundtek.nix
@@ -8,7 +8,7 @@ let
 in
 {
   options.services.sundtek = {
-    enable = mkEnableOption "Sundtek driver";
+    enable = mkEnableOption (lib.mdDoc "Sundtek driver");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/misc/svnserve.nix b/nixos/modules/services/misc/svnserve.nix
index 5fa262ca3b9..a0103641c65 100644
--- a/nixos/modules/services/misc/svnserve.nix
+++ b/nixos/modules/services/misc/svnserve.nix
@@ -20,13 +20,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable svnserve to serve Subversion repositories through the SVN protocol.";
+        description = lib.mdDoc "Whether to enable svnserve to serve Subversion repositories through the SVN protocol.";
       };
 
       svnBaseDir = mkOption {
         type = types.str;
         default = "/repos";
-        description = "Base directory from which Subversion repositories are accessed.";
+        description = lib.mdDoc "Base directory from which Subversion repositories are accessed.";
       };
     };
 
diff --git a/nixos/modules/services/misc/synergy.nix b/nixos/modules/services/misc/synergy.nix
index d6cd5d7f0d6..0cbdc7599c0 100644
--- a/nixos/modules/services/misc/synergy.nix
+++ b/nixos/modules/services/misc/synergy.nix
@@ -19,19 +19,19 @@ in
       # !!! All these option descriptions needs to be cleaned up.
 
       client = {
-        enable = mkEnableOption "the Synergy client (receive keyboard and mouse events from a Synergy server)";
+        enable = mkEnableOption (lib.mdDoc "the Synergy client (receive keyboard and mouse events from a Synergy server)");
 
         screenName = mkOption {
           default = "";
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             Use the given name instead of the hostname to identify
             ourselves to the server.
           '';
         };
         serverAddress = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             The server address is of the form: [hostname][:port].  The
             hostname must be the address or hostname of the server.  The
             port overrides the default port, 24800.
@@ -40,22 +40,22 @@ in
         autoStart = mkOption {
           default = true;
           type = types.bool;
-          description = "Whether the Synergy client should be started automatically.";
+          description = lib.mdDoc "Whether the Synergy client should be started automatically.";
         };
       };
 
       server = {
-        enable = mkEnableOption "the Synergy server (send keyboard and mouse events)";
+        enable = mkEnableOption (lib.mdDoc "the Synergy server (send keyboard and mouse events)");
 
         configFile = mkOption {
           type = types.path;
           default = "/etc/synergy-server.conf";
-          description = "The Synergy server configuration file.";
+          description = lib.mdDoc "The Synergy server configuration file.";
         };
         screenName = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Use the given name instead of the hostname to identify
             this screen in the configuration.
           '';
@@ -63,18 +63,18 @@ in
         address = mkOption {
           type = types.str;
           default = "";
-          description = "Address on which to listen for clients.";
+          description = lib.mdDoc "Address on which to listen for clients.";
         };
         autoStart = mkOption {
           default = true;
           type = types.bool;
-          description = "Whether the Synergy server should be started automatically.";
+          description = lib.mdDoc "Whether the Synergy server should be started automatically.";
         };
         tls = {
           enable = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Whether TLS encryption should be used.
 
               Using this requires a TLS certificate that can be
@@ -87,7 +87,7 @@ in
             type = types.nullOr types.str;
             default = null;
             example = "~/.synergy/SSL/Synergy.pem";
-            description = "The TLS certificate to use for encryption.";
+            description = lib.mdDoc "The TLS certificate to use for encryption.";
           };
         };
       };
@@ -115,7 +115,7 @@ in
         description = "Synergy server";
         wantedBy = optional cfgS.autoStart "graphical-session.target";
         path = [ pkgs.synergy ];
-        serviceConfig.ExecStart = ''${pkgs.synergy}/bin/synergys -c ${cfgS.configFile} -f${optionalString (cfgS.address != "") " -a ${cfgS.address}"}${optionalString (cfgS.screenName != "") " -n ${cfgS.screenName}"}${optionalString cfgS.tls.enable " --enable-crypto"}${optionalString (cfgS.tls.cert != null) (" --tls-cert=${cfgS.tls.cert}")}'';
+        serviceConfig.ExecStart = ''${pkgs.synergy}/bin/synergys -c ${cfgS.configFile} -f${optionalString (cfgS.address != "") " -a ${cfgS.address}"}${optionalString (cfgS.screenName != "") " -n ${cfgS.screenName}"}${optionalString cfgS.tls.enable " --enable-crypto"}${optionalString (cfgS.tls.cert != null) (" --tls-cert ${cfgS.tls.cert}")}'';
         serviceConfig.Restart = "on-failure";
       };
     })
diff --git a/nixos/modules/services/misc/sysprof.nix b/nixos/modules/services/misc/sysprof.nix
index ab91a8b586a..25c5b0fabf6 100644
--- a/nixos/modules/services/misc/sysprof.nix
+++ b/nixos/modules/services/misc/sysprof.nix
@@ -3,7 +3,7 @@
 {
   options = {
     services.sysprof = {
-      enable = lib.mkEnableOption "sysprof profiling daemon";
+      enable = lib.mkEnableOption (lib.mdDoc "sysprof profiling daemon");
     };
   };
 
diff --git a/nixos/modules/services/misc/tandoor-recipes.nix b/nixos/modules/services/misc/tandoor-recipes.nix
new file mode 100644
index 00000000000..a349bcac932
--- /dev/null
+++ b/nixos/modules/services/misc/tandoor-recipes.nix
@@ -0,0 +1,144 @@
+{ config, pkgs, lib, ... }:
+
+with lib;
+let
+  cfg = config.services.tandoor-recipes;
+  pkg = cfg.package;
+
+  # SECRET_KEY through an env file
+  env = {
+    GUNICORN_CMD_ARGS = "--bind=${cfg.address}:${toString cfg.port}";
+    DEBUG = "0";
+    MEDIA_ROOT = "/var/lib/tandoor-recipes";
+  } // optionalAttrs (config.time.timeZone != null) {
+    TIMEZONE = config.time.timeZone;
+  } // (
+    lib.mapAttrs (_: toString) cfg.extraConfig
+  );
+
+  manage =
+    let
+      setupEnv = lib.concatStringsSep "\n" (mapAttrsToList (name: val: "export ${name}=\"${val}\"") env);
+    in
+    pkgs.writeShellScript "manage" ''
+      ${setupEnv}
+      exec ${pkg}/bin/tandoor-recipes "$@"
+    '';
+in
+{
+  meta.maintainers = with maintainers; [ ambroisie ];
+
+  options.services.tandoor-recipes = {
+    enable = mkOption {
+      type = lib.types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Enable Tandoor Recipes.
+
+        When started, the Tandoor Recipes database is automatically created if
+        it doesn't exist and updated if the package has changed. Both tasks are
+        achieved by running a Django migration.
+
+        A script to manage the instance (by wrapping Django's manage.py) is linked to
+        `/var/lib/tandoor-recipes/tandoor-recipes-manage`.
+      '';
+    };
+
+    address = mkOption {
+      type = types.str;
+      default = "localhost";
+      description = lib.mdDoc "Web interface address.";
+    };
+
+    port = mkOption {
+      type = types.port;
+      default = 8080;
+      description = lib.mdDoc "Web interface port.";
+    };
+
+    extraConfig = mkOption {
+      type = types.attrs;
+      default = { };
+      description = lib.mdDoc ''
+        Extra tandoor recipes config options.
+
+        See [the example dot-env file](https://raw.githubusercontent.com/vabene1111/recipes/master/.env.template)
+        for available options.
+      '';
+      example = {
+        ENABLE_SIGNUP = "1";
+      };
+    };
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.tandoor-recipes;
+      defaultText = literalExpression "pkgs.tandoor-recipes";
+      description = lib.mdDoc "The Tandoor Recipes package to use.";
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.tandoor-recipes = {
+      description = "Tandoor Recipes server";
+
+      serviceConfig = {
+        ExecStart = ''
+          ${pkg.python.pkgs.gunicorn}/bin/gunicorn recipes.wsgi
+        '';
+        Restart = "on-failure";
+
+        User = "tandoor_recipes";
+        DynamicUser = true;
+        StateDirectory = "tandoor-recipes";
+        WorkingDirectory = "/var/lib/tandoor-recipes";
+        RuntimeDirectory = "tandoor-recipes";
+
+        BindReadOnlyPaths = [
+          "${config.environment.etc."ssl/certs/ca-certificates.crt".source}:/etc/ssl/certs/ca-certificates.crt"
+          builtins.storeDir
+          "-/etc/resolv.conf"
+          "-/etc/nsswitch.conf"
+          "-/etc/hosts"
+          "-/etc/localtime"
+          "-/run/postgresql"
+        ];
+        CapabilityBoundingSet = "";
+        LockPersonality = true;
+        MemoryDenyWriteExecute = true;
+        PrivateDevices = true;
+        PrivateUsers = true;
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        SystemCallArchitectures = "native";
+        # gunicorn needs setuid
+        SystemCallFilter = [ "@system-service" "~@privileged" "@resources" "@setuid" "@keyring" ];
+        UMask = "0066";
+      } // lib.optionalAttrs (cfg.port < 1024) {
+        AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
+        CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
+      };
+
+      wantedBy = [ "multi-user.target" ];
+
+      preStart = ''
+        ln -sf ${manage} tandoor-recipes-manage
+
+        # Let django migrate the DB as needed
+        ${pkg}/bin/tandoor-recipes migrate
+      '';
+
+      environment = env // {
+        PYTHONPATH = "${pkg.python.pkgs.makePythonPath pkg.propagatedBuildInputs}:${pkg}/lib/tandoor-recipes";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/misc/taskserver/default.nix b/nixos/modules/services/misc/taskserver/default.nix
index ff63c41e193..aeefd657f4d 100644
--- a/nixos/modules/services/misc/taskserver/default.nix
+++ b/nixos/modules/services/misc/taskserver/default.nix
@@ -10,10 +10,12 @@ let
   mkManualPkiOption = desc: mkOption {
     type = types.nullOr types.path;
     default = null;
-    description = desc + ''
-      <note><para>
+    description = lib.mdDoc ''
+      ${desc}
+
+      ::: {.note}
       Setting this option will prevent automatic CA creation and handling.
-      </para></note>
+      :::
     '';
   };
 
@@ -35,13 +37,13 @@ let
     '';
   };
 
-  mkAutoDesc = preamble: ''
+  mkAutoDesc = preamble: lib.mdDoc ''
     ${preamble}
 
-    <note><para>
+    ::: {.note}
     This option is for the automatically handled CA and will be ignored if any
-    of the <option>services.taskserver.pki.manual.*</option> options are set.
-    </para></note>
+    of the {option}`services.taskserver.pki.manual.*` options are set.
+    :::
   '';
 
   mkExpireOption = desc: mkOption {
@@ -50,7 +52,7 @@ let
     example = 365;
     apply = val: if val == null then -1 else val;
     description = mkAutoDesc ''
-      The expiration time of ${desc} in days or <literal>null</literal> for no
+      The expiration time of ${desc} in days or `null` for no
       expiration time.
     '';
   };
@@ -89,7 +91,7 @@ let
       type = types.uniq (types.listOf types.str);
       default = [];
       example = [ "alice" "bob" ];
-      description = ''
+      description = lib.mdDoc ''
         A list of user names that belong to the organization.
       '';
     };
@@ -98,7 +100,7 @@ let
       type = types.listOf types.str;
       default = [];
       example = [ "workers" "slackers" ];
-      description = ''
+      description = lib.mdDoc ''
         A list of group names that belong to the organization.
       '';
     };
@@ -106,7 +108,7 @@ let
 
   certtool = "${pkgs.gnutls.bin}/bin/certtool";
 
-  nixos-taskserver = with pkgs.python2.pkgs; buildPythonApplication {
+  nixos-taskserver = with pkgs.python3.pkgs; buildPythonApplication {
     name = "nixos-taskserver";
 
     src = pkgs.runCommand "nixos-taskserver-src" { preferLocalBuild = true; } ''
@@ -140,30 +142,30 @@ in {
         default = false;
         description = let
           url = "https://nixos.org/manual/nixos/stable/index.html#module-services-taskserver";
-        in ''
+        in lib.mdDoc ''
           Whether to enable the Taskwarrior server.
 
           More instructions about NixOS in conjuction with Taskserver can be
-          found <link xlink:href="${url}">in the NixOS manual</link>.
+          found [in the NixOS manual](${url}).
         '';
       };
 
       user = mkOption {
         type = types.str;
         default = "taskd";
-        description = "User for Taskserver.";
+        description = lib.mdDoc "User for Taskserver.";
       };
 
       group = mkOption {
         type = types.str;
         default = "taskd";
-        description = "Group for Taskserver.";
+        description = lib.mdDoc "Group for Taskserver.";
       };
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/taskserver";
-        description = "Data directory for Taskserver.";
+        description = lib.mdDoc "Data directory for Taskserver.";
       };
 
       ciphers = mkOption {
@@ -172,9 +174,9 @@ in {
         example = "NORMAL:-VERS-SSL3.0";
         description = let
           url = "https://gnutls.org/manual/html_node/Priority-Strings.html";
-        in ''
+        in lib.mdDoc ''
           List of GnuTLS ciphers to use. See the GnuTLS documentation about
-          priority strings at <link xlink:href="${url}"/> for full details.
+          priority strings at <${url}> for full details.
         '';
       };
 
@@ -184,17 +186,17 @@ in {
         example.myShinyOrganisation.users = [ "alice" "bob" ];
         example.myShinyOrganisation.groups = [ "staff" "outsiders" ];
         example.yetAnotherOrganisation.users = [ "foo" "bar" ];
-        description = ''
+        description = lib.mdDoc ''
           An attribute set where the keys name the organisation and the values
-          are a set of lists of <option>users</option> and
-          <option>groups</option>.
+          are a set of lists of {option}`users` and
+          {option}`groups`.
         '';
       };
 
       confirmation = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Determines whether certain commands are confirmed.
         '';
       };
@@ -202,7 +204,7 @@ in {
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Logs debugging information.
         '';
       };
@@ -210,7 +212,7 @@ in {
       extensions = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Fully qualified path of the Taskserver extension scripts.
           Currently there are none.
         '';
@@ -219,7 +221,7 @@ in {
       ipLog = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Logs the IP addresses of incoming requests.
         '';
       };
@@ -227,18 +229,15 @@ in {
       queueSize = mkOption {
         type = types.int;
         default = 10;
-        description = ''
-          Size of the connection backlog, see <citerefentry>
-            <refentrytitle>listen</refentrytitle>
-            <manvolnum>2</manvolnum>
-          </citerefentry>.
+        description = lib.mdDoc ''
+          Size of the connection backlog, see {manpage}`listen(2)`.
         '';
       };
 
       requestLimit = mkOption {
         type = types.int;
         default = 1048576;
-        description = ''
+        description = lib.mdDoc ''
           Size limit of incoming requests, in bytes.
         '';
       };
@@ -247,13 +246,13 @@ in {
         type = with types; either str (listOf str);
         default = [];
         example = [ "[Tt]ask [2-9]+" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of regular expressions that are matched against the reported
-          client id (such as <literal>task 2.3.0</literal>).
+          client id (such as `task 2.3.0`).
 
-          The values <literal>all</literal> or <literal>none</literal> have
+          The values `all` or `none` have
           special meaning. Overidden by any entry in the option
-          <option>services.taskserver.disallowedClientIDs</option>.
+          {option}`services.taskserver.disallowedClientIDs`.
         '';
       };
 
@@ -261,13 +260,13 @@ in {
         type = with types; either str (listOf str);
         default = [];
         example = [ "[Tt]ask [2-9]+" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of regular expressions that are matched against the reported
-          client id (such as <literal>task 2.3.0</literal>).
+          client id (such as `task 2.3.0`).
 
-          The values <literal>all</literal> or <literal>none</literal> have
+          The values `all` or `none` have
           special meaning. Any entry here overrides those in
-          <option>services.taskserver.allowedClientIDs</option>.
+          {option}`services.taskserver.allowedClientIDs`.
         '';
       };
 
@@ -275,27 +274,31 @@ in {
         type = types.str;
         default = "localhost";
         example = "::";
-        description = ''
+        description = lib.mdDoc ''
           The address (IPv4, IPv6 or DNS) to listen on.
-
-          If the value is something else than <literal>localhost</literal> the
-          port defined by <option>listenPort</option> is automatically added to
-          <option>networking.firewall.allowedTCPPorts</option>.
         '';
       };
 
       listenPort = mkOption {
         type = types.int;
         default = 53589;
-        description = ''
+        description = lib.mdDoc ''
           Port number of the Taskserver.
         '';
       };
 
+      openFirewall = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to open the firewall for the specified Taskserver port.
+        '';
+      };
+
       fqdn = mkOption {
         type = types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           The fully qualified domain name of this server, which is also used
           as the common name in the certificates.
         '';
@@ -304,12 +307,12 @@ in {
       trust = mkOption {
         type = types.enum [ "allow all" "strict" ];
         default = "strict";
-        description = ''
+        description = lib.mdDoc ''
           Determines how client certificates are validated.
 
-          The value <literal>allow all</literal> performs no client
+          The value `allow all` performs no client
           certificate validation. This is not recommended. The value
-          <literal>strict</literal> causes the client certificate to be
+          `strict` causes the client certificate to be
           validated against a CA.
         '';
       };
@@ -320,18 +323,16 @@ in {
       config = mkOption {
         type = types.attrs;
         example.client.cert = "/tmp/debugging.cert";
-        description = ''
+        description = lib.mdDoc ''
           Configuration options to pass to Taskserver.
 
-          The options here are the same as described in <citerefentry>
-            <refentrytitle>taskdrc</refentrytitle>
-            <manvolnum>5</manvolnum>
-          </citerefentry>, but with one difference:
+          The options here are the same as described in
+          {manpage}`taskdrc(5)`, but with one difference:
 
-          The <literal>server</literal> option is
-          <literal>server.listen</literal> here, because the
-          <literal>server</literal> option would collide with other options
-          like <literal>server.cert</literal> and we would run in a type error
+          The `server` option is
+          `server.listen` here, because the
+          `server` option would collide with other options
+          like `server.cert` and we would run in a type error
           (attribute set versus string).
 
           Nix types like integers or booleans are automatically converted to
@@ -560,7 +561,7 @@ in {
         '';
       };
     })
-    (mkIf (cfg.enable && cfg.listenHost != "localhost") {
+    (mkIf (cfg.enable && cfg.openFirewall) {
       networking.firewall.allowedTCPPorts = [ cfg.listenPort ];
     })
   ];
diff --git a/nixos/modules/services/misc/taskserver/helper-tool.py b/nixos/modules/services/misc/taskserver/helper-tool.py
index 22a3d8d5311..fec05728b2b 100644
--- a/nixos/modules/services/misc/taskserver/helper-tool.py
+++ b/nixos/modules/services/misc/taskserver/helper-tool.py
@@ -90,7 +90,7 @@ def certtool_cmd(*args, **kwargs):
     """
     return subprocess.check_output(
         [CERTTOOL_COMMAND] + list(args),
-        preexec_fn=lambda: os.umask(0077),
+        preexec_fn=lambda: os.umask(0o077),
         stderr=subprocess.STDOUT,
         **kwargs
     )
@@ -164,7 +164,7 @@ def generate_key(org, user):
     pubcert = os.path.join(basedir, "public.cert")
 
     try:
-        os.makedirs(basedir, mode=0700)
+        os.makedirs(basedir, mode=0o700)
 
         certtool_cmd("-p", "--bits", CERT_BITS, "--outfile", privkey)
 
@@ -301,7 +301,7 @@ class Organisation(object):
             return None
         if name not in self.users.keys():
             output = taskd_cmd("add", "user", self.name, name,
-                               capture_stdout=True)
+                               capture_stdout=True, encoding='utf-8')
             key = RE_USERKEY.search(output)
             if key is None:
                 msg = "Unable to find key while creating user {}."
@@ -412,9 +412,9 @@ class Manager(object):
         if org is not None:
             if self.ignore_imperative and is_imperative(name):
                 return
-            for user in org.users.keys():
+            for user in list(org.users.keys()):
                 org.del_user(user)
-            for group in org.groups.keys():
+            for group in list(org.groups.keys()):
                 org.del_group(group)
             taskd_cmd("remove", "org", name)
             del self._lazy_orgs[name]
diff --git a/nixos/modules/services/misc/tautulli.nix b/nixos/modules/services/misc/tautulli.nix
index 9a972b29122..b29e9dc0c8d 100644
--- a/nixos/modules/services/misc/tautulli.nix
+++ b/nixos/modules/services/misc/tautulli.nix
@@ -12,43 +12,49 @@ in
 
   options = {
     services.tautulli = {
-      enable = mkEnableOption "Tautulli Plex Monitor";
+      enable = mkEnableOption (lib.mdDoc "Tautulli Plex Monitor");
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/plexpy";
-        description = "The directory where Tautulli stores its data files.";
+        description = lib.mdDoc "The directory where Tautulli stores its data files.";
       };
 
       configFile = mkOption {
         type = types.str;
         default = "/var/lib/plexpy/config.ini";
-        description = "The location of Tautulli's config file.";
+        description = lib.mdDoc "The location of Tautulli's config file.";
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8181;
-        description = "TCP port where Tautulli listens.";
+        description = lib.mdDoc "TCP port where Tautulli listens.";
+      };
+
+      openFirewall = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc "Open ports in the firewall for Tautulli.";
       };
 
       user = mkOption {
         type = types.str;
         default = "plexpy";
-        description = "User account under which Tautulli runs.";
+        description = lib.mdDoc "User account under which Tautulli runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "nogroup";
-        description = "Group under which Tautulli runs.";
+        description = lib.mdDoc "Group under which Tautulli runs.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.tautulli;
         defaultText = literalExpression "pkgs.tautulli";
-        description = ''
+        description = lib.mdDoc ''
           The Tautulli package to use.
         '';
       };
@@ -74,6 +80,8 @@ in
       };
     };
 
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ];
+
     users.users = mkIf (cfg.user == "plexpy") {
       plexpy = { group = cfg.group; uid = config.ids.uids.plexpy; };
     };
diff --git a/nixos/modules/services/misc/tiddlywiki.nix b/nixos/modules/services/misc/tiddlywiki.nix
index 2adc08f6cfe..849f53ca2d4 100644
--- a/nixos/modules/services/misc/tiddlywiki.nix
+++ b/nixos/modules/services/misc/tiddlywiki.nix
@@ -14,7 +14,7 @@ in {
 
   options.services.tiddlywiki = {
 
-    enable = mkEnableOption "TiddlyWiki nodejs server";
+    enable = mkEnableOption (lib.mdDoc "TiddlyWiki nodejs server");
 
     listenOptions = mkOption {
       type = types.attrs;
@@ -24,9 +24,9 @@ in {
         readers="(authenticated)";
         port = 3456;
       };
-      description = ''
-        Parameters passed to <literal>--listen</literal> command.
-        Refer to <link xlink:href="https://tiddlywiki.com/#WebServer"/>
+      description = lib.mdDoc ''
+        Parameters passed to `--listen` command.
+        Refer to <https://tiddlywiki.com/#WebServer>
         for details on supported values.
       '';
     };
diff --git a/nixos/modules/services/misc/tp-auto-kbbl.nix b/nixos/modules/services/misc/tp-auto-kbbl.nix
index 59018f7f81f..8d92d3d9367 100644
--- a/nixos/modules/services/misc/tp-auto-kbbl.nix
+++ b/nixos/modules/services/misc/tp-auto-kbbl.nix
@@ -9,27 +9,27 @@ in {
 
   options = {
     services.tp-auto-kbbl = {
-      enable = mkEnableOption "Auto toggle keyboard back-lighting on Thinkpads (and maybe other laptops) for Linux";
+      enable = mkEnableOption (lib.mdDoc "Auto toggle keyboard back-lighting on Thinkpads (and maybe other laptops) for Linux");
 
       package = mkOption {
         type = types.package;
         default = pkgs.tp-auto-kbbl;
         defaultText = literalExpression "pkgs.tp-auto-kbbl";
-        description = "Package providing <command>tp-auto-kbbl</command>.";
+        description = lib.mdDoc "Package providing {command}`tp-auto-kbbl`.";
       };
 
       arguments = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = ''
-          List of arguments appended to <literal>./tp-auto-kbbl --device [device] [arguments]</literal>
+        description = lib.mdDoc ''
+          List of arguments appended to `./tp-auto-kbbl --device [device] [arguments]`
         '';
       };
 
       device = mkOption {
         type = types.str;
         default = "/dev/input/event0";
-        description = "Device watched for activities.";
+        description = lib.mdDoc "Device watched for activities.";
       };
 
     };
diff --git a/nixos/modules/services/misc/tzupdate.nix b/nixos/modules/services/misc/tzupdate.nix
index eac1e1112a5..300a578f7c4 100644
--- a/nixos/modules/services/misc/tzupdate.nix
+++ b/nixos/modules/services/misc/tzupdate.nix
@@ -9,7 +9,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable the tzupdate timezone updating service. This provides
         a one-shot service which can be activated with systemctl to
         update the timezone.
diff --git a/nixos/modules/services/misc/uhub.nix b/nixos/modules/services/misc/uhub.nix
index 0d0a8c2a4cb..80266b024e3 100644
--- a/nixos/modules/services/misc/uhub.nix
+++ b/nixos/modules/services/misc/uhub.nix
@@ -15,21 +15,21 @@ in {
 
     services.uhub = mkOption {
       default = { };
-      description = "Uhub ADC hub instances";
+      description = lib.mdDoc "Uhub ADC hub instances";
       type = types.attrsOf (types.submodule {
         options = {
 
-          enable = mkEnableOption "hub instance" // { default = true; };
+          enable = mkEnableOption (lib.mdDoc "hub instance") // { default = true; };
 
           enableTLS = mkOption {
             type = types.bool;
             default = false;
-            description = "Whether to enable TLS support.";
+            description = lib.mdDoc "Whether to enable TLS support.";
           };
 
           settings = mkOption {
             inherit (settingsFormat) type;
-            description = ''
+            description = lib.mdDoc ''
               Configuration of uhub.
               See https://www.uhub.org/doc/config.php for a list of options.
             '';
@@ -44,7 +44,7 @@ in {
           };
 
           plugins = mkOption {
-            description = "Uhub plugin configuration.";
+            description = lib.mdDoc "Uhub plugin configuration.";
             type = with types;
               listOf (submodule {
                 options = {
@@ -52,10 +52,10 @@ in {
                     type = path;
                     example = literalExpression
                       "$${pkgs.uhub}/plugins/mod_auth_sqlite.so";
-                    description = "Path to plugin file.";
+                    description = lib.mdDoc "Path to plugin file.";
                   };
                   settings = mkOption {
-                    description = "Settings specific to this plugin.";
+                    description = lib.mdDoc "Settings specific to this plugin.";
                     type = with types; attrsOf str;
                     example = { file = "/etc/uhub/users.db"; };
                   };
@@ -80,11 +80,12 @@ in {
           tls_enable = cfg.enableTLS;
           file_plugins = pkgs.writeText "uhub-plugins.conf"
             (lib.strings.concatStringsSep "\n" (map ({ plugin, settings }:
-              "plugin ${plugin} ${
-                toString
-                (lib.attrsets.mapAttrsToList (key: value: ''"${key}=${value}"'')
-                  settings)
-              }") cfg.plugins));
+              ''
+                plugin ${plugin} "${
+                  toString
+                  (lib.attrsets.mapAttrsToList (key: value: "${key}=${value}")
+                    settings)
+                }"'') cfg.plugins));
         };
       in {
         name = "uhub/${name}.conf";
@@ -104,6 +105,9 @@ in {
           ExecStart = "${pkg}/bin/uhub -c /etc/uhub/${name}.conf -L";
           ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
           DynamicUser = true;
+
+          AmbientCapabilities = "CAP_NET_BIND_SERVICE";
+          CapabilityBoundingSet = "CAP_NET_BIND_SERVICE";
         };
       };
     }) hubs;
diff --git a/nixos/modules/services/misc/weechat.nix b/nixos/modules/services/misc/weechat.nix
index 7a4c4dca2ac..663a767a0c1 100644
--- a/nixos/modules/services/misc/weechat.nix
+++ b/nixos/modules/services/misc/weechat.nix
@@ -8,20 +8,20 @@ in
 
 {
   options.services.weechat = {
-    enable = mkEnableOption "weechat";
+    enable = mkEnableOption (lib.mdDoc "weechat");
     root = mkOption {
-      description = "Weechat state directory.";
+      description = lib.mdDoc "Weechat state directory.";
       type = types.str;
       default = "/var/lib/weechat";
     };
     sessionName = mkOption {
-      description = "Name of the `screen' session for weechat.";
+      description = lib.mdDoc "Name of the `screen' session for weechat.";
       default = "weechat-screen";
       type = types.str;
     };
     binary = mkOption {
       type = types.path;
-      description = "Binary to execute.";
+      description = lib.mdDoc "Binary to execute.";
       default = "${pkgs.weechat}/bin/weechat";
       defaultText = literalExpression ''"''${pkgs.weechat}/bin/weechat"'';
       example = literalExpression ''"''${pkgs.weechat}/bin/weechat-headless"'';
diff --git a/nixos/modules/services/misc/xmr-stak.nix b/nixos/modules/services/misc/xmr-stak.nix
index 9256e9ae01c..6e123cf0380 100644
--- a/nixos/modules/services/misc/xmr-stak.nix
+++ b/nixos/modules/services/misc/xmr-stak.nix
@@ -15,15 +15,15 @@ in
 {
   options = {
     services.xmr-stak = {
-      enable = mkEnableOption "xmr-stak miner";
-      openclSupport = mkEnableOption "support for OpenCL (AMD/ATI graphics cards)";
-      cudaSupport = mkEnableOption "support for CUDA (NVidia graphics cards)";
+      enable = mkEnableOption (lib.mdDoc "xmr-stak miner");
+      openclSupport = mkEnableOption (lib.mdDoc "support for OpenCL (AMD/ATI graphics cards)");
+      cudaSupport = mkEnableOption (lib.mdDoc "support for CUDA (NVidia graphics cards)");
 
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "--noCPU" "--currency monero" ];
-        description = "List of parameters to pass to xmr-stak.";
+        description = lib.mdDoc "List of parameters to pass to xmr-stak.";
       };
 
       configFiles = mkOption {
@@ -52,7 +52,7 @@ in
             ''';
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Content of config files like config.txt, pools.txt or cpu.txt.
         '';
       };
diff --git a/nixos/modules/services/misc/xmrig.nix b/nixos/modules/services/misc/xmrig.nix
index c5c3803920c..d2aa3df45d5 100644
--- a/nixos/modules/services/misc/xmrig.nix
+++ b/nixos/modules/services/misc/xmrig.nix
@@ -13,14 +13,14 @@ with lib;
 {
   options = {
     services.xmrig = {
-      enable = mkEnableOption "XMRig Mining Software";
+      enable = mkEnableOption (lib.mdDoc "XMRig Mining Software");
 
       package = mkOption {
         type = types.package;
         default = pkgs.xmrig;
         defaultText = literalExpression "pkgs.xmrig";
         example = literalExpression "pkgs.xmrig-mo";
-        description = "XMRig package to use.";
+        description = lib.mdDoc "XMRig package to use.";
       };
 
       settings = mkOption {
@@ -42,9 +42,9 @@ with lib;
             ]
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           XMRig configuration. Refer to
-          <link xlink:href="https://xmrig.com/docs/miner/config"/>
+          <https://xmrig.com/docs/miner/config>
           for details on supported values.
         '';
       };
diff --git a/nixos/modules/services/misc/zoneminder.nix b/nixos/modules/services/misc/zoneminder.nix
index a557e742b7c..109415a20ee 100644
--- a/nixos/modules/services/misc/zoneminder.nix
+++ b/nixos/modules/services/misc/zoneminder.nix
@@ -66,24 +66,22 @@ let
 in {
   options = {
     services.zoneminder = with lib; {
-      enable = lib.mkEnableOption ''
+      enable = lib.mkEnableOption (lib.mdDoc ''
         ZoneMinder
-        </para><para>
+
         If you intend to run the database locally, you should set
         `config.services.zoneminder.database.createLocally` to true. Otherwise,
         when set to `false` (the default), you will have to create the database
         and database user as well as populate the database yourself.
         Additionally, you will need to run `zmupdate.pl` yourself when
         upgrading to a newer version.
-      '';
+      '');
 
       webserver = mkOption {
         type = types.enum [ "nginx" "none" ];
         default = "nginx";
-        description = ''
+        description = lib.mdDoc ''
           The webserver to configure for the PHP frontend.
-          </para>
-          <para>
 
           Set it to `none` if you want to configure it yourself. PRs are welcome
           for support for other web servers.
@@ -93,15 +91,15 @@ in {
       hostname = mkOption {
         type = types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           The hostname on which to listen.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8095;
-        description = ''
+        description = lib.mdDoc ''
           The port on which to listen.
         '';
       };
@@ -109,7 +107,7 @@ in {
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open the firewall port(s).
         '';
       };
@@ -118,7 +116,7 @@ in {
         createLocally = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Create the database and database user locally.
           '';
         };
@@ -126,7 +124,7 @@ in {
         host = mkOption {
           type = types.str;
           default = "localhost";
-          description = ''
+          description = lib.mdDoc ''
             Hostname hosting the database.
           '';
         };
@@ -134,7 +132,7 @@ in {
         name = mkOption {
           type = types.str;
           default = "zm";
-          description = ''
+          description = lib.mdDoc ''
             Name of database.
           '';
         };
@@ -142,7 +140,7 @@ in {
         username = mkOption {
           type = types.str;
           default = "zmuser";
-          description = ''
+          description = lib.mdDoc ''
             Username for accessing the database.
           '';
         };
@@ -150,9 +148,9 @@ in {
         password = mkOption {
           type = types.str;
           default = "zmpass";
-          description = ''
+          description = lib.mdDoc ''
             Username for accessing the database.
-            Not used if <literal>createLocally</literal> is set.
+            Not used if `createLocally` is set.
           '';
         };
       };
@@ -160,7 +158,7 @@ in {
       cameras = mkOption {
         type = types.int;
         default = 1;
-        description = ''
+        description = lib.mdDoc ''
           Set this to the number of cameras you expect to support.
         '';
       };
@@ -169,7 +167,7 @@ in {
         type = types.nullOr types.str;
         default = null;
         example = "/storage/tank";
-        description = ''
+        description = lib.mdDoc ''
           ZoneMinder can generate quite a lot of data, so in case you don't want
           to use the default ${defaultDir}, you can override the path here.
         '';
@@ -178,7 +176,7 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Additional configuration added verbatim to the configuration file.
         '';
       };
diff --git a/nixos/modules/services/misc/zookeeper.nix b/nixos/modules/services/misc/zookeeper.nix
index 3809a93a61e..fb51be698e7 100644
--- a/nixos/modules/services/misc/zookeeper.nix
+++ b/nixos/modules/services/misc/zookeeper.nix
@@ -24,26 +24,22 @@ let
 in {
 
   options.services.zookeeper = {
-    enable = mkOption {
-      description = "Whether to enable Zookeeper.";
-      default = false;
-      type = types.bool;
-    };
+    enable = mkEnableOption (lib.mdDoc "Zookeeper");
 
     port = mkOption {
-      description = "Zookeeper Client port.";
+      description = lib.mdDoc "Zookeeper Client port.";
       default = 2181;
-      type = types.int;
+      type = types.port;
     };
 
     id = mkOption {
-      description = "Zookeeper ID.";
+      description = lib.mdDoc "Zookeeper ID.";
       default = 0;
       type = types.int;
     };
 
     purgeInterval = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The time interval in hours for which the purge task has to be triggered. Set to a positive integer (1 and above) to enable the auto purging.
       '';
       default = 1;
@@ -51,7 +47,7 @@ in {
     };
 
     extraConf = mkOption {
-      description = "Extra configuration for Zookeeper.";
+      description = lib.mdDoc "Extra configuration for Zookeeper.";
       type = types.lines;
       default = ''
         initLimit=5
@@ -61,7 +57,7 @@ in {
     };
 
     servers = mkOption {
-      description = "All Zookeeper Servers.";
+      description = lib.mdDoc "All Zookeeper Servers.";
       default = "";
       type = types.lines;
       example = ''
@@ -72,7 +68,7 @@ in {
     };
 
     logging = mkOption {
-      description = "Zookeeper logging configuration.";
+      description = lib.mdDoc "Zookeeper logging configuration.";
       default = ''
         zookeeper.root.logger=INFO, CONSOLE
         log4j.rootLogger=INFO, CONSOLE
@@ -87,13 +83,13 @@ in {
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/zookeeper";
-      description = ''
+      description = lib.mdDoc ''
         Data directory for Zookeeper
       '';
     };
 
     extraCmdLineOptions = mkOption {
-      description = "Extra command line options for the Zookeeper launcher.";
+      description = lib.mdDoc "Extra command line options for the Zookeeper launcher.";
       default = [ "-Dcom.sun.management.jmxremote" "-Dcom.sun.management.jmxremote.local.only=true" ];
       type = types.listOf types.str;
       example = [ "-Djava.net.preferIPv4Stack=true" "-Dcom.sun.management.jmxremote" "-Dcom.sun.management.jmxremote.local.only=true" ];
@@ -102,18 +98,25 @@ in {
     preferIPv4 = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Add the -Djava.net.preferIPv4Stack=true flag to the Zookeeper server.
       '';
     };
 
     package = mkOption {
-      description = "The zookeeper package to use";
+      description = lib.mdDoc "The zookeeper package to use";
       default = pkgs.zookeeper;
       defaultText = literalExpression "pkgs.zookeeper";
       type = types.package;
     };
 
+    jre = mkOption {
+      description = lib.mdDoc "The JRE with which to run Zookeeper";
+      default = cfg.package.jre;
+      defaultText = literalExpression "pkgs.zookeeper.jre";
+      example = literalExpression "pkgs.jre";
+      type = types.package;
+    };
   };
 
 
@@ -131,7 +134,7 @@ in {
       after = [ "network.target" ];
       serviceConfig = {
         ExecStart = ''
-          ${pkgs.jre}/bin/java \
+          ${cfg.jre}/bin/java \
             -cp "${cfg.package}/lib/*:${configDir}" \
             ${escapeShellArgs cfg.extraCmdLineOptions} \
             -Dzookeeper.datadir.autocreate=false \
diff --git a/nixos/modules/services/monitoring/alerta.nix b/nixos/modules/services/monitoring/alerta.nix
index a73d94001f7..6c7ebec4191 100644
--- a/nixos/modules/services/monitoring/alerta.nix
+++ b/nixos/modules/services/monitoring/alerta.nix
@@ -21,58 +21,58 @@ let
 in
 {
   options.services.alerta = {
-    enable = mkEnableOption "alerta";
+    enable = mkEnableOption (lib.mdDoc "alerta");
 
     port = mkOption {
-      type = types.int;
+      type = types.port;
       default = 5000;
-      description = "Port of Alerta";
+      description = lib.mdDoc "Port of Alerta";
     };
 
     bind = mkOption {
       type = types.str;
       default = "0.0.0.0";
-      description = "Address to bind to. The default is to bind to all addresses";
+      description = lib.mdDoc "Address to bind to. The default is to bind to all addresses";
     };
 
     logDir = mkOption {
       type = types.path;
-      description = "Location where the logfiles are stored";
+      description = lib.mdDoc "Location where the logfiles are stored";
       default = "/var/log/alerta";
     };
 
     databaseUrl = mkOption {
       type = types.str;
-      description = "URL of the MongoDB or PostgreSQL database to connect to";
+      description = lib.mdDoc "URL of the MongoDB or PostgreSQL database to connect to";
       default = "mongodb://localhost";
     };
 
     databaseName = mkOption {
       type = types.str;
-      description = "Name of the database instance to connect to";
+      description = lib.mdDoc "Name of the database instance to connect to";
       default = "monitoring";
     };
 
     corsOrigins = mkOption {
       type = types.listOf types.str;
-      description = "List of URLs that can access the API for Cross-Origin Resource Sharing (CORS)";
+      description = lib.mdDoc "List of URLs that can access the API for Cross-Origin Resource Sharing (CORS)";
       default = [ "http://localhost" "http://localhost:5000" ];
     };
 
     authenticationRequired = mkOption {
       type = types.bool;
-      description = "Whether users must authenticate when using the web UI or command-line tool";
+      description = lib.mdDoc "Whether users must authenticate when using the web UI or command-line tool";
       default = false;
     };
 
     signupEnabled = mkOption {
       type = types.bool;
-      description = "Whether to prevent sign-up of new users via the web UI";
+      description = lib.mdDoc "Whether to prevent sign-up of new users via the web UI";
       default = true;
     };
 
     extraConfig = mkOption {
-      description = "These lines go into alertad.conf verbatim.";
+      description = lib.mdDoc "These lines go into alertad.conf verbatim.";
       default = "";
       type = types.lines;
     };
diff --git a/nixos/modules/services/monitoring/apcupsd.nix b/nixos/modules/services/monitoring/apcupsd.nix
index 1dccbc93edf..d4216b44cdc 100644
--- a/nixos/modules/services/monitoring/apcupsd.nix
+++ b/nixos/modules/services/monitoring/apcupsd.nix
@@ -75,7 +75,7 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the APC UPS daemon. apcupsd monitors your UPS and
           permits orderly shutdown of your computer in the event of a power
           failure. User manual: http://www.apcupsd.com/manual/manual.html.
@@ -92,7 +92,7 @@ in
           MINUTES 5
         '';
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Contents of the runtime configuration file, apcupsd.conf. The default
           settings makes apcupsd autodetect USB UPSes, limit network access to
           localhost and shutdown the system when the battery level is below 50
@@ -107,7 +107,7 @@ in
           doshutdown = "# shell commands to notify that the computer is shutting down";
         };
         type = types.attrsOf types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Each attribute in this option names an apcupsd event and the string
           value it contains will be executed in a shell, in response to that
           event (prior to the default action). See "man apccontrol" for the
diff --git a/nixos/modules/services/monitoring/arbtt.nix b/nixos/modules/services/monitoring/arbtt.nix
index 94eead220ae..f07ecc5d5dd 100644
--- a/nixos/modules/services/monitoring/arbtt.nix
+++ b/nixos/modules/services/monitoring/arbtt.nix
@@ -7,19 +7,13 @@ let
 in {
   options = {
     services.arbtt = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Enable the arbtt statistics capture service.
-        '';
-      };
+      enable = mkEnableOption (lib.mdDoc "Arbtt statistics capture service");
 
       package = mkOption {
         type = types.package;
         default = pkgs.haskellPackages.arbtt;
         defaultText = literalExpression "pkgs.haskellPackages.arbtt";
-        description = ''
+        description = lib.mdDoc ''
           The package to use for the arbtt binaries.
         '';
       };
@@ -28,7 +22,7 @@ in {
         type = types.str;
         default = "%h/.arbtt/capture.log";
         example = "/home/username/.arbtt-capture.log";
-        description = ''
+        description = lib.mdDoc ''
           The log file for captured samples.
         '';
       };
@@ -37,7 +31,7 @@ in {
         type = types.int;
         default = 60;
         example = 120;
-        description = ''
+        description = lib.mdDoc ''
           The sampling interval in seconds.
         '';
       };
diff --git a/nixos/modules/services/monitoring/bosun.nix b/nixos/modules/services/monitoring/bosun.nix
index 4b278b9c200..dc75fda6ed8 100644
--- a/nixos/modules/services/monitoring/bosun.nix
+++ b/nixos/modules/services/monitoring/bosun.nix
@@ -22,19 +22,13 @@ in {
 
     services.bosun = {
 
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Whether to run bosun.
-        '';
-      };
+      enable = mkEnableOption (lib.mdDoc "bosun");
 
       package = mkOption {
         type = types.package;
         default = pkgs.bosun;
         defaultText = literalExpression "pkgs.bosun";
-        description = ''
+        description = lib.mdDoc ''
           bosun binary to use.
         '';
       };
@@ -42,7 +36,7 @@ in {
       user = mkOption {
         type = types.str;
         default = "bosun";
-        description = ''
+        description = lib.mdDoc ''
           User account under which bosun runs.
         '';
       };
@@ -50,7 +44,7 @@ in {
       group = mkOption {
         type = types.str;
         default = "bosun";
-        description = ''
+        description = lib.mdDoc ''
           Group account under which bosun runs.
         '';
       };
@@ -58,7 +52,7 @@ in {
       opentsdbHost = mkOption {
         type = types.nullOr types.str;
         default = "localhost:4242";
-        description = ''
+        description = lib.mdDoc ''
           Host and port of the OpenTSDB database that stores bosun data.
           To disable opentsdb you can pass null as parameter.
         '';
@@ -68,7 +62,7 @@ in {
         type = types.nullOr types.str;
         default = null;
         example = "localhost:8086";
-        description = ''
+        description = lib.mdDoc ''
            Host and port of the influxdb database.
         '';
       };
@@ -76,7 +70,7 @@ in {
       listenAddress = mkOption {
         type = types.str;
         default = ":8070";
-        description = ''
+        description = lib.mdDoc ''
           The host address and port that bosun's web interface will listen on.
         '';
       };
@@ -84,7 +78,7 @@ in {
       stateFile = mkOption {
         type = types.path;
         default = "/var/lib/bosun/bosun.state";
-        description = ''
+        description = lib.mdDoc ''
           Path to bosun's state file.
         '';
       };
@@ -92,7 +86,7 @@ in {
       ledisDir = mkOption {
         type = types.path;
         default = "/var/lib/bosun/ledis_data";
-        description = ''
+        description = lib.mdDoc ''
           Path to bosun's ledis data dir
         '';
       };
@@ -100,7 +94,7 @@ in {
       checkFrequency = mkOption {
         type = types.str;
         default = "5m";
-        description = ''
+        description = lib.mdDoc ''
           Bosun's check frequency
         '';
       };
@@ -108,7 +102,7 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration options for Bosun. You should describe your
           desired templates, alerts, macros, etc through this configuration
           option.
diff --git a/nixos/modules/services/monitoring/cadvisor.nix b/nixos/modules/services/monitoring/cadvisor.nix
index dfbf07efcae..a8fba4e6e8c 100644
--- a/nixos/modules/services/monitoring/cadvisor.nix
+++ b/nixos/modules/services/monitoring/cadvisor.nix
@@ -8,90 +8,86 @@ let
 in {
   options = {
     services.cadvisor = {
-      enable = mkOption {
-        default = false;
-        type = types.bool;
-        description = "Whether to enable cadvisor service.";
-      };
+      enable = mkEnableOption (lib.mdDoc "Cadvisor service");
 
       listenAddress = mkOption {
         default = "127.0.0.1";
         type = types.str;
-        description = "Cadvisor listening host";
+        description = lib.mdDoc "Cadvisor listening host";
       };
 
       port = mkOption {
         default = 8080;
-        type = types.int;
-        description = "Cadvisor listening port";
+        type = types.port;
+        description = lib.mdDoc "Cadvisor listening port";
       };
 
       storageDriver = mkOption {
         default = null;
         type = types.nullOr types.str;
         example = "influxdb";
-        description = "Cadvisor storage driver.";
+        description = lib.mdDoc "Cadvisor storage driver.";
       };
 
       storageDriverHost = mkOption {
         default = "localhost:8086";
         type = types.str;
-        description = "Cadvisor storage driver host.";
+        description = lib.mdDoc "Cadvisor storage driver host.";
       };
 
       storageDriverDb = mkOption {
         default = "root";
         type = types.str;
-        description = "Cadvisord storage driver database name.";
+        description = lib.mdDoc "Cadvisord storage driver database name.";
       };
 
       storageDriverUser = mkOption {
         default = "root";
         type = types.str;
-        description = "Cadvisor storage driver username.";
+        description = lib.mdDoc "Cadvisor storage driver username.";
       };
 
       storageDriverPassword = mkOption {
         default = "root";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Cadvisor storage driver password.
 
           Warning: this password is stored in the world-readable Nix store. It's
-          recommended to use the <option>storageDriverPasswordFile</option> option
+          recommended to use the {option}`storageDriverPasswordFile` option
           since that gives you control over the security of the password.
-          <option>storageDriverPasswordFile</option> also takes precedence over <option>storageDriverPassword</option>.
+          {option}`storageDriverPasswordFile` also takes precedence over {option}`storageDriverPassword`.
         '';
       };
 
       storageDriverPasswordFile = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           File that contains the cadvisor storage driver password.
 
-          <option>storageDriverPasswordFile</option> takes precedence over <option>storageDriverPassword</option>
+          {option}`storageDriverPasswordFile` takes precedence over {option}`storageDriverPassword`
 
-          Warning: when <option>storageDriverPassword</option> is non-empty this defaults to a file in the
-          world-readable Nix store that contains the value of <option>storageDriverPassword</option>.
+          Warning: when {option}`storageDriverPassword` is non-empty this defaults to a file in the
+          world-readable Nix store that contains the value of {option}`storageDriverPassword`.
 
           It's recommended to override this with a path not in the Nix store.
-          Tip: use <link xlink:href='https://nixos.org/nixops/manual/#idm140737318306400'>nixops key management</link>
+          Tip: use [nixops key management](https://nixos.org/nixops/manual/#idm140737318306400)
         '';
       };
 
       storageDriverSecure = mkOption {
         default = false;
         type = types.bool;
-        description = "Cadvisor storage driver, enable secure communication.";
+        description = lib.mdDoc "Cadvisor storage driver, enable secure communication.";
       };
 
       extraOptions = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Additional cadvisor options.
 
-          See <link xlink:href='https://github.com/google/cadvisor/blob/master/docs/runtime_options.md'/> for available options.
+          See <https://github.com/google/cadvisor/blob/master/docs/runtime_options.md> for available options.
         '';
       };
     };
diff --git a/nixos/modules/services/monitoring/collectd.nix b/nixos/modules/services/monitoring/collectd.nix
index 8d81737a3ef..5d525995c67 100644
--- a/nixos/modules/services/monitoring/collectd.nix
+++ b/nixos/modules/services/monitoring/collectd.nix
@@ -5,36 +5,15 @@ with lib;
 let
   cfg = config.services.collectd;
 
-  unvalidated_conf = pkgs.writeText "collectd-unvalidated.conf" ''
-    BaseDir "${cfg.dataDir}"
-    AutoLoadPlugin ${boolToString cfg.autoLoadPlugin}
-    Hostname "${config.networking.hostName}"
-
-    LoadPlugin syslog
-    <Plugin "syslog">
-      LogLevel "info"
-      NotifyLevel "OKAY"
-    </Plugin>
-
-    ${concatStrings (mapAttrsToList (plugin: pluginConfig: ''
-      LoadPlugin ${plugin}
-      <Plugin "${plugin}">
-      ${pluginConfig}
-      </Plugin>
-    '') cfg.plugins)}
-
-    ${concatMapStrings (f: ''
-      Include "${f}"
-    '') cfg.include}
-
-    ${cfg.extraConfig}
-  '';
+  baseDirLine = ''BaseDir "${cfg.dataDir}"'';
+  unvalidated_conf = pkgs.writeText "collectd-unvalidated.conf" cfg.extraConfig;
 
   conf = if cfg.validateConfig then
     pkgs.runCommand "collectd.conf" {} ''
       echo testing ${unvalidated_conf}
+      cp ${unvalidated_conf} collectd.conf
       # collectd -t fails if BaseDir does not exist.
-      sed '1s/^BaseDir.*$/BaseDir "."/' ${unvalidated_conf} > collectd.conf
+      substituteInPlace collectd.conf --replace ${lib.escapeShellArgs [ baseDirLine ]} 'BaseDir "."'
       ${package}/bin/collectd -t -C collectd.conf
       cp ${unvalidated_conf} $out
     '' else unvalidated_conf;
@@ -50,11 +29,11 @@ let
 
 in {
   options.services.collectd = with types; {
-    enable = mkEnableOption "collectd agent";
+    enable = mkEnableOption (lib.mdDoc "collectd agent");
 
     validateConfig = mkOption {
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Validate the syntax of collectd configuration file at build time.
         Disable this if you use the Include directive on files unavailable in
         the build sandbox, or when cross-compiling.
@@ -65,7 +44,7 @@ in {
     package = mkOption {
       default = pkgs.collectd;
       defaultText = literalExpression "pkgs.collectd";
-      description = ''
+      description = lib.mdDoc ''
         Which collectd package to use.
       '';
       type = types.package;
@@ -73,7 +52,7 @@ in {
 
     buildMinimalPackage = mkOption {
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Build a minimal collectd package with only the configured `services.collectd.plugins`
       '';
       type = bool;
@@ -81,7 +60,7 @@ in {
 
     user = mkOption {
       default = "collectd";
-      description = ''
+      description = lib.mdDoc ''
         User under which to run collectd.
       '';
       type = nullOr str;
@@ -89,7 +68,7 @@ in {
 
     dataDir = mkOption {
       default = "/var/lib/collectd";
-      description = ''
+      description = lib.mdDoc ''
         Data directory for collectd agent.
       '';
       type = path;
@@ -97,7 +76,7 @@ in {
 
     autoLoadPlugin = mkOption {
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable plugin autoloading.
       '';
       type = bool;
@@ -105,7 +84,7 @@ in {
 
     include = mkOption {
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Additional paths to load config from.
       '';
       type = listOf str;
@@ -114,7 +93,7 @@ in {
     plugins = mkOption {
       default = {};
       example = { cpu = ""; memory = ""; network = "Server 192.168.1.1 25826"; };
-      description = ''
+      description = lib.mdDoc ''
         Attribute set of plugin names to plugin config segments
       '';
       type = attrsOf lines;
@@ -122,8 +101,9 @@ in {
 
     extraConfig = mkOption {
       default = "";
-      description = ''
-        Extra configuration for collectd.
+      description = lib.mdDoc ''
+        Extra configuration for collectd. Use mkBefore to add lines before the
+        default config, and mkAfter to add them below.
       '';
       type = lines;
     };
@@ -131,6 +111,30 @@ in {
   };
 
   config = mkIf cfg.enable {
+    # 1200 is after the default (1000) but before mkAfter (1500).
+    services.collectd.extraConfig = lib.mkOrder 1200 ''
+      ${baseDirLine}
+      AutoLoadPlugin ${boolToString cfg.autoLoadPlugin}
+      Hostname "${config.networking.hostName}"
+
+      LoadPlugin syslog
+      <Plugin "syslog">
+        LogLevel "info"
+        NotifyLevel "OKAY"
+      </Plugin>
+
+      ${concatStrings (mapAttrsToList (plugin: pluginConfig: ''
+        LoadPlugin ${plugin}
+        <Plugin "${plugin}">
+        ${pluginConfig}
+        </Plugin>
+      '') cfg.plugins)}
+
+      ${concatMapStrings (f: ''
+        Include "${f}"
+      '') cfg.include}
+    '';
+
     systemd.tmpfiles.rules = [
       "d '${cfg.dataDir}' - ${cfg.user} - - -"
     ];
diff --git a/nixos/modules/services/monitoring/das_watchdog.nix b/nixos/modules/services/monitoring/das_watchdog.nix
index 88ca3a9227d..fd420b0c8a0 100644
--- a/nixos/modules/services/monitoring/das_watchdog.nix
+++ b/nixos/modules/services/monitoring/das_watchdog.nix
@@ -12,7 +12,7 @@ in {
   ###### interface
 
   options = {
-    services.das_watchdog.enable = mkEnableOption "realtime watchdog";
+    services.das_watchdog.enable = mkEnableOption (lib.mdDoc "realtime watchdog");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/monitoring/datadog-agent.nix b/nixos/modules/services/monitoring/datadog-agent.nix
index 6d9d1ef973a..15deef18b60 100644
--- a/nixos/modules/services/monitoring/datadog-agent.nix
+++ b/nixos/modules/services/monitoring/datadog-agent.nix
@@ -49,18 +49,12 @@ let
   };
 in {
   options.services.datadog-agent = {
-    enable = mkOption {
-      description = ''
-        Whether to enable the datadog-agent v7 monitoring service
-      '';
-      default = false;
-      type = types.bool;
-    };
+    enable = mkEnableOption (lib.mdDoc "Datadog-agent v7 monitoring service");
 
     package = mkOption {
       default = pkgs.datadog-agent;
       defaultText = literalExpression "pkgs.datadog-agent";
-      description = ''
+      description = lib.mdDoc ''
         Which DataDog v7 agent package to use. Note that the provided
         package is expected to have an overridable `pythonPackages`-attribute
         which configures the Python environment with the Datadog
@@ -70,7 +64,7 @@ in {
     };
 
     apiKeyFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Path to a file containing the Datadog API key to associate the
         agent with your account.
       '';
@@ -79,7 +73,7 @@ in {
     };
 
     ddUrl = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Custom dd_url to configure the agent with. Useful if traffic to datadog
         needs to go through a proxy.
         Don't use this to point to another datadog site (EU) - use site instead.
@@ -90,7 +84,7 @@ in {
     };
 
     site = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The datadog site to point the agent towards.
         Set to datadoghq.eu to point it to their EU site.
       '';
@@ -100,21 +94,21 @@ in {
     };
 
     tags = mkOption {
-      description = "The tags to mark this Datadog agent";
+      description = lib.mdDoc "The tags to mark this Datadog agent";
       example = [ "test" "service" ];
       default = null;
       type = types.nullOr (types.listOf types.str);
     };
 
     hostname = mkOption {
-      description = "The hostname to show in the Datadog dashboard (optional)";
+      description = lib.mdDoc "The hostname to show in the Datadog dashboard (optional)";
       default = null;
       example = "mymachine.mydomain";
       type = types.nullOr types.str;
     };
 
     logLevel = mkOption {
-      description = "Logging verbosity.";
+      description = lib.mdDoc "Logging verbosity.";
       default = null;
       type = types.nullOr (types.enum ["DEBUG" "INFO" "WARN" "ERROR"]);
     };
@@ -123,7 +117,7 @@ in {
       default = {};
       type    = types.attrs;
 
-      description = ''
+      description = lib.mdDoc ''
         Extra integrations from the Datadog core-integrations
         repository that should be built and included.
 
@@ -145,14 +139,14 @@ in {
     extraConfig = mkOption {
       default = {};
       type = types.attrs;
-      description = ''
+      description = lib.mdDoc ''
         Extra configuration options that will be merged into the
-        main config file <filename>datadog.yaml</filename>.
+        main config file {file}`datadog.yaml`.
       '';
      };
 
     enableLiveProcessCollection = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable the live process collection agent.
       '';
       default = false;
@@ -160,7 +154,7 @@ in {
     };
 
     enableTraceAgent = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable the trace agent.
       '';
       default = false;
@@ -168,7 +162,7 @@ in {
     };
 
     checks = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Configuration for all Datadog checks. Keys of this attribute
         set will be used as the name of the check to create the
         appropriate configuration in `conf.d/$check.d/conf.yaml`.
@@ -207,7 +201,7 @@ in {
     };
 
     diskCheck = mkOption {
-      description = "Disk check config";
+      description = lib.mdDoc "Disk check config";
       type = types.attrs;
       default = {
         init_config = {};
@@ -216,7 +210,7 @@ in {
     };
 
     networkCheck = mkOption {
-      description = "Network check config";
+      description = lib.mdDoc "Network check config";
       type = types.attrs;
       default = {
         init_config = {};
diff --git a/nixos/modules/services/monitoring/dd-agent/dd-agent-defaults.nix b/nixos/modules/services/monitoring/dd-agent/dd-agent-defaults.nix
deleted file mode 100644
index 04512819742..00000000000
--- a/nixos/modules/services/monitoring/dd-agent/dd-agent-defaults.nix
+++ /dev/null
@@ -1,8 +0,0 @@
-# Generated using update-dd-agent-default, please re-run after updating dd-agent. DO NOT EDIT MANUALLY.
-[
-  "auto_conf"
-  "agent_metrics.yaml.default"
-  "disk.yaml.default"
-  "network.yaml.default"
-  "ntp.yaml.default"
-]
diff --git a/nixos/modules/services/monitoring/dd-agent/dd-agent.nix b/nixos/modules/services/monitoring/dd-agent/dd-agent.nix
deleted file mode 100644
index a290dae8d4b..00000000000
--- a/nixos/modules/services/monitoring/dd-agent/dd-agent.nix
+++ /dev/null
@@ -1,236 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-let
-  cfg = config.services.dd-agent;
-
-  ddConf = pkgs.writeText "datadog.conf" ''
-    [Main]
-    dd_url: https://app.datadoghq.com
-    skip_ssl_validation: no
-    api_key: ${cfg.api_key}
-    ${optionalString (cfg.hostname != null) "hostname: ${cfg.hostname}"}
-
-    collector_log_file: /var/log/datadog/collector.log
-    forwarder_log_file: /var/log/datadog/forwarder.log
-    dogstatsd_log_file: /var/log/datadog/dogstatsd.log
-    pup_log_file:       /var/log/datadog/pup.log
-
-    # proxy_host: my-proxy.com
-    # proxy_port: 3128
-    # proxy_user: user
-    # proxy_password: password
-
-    # tags: mytag0, mytag1
-    ${optionalString (cfg.tags != null ) "tags: ${concatStringsSep ", " cfg.tags }"}
-
-    # collect_ec2_tags: no
-    # recent_point_threshold: 30
-    # use_mount: no
-    # listen_port: 17123
-    # graphite_listen_port: 17124
-    # non_local_traffic: no
-    # use_curl_http_client: False
-    # bind_host: localhost
-
-    # use_pup: no
-    # pup_port: 17125
-    # pup_interface: localhost
-    # pup_url: http://localhost:17125
-
-    # dogstatsd_port : 8125
-    # dogstatsd_interval : 10
-    # dogstatsd_normalize : yes
-    # statsd_forward_host: address_of_own_statsd_server
-    # statsd_forward_port: 8125
-
-    # device_blacklist_re: .*\/dev\/mapper\/lxc-box.*
-
-    # ganglia_host: localhost
-    # ganglia_port: 8651
-  '';
-
-  diskConfig = pkgs.writeText "disk.yaml" ''
-    init_config:
-
-    instances:
-      - use_mount: no
-  '';
-
-  networkConfig = pkgs.writeText "network.yaml" ''
-    init_config:
-
-    instances:
-      # Network check only supports one configured instance
-      - collect_connection_state: false
-        excluded_interfaces:
-          - lo
-          - lo0
-  '';
-
-  postgresqlConfig = pkgs.writeText "postgres.yaml" cfg.postgresqlConfig;
-  nginxConfig = pkgs.writeText "nginx.yaml" cfg.nginxConfig;
-  mongoConfig = pkgs.writeText "mongo.yaml" cfg.mongoConfig;
-  jmxConfig = pkgs.writeText "jmx.yaml" cfg.jmxConfig;
-  processConfig = pkgs.writeText "process.yaml" cfg.processConfig;
-
-  etcfiles =
-    let
-      defaultConfd = import ./dd-agent-defaults.nix;
-    in
-      listToAttrs (map (f: {
-        name = "dd-agent/conf.d/${f}";
-        value.source = "${pkgs.dd-agent}/agent/conf.d-system/${f}";
-      }) defaultConfd) //
-      {
-        "dd-agent/datadog.conf".source = ddConf;
-        "dd-agent/conf.d/disk.yaml".source = diskConfig;
-        "dd-agent/conf.d/network.yaml".source = networkConfig;
-      } //
-      (optionalAttrs (cfg.postgresqlConfig != null)
-      {
-        "dd-agent/conf.d/postgres.yaml".source = postgresqlConfig;
-      }) //
-      (optionalAttrs (cfg.nginxConfig != null)
-      {
-        "dd-agent/conf.d/nginx.yaml".source = nginxConfig;
-      }) //
-      (optionalAttrs (cfg.mongoConfig != null)
-      {
-        "dd-agent/conf.d/mongo.yaml".source = mongoConfig;
-      }) //
-      (optionalAttrs (cfg.processConfig != null)
-      {
-        "dd-agent/conf.d/process.yaml".source = processConfig;
-      }) //
-      (optionalAttrs (cfg.jmxConfig != null)
-      {
-        "dd-agent/conf.d/jmx.yaml".source = jmxConfig;
-      });
-
-in {
-  options.services.dd-agent = {
-    enable = mkOption {
-      description = ''
-        Whether to enable the dd-agent v5 monitoring service.
-        For datadog-agent v6, see <option>services.datadog-agent.enable</option>.
-      '';
-      default = false;
-      type = types.bool;
-    };
-
-    api_key = mkOption {
-      description = ''
-        The Datadog API key to associate the agent with your account.
-
-        Warning: this key is stored in cleartext within the world-readable
-        Nix store! Consider using the new v6
-        <option>services.datadog-agent</option> module instead.
-      '';
-      example = "ae0aa6a8f08efa988ba0a17578f009ab";
-      type = types.str;
-    };
-
-    tags = mkOption {
-      description = "The tags to mark this Datadog agent";
-      example = [ "test" "service" ];
-      default = null;
-      type = types.nullOr (types.listOf types.str);
-    };
-
-    hostname = mkOption {
-      description = "The hostname to show in the Datadog dashboard (optional)";
-      default = null;
-      example = "mymachine.mydomain";
-      type = types.nullOr types.str;
-    };
-
-    postgresqlConfig = mkOption {
-      description = "Datadog PostgreSQL integration configuration";
-      default = null;
-      type = types.nullOr types.lines;
-    };
-
-    nginxConfig = mkOption {
-      description = "Datadog nginx integration configuration";
-      default = null;
-      type = types.nullOr types.lines;
-    };
-
-    mongoConfig = mkOption {
-      description = "MongoDB integration configuration";
-      default = null;
-      type = types.nullOr types.lines;
-    };
-
-    jmxConfig = mkOption {
-      description = "JMX integration configuration";
-      default = null;
-      type = types.nullOr types.lines;
-    };
-
-    processConfig = mkOption {
-      description = ''
-        Process integration configuration
-        See <link xlink:href="https://docs.datadoghq.com/integrations/process/"/>
-      '';
-      default = null;
-      type = types.nullOr types.lines;
-    };
-
-  };
-
-  config = mkIf cfg.enable {
-    environment.systemPackages = [ pkgs.dd-agent pkgs.sysstat pkgs.procps ];
-
-    users.users.datadog = {
-      description = "Datadog Agent User";
-      uid = config.ids.uids.datadog;
-      group = "datadog";
-      home = "/var/log/datadog/";
-      createHome = true;
-    };
-
-    users.groups.datadog.gid = config.ids.gids.datadog;
-
-    systemd.services = let
-      makeService = attrs: recursiveUpdate {
-        path = [ pkgs.dd-agent pkgs.python pkgs.sysstat pkgs.procps pkgs.gohai ];
-        wantedBy = [ "multi-user.target" ];
-        serviceConfig = {
-          User = "datadog";
-          Group = "datadog";
-          Restart = "always";
-          RestartSec = 2;
-          PrivateTmp = true;
-        };
-        restartTriggers = [ pkgs.dd-agent ddConf diskConfig networkConfig postgresqlConfig nginxConfig mongoConfig jmxConfig processConfig ];
-      } attrs;
-    in {
-      dd-agent = makeService {
-        description = "Datadog agent monitor";
-        serviceConfig.ExecStart = "${pkgs.dd-agent}/bin/dd-agent foreground";
-      };
-
-      dogstatsd = makeService {
-        description = "Datadog statsd";
-        environment.TMPDIR = "/run/dogstatsd";
-        serviceConfig = {
-          ExecStart = "${pkgs.dd-agent}/bin/dogstatsd start";
-          Type = "forking";
-          PIDFile = "/run/dogstatsd/dogstatsd.pid";
-          RuntimeDirectory = "dogstatsd";
-        };
-      };
-
-      dd-jmxfetch = lib.mkIf (cfg.jmxConfig != null) {
-        description = "Datadog JMX Fetcher";
-        path = [ pkgs.dd-agent pkgs.python pkgs.sysstat pkgs.procps pkgs.jdk ];
-        serviceConfig.ExecStart = "${pkgs.dd-agent}/bin/dd-jmxfetch";
-      };
-    };
-
-    environment.etc = etcfiles;
-  };
-}
diff --git a/nixos/modules/services/monitoring/dd-agent/update-dd-agent-defaults b/nixos/modules/services/monitoring/dd-agent/update-dd-agent-defaults
deleted file mode 100755
index 76724173171..00000000000
--- a/nixos/modules/services/monitoring/dd-agent/update-dd-agent-defaults
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/usr/bin/env bash
-dd=$(nix-build --no-out-link -A dd-agent ../../../..)
-echo '# Generated using update-dd-agent-default, please re-run after updating dd-agent. DO NOT EDIT MANUALLY.' > dd-agent-defaults.nix
-echo '[' >> dd-agent-defaults.nix
-echo '  "auto_conf"' >> dd-agent-defaults.nix
-for f in $(find $dd/agent/conf.d-system -maxdepth 1 -type f | grep -v '\.example' | sort); do
-  echo "  \"$(basename $f)\"" >> dd-agent-defaults.nix
-done
-echo ']' >> dd-agent-defaults.nix
diff --git a/nixos/modules/services/monitoring/do-agent.nix b/nixos/modules/services/monitoring/do-agent.nix
index 4dfb6236727..c1788c640c2 100644
--- a/nixos/modules/services/monitoring/do-agent.nix
+++ b/nixos/modules/services/monitoring/do-agent.nix
@@ -8,7 +8,7 @@ let
 in
 {
   options.services.do-agent = {
-    enable = mkEnableOption "do-agent, the DigitalOcean droplet metrics agent";
+    enable = mkEnableOption (lib.mdDoc "do-agent, the DigitalOcean droplet metrics agent");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/monitoring/fusion-inventory.nix b/nixos/modules/services/monitoring/fusion-inventory.nix
index 9b65c76ce02..7b28e8de122 100644
--- a/nixos/modules/services/monitoring/fusion-inventory.nix
+++ b/nixos/modules/services/monitoring/fusion-inventory.nix
@@ -22,11 +22,11 @@ in {
 
     services.fusionInventory = {
 
-      enable = mkEnableOption "Fusion Inventory Agent";
+      enable = mkEnableOption (lib.mdDoc "Fusion Inventory Agent");
 
       servers = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The urls of the OCS/GLPI servers to connect to.
         '';
       };
@@ -34,7 +34,7 @@ in {
       extraConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Configuration that is injected verbatim into the configuration file.
         '';
       };
diff --git a/nixos/modules/services/monitoring/grafana-agent.nix b/nixos/modules/services/monitoring/grafana-agent.nix
new file mode 100644
index 00000000000..ecb39a924f5
--- /dev/null
+++ b/nixos/modules/services/monitoring/grafana-agent.nix
@@ -0,0 +1,157 @@
+{ lib, pkgs, config, generators, ... }:
+with lib;
+let
+  cfg = config.services.grafana-agent;
+  settingsFormat = pkgs.formats.yaml { };
+  configFile = settingsFormat.generate "grafana-agent.yaml" cfg.settings;
+in
+{
+  meta = {
+    maintainers = with maintainers; [ flokli zimbatm ];
+  };
+
+  options.services.grafana-agent = {
+    enable = mkEnableOption (lib.mdDoc "grafana-agent");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.grafana-agent;
+      defaultText = "pkgs.grafana-agent";
+      description = lib.mdDoc "The grafana-agent package to use.";
+    };
+
+    credentials = mkOption {
+      description = lib.mdDoc ''
+        Credentials to load at service startup. Keys that are UPPER_SNAKE will be loaded as env vars. Values are absolute paths to the credentials.
+      '';
+      type = types.attrsOf types.str;
+      default = { };
+
+      example = {
+        logs_remote_write_password = "/run/keys/grafana_agent_logs_remote_write_password";
+        LOGS_REMOTE_WRITE_URL = "/run/keys/grafana_agent_logs_remote_write_url";
+        LOGS_REMOTE_WRITE_USERNAME = "/run/keys/grafana_agent_logs_remote_write_username";
+        metrics_remote_write_password = "/run/keys/grafana_agent_metrics_remote_write_password";
+        METRICS_REMOTE_WRITE_URL = "/run/keys/grafana_agent_metrics_remote_write_url";
+        METRICS_REMOTE_WRITE_USERNAME = "/run/keys/grafana_agent_metrics_remote_write_username";
+      };
+    };
+
+    settings = mkOption {
+      description = lib.mdDoc ''
+        Configuration for `grafana-agent`.
+
+        See https://grafana.com/docs/agent/latest/configuration/
+      '';
+
+      type = types.submodule {
+        freeformType = settingsFormat.type;
+      };
+
+      default = { };
+      defaultText = ''
+        metrics = {
+          wal_directory = "\''${STATE_DIRECTORY}";
+          global.scrape_interval = "5s";
+        };
+        integrations = {
+          agent.enabled = true;
+          agent.scrape_integration = true;
+          node_exporter.enabled = true;
+          replace_instance_label = true;
+        };
+      '';
+      example = {
+        metrics.global.remote_write = [{
+          url = "\${METRICS_REMOTE_WRITE_URL}";
+          basic_auth.username = "\${METRICS_REMOTE_WRITE_USERNAME}";
+          basic_auth.password_file = "\${CREDENTIALS_DIRECTORY}/metrics_remote_write_password";
+        }];
+        logs.configs = [{
+          name = "default";
+          scrape_configs = [
+            {
+              job_name = "journal";
+              journal = {
+                max_age = "12h";
+                labels.job = "systemd-journal";
+              };
+              relabel_configs = [
+                {
+                  source_labels = [ "__journal__systemd_unit" ];
+                  target_label = "systemd_unit";
+                }
+                {
+                  source_labels = [ "__journal__hostname" ];
+                  target_label = "nodename";
+                }
+                {
+                  source_labels = [ "__journal_syslog_identifier" ];
+                  target_label = "syslog_identifier";
+                }
+              ];
+            }
+          ];
+          positions.filename = "\${STATE_DIRECTORY}/loki_positions.yaml";
+          clients = [{
+            url = "\${LOGS_REMOTE_WRITE_URL}";
+            basic_auth.username = "\${LOGS_REMOTE_WRITE_USERNAME}";
+            basic_auth.password_file = "\${CREDENTIALS_DIRECTORY}/logs_remote_write_password";
+          }];
+        }];
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    services.grafana-agent.settings = {
+      # keep this in sync with config.services.grafana-agent.settings.defaultText.
+      metrics = {
+        wal_directory = mkDefault "\${STATE_DIRECTORY}";
+        global.scrape_interval = mkDefault "5s";
+      };
+      integrations = {
+        agent.enabled = mkDefault true;
+        agent.scrape_integration = mkDefault true;
+        node_exporter.enabled = mkDefault true;
+        replace_instance_label = mkDefault true;
+      };
+    };
+
+    systemd.services.grafana-agent = {
+      wantedBy = [ "multi-user.target" ];
+      script = ''
+        set -euo pipefail
+        shopt -u nullglob
+
+        # Load all credentials into env if they are in UPPER_SNAKE form.
+        if [[ -n "''${CREDENTIALS_DIRECTORY:-}" ]]; then
+          for file in "$CREDENTIALS_DIRECTORY"/*; do
+            key=$(basename "$file")
+            if [[ $key =~ ^[A-Z0-9_]+$ ]]; then
+              echo "Environ $key"
+              export "$key=$(< "$file")"
+            fi
+          done
+        fi
+
+        # We can't use Environment=HOSTNAME=%H, as it doesn't include the domain part.
+        export HOSTNAME=$(< /proc/sys/kernel/hostname)
+
+        exec ${cfg.package}/bin/agent -config.expand-env -config.file ${configFile}
+      '';
+      serviceConfig = {
+        Restart = "always";
+        DynamicUser = true;
+        RestartSec = 2;
+        SupplementaryGroups = [
+          # allow to read the systemd journal for loki log forwarding
+          "systemd-journal"
+        ];
+        StateDirectory = "grafana-agent";
+        LoadCredential = lib.mapAttrsToList (key: value: "${key}:${value}") cfg.credentials;
+        Type = "simple";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/monitoring/grafana-image-renderer.nix b/nixos/modules/services/monitoring/grafana-image-renderer.nix
index b8b95d846c6..60f6e84c63c 100644
--- a/nixos/modules/services/monitoring/grafana-image-renderer.nix
+++ b/nixos/modules/services/monitoring/grafana-image-renderer.nix
@@ -10,18 +10,18 @@ let
   configFile = format.generate "grafana-image-renderer-config.json" cfg.settings;
 in {
   options.services.grafana-image-renderer = {
-    enable = mkEnableOption "grafana-image-renderer";
+    enable = mkEnableOption (lib.mdDoc "grafana-image-renderer");
 
     chromium = mkOption {
       type = types.package;
-      description = ''
+      description = lib.mdDoc ''
         The chromium to use for image rendering.
       '';
     };
 
-    verbose = mkEnableOption "verbosity for the service";
+    verbose = mkEnableOption (lib.mdDoc "verbosity for the service");
 
-    provisionGrafana = mkEnableOption "Grafana configuration for grafana-image-renderer";
+    provisionGrafana = mkEnableOption (lib.mdDoc "Grafana configuration for grafana-image-renderer");
 
     settings = mkOption {
       type = types.submodule {
@@ -32,15 +32,15 @@ in {
             port = mkOption {
               type = types.port;
               default = 8081;
-              description = ''
+              description = lib.mdDoc ''
                 The TCP port to use for the rendering server.
               '';
             };
             logging.level = mkOption {
               type = types.enum [ "error" "warning" "info" "debug" ];
               default = "info";
-              description = ''
-                The log-level of the <filename>grafana-image-renderer.service</filename>-unit.
+              description = lib.mdDoc ''
+                The log-level of the {file}`grafana-image-renderer.service`-unit.
               '';
             };
           };
@@ -48,39 +48,37 @@ in {
             width = mkOption {
               default = 1000;
               type = types.ints.positive;
-              description = ''
+              description = lib.mdDoc ''
                 Width of the PNG used to display the alerting graph.
               '';
             };
             height = mkOption {
               default = 500;
               type = types.ints.positive;
-              description = ''
+              description = lib.mdDoc ''
                 Height of the PNG used to display the alerting graph.
               '';
             };
             mode = mkOption {
               default = "default";
               type = types.enum [ "default" "reusable" "clustered" ];
-              description = ''
-                Rendering mode of <package>grafana-image-renderer</package>:
-                <itemizedlist>
-                <listitem><para><literal>default:</literal> Creates on browser-instance
-                  per rendering request.</para></listitem>
-                <listitem><para><literal>reusable:</literal> One browser instance
-                  will be started and reused for each rendering request.</para></listitem>
-                <listitem><para><literal>clustered:</literal> allows to precisely
+              description = lib.mdDoc ''
+                Rendering mode of `grafana-image-renderer`:
+
+                - `default:` Creates on browser-instance
+                  per rendering request.
+                - `reusable:` One browser instance
+                  will be started and reused for each rendering request.
+                - `clustered:` allows to precisely
                   configure how many browser-instances are supposed to be used. The values
-                  for that mode can be declared in <literal>rendering.clustering</literal>.
-                  </para></listitem>
-                </itemizedlist>
+                  for that mode can be declared in `rendering.clustering`.
               '';
             };
             args = mkOption {
               type = types.listOf types.str;
               default = [ "--no-sandbox" ];
-              description = ''
-                List of CLI flags passed to <package>chromium</package>.
+              description = lib.mdDoc ''
+                List of CLI flags passed to `chromium`.
               '';
             };
           };
@@ -89,10 +87,10 @@ in {
 
       default = {};
 
-      description = ''
-        Configuration attributes for <package>grafana-image-renderer</package>.
+      description = lib.mdDoc ''
+        Configuration attributes for `grafana-image-renderer`.
 
-        See <link xlink:href="https://github.com/grafana/grafana-image-renderer/blob/ce1f81438e5f69c7fd7c73ce08bab624c4c92e25/default.json" />
+        See <https://github.com/grafana/grafana-image-renderer/blob/ce1f81438e5f69c7fd7c73ce08bab624c4c92e25/default.json>
         for supported values.
       '';
     };
@@ -108,9 +106,9 @@ in {
       }
     ];
 
-    services.grafana.extraOptions = mkIf cfg.provisionGrafana {
-      RENDERING_SERVER_URL = "http://localhost:${toString cfg.settings.service.port}/render";
-      RENDERING_CALLBACK_URL = "http://localhost:${toString config.services.grafana.port}";
+    services.grafana.settings.rendering = mkIf cfg.provisionGrafana {
+      url = "http://localhost:${toString cfg.settings.service.port}/render";
+      callback_url = "http://localhost:${toString config.services.grafana.port}";
     };
 
     services.grafana-image-renderer.chromium = mkDefault pkgs.chromium;
diff --git a/nixos/modules/services/monitoring/grafana-reporter.nix b/nixos/modules/services/monitoring/grafana-reporter.nix
index e40d78f538f..eac304d63aa 100644
--- a/nixos/modules/services/monitoring/grafana-reporter.nix
+++ b/nixos/modules/services/monitoring/grafana-reporter.nix
@@ -7,40 +7,40 @@ let
 
 in {
   options.services.grafana_reporter = {
-    enable = mkEnableOption "grafana_reporter";
+    enable = mkEnableOption (lib.mdDoc "grafana_reporter");
 
     grafana = {
       protocol = mkOption {
-        description = "Grafana protocol.";
+        description = lib.mdDoc "Grafana protocol.";
         default = "http";
         type = types.enum ["http" "https"];
       };
       addr = mkOption {
-        description = "Grafana address.";
+        description = lib.mdDoc "Grafana address.";
         default = "127.0.0.1";
         type = types.str;
       };
       port = mkOption {
-        description = "Grafana port.";
+        description = lib.mdDoc "Grafana port.";
         default = 3000;
-        type = types.int;
+        type = types.port;
       };
 
     };
     addr = mkOption {
-      description = "Listening address.";
+      description = lib.mdDoc "Listening address.";
       default = "127.0.0.1";
       type = types.str;
     };
 
     port = mkOption {
-      description = "Listening port.";
+      description = lib.mdDoc "Listening port.";
       default = 8686;
-      type = types.int;
+      type = types.port;
     };
 
     templateDir = mkOption {
-      description = "Optional template directory to use custom tex templates";
+      description = lib.mdDoc "Optional template directory to use custom tex templates";
       default = pkgs.grafana_reporter;
       defaultText = literalExpression "pkgs.grafana_reporter";
       type = types.either types.str types.path;
diff --git a/nixos/modules/services/monitoring/grafana.nix b/nixos/modules/services/monitoring/grafana.nix
index 81fca33f5fe..9b3068796d8 100644
--- a/nixos/modules/services/monitoring/grafana.nix
+++ b/nixos/modules/services/monitoring/grafana.nix
@@ -5,215 +5,165 @@ with lib;
 let
   cfg = config.services.grafana;
   opt = options.services.grafana;
+  provisioningSettingsFormat = pkgs.formats.yaml {};
   declarativePlugins = pkgs.linkFarm "grafana-plugins" (builtins.map (pkg: { name = pkg.pname; path = pkg; }) cfg.declarativePlugins);
-  useMysql = cfg.database.type == "mysql";
-  usePostgresql = cfg.database.type == "postgres";
-
-  envOptions = {
-    PATHS_DATA = cfg.dataDir;
-    PATHS_PLUGINS = if builtins.isNull cfg.declarativePlugins then "${cfg.dataDir}/plugins" else declarativePlugins;
-    PATHS_LOGS = "${cfg.dataDir}/log";
-
-    SERVER_PROTOCOL = cfg.protocol;
-    SERVER_HTTP_ADDR = cfg.addr;
-    SERVER_HTTP_PORT = cfg.port;
-    SERVER_SOCKET = cfg.socket;
-    SERVER_DOMAIN = cfg.domain;
-    SERVER_ROOT_URL = cfg.rootUrl;
-    SERVER_STATIC_ROOT_PATH = cfg.staticRootPath;
-    SERVER_CERT_FILE = cfg.certFile;
-    SERVER_CERT_KEY = cfg.certKey;
-
-    DATABASE_TYPE = cfg.database.type;
-    DATABASE_HOST = cfg.database.host;
-    DATABASE_NAME = cfg.database.name;
-    DATABASE_USER = cfg.database.user;
-    DATABASE_PASSWORD = cfg.database.password;
-    DATABASE_PATH = cfg.database.path;
-    DATABASE_CONN_MAX_LIFETIME = cfg.database.connMaxLifetime;
-
-    SECURITY_ADMIN_USER = cfg.security.adminUser;
-    SECURITY_ADMIN_PASSWORD = cfg.security.adminPassword;
-    SECURITY_SECRET_KEY = cfg.security.secretKey;
-
-    USERS_ALLOW_SIGN_UP = boolToString cfg.users.allowSignUp;
-    USERS_ALLOW_ORG_CREATE = boolToString cfg.users.allowOrgCreate;
-    USERS_AUTO_ASSIGN_ORG = boolToString cfg.users.autoAssignOrg;
-    USERS_AUTO_ASSIGN_ORG_ROLE = cfg.users.autoAssignOrgRole;
-
-    AUTH_ANONYMOUS_ENABLED = boolToString cfg.auth.anonymous.enable;
-    AUTH_ANONYMOUS_ORG_NAME = cfg.auth.anonymous.org_name;
-    AUTH_ANONYMOUS_ORG_ROLE = cfg.auth.anonymous.org_role;
-    AUTH_GOOGLE_ENABLED = boolToString cfg.auth.google.enable;
-    AUTH_GOOGLE_ALLOW_SIGN_UP = boolToString cfg.auth.google.allowSignUp;
-    AUTH_GOOGLE_CLIENT_ID = cfg.auth.google.clientId;
-
-    ANALYTICS_REPORTING_ENABLED = boolToString cfg.analytics.reporting.enable;
-
-    SMTP_ENABLED = boolToString cfg.smtp.enable;
-    SMTP_HOST = cfg.smtp.host;
-    SMTP_USER = cfg.smtp.user;
-    SMTP_PASSWORD = cfg.smtp.password;
-    SMTP_FROM_ADDRESS = cfg.smtp.fromAddress;
-  } // cfg.extraOptions;
-
-  datasourceConfiguration = {
-    apiVersion = 1;
-    datasources = cfg.provision.datasources;
-  };
+  useMysql = cfg.settings.database.type == "mysql";
+  usePostgresql = cfg.settings.database.type == "postgres";
 
-  datasourceFile = pkgs.writeText "datasource.yaml" (builtins.toJSON datasourceConfiguration);
+  settingsFormatIni = pkgs.formats.ini {};
+  configFile = settingsFormatIni.generate "config.ini" cfg.settings;
 
-  dashboardConfiguration = {
-    apiVersion = 1;
-    providers = cfg.provision.dashboards;
-  };
+  mkProvisionCfg = name: attr: provisionCfg:
+    if provisionCfg.path != null
+      then provisionCfg.path
+    else
+      provisioningSettingsFormat.generate "${name}.yaml"
+        (if provisionCfg.settings != null
+          then provisionCfg.settings
+          else {
+            apiVersion = 1;
+            ${attr} = [];
+          });
 
-  dashboardFile = pkgs.writeText "dashboard.yaml" (builtins.toJSON dashboardConfiguration);
+  datasourceFileOrDir = mkProvisionCfg "datasource" "datasources" cfg.provision.datasources;
+  dashboardFileOrDir = mkProvisionCfg "dashboard" "providers" cfg.provision.dashboards;
 
   notifierConfiguration = {
     apiVersion = 1;
     notifiers = cfg.provision.notifiers;
   };
 
-  notifierFile = pkgs.writeText "notifier.yaml" (builtins.toJSON notifierConfiguration);
+  notifierFileOrDir = pkgs.writeText "notifier.yaml" (builtins.toJSON notifierConfiguration);
 
-  provisionConfDir =  pkgs.runCommand "grafana-provisioning" { } ''
-    mkdir -p $out/{datasources,dashboards,notifiers}
-    ln -sf ${datasourceFile} $out/datasources/datasource.yaml
-    ln -sf ${dashboardFile} $out/dashboards/dashboard.yaml
-    ln -sf ${notifierFile} $out/notifiers/notifier.yaml
+  generateAlertingProvisioningYaml = x: if (cfg.provision.alerting."${x}".path == null)
+                                        then provisioningSettingsFormat.generate "${x}.yaml" cfg.provision.alerting."${x}".settings
+                                        else cfg.provision.alerting."${x}".path;
+  rulesFileOrDir = generateAlertingProvisioningYaml "rules";
+  contactPointsFileOrDir = generateAlertingProvisioningYaml "contactPoints";
+  policiesFileOrDir = generateAlertingProvisioningYaml "policies";
+  templatesFileOrDir = generateAlertingProvisioningYaml "templates";
+  muteTimingsFileOrDir = generateAlertingProvisioningYaml "muteTimings";
+
+  ln = { src, dir, filename }: ''
+    if [[ -d "${src}" ]]; then
+      pushd $out/${dir} &>/dev/null
+        lndir "${src}"
+      popd &>/dev/null
+    else
+      ln -sf ${src} $out/${dir}/${filename}.yaml
+    fi
+  '';
+  provisionConfDir = pkgs.runCommand "grafana-provisioning" { nativeBuildInputs = [ pkgs.xorg.lndir ]; } ''
+    mkdir -p $out/{datasources,dashboards,notifiers,alerting}
+    ${ln { src = datasourceFileOrDir;    dir = "datasources"; filename = "datasource"; }}
+    ${ln { src = dashboardFileOrDir;     dir = "dashboards";  filename = "dashbaord"; }}
+    ${ln { src = notifierFileOrDir;      dir = "notifiers";   filename = "notifier"; }}
+    ${ln { src = rulesFileOrDir;         dir = "alerting";    filename = "rules"; }}
+    ${ln { src = contactPointsFileOrDir; dir = "alerting";    filename = "contactPoints"; }}
+    ${ln { src = policiesFileOrDir;      dir = "alerting";    filename = "policies"; }}
+    ${ln { src = templatesFileOrDir;     dir = "alerting";    filename = "templates"; }}
+    ${ln { src = muteTimingsFileOrDir;   dir = "alerting";    filename = "muteTimings"; }}
   '';
 
   # Get a submodule without any embedded metadata:
   _filter = x: filterAttrs (k: v: k != "_module") x;
 
+  # FIXME(@Ma27) remove before 23.05. This is just a helper-type
+  # because `mkRenamedOptionModule` doesn't work if `foo.bar` is renamed
+  # to `foo.bar.baz`.
+  submodule' = module: types.coercedTo
+    (mkOptionType {
+      name = "grafana-provision-submodule";
+      description = "Wrapper-type for backwards compat of Grafana's declarative provisioning";
+      check = x:
+        if builtins.isList x then
+          throw ''
+            Provisioning dashboards and datasources declaratively by
+            setting `dashboards` or `datasources` to a list is not supported
+            anymore. Use `services.grafana.provision.datasources.settings.datasources`
+            (or `services.grafana.provision.dashboards.settings.providers`) instead.
+          ''
+        else isAttrs x || isFunction x;
+    })
+    id
+    (types.submodule module);
+
   # http://docs.grafana.org/administration/provisioning/#datasources
   grafanaTypes.datasourceConfig = types.submodule {
+    freeformType = provisioningSettingsFormat.type;
+
+    imports = [
+      (mkRemovedOptionModule [ "password" ] ''
+        `services.grafana.provision.datasources.settings.datasources.<name>.password` has been removed
+        in Grafana 9. Use `secureJsonData` instead.
+      '')
+      (mkRemovedOptionModule [ "basicAuthPassword" ] ''
+        `services.grafana.provision.datasources.settings.datasources.<name>.basicAuthPassword` has been removed
+        in Grafana 9. Use `secureJsonData` instead.
+      '')
+    ];
+
     options = {
       name = mkOption {
         type = types.str;
-        description = "Name of the datasource. Required.";
+        description = lib.mdDoc "Name of the datasource. Required.";
       };
       type = mkOption {
         type = types.str;
-        description = "Datasource type. Required.";
+        description = lib.mdDoc "Datasource type. Required.";
       };
       access = mkOption {
         type = types.enum ["proxy" "direct"];
         default = "proxy";
-        description = "Access mode. proxy or direct (Server or Browser in the UI). Required.";
-      };
-      orgId = mkOption {
-        type = types.int;
-        default = 1;
-        description = "Org id. will default to orgId 1 if not specified.";
-      };
-      url = mkOption {
-        type = types.str;
-        description = "Url of the datasource.";
+        description = lib.mdDoc "Access mode. proxy or direct (Server or Browser in the UI). Required.";
       };
-      password = mkOption {
-        type = types.nullOr types.str;
-        default = null;
-        description = "Database password, if used.";
-      };
-      user = mkOption {
-        type = types.nullOr types.str;
-        default = null;
-        description = "Database user, if used.";
-      };
-      database = mkOption {
-        type = types.nullOr types.str;
-        default = null;
-        description = "Database name, if used.";
-      };
-      basicAuth = mkOption {
-        type = types.nullOr types.bool;
-        default = null;
-        description = "Enable/disable basic auth.";
-      };
-      basicAuthUser = mkOption {
-        type = types.nullOr types.str;
-        default = null;
-        description = "Basic auth username.";
-      };
-      basicAuthPassword = mkOption {
+      uid = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "Basic auth password.";
+        description = lib.mdDoc "Custom UID which can be used to reference this datasource in other parts of the configuration, if not specified will be generated automatically.";
       };
-      withCredentials = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Enable/disable with credentials headers.";
+      url = mkOption {
+        type = types.str;
+        default = "localhost";
+        description = lib.mdDoc "Url of the datasource.";
       };
-      isDefault = mkOption {
+      editable = mkOption {
         type = types.bool;
         default = false;
-        description = "Mark as default datasource. Max one per org.";
-      };
-      jsonData = mkOption {
-        type = types.nullOr types.attrs;
-        default = null;
-        description = "Datasource specific configuration.";
+        description = lib.mdDoc "Allow users to edit datasources from the UI.";
       };
       secureJsonData = mkOption {
         type = types.nullOr types.attrs;
         default = null;
-        description = "Datasource specific secure configuration.";
-      };
-      version = mkOption {
-        type = types.int;
-        default = 1;
-        description = "Version.";
-      };
-      editable = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Allow users to edit datasources from the UI.";
+        description = lib.mdDoc ''
+          Datasource specific secure configuration. Please note that the contents of this option
+          will end up in a world-readable Nix store. Use the file provider
+          pointing at a reasonably secured file in the local filesystem
+          to work around that. Look at the documentation for details:
+          <https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#file-provider>
+        '';
       };
     };
   };
 
   # http://docs.grafana.org/administration/provisioning/#dashboards
   grafanaTypes.dashboardConfig = types.submodule {
+    freeformType = provisioningSettingsFormat.type;
+
     options = {
       name = mkOption {
         type = types.str;
         default = "default";
-        description = "Provider name.";
-      };
-      orgId = mkOption {
-        type = types.int;
-        default = 1;
-        description = "Organization ID.";
-      };
-      folder = mkOption {
-        type = types.str;
-        default = "";
-        description = "Add dashboards to the specified folder.";
+        description = lib.mdDoc "A unique provider name.";
       };
       type = mkOption {
         type = types.str;
         default = "file";
-        description = "Dashboard provider type.";
+        description = lib.mdDoc "Dashboard provider type.";
       };
-      disableDeletion = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Disable deletion when JSON file is removed.";
-      };
-      updateIntervalSeconds = mkOption {
-        type = types.int;
-        default = 10;
-        description = "How often Grafana will scan for changed dashboards.";
-      };
-      options = {
-        path = mkOption {
-          type = types.path;
-          description = "Path grafana will watch for dashboards.";
-        };
+      options.path = mkOption {
+        type = types.path;
+        description = lib.mdDoc "Path grafana will watch for dashboards. Required when using the 'file' type.";
       };
     };
   };
@@ -223,128 +173,141 @@ let
       name = mkOption {
         type = types.str;
         default = "default";
-        description = "Notifier name.";
+        description = lib.mdDoc "Notifier name.";
       };
       type = mkOption {
         type = types.enum ["dingding" "discord" "email" "googlechat" "hipchat" "kafka" "line" "teams" "opsgenie" "pagerduty" "prometheus-alertmanager" "pushover" "sensu" "sensugo" "slack" "telegram" "threema" "victorops" "webhook"];
-        description = "Notifier type.";
+        description = lib.mdDoc "Notifier type.";
       };
       uid = mkOption {
         type = types.str;
-        description = "Unique notifier identifier.";
+        description = lib.mdDoc "Unique notifier identifier.";
       };
       org_id = mkOption {
         type = types.int;
         default = 1;
-        description = "Organization ID.";
+        description = lib.mdDoc "Organization ID.";
       };
       org_name = mkOption {
         type = types.str;
         default = "Main Org.";
-        description = "Organization name.";
+        description = lib.mdDoc "Organization name.";
       };
       is_default = mkOption {
         type = types.bool;
-        description = "Is the default notifier.";
+        description = lib.mdDoc "Is the default notifier.";
         default = false;
       };
       send_reminder = mkOption {
         type = types.bool;
         default = true;
-        description = "Should the notifier be sent reminder notifications while alerts continue to fire.";
+        description = lib.mdDoc "Should the notifier be sent reminder notifications while alerts continue to fire.";
       };
       frequency = mkOption {
         type = types.str;
         default = "5m";
-        description = "How frequently should the notifier be sent reminders.";
+        description = lib.mdDoc "How frequently should the notifier be sent reminders.";
       };
       disable_resolve_message = mkOption {
         type = types.bool;
         default = false;
-        description = "Turn off the message that sends when an alert returns to OK.";
+        description = lib.mdDoc "Turn off the message that sends when an alert returns to OK.";
       };
       settings = mkOption {
         type = types.nullOr types.attrs;
         default = null;
-        description = "Settings for the notifier type.";
+        description = lib.mdDoc "Settings for the notifier type.";
       };
       secure_settings = mkOption {
         type = types.nullOr types.attrs;
         default = null;
-        description = "Secure settings for the notifier type.";
+        description = lib.mdDoc ''
+          Secure settings for the notifier type. Please note that the contents of this option
+          will end up in a world-readable Nix store. Use the file provider
+          pointing at a reasonably secured file in the local filesystem
+          to work around that. Look at the documentation for details:
+          <https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#file-provider>
+        '';
       };
     };
   };
 in {
-  options.services.grafana = {
-    enable = mkEnableOption "grafana";
-
-    protocol = mkOption {
-      description = "Which protocol to listen.";
-      default = "http";
-      type = types.enum ["http" "https" "socket"];
-    };
-
-    addr = mkOption {
-      description = "Listening address.";
-      default = "127.0.0.1";
-      type = types.str;
-    };
-
-    port = mkOption {
-      description = "Listening port.";
-      default = 3000;
-      type = types.port;
-    };
-
-    socket = mkOption {
-      description = "Listening socket.";
-      default = "/run/grafana/grafana.sock";
-      type = types.str;
-    };
-
-    domain = mkOption {
-      description = "The public facing domain name used to access grafana from a browser.";
-      default = "localhost";
-      type = types.str;
-    };
-
-    rootUrl = mkOption {
-      description = "Full public facing url.";
-      default = "%(protocol)s://%(domain)s:%(http_port)s/";
-      type = types.str;
-    };
+  imports = [
+    (mkRenamedOptionModule [ "services" "grafana" "protocol" ] [ "services" "grafana" "settings" "server" "protocol" ])
+    (mkRenamedOptionModule [ "services" "grafana" "addr" ] [ "services" "grafana" "settings" "server" "http_addr" ])
+    (mkRenamedOptionModule [ "services" "grafana" "port" ] [ "services" "grafana" "settings" "server" "http_port" ])
+    (mkRenamedOptionModule [ "services" "grafana" "domain" ] [ "services" "grafana" "settings" "server" "domain" ])
+    (mkRenamedOptionModule [ "services" "grafana" "rootUrl" ] [ "services" "grafana" "settings" "server" "root_url" ])
+    (mkRenamedOptionModule [ "services" "grafana" "staticRootPath" ] [ "services" "grafana" "settings" "server" "static_root_path" ])
+    (mkRenamedOptionModule [ "services" "grafana" "certFile" ] [ "services" "grafana" "settings" "server" "cert_file" ])
+    (mkRenamedOptionModule [ "services" "grafana" "certKey" ] [ "services" "grafana" "settings" "server" "cert_key" ])
+    (mkRenamedOptionModule [ "services" "grafana" "socket" ] [ "services" "grafana" "settings" "server" "socket" ])
+    (mkRenamedOptionModule [ "services" "grafana" "database" "type" ] [ "services" "grafana" "settings" "database" "type" ])
+    (mkRenamedOptionModule [ "services" "grafana" "database" "host" ] [ "services" "grafana" "settings" "database" "host" ])
+    (mkRenamedOptionModule [ "services" "grafana" "database" "name" ] [ "services" "grafana" "settings" "database" "name" ])
+    (mkRenamedOptionModule [ "services" "grafana" "database" "user" ] [ "services" "grafana" "settings" "database" "user" ])
+    (mkRenamedOptionModule [ "services" "grafana" "database" "password" ] [ "services" "grafana" "settings" "database" "password" ])
+    (mkRenamedOptionModule [ "services" "grafana" "database" "path" ] [ "services" "grafana" "settings" "database" "path" ])
+    (mkRenamedOptionModule [ "services" "grafana" "database" "connMaxLifetime" ] [ "services" "grafana" "settings" "database" "conn_max_lifetime" ])
+    (mkRenamedOptionModule [ "services" "grafana" "security" "adminUser" ] [ "services" "grafana" "settings" "security" "admin_user" ])
+    (mkRenamedOptionModule [ "services" "grafana" "security" "adminPassword" ] [ "services" "grafana" "settings" "security" "admin_password" ])
+    (mkRenamedOptionModule [ "services" "grafana" "security" "secretKey" ] [ "services" "grafana" "settings" "security" "secret_key" ])
+    (mkRenamedOptionModule [ "services" "grafana" "server" "serveFromSubPath" ] [ "services" "grafana" "settings" "server" "serve_from_sub_path" ])
+    (mkRenamedOptionModule [ "services" "grafana" "smtp" "enable" ] [ "services" "grafana" "settings" "smtp" "enabled" ])
+    (mkRenamedOptionModule [ "services" "grafana" "smtp" "user" ] [ "services" "grafana" "settings" "smtp" "user" ])
+    (mkRenamedOptionModule [ "services" "grafana" "smtp" "password" ] [ "services" "grafana" "settings" "smtp" "password" ])
+    (mkRenamedOptionModule [ "services" "grafana" "smtp" "fromAddress" ] [ "services" "grafana" "settings" "smtp" "from_address" ])
+    (mkRenamedOptionModule [ "services" "grafana" "users" "allowSignUp" ] [ "services" "grafana" "settings" "users" "allow_sign_up" ])
+    (mkRenamedOptionModule [ "services" "grafana" "users" "allowOrgCreate" ] [ "services" "grafana" "settings" "users" "allow_org_create" ])
+    (mkRenamedOptionModule [ "services" "grafana" "users" "autoAssignOrg" ] [ "services" "grafana" "settings" "users" "auto_assign_org" ])
+    (mkRenamedOptionModule [ "services" "grafana" "users" "autoAssignOrgRole" ] [ "services" "grafana" "settings" "users" "auto_assign_org_role" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "disableLoginForm" ] [ "services" "grafana" "settings" "auth" "disable_login_form" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "enable" ] [ "services" "grafana" "settings" "auth.anonymous" "enabled" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "org_name" ] [ "services" "grafana" "settings" "auth.anonymous" "org_name" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "anonymous" "org_role" ] [ "services" "grafana" "settings" "auth.anonymous" "org_role" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "enable" ] [ "services" "grafana" "settings" "auth.azuread" "enabled" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowSignUp" ] [ "services" "grafana" "settings" "auth.azuread" "allow_sign_up" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "clientId" ] [ "services" "grafana" "settings" "auth.azuread" "client_id" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowedDomains" ] [ "services" "grafana" "settings" "auth.azuread" "allowed_domains" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "azuread" "allowedGroups" ] [ "services" "grafana" "settings" "auth.azuread" "allowed_groups" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "google" "enable" ] [ "services" "grafana" "settings" "auth.google" "enabled" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "google" "allowSignUp" ] [ "services" "grafana" "settings" "auth.google" "allow_sign_up" ])
+    (mkRenamedOptionModule [ "services" "grafana" "auth" "google" "clientId" ] [ "services" "grafana" "settings" "auth.google" "client_id" ])
+    (mkRenamedOptionModule [ "services" "grafana" "analytics" "reporting" "enable" ] [ "services" "grafana" "settings" "analytics" "reporting_enabled" ])
 
-    certFile = mkOption {
-      description = "Cert file for ssl.";
-      default = "";
-      type = types.str;
-    };
+    (mkRemovedOptionModule [ "services" "grafana" "database" "passwordFile" ] ''
+      This option has been removed. Use 'services.grafana.settings.database.password' with file provider instead.
+    '')
+    (mkRemovedOptionModule [ "services" "grafana" "security" "adminPasswordFile" ] ''
+      This option has been removed. Use 'services.grafana.settings.security.admin_password' with file provider instead.
+    '')
+    (mkRemovedOptionModule [ "services" "grafana" "security" "secretKeyFile" ] ''
+      This option has been removed. Use 'services.grafana.settings.security.secret_key' with file provider instead.
+    '')
+    (mkRemovedOptionModule [ "services" "grafana" "smtp" "passwordFile" ] ''
+      This option has been removed. Use 'services.grafana.settings.smtp.password' with file provider instead.
+    '')
+    (mkRemovedOptionModule [ "services" "grafana" "auth" "azuread" "clientSecretFile" ] ''
+      This option has been removed. Use 'services.grafana.settings.azuread.client_secret' with file provider instead.
+    '')
+    (mkRemovedOptionModule [ "services" "grafana" "auth" "google" "clientSecretFile" ] ''
+      This option has been removed. Use 'services.grafana.settings.google.client_secret' with file provider instead.
+    '')
+    (mkRemovedOptionModule [ "services" "grafana" "extraOptions" ] ''
+      This option has been removed. Use 'services.grafana.settings' instead. For a detailed migration guide, please
+      review the release notes of NixOS 22.11.
+    '')
 
-    certKey = mkOption {
-      description = "Cert key for ssl.";
-      default = "";
-      type = types.str;
-    };
+    (mkRemovedOptionModule [ "services" "grafana" "auth" "azuread" "tenantId" ] "This option has been deprecated upstream.")
+  ];
 
-    staticRootPath = mkOption {
-      description = "Root path for static assets.";
-      default = "${cfg.package}/share/grafana/public";
-      defaultText = literalExpression ''"''${package}/share/grafana/public"'';
-      type = types.str;
-    };
-
-    package = mkOption {
-      description = "Package to use.";
-      default = pkgs.grafana;
-      defaultText = literalExpression "pkgs.grafana";
-      type = types.package;
-    };
+  options.services.grafana = {
+    enable = mkEnableOption (lib.mdDoc "grafana");
 
     declarativePlugins = mkOption {
       type = with types; nullOr (listOf path);
       default = null;
-      description = "If non-null, then a list of packages containing Grafana plugins to install. If set, plugins cannot be manually installed.";
+      description = lib.mdDoc "If non-null, then a list of packages containing Grafana plugins to install. If set, plugins cannot be manually installed.";
       example = literalExpression "with pkgs.grafanaPlugins; [ grafana-piechart-panel ]";
       # Make sure each plugin is added only once; otherwise building
       # the link farm fails, since the same path is added multiple
@@ -352,287 +315,939 @@ in {
       apply = x: if isList x then lib.unique x else x;
     };
 
+    package = mkOption {
+      description = lib.mdDoc "Package to use.";
+      default = pkgs.grafana;
+      defaultText = literalExpression "pkgs.grafana";
+      type = types.package;
+    };
+
     dataDir = mkOption {
-      description = "Data directory.";
+      description = lib.mdDoc "Data directory.";
       default = "/var/lib/grafana";
       type = types.path;
     };
 
-    database = {
-      type = mkOption {
-        description = "Database type.";
-        default = "sqlite3";
-        type = types.enum ["mysql" "sqlite3" "postgres"];
-      };
+    settings = mkOption {
+      description = lib.mdDoc ''
+        Grafana settings. See <https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/>
+        for available options. INI format is used.
+      '';
+      type = types.submodule {
+        freeformType = settingsFormatIni.type;
 
-      host = mkOption {
-        description = "Database host.";
-        default = "127.0.0.1:3306";
-        type = types.str;
-      };
+        options = {
+          paths = {
+            plugins = mkOption {
+              description = lib.mdDoc "Directory where grafana will automatically scan and look for plugins";
+              default = if (cfg.declarativePlugins == null) then "${cfg.dataDir}/plugins" else declarativePlugins;
+              defaultText = literalExpression "if (cfg.declarativePlugins == null) then \"\${cfg.dataDir}/plugins\" else declarativePlugins";
+              type = types.path;
+            };
 
-      name = mkOption {
-        description = "Database name.";
-        default = "grafana";
-        type = types.str;
-      };
+            provisioning = mkOption {
+              description = lib.mdDoc ''
+                Folder that contains provisioning config files that grafana will apply on startup and while running.
+                Don't change the value of this option if you are planning to use `services.grafana.provision` options.
+              '';
+              default = provisionConfDir;
+              defaultText = "directory with links to files generated from services.grafana.provision";
+              type = types.path;
+            };
+          };
 
-      user = mkOption {
-        description = "Database user.";
-        default = "root";
-        type = types.str;
-      };
+          server = {
+            protocol = mkOption {
+              description = lib.mdDoc "Which protocol to listen.";
+              default = "http";
+              type = types.enum ["http" "https" "h2" "socket"];
+            };
 
-      password = mkOption {
-        description = ''
-          Database password.
-          This option is mutual exclusive with the passwordFile option.
-        '';
-        default = "";
-        type = types.str;
-      };
+            http_addr = mkOption {
+              description = lib.mdDoc "Listening address.";
+              default = "";
+              type = types.str;
+            };
 
-      passwordFile = mkOption {
-        description = ''
-          File that containts the database password.
-          This option is mutual exclusive with the password option.
-        '';
-        default = null;
-        type = types.nullOr types.path;
-      };
+            http_port = mkOption {
+              description = lib.mdDoc "Listening port.";
+              default = 3000;
+              type = types.port;
+            };
 
-      path = mkOption {
-        description = "Database path.";
-        default = "${cfg.dataDir}/data/grafana.db";
-        defaultText = literalExpression ''"''${config.${opt.dataDir}}/data/grafana.db"'';
-        type = types.path;
-      };
+            domain = mkOption {
+              description = lib.mdDoc "The public facing domain name used to access grafana from a browser.";
+              default = "localhost";
+              type = types.str;
+            };
 
-      connMaxLifetime = mkOption {
-        description = ''
-          Sets the maximum amount of time (in seconds) a connection may be reused.
-          For MySQL this setting should be shorter than the `wait_timeout' variable.
-        '';
-        default = "unlimited";
-        example = 14400;
-        type = types.either types.int (types.enum [ "unlimited" ]);
+            root_url = mkOption {
+              description = lib.mdDoc "Full public facing url.";
+              default = "%(protocol)s://%(domain)s:%(http_port)s/";
+              type = types.str;
+            };
+
+            static_root_path = mkOption {
+              description = lib.mdDoc "Root path for static assets.";
+              default = "${cfg.package}/share/grafana/public";
+              defaultText = literalExpression ''"''${package}/share/grafana/public"'';
+              type = types.str;
+            };
+
+            enable_gzip = mkOption {
+              description = lib.mdDoc ''
+                Set this option to true to enable HTTP compression, this can improve transfer speed and bandwidth utilization.
+                It is recommended that most users set it to true. By default it is set to false for compatibility reasons.
+              '';
+              default = false;
+              type = types.bool;
+            };
+
+            cert_file = mkOption {
+              description = lib.mdDoc "Cert file for ssl.";
+              default = "";
+              type = types.str;
+            };
+
+            cert_key = mkOption {
+              description = lib.mdDoc "Cert key for ssl.";
+              default = "";
+              type = types.str;
+            };
+
+            socket = mkOption {
+              description = lib.mdDoc "Path where the socket should be created when protocol=socket. Make sure that Grafana has appropriate permissions before you change this setting.";
+              default = "/run/grafana/grafana.sock";
+              type = types.str;
+            };
+          };
+
+          database = {
+            type = mkOption {
+              description = lib.mdDoc "Database type.";
+              default = "sqlite3";
+              type = types.enum ["mysql" "sqlite3" "postgres"];
+            };
+
+            host = mkOption {
+              description = lib.mdDoc "Database host.";
+              default = "127.0.0.1:3306";
+              type = types.str;
+            };
+
+            name = mkOption {
+              description = lib.mdDoc "Database name.";
+              default = "grafana";
+              type = types.str;
+            };
+
+            user = mkOption {
+              description = lib.mdDoc "Database user.";
+              default = "root";
+              type = types.str;
+            };
+
+            password = mkOption {
+              description = lib.mdDoc ''
+                Database password. Please note that the contents of this option
+                will end up in a world-readable Nix store. Use the file provider
+                pointing at a reasonably secured file in the local filesystem
+                to work around that. Look at the documentation for details:
+                <https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#file-provider>
+              '';
+              default = "";
+              type = types.str;
+            };
+
+            path = mkOption {
+              description = lib.mdDoc "Only applicable to sqlite3 database. The file path where the database will be stored.";
+              default = "${cfg.dataDir}/data/grafana.db";
+              defaultText = literalExpression ''"''${config.${opt.dataDir}}/data/grafana.db"'';
+              type = types.path;
+            };
+          };
+
+          security = {
+            admin_user = mkOption {
+              description = lib.mdDoc "Default admin username.";
+              default = "admin";
+              type = types.str;
+            };
+
+            admin_password = mkOption {
+              description = lib.mdDoc ''
+                Default admin password. Please note that the contents of this option
+                will end up in a world-readable Nix store. Use the file provider
+                pointing at a reasonably secured file in the local filesystem
+                to work around that. Look at the documentation for details:
+                <https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#file-provider>
+              '';
+              default = "admin";
+              type = types.str;
+            };
+
+            secret_key = mkOption {
+              description = lib.mdDoc ''
+                Secret key used for signing. Please note that the contents of this option
+                will end up in a world-readable Nix store. Use the file provider
+                pointing at a reasonably secured file in the local filesystem
+                to work around that. Look at the documentation for details:
+                <https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#file-provider>
+              '';
+              default = "SW2YcwTIb9zpOOhoPsMm";
+              type = types.str;
+            };
+          };
+
+          smtp = {
+            enabled = mkOption {
+              description = lib.mdDoc "Whether to enable SMTP.";
+              default = false;
+              type = types.bool;
+            };
+            host = mkOption {
+              description = lib.mdDoc "Host to connect to.";
+              default = "localhost:25";
+              type = types.str;
+            };
+            user = mkOption {
+              description = lib.mdDoc "User used for authentication.";
+              default = "";
+              type = types.str;
+            };
+            password = mkOption {
+              description = lib.mdDoc ''
+                Password used for authentication. Please note that the contents of this option
+                will end up in a world-readable Nix store. Use the file provider
+                pointing at a reasonably secured file in the local filesystem
+                to work around that. Look at the documentation for details:
+                <https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#file-provider>
+              '';
+              default = "";
+              type = types.str;
+            };
+            from_address = mkOption {
+              description = lib.mdDoc "Email address used for sending.";
+              default = "admin@grafana.localhost";
+              type = types.str;
+            };
+          };
+
+          users = {
+            allow_sign_up = mkOption {
+              description = lib.mdDoc "Disable user signup / registration.";
+              default = false;
+              type = types.bool;
+            };
+
+            allow_org_create = mkOption {
+              description = lib.mdDoc "Whether user is allowed to create organizations.";
+              default = false;
+              type = types.bool;
+            };
+
+            auto_assign_org = mkOption {
+              description = lib.mdDoc "Whether to automatically assign new users to default org.";
+              default = true;
+              type = types.bool;
+            };
+
+            auto_assign_org_role = mkOption {
+              description = lib.mdDoc "Default role new users will be auto assigned.";
+              default = "Viewer";
+              type = types.enum ["Viewer" "Editor"];
+            };
+          };
+
+          analytics.reporting_enabled = mkOption {
+            description = lib.mdDoc "Whether to allow anonymous usage reporting to stats.grafana.net.";
+            default = true;
+            type = types.bool;
+          };
+        };
       };
     };
 
     provision = {
-      enable = mkEnableOption "provision";
+      enable = mkEnableOption (lib.mdDoc "provision");
+
       datasources = mkOption {
-        description = "Grafana datasources configuration.";
-        default = [];
-        type = types.listOf grafanaTypes.datasourceConfig;
-        apply = x: map _filter x;
+        description = lib.mdDoc ''
+          Declaratively provision Grafana's datasources.
+        '';
+        default = {};
+        type = submodule' {
+          options.settings = mkOption {
+            description = lib.mdDoc ''
+              Grafana datasource configuration in Nix. Can't be used with
+              [](#opt-services.grafana.provision.datasources.path) simultaneously. See
+              <https://grafana.com/docs/grafana/latest/administration/provisioning/#data-sources>
+              for supported options.
+            '';
+            default = null;
+            type = types.nullOr (types.submodule {
+              options = {
+                apiVersion = mkOption {
+                  description = lib.mdDoc "Config file version.";
+                  default = 1;
+                  type = types.int;
+                };
+
+                datasources = mkOption {
+                  description = lib.mdDoc "List of datasources to insert/update.";
+                  default = [];
+                  type = types.listOf grafanaTypes.datasourceConfig;
+                  apply = map (flip builtins.removeAttrs [ "password" "basicAuthPassword" ]);
+                };
+
+                deleteDatasources = mkOption {
+                  description = lib.mdDoc "List of datasources that should be deleted from the database.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    options.name = mkOption {
+                      description = lib.mdDoc "Name of the datasource to delete.";
+                      type = types.str;
+                    };
+
+                    options.orgId = mkOption {
+                      description = lib.mdDoc "Organization ID of the datasource to delete.";
+                      type = types.int;
+                    };
+                  });
+                };
+              };
+            });
+            example = literalExpression ''
+              {
+                apiVersion = 1;
+
+                datasources = [{
+                  name = "Graphite";
+                  type = "graphite";
+                }];
+
+                deleteDatasources = [{
+                  name = "Graphite";
+                  orgId = 1;
+                }];
+              }
+            '';
+          };
+
+          options.path = mkOption {
+            description = lib.mdDoc ''
+              Path to YAML datasource configuration. Can't be used with
+              [](#opt-services.grafana.provision.datasources.settings) simultaneously.
+              Can be either a directory or a single YAML file. Will end up in the store.
+            '';
+            default = null;
+            type = types.nullOr types.path;
+          };
+        };
       };
+
+
       dashboards = mkOption {
-        description = "Grafana dashboard configuration.";
-        default = [];
-        type = types.listOf grafanaTypes.dashboardConfig;
-        apply = x: map _filter x;
+        description = lib.mdDoc ''
+          Declaratively provision Grafana's dashboards.
+        '';
+        default = {};
+        type = submodule' {
+          options.settings = mkOption {
+            description = lib.mdDoc ''
+              Grafana dashboard configuration in Nix. Can't be used with
+              [](#opt-services.grafana.provision.dashboards.path) simultaneously. See
+              <https://grafana.com/docs/grafana/latest/administration/provisioning/#dashboards>
+              for supported options.
+            '';
+            default = null;
+            type = types.nullOr (types.submodule {
+              options.apiVersion = mkOption {
+                description = lib.mdDoc "Config file version.";
+                default = 1;
+                type = types.int;
+              };
+
+              options.providers = mkOption {
+                description = lib.mdDoc "List of dashboards to insert/update.";
+                default = [];
+                type = types.listOf grafanaTypes.dashboardConfig;
+              };
+            });
+            example = literalExpression ''
+              {
+                apiVersion = 1;
+
+                providers = [{
+                    name = "default";
+                    options.path = "/var/lib/grafana/dashboards";
+                }];
+              }
+            '';
+          };
+
+          options.path = mkOption {
+            description = lib.mdDoc ''
+              Path to YAML dashboard configuration. Can't be used with
+              [](#opt-services.grafana.provision.dashboards.settings) simultaneously.
+              Can be either a directory or a single YAML file. Will end up in the store.
+            '';
+            default = null;
+            type = types.nullOr types.path;
+          };
+        };
       };
+
+
       notifiers = mkOption {
-        description = "Grafana notifier configuration.";
+        description = lib.mdDoc "Grafana notifier configuration.";
         default = [];
         type = types.listOf grafanaTypes.notifierConfig;
         apply = x: map _filter x;
       };
-    };
 
-    security = {
-      adminUser = mkOption {
-        description = "Default admin username.";
-        default = "admin";
-        type = types.str;
-      };
 
-      adminPassword = mkOption {
-        description = ''
-          Default admin password.
-          This option is mutual exclusive with the adminPasswordFile option.
-        '';
-        default = "admin";
-        type = types.str;
-      };
+      alerting = {
+        rules = {
+          path = mkOption {
+            description = lib.mdDoc ''
+              Path to YAML rules configuration. Can't be used with
+              [](#opt-services.grafana.provision.alerting.rules.settings) simultaneously.
+              Can be either a directory or a single YAML file. Will end up in the store.
+            '';
+            default = null;
+            type = types.nullOr types.path;
+          };
 
-      adminPasswordFile = mkOption {
-        description = ''
-          Default admin password.
-          This option is mutual exclusive with the <literal>adminPassword</literal> option.
-        '';
-        default = null;
-        type = types.nullOr types.path;
-      };
+          settings = mkOption {
+            description = lib.mdDoc ''
+              Grafana rules configuration in Nix. Can't be used with
+              [](#opt-services.grafana.provision.alerting.rules.path) simultaneously. See
+              <https://grafana.com/docs/grafana/latest/administration/provisioning/#rules>
+              for supported options.
+            '';
+            default = null;
+            type = types.nullOr (types.submodule {
+              options = {
+                apiVersion = mkOption {
+                  description = lib.mdDoc "Config file version.";
+                  default = 1;
+                  type = types.int;
+                };
 
-      secretKey = mkOption {
-        description = "Secret key used for signing.";
-        default = "SW2YcwTIb9zpOOhoPsMm";
-        type = types.str;
-      };
+                groups = mkOption {
+                  description = lib.mdDoc "List of rule groups to import or update.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    freeformType = provisioningSettingsFormat.type;
 
-      secretKeyFile = mkOption {
-        description = "Secret key used for signing.";
-        default = null;
-        type = types.nullOr types.path;
-      };
-    };
+                    options.name = mkOption {
+                      description = lib.mdDoc "Name of the rule group. Required.";
+                      type = types.str;
+                    };
 
-    smtp = {
-      enable = mkEnableOption "smtp";
-      host = mkOption {
-        description = "Host to connect to.";
-        default = "localhost:25";
-        type = types.str;
-      };
-      user = mkOption {
-        description = "User used for authentication.";
-        default = "";
-        type = types.str;
-      };
-      password = mkOption {
-        description = ''
-          Password used for authentication.
-          This option is mutual exclusive with the passwordFile option.
-        '';
-        default = "";
-        type = types.str;
-      };
-      passwordFile = mkOption {
-        description = ''
-          Password used for authentication.
-          This option is mutual exclusive with the password option.
-        '';
-        default = null;
-        type = types.nullOr types.path;
-      };
-      fromAddress = mkOption {
-        description = "Email address used for sending.";
-        default = "admin@grafana.localhost";
-        type = types.str;
-      };
-    };
+                    options.folder = mkOption {
+                      description = lib.mdDoc "Name of the folder the rule group will be stored in. Required.";
+                      type = types.str;
+                    };
 
-    users = {
-      allowSignUp = mkOption {
-        description = "Disable user signup / registration.";
-        default = false;
-        type = types.bool;
-      };
+                    options.interval = mkOption {
+                      description = lib.mdDoc "Interval that the rule group should be evaluated at. Required.";
+                      type = types.str;
+                    };
+                  });
+                };
 
-      allowOrgCreate = mkOption {
-        description = "Whether user is allowed to create organizations.";
-        default = false;
-        type = types.bool;
-      };
+                deleteRules = mkOption {
+                  description = lib.mdDoc "List of alert rule UIDs that should be deleted.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    options.orgId = mkOption {
+                      description = lib.mdDoc "Organization ID, default = 1";
+                      default = 1;
+                      type = types.int;
+                    };
 
-      autoAssignOrg = mkOption {
-        description = "Whether to automatically assign new users to default org.";
-        default = true;
-        type = types.bool;
-      };
+                    options.uid = mkOption {
+                      description = lib.mdDoc "Unique identifier for the rule. Required.";
+                      type = types.str;
+                    };
+                  });
+                };
+              };
+            });
+            example = literalExpression ''
+              {
+                apiVersion = 1;
 
-      autoAssignOrgRole = mkOption {
-        description = "Default role new users will be auto assigned.";
-        default = "Viewer";
-        type = types.enum ["Viewer" "Editor"];
-      };
-    };
+                groups = [{
+                  orgId = 1;
+                  name = "my_rule_group";
+                  folder = "my_first_folder";
+                  interval = "60s";
+                  rules = [{
+                    uid = "my_id_1";
+                    title = "my_first_rule";
+                    condition = "A";
+                    data = [{
+                      refId = "A";
+                      datasourceUid = "-100";
+                      model = {
+                        conditions = [{
+                          evaluator = {
+                            params = [ 3 ];
+                            type = "git";
+                          };
+                          operator.type = "and";
+                          query.params = [ "A" ];
+                          reducer.type = "last";
+                          type = "query";
+                        }];
+                        datasource = {
+                          type = "__expr__";
+                          uid = "-100";
+                        };
+                        expression = "1==0";
+                        intervalMs = 1000;
+                        maxDataPoints = 43200;
+                        refId = "A";
+                        type = "math";
+                      };
+                    }];
+                    dashboardUid = "my_dashboard";
+                    panelId = 123;
+                    noDataState = "Alerting";
+                    for = "60s";
+                    annotations.some_key = "some_value";
+                    labels.team = "sre_team1";
+                  }];
+                }];
 
-    auth = {
-      anonymous = {
-        enable = mkOption {
-          description = "Whether to allow anonymous access.";
-          default = false;
-          type = types.bool;
-        };
-        org_name = mkOption {
-          description = "Which organization to allow anonymous access to.";
-          default = "Main Org.";
-          type = types.str;
+                deleteRules = [{
+                  orgId = 1;
+                  uid = "my_id_1";
+                }];
+              }
+            '';
+          };
         };
-        org_role = mkOption {
-          description = "Which role anonymous users have in the organization.";
-          default = "Viewer";
-          type = types.str;
-        };
-      };
-      google = {
-        enable = mkOption {
-          description = "Whether to allow Google OAuth2.";
-          default = false;
-          type = types.bool;
-        };
-        allowSignUp = mkOption {
-          description = "Whether to allow sign up with Google OAuth2.";
-          default = false;
-          type = types.bool;
+
+        contactPoints = {
+          path = mkOption {
+            description = lib.mdDoc ''
+              Path to YAML contact points configuration. Can't be used with
+              [](#opt-services.grafana.provision.alerting.contactPoints.settings) simultaneously.
+              Can be either a directory or a single YAML file. Will end up in the store.
+            '';
+            default = null;
+            type = types.nullOr types.path;
+          };
+
+          settings = mkOption {
+            description = lib.mdDoc ''
+              Grafana contact points configuration in Nix. Can't be used with
+              [](#opt-services.grafana.provision.alerting.contactPoints.path) simultaneously. See
+              <https://grafana.com/docs/grafana/latest/administration/provisioning/#contact-points>
+              for supported options.
+            '';
+            default = null;
+            type = types.nullOr (types.submodule {
+              options = {
+                apiVersion = mkOption {
+                  description = lib.mdDoc "Config file version.";
+                  default = 1;
+                  type = types.int;
+                };
+
+                contactPoints = mkOption {
+                  description = lib.mdDoc "List of contact points to import or update.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    freeformType = provisioningSettingsFormat.type;
+
+                    options.name = mkOption {
+                      description = lib.mdDoc "Name of the contact point. Required.";
+                      type = types.str;
+                    };
+                  });
+                };
+
+                deleteContactPoints = mkOption {
+                  description = lib.mdDoc "List of receivers that should be deleted.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    options.orgId = mkOption {
+                      description = lib.mdDoc "Organization ID, default = 1.";
+                      default = 1;
+                      type = types.int;
+                    };
+
+                    options.uid = mkOption {
+                      description = lib.mdDoc "Unique identifier for the receiver. Required.";
+                      type = types.str;
+                    };
+                  });
+                };
+              };
+            });
+            example = literalExpression ''
+              {
+                apiVersion = 1;
+
+                contactPoints = [{
+                  orgId = 1;
+                  name = "cp_1";
+                  receivers = [{
+                    uid = "first_uid";
+                    type = "prometheus-alertmanager";
+                    settings.url = "http://test:9000";
+                  }];
+                }];
+
+                deleteContactPoints = [{
+                  orgId = 1;
+                  uid = "first_uid";
+                }];
+              }
+            '';
+          };
         };
-        clientId = mkOption {
-          description = "Google OAuth2 client ID.";
-          default = "";
-          type = types.str;
+
+        policies = {
+          path = mkOption {
+            description = lib.mdDoc ''
+              Path to YAML notification policies configuration. Can't be used with
+              [](#opt-services.grafana.provision.alerting.policies.settings) simultaneously.
+              Can be either a directory or a single YAML file. Will end up in the store.
+            '';
+            default = null;
+            type = types.nullOr types.path;
+          };
+
+          settings = mkOption {
+            description = lib.mdDoc ''
+              Grafana notification policies configuration in Nix. Can't be used with
+              [](#opt-services.grafana.provision.alerting.policies.path) simultaneously. See
+              <https://grafana.com/docs/grafana/latest/administration/provisioning/#notification-policies>
+              for supported options.
+            '';
+            default = null;
+            type = types.nullOr (types.submodule {
+              options = {
+                apiVersion = mkOption {
+                  description = lib.mdDoc "Config file version.";
+                  default = 1;
+                  type = types.int;
+                };
+
+                policies = mkOption {
+                  description = lib.mdDoc "List of contact points to import or update.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    freeformType = provisioningSettingsFormat.type;
+                  });
+                };
+
+                resetPolicies = mkOption {
+                  description = lib.mdDoc "List of orgIds that should be reset to the default policy.";
+                  default = [];
+                  type = types.listOf types.int;
+                };
+              };
+            });
+            example = literalExpression ''
+              {
+                apiVersion = 1;
+
+                policies = [{
+                  orgId = 1;
+                  receiver = "grafana-default-email";
+                  group_by = [ "..." ];
+                  matchers = [
+                    "alertname = Watchdog"
+                    "severity =~ \"warning|critical\""
+                  ];
+                  mute_time_intervals = [
+                    "abc"
+                  ];
+                  group_wait = "30s";
+                  group_interval = "5m";
+                  repeat_interval = "4h";
+                }];
+
+                resetPolicies = [
+                  1
+                ];
+              }
+            '';
+          };
         };
-        clientSecretFile = mkOption {
-          description = "Google OAuth2 client secret.";
-          default = null;
-          type = types.nullOr types.path;
+
+        templates = {
+          path = mkOption {
+            description = lib.mdDoc ''
+              Path to YAML templates configuration. Can't be used with
+              [](#opt-services.grafana.provision.alerting.templates.settings) simultaneously.
+              Can be either a directory or a single YAML file. Will end up in the store.
+            '';
+            default = null;
+            type = types.nullOr types.path;
+          };
+
+          settings = mkOption {
+            description = lib.mdDoc ''
+              Grafana templates configuration in Nix. Can't be used with
+              [](#opt-services.grafana.provision.alerting.templates.path) simultaneously. See
+              <https://grafana.com/docs/grafana/latest/administration/provisioning/#templates>
+              for supported options.
+            '';
+            default = null;
+            type = types.nullOr (types.submodule {
+              options = {
+                apiVersion = mkOption {
+                  description = lib.mdDoc "Config file version.";
+                  default = 1;
+                  type = types.int;
+                };
+
+                templates = mkOption {
+                  description = lib.mdDoc "List of templates to import or update.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    freeformType = provisioningSettingsFormat.type;
+
+                    options.name = mkOption {
+                      description = lib.mdDoc "Name of the template, must be unique. Required.";
+                      type = types.str;
+                    };
+
+                    options.template = mkOption {
+                      description = lib.mdDoc "Alerting with a custom text template";
+                      type = types.str;
+                    };
+                  });
+                };
+
+                deleteTemplates = mkOption {
+                  description = lib.mdDoc "List of alert rule UIDs that should be deleted.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    options.orgId = mkOption {
+                      description = lib.mdDoc "Organization ID, default = 1.";
+                      default = 1;
+                      type = types.int;
+                    };
+
+                    options.name = mkOption {
+                      description = lib.mdDoc "Name of the template, must be unique. Required.";
+                      type = types.str;
+                    };
+                  });
+                };
+              };
+            });
+            example = literalExpression ''
+              {
+                apiVersion = 1;
+
+                templates = [{
+                  orgId = 1;
+                  name = "my_first_template";
+                  template = "Alerting with a custom text template";
+                }];
+
+                deleteTemplates = [{
+                  orgId = 1;
+                  name = "my_first_template";
+                }];
+              }
+            '';
+          };
         };
-      };
-    };
 
-    analytics.reporting = {
-      enable = mkOption {
-        description = "Whether to allow anonymous usage reporting to stats.grafana.net.";
-        default = true;
-        type = types.bool;
-      };
-    };
+        muteTimings = {
+          path = mkOption {
+            description = lib.mdDoc ''
+              Path to YAML mute timings configuration. Can't be used with
+              [](#opt-services.grafana.provision.alerting.muteTimings.settings) simultaneously.
+              Can be either a directory or a single YAML file. Will end up in the store.
+            '';
+            default = null;
+            type = types.nullOr types.path;
+          };
 
-    extraOptions = mkOption {
-      description = ''
-        Extra configuration options passed as env variables as specified in
-        <link xlink:href="http://docs.grafana.org/installation/configuration/">documentation</link>,
-        but without GF_ prefix
-      '';
-      default = {};
-      type = with types; attrsOf (either str path);
+          settings = mkOption {
+            description = lib.mdDoc ''
+              Grafana mute timings configuration in Nix. Can't be used with
+              [](#opt-services.grafana.provision.alerting.muteTimings.path) simultaneously. See
+              <https://grafana.com/docs/grafana/latest/administration/provisioning/#mute-timings>
+              for supported options.
+            '';
+            default = null;
+            type = types.nullOr (types.submodule {
+              options = {
+                apiVersion = mkOption {
+                  description = lib.mdDoc "Config file version.";
+                  default = 1;
+                  type = types.int;
+                };
+
+                muteTimes = mkOption {
+                  description = lib.mdDoc "List of mute time intervals to import or update.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    freeformType = provisioningSettingsFormat.type;
+
+                    options.name = mkOption {
+                      description = lib.mdDoc "Name of the mute time interval, must be unique. Required.";
+                      type = types.str;
+                    };
+                  });
+                };
+
+                deleteMuteTimes = mkOption {
+                  description = lib.mdDoc "List of mute time intervals that should be deleted.";
+                  default = [];
+                  type = types.listOf (types.submodule {
+                    options.orgId = mkOption {
+                      description = lib.mdDoc "Organization ID, default = 1.";
+                      default = 1;
+                      type = types.int;
+                    };
+
+                    options.name = mkOption {
+                      description = lib.mdDoc "Name of the mute time interval, must be unique. Required.";
+                      type = types.str;
+                    };
+                  });
+                };
+              };
+            });
+            example = literalExpression ''
+              {
+                apiVersion = 1;
+
+                muteTimes = [{
+                  orgId = 1;
+                  name = "mti_1";
+                  time_intervals = [{
+                    times = [{
+                      start_time = "06:00";
+                      end_time = "23:59";
+                    }];
+                    weekdays = [
+                      "monday:wednesday"
+                      "saturday"
+                      "sunday"
+                    ];
+                    months = [
+                      "1:3"
+                      "may:august"
+                      "december"
+                    ];
+                    years = [
+                      "2020:2022"
+                      "2030"
+                    ];
+                    days_of_month = [
+                      "1:5"
+                      "-3:-1"
+                    ];
+                  }];
+                }];
+
+                deleteMuteTimes = [{
+                  orgId = 1;
+                  name = "mti_1";
+                }];
+              }
+            '';
+          };
+        };
+      };
     };
   };
 
   config = mkIf cfg.enable {
-    warnings = flatten [
-      (optional (
-        cfg.database.password != opt.database.password.default ||
-        cfg.security.adminPassword != opt.security.adminPassword.default
-      ) "Grafana passwords will be stored as plaintext in the Nix store!")
-      (optional (
-        any (x: x.password != null || x.basicAuthPassword != null || x.secureJsonData != null) cfg.provision.datasources
-      ) "Datasource passwords will be stored as plaintext in the Nix store!")
+    warnings = let
+      doesntUseFileProvider = opt: defaultValue:
+        let
+          regex = "${optionalString (defaultValue != null) "^${defaultValue}$|"}^\\$__(file|env)\\{.*}$|^\\$[^_\\$][^ ]+$";
+        in builtins.match regex opt == null;
+    in
+      # Ensure that no custom credentials are leaked into the Nix store. Unless the default value
+      # is specified, this can be achieved by using the file/env provider:
+      # https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#variable-expansion
       (optional (
+        doesntUseFileProvider cfg.settings.database.password "" ||
+        doesntUseFileProvider cfg.settings.security.admin_password "admin"
+      ) ''
+        Grafana passwords will be stored as plaintext in the Nix store!
+        Use file provider or an env-var instead.
+      '')
+      # Warn about deprecated notifiers.
+      ++ (optional (cfg.provision.notifiers != []) ''
+        Notifiers are deprecated upstream and will be removed in Grafana 10.
+        Use `services.grafana.provision.alerting.contactPoints` instead.
+      '')
+      # Ensure that `secureJsonData` of datasources provisioned via `datasources.settings`
+      # only uses file/env providers.
+      ++ (optional (
+        let
+          datasourcesToCheck = optionals
+            (cfg.provision.datasources.settings != null)
+            cfg.provision.datasources.settings.datasources;
+          declarationUnsafe = { secureJsonData, ... }:
+            secureJsonData != null
+            && any (flip doesntUseFileProvider null) (attrValues secureJsonData);
+        in any declarationUnsafe datasourcesToCheck
+      ) ''
+        Declarations in the `secureJsonData`-block of a datasource will be leaked to the
+        Nix store unless a file-provider or an env-var is used!
+      '')
+      ++ (optional (
         any (x: x.secure_settings != null) cfg.provision.notifiers
-      ) "Notifier secure settings will be stored as plaintext in the Nix store!")
-    ];
+      ) "Notifier secure settings will be stored as plaintext in the Nix store! Use file provider instead.");
 
     environment.systemPackages = [ cfg.package ];
 
     assertions = [
       {
-        assertion = cfg.database.password != opt.database.password.default -> cfg.database.passwordFile == null;
-        message = "Cannot set both password and passwordFile";
+        assertion = cfg.provision.datasources.settings == null || cfg.provision.datasources.path == null;
+        message = "Cannot set both datasources settings and datasources path";
+      }
+      {
+        assertion = let
+          prometheusIsNotDirect = opt: all
+          ({ type, access, ... }: type == "prometheus" -> access != "direct")
+          opt;
+        in
+          cfg.provision.datasources.settings == null || prometheusIsNotDirect cfg.provision.datasources.settings.datasources;
+        message = "For datasources of type `prometheus`, the `direct` access mode is not supported anymore (since Grafana 9.2.0)";
+      }
+      {
+        assertion = cfg.provision.dashboards.settings == null || cfg.provision.dashboards.path == null;
+        message = "Cannot set both dashboards settings and dashboards path";
+      }
+      {
+        assertion = cfg.provision.alerting.rules.settings == null || cfg.provision.alerting.rules.path == null;
+        message = "Cannot set both rules settings and rules path";
+      }
+      {
+        assertion = cfg.provision.alerting.contactPoints.settings == null || cfg.provision.alerting.contactPoints.path == null;
+        message = "Cannot set both contact points settings and contact points path";
       }
       {
-        assertion = cfg.security.adminPassword != opt.security.adminPassword.default -> cfg.security.adminPasswordFile == null;
-        message = "Cannot set both adminPassword and adminPasswordFile";
+        assertion = cfg.provision.alerting.policies.settings == null || cfg.provision.alerting.policies.path == null;
+        message = "Cannot set both policies settings and policies path";
       }
       {
-        assertion = cfg.security.secretKey != opt.security.secretKey.default -> cfg.security.secretKeyFile == null;
-        message = "Cannot set both secretKey and secretKeyFile";
+        assertion = cfg.provision.alerting.templates.settings == null || cfg.provision.alerting.templates.path == null;
+        message = "Cannot set both templates settings and templates path";
       }
       {
-        assertion = cfg.smtp.password != opt.smtp.password.default -> cfg.smtp.passwordFile == null;
-        message = "Cannot set both password and passwordFile";
+        assertion = cfg.provision.alerting.muteTimings.settings == null || cfg.provision.alerting.muteTimings.path == null;
+        message = "Cannot set both mute timings settings and mute timings path";
       }
     ];
 
@@ -640,37 +1255,11 @@ in {
       description = "Grafana Service Daemon";
       wantedBy = ["multi-user.target"];
       after = ["networking.target"] ++ lib.optional usePostgresql "postgresql.service" ++ lib.optional useMysql "mysql.service";
-      environment = {
-        QT_QPA_PLATFORM = "offscreen";
-      } // mapAttrs' (n: v: nameValuePair "GF_${n}" (toString v)) envOptions;
       script = ''
         set -o errexit -o pipefail -o nounset -o errtrace
         shopt -s inherit_errexit
 
-        ${optionalString (cfg.auth.google.clientSecretFile != null) ''
-          GF_AUTH_GOOGLE_CLIENT_SECRET="$(<${escapeShellArg cfg.auth.google.clientSecretFile})"
-          export GF_AUTH_GOOGLE_CLIENT_SECRET
-        ''}
-        ${optionalString (cfg.database.passwordFile != null) ''
-          GF_DATABASE_PASSWORD="$(<${escapeShellArg cfg.database.passwordFile})"
-          export GF_DATABASE_PASSWORD
-        ''}
-        ${optionalString (cfg.security.adminPasswordFile != null) ''
-          GF_SECURITY_ADMIN_PASSWORD="$(<${escapeShellArg cfg.security.adminPasswordFile})"
-          export GF_SECURITY_ADMIN_PASSWORD
-        ''}
-        ${optionalString (cfg.security.secretKeyFile != null) ''
-          GF_SECURITY_SECRET_KEY="$(<${escapeShellArg cfg.security.secretKeyFile})"
-          export GF_SECURITY_SECRET_KEY
-        ''}
-        ${optionalString (cfg.smtp.passwordFile != null) ''
-          GF_SMTP_PASSWORD="$(<${escapeShellArg cfg.smtp.passwordFile})"
-          export GF_SMTP_PASSWORD
-        ''}
-        ${optionalString cfg.provision.enable ''
-          export GF_PATHS_PROVISIONING=${provisionConfDir};
-        ''}
-        exec ${cfg.package}/bin/grafana-server -homepath ${cfg.dataDir}
+        exec ${cfg.package}/bin/grafana-server -homepath ${cfg.dataDir} -config ${configFile}
       '';
       serviceConfig = {
         WorkingDirectory = cfg.dataDir;
@@ -678,8 +1267,8 @@ in {
         RuntimeDirectory = "grafana";
         RuntimeDirectoryMode = "0755";
         # Hardening
-        AmbientCapabilities = lib.mkIf (cfg.port < 1024) [ "CAP_NET_BIND_SERVICE" ];
-        CapabilityBoundingSet = if (cfg.port < 1024) then [ "CAP_NET_BIND_SERVICE" ] else [ "" ];
+        AmbientCapabilities = lib.mkIf (cfg.settings.server.http_port < 1024) [ "CAP_NET_BIND_SERVICE" ];
+        CapabilityBoundingSet = if (cfg.settings.server.http_port < 1024) then [ "CAP_NET_BIND_SERVICE" ] else [ "" ];
         DeviceAllow = [ "" ];
         LockPersonality = true;
         NoNewPrivileges = true;
@@ -702,7 +1291,7 @@ in {
         SystemCallArchitectures = "native";
         # Upstream grafana is not setting SystemCallFilter for compatibility
         # reasons, see https://github.com/grafana/grafana/pull/40176
-        SystemCallFilter = [ "@system-service" "~@privileged" "~@resources" ];
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
         UMask = "0027";
       };
       preStart = ''
diff --git a/nixos/modules/services/monitoring/graphite.nix b/nixos/modules/services/monitoring/graphite.nix
index baa943302a0..017e8a1ba47 100644
--- a/nixos/modules/services/monitoring/graphite.nix
+++ b/nixos/modules/services/monitoring/graphite.nix
@@ -24,16 +24,6 @@ let
     + cfg.web.extraConfig
   );
 
-  graphiteApiConfig = pkgs.writeText "graphite-api.yaml" ''
-    search_index: ${dataDir}/index
-    ${optionalString (config.time.timeZone != null) "time_zone: ${config.time.timeZone}"}
-    ${optionalString (cfg.api.finders != []) "finders:"}
-    ${concatMapStringsSep "\n" (f: "  - " + f.moduleName) cfg.api.finders}
-    ${optionalString (cfg.api.functions != []) "functions:"}
-    ${concatMapStringsSep "\n" (f: "  - " + f) cfg.api.functions}
-    ${cfg.api.extraConfig}
-  '';
-
   seyrenConfig = {
     SEYREN_URL = cfg.seyren.seyrenUrl;
     MONGO_URL = cfg.seyren.mongoUrl;
@@ -72,6 +62,8 @@ let
 in {
 
   imports = [
+    (mkRemovedOptionModule ["services" "graphite" "api"] "")
+    (mkRemovedOptionModule ["services" "graphite" "beacon"] "")
     (mkRemovedOptionModule ["services" "graphite" "pager"] "")
   ];
 
@@ -81,125 +73,43 @@ in {
     dataDir = mkOption {
       type = types.path;
       default = "/var/db/graphite";
-      description = ''
+      description = lib.mdDoc ''
         Data directory for graphite.
       '';
     };
 
     web = {
       enable = mkOption {
-        description = "Whether to enable graphite web frontend.";
+        description = lib.mdDoc "Whether to enable graphite web frontend.";
         default = false;
         type = types.bool;
       };
 
       listenAddress = mkOption {
-        description = "Graphite web frontend listen address.";
+        description = lib.mdDoc "Graphite web frontend listen address.";
         default = "127.0.0.1";
         type = types.str;
       };
 
       port = mkOption {
-        description = "Graphite web frontend port.";
+        description = lib.mdDoc "Graphite web frontend port.";
         default = 8080;
-        type = types.int;
+        type = types.port;
       };
 
       extraConfig = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Graphite webapp settings. See:
-          <link xlink:href="http://graphite.readthedocs.io/en/latest/config-local-settings.html"/>
+          <http://graphite.readthedocs.io/en/latest/config-local-settings.html>
         '';
       };
     };
 
-    api = {
-      enable = mkOption {
-        description = ''
-          Whether to enable graphite api. Graphite api is lightweight alternative
-          to graphite web, with api and without dashboard. It's advised to use
-          grafana as alternative dashboard and influxdb as alternative to
-          graphite carbon.
-
-          For more information visit
-          <link xlink:href="https://graphite-api.readthedocs.org/en/latest/"/>
-        '';
-        default = false;
-        type = types.bool;
-      };
-
-      finders = mkOption {
-        description = "List of finder plugins to load.";
-        default = [];
-        example = literalExpression "[ pkgs.python3Packages.influxgraph ]";
-        type = types.listOf types.package;
-      };
-
-      functions = mkOption {
-        description = "List of functions to load.";
-        default = [
-          "graphite_api.functions.SeriesFunctions"
-          "graphite_api.functions.PieFunctions"
-        ];
-        type = types.listOf types.str;
-      };
-
-      listenAddress = mkOption {
-        description = "Graphite web service listen address.";
-        default = "127.0.0.1";
-        type = types.str;
-      };
-
-      port = mkOption {
-        description = "Graphite api service port.";
-        default = 8080;
-        type = types.int;
-      };
-
-      package = mkOption {
-        description = "Package to use for graphite api.";
-        default = pkgs.python3Packages.graphite_api;
-        defaultText = literalExpression "pkgs.python3Packages.graphite_api";
-        type = types.package;
-      };
-
-      extraConfig = mkOption {
-        description = "Extra configuration for graphite api.";
-        default = ''
-          whisper:
-            directories:
-                - ${dataDir}/whisper
-        '';
-        defaultText = literalExpression ''
-          '''
-            whisper:
-              directories:
-                - ''${config.${opt.dataDir}}/whisper
-          '''
-        '';
-        example = ''
-          allowed_origins:
-            - dashboard.example.com
-          cheat_times: true
-          influxdb:
-            host: localhost
-            port: 8086
-            user: influxdb
-            pass: influxdb
-            db: metrics
-          cache:
-            CACHE_TYPE: 'filesystem'
-            CACHE_DIR: '/tmp/graphite-api-cache'
-        '';
-        type = types.lines;
-      };
-    };
-
     carbon = {
       config = mkOption {
-        description = "Content of carbon configuration file.";
+        description = lib.mdDoc "Content of carbon configuration file.";
         default = ''
           [cache]
           # Listen on localhost by default for security reasons
@@ -215,13 +125,13 @@ in {
       };
 
       enableCache = mkOption {
-        description = "Whether to enable carbon cache, the graphite storage daemon.";
+        description = lib.mdDoc "Whether to enable carbon cache, the graphite storage daemon.";
         default = false;
         type = types.bool;
       };
 
       storageAggregation = mkOption {
-        description = "Defines how to aggregate data to lower-precision retentions.";
+        description = lib.mdDoc "Defines how to aggregate data to lower-precision retentions.";
         default = null;
         type = types.nullOr types.str;
         example = ''
@@ -233,7 +143,7 @@ in {
       };
 
       storageSchemas = mkOption {
-        description = "Defines retention rates for storing metrics.";
+        description = lib.mdDoc "Defines retention rates for storing metrics.";
         default = "";
         type = types.nullOr types.str;
         example = ''
@@ -244,21 +154,21 @@ in {
       };
 
       blacklist = mkOption {
-        description = "Any metrics received which match one of the experssions will be dropped.";
+        description = lib.mdDoc "Any metrics received which match one of the experssions will be dropped.";
         default = null;
         type = types.nullOr types.str;
         example = "^some\\.noisy\\.metric\\.prefix\\..*";
       };
 
       whitelist = mkOption {
-        description = "Only metrics received which match one of the experssions will be persisted.";
+        description = lib.mdDoc "Only metrics received which match one of the experssions will be persisted.";
         default = null;
         type = types.nullOr types.str;
         example = ".*";
       };
 
       rewriteRules = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Regular expression patterns that can be used to rewrite metric names
           in a search and replace fashion.
         '';
@@ -272,13 +182,13 @@ in {
       };
 
       enableRelay = mkOption {
-        description = "Whether to enable carbon relay, the carbon replication and sharding service.";
+        description = lib.mdDoc "Whether to enable carbon relay, the carbon replication and sharding service.";
         default = false;
         type = types.bool;
       };
 
       relayRules = mkOption {
-        description = "Relay rules are used to send certain metrics to a certain backend.";
+        description = lib.mdDoc "Relay rules are used to send certain metrics to a certain backend.";
         default = null;
         type = types.nullOr types.str;
         example = ''
@@ -289,13 +199,13 @@ in {
       };
 
       enableAggregator = mkOption {
-        description = "Whether to enable carbon aggregator, the carbon buffering service.";
+        description = lib.mdDoc "Whether to enable carbon aggregator, the carbon buffering service.";
         default = false;
         type = types.bool;
       };
 
       aggregationRules = mkOption {
-        description = "Defines if and how received metrics will be aggregated.";
+        description = lib.mdDoc "Defines if and how received metrics will be aggregated.";
         default = null;
         type = types.nullOr types.str;
         example = ''
@@ -307,13 +217,13 @@ in {
 
     seyren = {
       enable = mkOption {
-        description = "Whether to enable seyren service.";
+        description = lib.mdDoc "Whether to enable seyren service.";
         default = false;
         type = types.bool;
       };
 
       port = mkOption {
-        description = "Seyren listening port.";
+        description = lib.mdDoc "Seyren listening port.";
         default = 8081;
         type = types.int;
       };
@@ -321,29 +231,29 @@ in {
       seyrenUrl = mkOption {
         default = "http://localhost:${toString cfg.seyren.port}/";
         defaultText = literalExpression ''"http://localhost:''${toString config.${opt.seyren.port}}/"'';
-        description = "Host where seyren is accessible.";
+        description = lib.mdDoc "Host where seyren is accessible.";
         type = types.str;
       };
 
       graphiteUrl = mkOption {
         default = "http://${cfg.web.listenAddress}:${toString cfg.web.port}";
         defaultText = literalExpression ''"http://''${config.${opt.web.listenAddress}}:''${toString config.${opt.web.port}}"'';
-        description = "Host where graphite service runs.";
+        description = lib.mdDoc "Host where graphite service runs.";
         type = types.str;
       };
 
       mongoUrl = mkOption {
         default = "mongodb://${config.services.mongodb.bind_ip}:27017/seyren";
         defaultText = literalExpression ''"mongodb://''${config.services.mongodb.bind_ip}:27017/seyren"'';
-        description = "Mongodb connection string.";
+        description = lib.mdDoc "Mongodb connection string.";
         type = types.str;
       };
 
       extraConfig = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Extra seyren configuration. See
-          <link xlink:href='https://github.com/scobal/seyren#config' />
+          <https://github.com/scobal/seyren#config>
         '';
         type = types.attrsOf types.str;
         example = literalExpression ''
@@ -354,16 +264,6 @@ in {
         '';
       };
     };
-
-    beacon = {
-      enable = mkEnableOption "graphite beacon";
-
-      config = mkOption {
-        description = "Graphite beacon configuration.";
-        default = {};
-        type = types.attrs;
-      };
-    };
   };
 
   ###### implementation
@@ -489,44 +389,6 @@ in {
       environment.systemPackages = [ pkgs.python3Packages.graphite-web ];
     }))
 
-    (mkIf cfg.api.enable {
-      systemd.services.graphiteApi = {
-        description = "Graphite Api Interface";
-        wantedBy = [ "multi-user.target" ];
-        after = [ "network.target" ];
-        environment = {
-          PYTHONPATH = let
-              aenv = pkgs.python3.buildEnv.override {
-                extraLibs = [ cfg.api.package pkgs.cairo pkgs.python3Packages.cffi ] ++ cfg.api.finders;
-              };
-            in "${aenv}/${pkgs.python3.sitePackages}";
-          GRAPHITE_API_CONFIG = graphiteApiConfig;
-          LD_LIBRARY_PATH = "${pkgs.cairo.out}/lib";
-        };
-        serviceConfig = {
-          ExecStart = ''
-            ${pkgs.python3Packages.waitress}/bin/waitress-serve \
-            --host=${cfg.api.listenAddress} --port=${toString cfg.api.port} \
-            graphite_api.app:app
-          '';
-          User = "graphite";
-          Group = "graphite";
-          PermissionsStartOnly = true;
-        };
-        preStart = ''
-          if ! test -e ${dataDir}/db-created; then
-            mkdir -p ${dataDir}/cache/
-            chmod 0700 ${dataDir}/cache/
-
-            chown graphite:graphite ${cfg.dataDir}
-            chown -R graphite:graphite ${cfg.dataDir}/cache
-
-            touch ${dataDir}/db-created
-          fi
-        '';
-      };
-    })
-
     (mkIf cfg.seyren.enable {
       systemd.services.seyren = {
         description = "Graphite Alerting Dashboard";
@@ -550,25 +412,9 @@ in {
       services.mongodb.enable = mkDefault true;
     })
 
-    (mkIf cfg.beacon.enable {
-      systemd.services.graphite-beacon = {
-        description = "Grpahite Beacon Alerting Daemon";
-        wantedBy = [ "multi-user.target" ];
-        serviceConfig = {
-          ExecStart = ''
-            ${pkgs.python3Packages.graphite_beacon}/bin/graphite-beacon \
-              --config=${pkgs.writeText "graphite-beacon.json" (builtins.toJSON cfg.beacon.config)}
-          '';
-          User = "graphite";
-          Group = "graphite";
-        };
-      };
-    })
-
     (mkIf (
       cfg.carbon.enableCache || cfg.carbon.enableAggregator || cfg.carbon.enableRelay ||
-      cfg.web.enable || cfg.api.enable ||
-      cfg.seyren.enable || cfg.beacon.enable
+      cfg.web.enable || cfg.seyren.enable
      ) {
       users.users.graphite = {
         uid = config.ids.uids.graphite;
diff --git a/nixos/modules/services/monitoring/hdaps.nix b/nixos/modules/services/monitoring/hdaps.nix
index 2cad3b84d84..59b8b9b3c05 100644
--- a/nixos/modules/services/monitoring/hdaps.nix
+++ b/nixos/modules/services/monitoring/hdaps.nix
@@ -9,10 +9,10 @@ in
 {
   options = {
     services.hdapsd.enable = mkEnableOption
-      ''
+      (lib.mdDoc ''
         Hard Drive Active Protection System Daemon,
         devices are detected and managed automatically by udev and systemd
-      '';
+      '');
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/monitoring/heapster.nix b/nixos/modules/services/monitoring/heapster.nix
index 44f53e1890a..fc63276b62f 100644
--- a/nixos/modules/services/monitoring/heapster.nix
+++ b/nixos/modules/services/monitoring/heapster.nix
@@ -6,32 +6,28 @@ let
   cfg = config.services.heapster;
 in {
   options.services.heapster = {
-    enable = mkOption {
-      description = "Whether to enable heapster monitoring";
-      default = false;
-      type = types.bool;
-    };
+    enable = mkEnableOption (lib.mdDoc "Heapster monitoring");
 
     source = mkOption {
-      description = "Heapster metric source";
+      description = lib.mdDoc "Heapster metric source";
       example = "kubernetes:https://kubernetes.default";
       type = types.str;
     };
 
     sink = mkOption {
-      description = "Heapster metic sink";
+      description = lib.mdDoc "Heapster metic sink";
       example = "influxdb:http://localhost:8086";
       type = types.str;
     };
 
     extraOpts = mkOption {
-      description = "Heapster extra options";
+      description = lib.mdDoc "Heapster extra options";
       default = "";
       type = types.separatedString " ";
     };
 
     package = mkOption {
-      description = "Package to use by heapster";
+      description = lib.mdDoc "Package to use by heapster";
       default = pkgs.heapster;
       defaultText = literalExpression "pkgs.heapster";
       type = types.package;
diff --git a/nixos/modules/services/monitoring/incron.nix b/nixos/modules/services/monitoring/incron.nix
index 2681c35d6a0..3766f1fa238 100644
--- a/nixos/modules/services/monitoring/incron.nix
+++ b/nixos/modules/services/monitoring/incron.nix
@@ -17,22 +17,22 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the incron daemon.
 
-          Note that commands run under incrontab only support common Nix profiles for the <envar>PATH</envar> provided variable.
+          Note that commands run under incrontab only support common Nix profiles for the {env}`PATH` provided variable.
         '';
       };
 
       allow = mkOption {
         type = types.nullOr (types.listOf types.str);
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Users allowed to use incrontab.
 
           If empty then no user will be allowed to have their own incrontab.
-          If <literal>null</literal> then will defer to <option>deny</option>.
-          If both <option>allow</option> and <option>deny</option> are null
+          If `null` then will defer to {option}`deny`.
+          If both {option}`allow` and {option}`deny` are null
           then all users will be allowed to have their own incrontab.
         '';
       };
@@ -40,13 +40,13 @@ in
       deny = mkOption {
         type = types.nullOr (types.listOf types.str);
         default = null;
-        description = "Users forbidden from using incrontab.";
+        description = lib.mdDoc "Users forbidden from using incrontab.";
       };
 
       systab = mkOption {
         type = types.lines;
         default = "";
-        description = "The system incrontab contents.";
+        description = lib.mdDoc "The system incrontab contents.";
         example = ''
           /var/mail IN_CLOSE_WRITE abc $@/$#
           /tmp IN_ALL_EVENTS efg $@/$# $&
@@ -57,7 +57,7 @@ in
         type = types.listOf types.package;
         default = [];
         example = literalExpression "[ pkgs.rsync ]";
-        description = "Extra packages available to the system incrontab.";
+        description = lib.mdDoc "Extra packages available to the system incrontab.";
       };
 
     };
diff --git a/nixos/modules/services/monitoring/kapacitor.nix b/nixos/modules/services/monitoring/kapacitor.nix
index a79c647becf..61529c2e452 100644
--- a/nixos/modules/services/monitoring/kapacitor.nix
+++ b/nixos/modules/services/monitoring/kapacitor.nix
@@ -57,29 +57,29 @@ let
 in
 {
   options.services.kapacitor = {
-    enable = mkEnableOption "kapacitor";
+    enable = mkEnableOption (lib.mdDoc "kapacitor");
 
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/kapacitor";
-      description = "Location where Kapacitor stores its state";
+      description = lib.mdDoc "Location where Kapacitor stores its state";
     };
 
     port = mkOption {
       type = types.int;
       default = 9092;
-      description = "Port of Kapacitor";
+      description = lib.mdDoc "Port of Kapacitor";
     };
 
     bind = mkOption {
       type = types.str;
       default = "";
       example = "0.0.0.0";
-      description = "Address to bind to. The default is to bind to all addresses";
+      description = lib.mdDoc "Address to bind to. The default is to bind to all addresses";
     };
 
     extraConfig = mkOption {
-      description = "These lines go into kapacitord.conf verbatim.";
+      description = lib.mdDoc "These lines go into kapacitord.conf verbatim.";
       default = "";
       type = types.lines;
     };
@@ -87,70 +87,70 @@ in
     user = mkOption {
       type = types.str;
       default = "kapacitor";
-      description = "User account under which Kapacitor runs";
+      description = lib.mdDoc "User account under which Kapacitor runs";
     };
 
     group = mkOption {
       type = types.str;
       default = "kapacitor";
-      description = "Group under which Kapacitor runs";
+      description = lib.mdDoc "Group under which Kapacitor runs";
     };
 
     taskSnapshotInterval = mkOption {
       type = types.str;
-      description = "Specifies how often to snapshot the task state  (in InfluxDB time units)";
+      description = lib.mdDoc "Specifies how often to snapshot the task state  (in InfluxDB time units)";
       default = "1m0s";
     };
 
     loadDirectory = mkOption {
       type = types.nullOr types.path;
-      description = "Directory where to load services from, such as tasks, templates and handlers (or null to disable service loading on startup)";
+      description = lib.mdDoc "Directory where to load services from, such as tasks, templates and handlers (or null to disable service loading on startup)";
       default = null;
     };
 
     defaultDatabase = {
-      enable = mkEnableOption "kapacitor.defaultDatabase";
+      enable = mkEnableOption (lib.mdDoc "kapacitor.defaultDatabase");
 
       url = mkOption {
-        description = "The URL to an InfluxDB server that serves as the default database";
+        description = lib.mdDoc "The URL to an InfluxDB server that serves as the default database";
         example = "http://localhost:8086";
         type = types.str;
       };
 
       username = mkOption {
-        description = "The username to connect to the remote InfluxDB server";
+        description = lib.mdDoc "The username to connect to the remote InfluxDB server";
         type = types.str;
       };
 
       password = mkOption {
-        description = "The password to connect to the remote InfluxDB server";
+        description = lib.mdDoc "The password to connect to the remote InfluxDB server";
         type = types.str;
       };
     };
 
     alerta = {
-      enable = mkEnableOption "kapacitor alerta integration";
+      enable = mkEnableOption (lib.mdDoc "kapacitor alerta integration");
 
       url = mkOption {
-        description = "The URL to the Alerta REST API";
+        description = lib.mdDoc "The URL to the Alerta REST API";
         default = "http://localhost:5000";
         type = types.str;
       };
 
       token = mkOption {
-        description = "Default Alerta authentication token";
+        description = lib.mdDoc "Default Alerta authentication token";
         type = types.str;
         default = "";
       };
 
       environment = mkOption {
-        description = "Default Alerta environment";
+        description = lib.mdDoc "Default Alerta environment";
         type = types.str;
         default = "Production";
       };
 
       origin = mkOption {
-        description = "Default origin of alert";
+        description = lib.mdDoc "Default origin of alert";
         type = types.str;
         default = "kapacitor";
       };
diff --git a/nixos/modules/services/monitoring/karma.nix b/nixos/modules/services/monitoring/karma.nix
new file mode 100644
index 00000000000..85dbc81f443
--- /dev/null
+++ b/nixos/modules/services/monitoring/karma.nix
@@ -0,0 +1,128 @@
+{ config, pkgs, lib, ... }:
+with lib;
+let
+  cfg = config.services.karma;
+  yaml = pkgs.formats.yaml { };
+in
+{
+  options.services.karma = {
+    enable = mkEnableOption (mdDoc "the Karma dashboard service");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.karma;
+      defaultText = literalExpression "pkgs.karma";
+      description = mdDoc ''
+        The Karma package that should be used.
+      '';
+    };
+
+    configFile = mkOption {
+      type = types.path;
+      default = yaml.generate "karma.yaml" cfg.settings;
+      defaultText = "A configuration file generated from the provided nix attributes settings option.";
+      description = mdDoc ''
+        A YAML config file which can be used to configure karma instead of the nix-generated file.
+      '';
+      example = "/etc/karma/karma.conf";
+    };
+
+    environment = mkOption {
+      type = with types; attrsOf str;
+      default = {};
+      description = mdDoc ''
+        Additional environment variables to provide to karma.
+      '';
+      example = {
+        ALERTMANAGER_URI = "https://alertmanager.example.com";
+        ALERTMANAGER_NAME= "single";
+      };
+    };
+
+    openFirewall = mkOption {
+      type = types.bool;
+      default = false;
+      description = mdDoc ''
+        Whether to open ports in the firewall needed for karma to function.
+      '';
+    };
+
+    extraOptions = mkOption {
+      type = with types; listOf str;
+      default = [];
+      description = mdDoc ''
+        Extra command line options.
+      '';
+      example = [
+        "--alertmanager.timeout 10s"
+      ];
+    };
+
+    settings = mkOption {
+      type = types.submodule {
+        freeformType = yaml.type;
+
+        options.listen = {
+          address = mkOption {
+            type = types.str;
+            default = "127.0.0.1";
+            description = mdDoc ''
+              Hostname or IP to listen on.
+            '';
+            example = "[::]";
+          };
+
+          port = mkOption {
+            type = types.port;
+            default = 8080;
+            description = mdDoc ''
+              HTTP port to listen on.
+            '';
+            example = 8182;
+          };
+        };
+      };
+      default = {
+        listen = {
+          address = "127.0.0.1";
+        };
+      };
+      description = mdDoc ''
+        Karma dashboard configuration as nix attributes.
+
+        Reference: <https://github.com/prymitive/karma/blob/main/docs/CONFIGURATION.md>
+      '';
+      example = {
+        listen = {
+          address = "192.168.1.4";
+          port = "8000";
+          prefix = "/dashboard";
+        };
+        alertmanager = {
+          interval = "15s";
+          servers = [
+            {
+              name = "prod";
+              uri = "http://alertmanager.example.com";
+            }
+          ];
+        };
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.karma = {
+      description = "Alert dashboard for Prometheus Alertmanager";
+      wantedBy = [ "multi-user.target" ];
+      environment = cfg.environment;
+      serviceConfig = {
+        Type = "simple";
+        DynamicUser = true;
+        Restart = "on-failure";
+        ExecStart = "${pkgs.karma}/bin/karma --config.file ${cfg.configFile} ${concatStringsSep " " cfg.extraOptions}";
+      };
+    };
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.settings.listen.port ];
+  };
+}
diff --git a/nixos/modules/services/monitoring/kthxbye.nix b/nixos/modules/services/monitoring/kthxbye.nix
new file mode 100644
index 00000000000..3f988dcb722
--- /dev/null
+++ b/nixos/modules/services/monitoring/kthxbye.nix
@@ -0,0 +1,166 @@
+{ config, pkgs, lib, ... }:
+with lib;
+
+let
+  cfg = config.services.kthxbye;
+in
+
+{
+  options.services.kthxbye = {
+    enable = mkEnableOption (mdDoc "kthxbye alert acknowledgement management daemon");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.kthxbye;
+      defaultText = literalExpression "pkgs.kthxbye";
+      description = mdDoc ''
+        The kthxbye package that should be used.
+      '';
+    };
+
+    openFirewall = mkOption {
+      type = types.bool;
+      default = false;
+      description = mdDoc ''
+        Whether to open ports in the firewall needed for the daemon to function.
+      '';
+    };
+
+    extraOptions = mkOption {
+      type = with types; listOf str;
+      default = [];
+      description = mdDoc ''
+        Extra command line options.
+
+        Documentation can be found [here](https://github.com/prymitive/kthxbye/blob/main/README.md).
+      '';
+      example = literalExpression ''
+        [
+          "-extend-with-prefix 'ACK!'"
+        ];
+      '';
+    };
+
+    alertmanager = {
+      timeout = mkOption {
+        type = types.str;
+        default = "1m0s";
+        description = mdDoc ''
+          Alertmanager request timeout duration in the [time.Duration](https://pkg.go.dev/time#ParseDuration) format.
+        '';
+        example = "30s";
+      };
+      uri = mkOption {
+        type = types.str;
+        default = "http://localhost:9093";
+        description = mdDoc ''
+          Alertmanager URI to use.
+        '';
+        example = "https://alertmanager.example.com";
+      };
+    };
+
+    extendBy = mkOption {
+      type = types.str;
+      default = "15m0s";
+      description = mdDoc ''
+        Extend silences by adding DURATION seconds.
+
+        DURATION should be provided in the [time.Duration](https://pkg.go.dev/time#ParseDuration) format.
+      '';
+      example = "6h0m0s";
+    };
+
+    extendIfExpiringIn = mkOption {
+      type = types.str;
+      default = "5m0s";
+      description = mdDoc ''
+        Extend silences that are about to expire in the next DURATION seconds.
+
+        DURATION should be provided in the [time.Duration](https://pkg.go.dev/time#ParseDuration) format.
+      '';
+      example = "1m0s";
+    };
+
+    extendWithPrefix = mkOption {
+      type = types.str;
+      default = "ACK!";
+      description = mdDoc ''
+        Extend silences with comment starting with PREFIX string.
+      '';
+      example = "!perma-silence";
+    };
+
+    interval = mkOption {
+      type = types.str;
+      default = "45s";
+      description = mdDoc ''
+        Silence check interval duration in the [time.Duration](https://pkg.go.dev/time#ParseDuration) format.
+      '';
+      example = "30s";
+    };
+
+    listenAddress = mkOption {
+      type = types.str;
+      default = "0.0.0.0";
+      description = mdDoc ''
+        The address to listen on for HTTP requests.
+      '';
+      example = "127.0.0.1";
+    };
+
+    port = mkOption {
+      type = types.port;
+      default = 8080;
+      description = mdDoc ''
+        The port to listen on for HTTP requests.
+      '';
+    };
+
+    logJSON = mkOption {
+      type = types.bool;
+      default = false;
+      description = mdDoc ''
+        Format logged messages as JSON.
+      '';
+    };
+
+    maxDuration = mkOption {
+      type = with types; nullOr str;
+      default = null;
+      description = mdDoc ''
+        Maximum duration of a silence, it won't be extended anymore after reaching it.
+
+        Duration should be provided in the [time.Duration](https://pkg.go.dev/time#ParseDuration) format.
+      '';
+      example = "30d";
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.kthxbye = {
+      description = "kthxbye Alertmanager ack management daemon";
+      wantedBy = [ "multi-user.target" ];
+      script = ''
+        ${cfg.package}/bin/kthxbye \
+          -alertmanager.timeout ${cfg.alertmanager.timeout} \
+          -alertmanager.uri ${cfg.alertmanager.uri} \
+          -extend-by ${cfg.extendBy} \
+          -extend-if-expiring-in ${cfg.extendIfExpiringIn} \
+          -extend-with-prefix ${cfg.extendWithPrefix} \
+          -interval ${cfg.interval} \
+          -listen ${cfg.listenAddress}:${toString cfg.port} \
+          ${optionalString cfg.logJSON "-log-json"} \
+          ${optionalString (cfg.maxDuration != null) "-max-duration ${cfg.maxDuration}"} \
+          ${concatStringsSep " " cfg.extraOptions}
+      '';
+      serviceConfig = {
+        Type = "simple";
+        DynamicUser = true;
+        Restart = "on-failure";
+      };
+    };
+
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ];
+  };
+}
diff --git a/nixos/modules/services/monitoring/loki.nix b/nixos/modules/services/monitoring/loki.nix
index ebac70c30c2..11bb8497c9b 100644
--- a/nixos/modules/services/monitoring/loki.nix
+++ b/nixos/modules/services/monitoring/loki.nix
@@ -12,12 +12,12 @@ let
 
 in {
   options.services.loki = {
-    enable = mkEnableOption "loki";
+    enable = mkEnableOption (lib.mdDoc "loki");
 
     user = mkOption {
       type = types.str;
       default = "loki";
-      description = ''
+      description = lib.mdDoc ''
         User under which the Loki service runs.
       '';
     };
@@ -25,7 +25,7 @@ in {
     group = mkOption {
       type = types.str;
       default = "loki";
-      description = ''
+      description = lib.mdDoc ''
         Group under which the Loki service runs.
       '';
     };
@@ -33,7 +33,7 @@ in {
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/loki";
-      description = ''
+      description = lib.mdDoc ''
         Specify the directory for Loki.
       '';
     };
@@ -41,7 +41,7 @@ in {
     configuration = mkOption {
       type = (pkgs.formats.json {}).type;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         Specify the configuration for Loki in Nix.
       '';
     };
@@ -49,7 +49,7 @@ in {
     configFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Specify a configuration file that Loki should use.
       '';
     };
@@ -58,7 +58,7 @@ in {
       type = types.listOf types.str;
       default = [];
       example = [ "--server.http-listen-port=3101" ];
-      description = ''
+      description = lib.mdDoc ''
         Specify a list of additional command line flags,
         which get escaped and are then passed to Loki.
       '';
diff --git a/nixos/modules/services/monitoring/longview.nix b/nixos/modules/services/monitoring/longview.nix
index 9c38956f9ba..5825cab0134 100644
--- a/nixos/modules/services/monitoring/longview.nix
+++ b/nixos/modules/services/monitoring/longview.nix
@@ -16,7 +16,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, system metrics will be sent to Linode LongView.
         '';
       };
@@ -25,12 +25,12 @@ in {
         type = types.str;
         default = "";
         example = "01234567-89AB-CDEF-0123456789ABCDEF";
-        description = ''
+        description = lib.mdDoc ''
           Longview API key. To get this, look in Longview settings which
           are found at https://manager.linode.com/longview/.
 
           Warning: this secret is stored in the world-readable Nix store!
-          Use <option>apiKeyFile</option> instead.
+          Use {option}`apiKeyFile` instead.
         '';
       };
 
@@ -38,12 +38,12 @@ in {
         type = types.nullOr types.path;
         default = null;
         example = "/run/keys/longview-api-key";
-        description = ''
+        description = lib.mdDoc ''
           A file containing the Longview API key.
           To get this, look in Longview settings which
           are found at https://manager.linode.com/longview/.
 
-          <option>apiKeyFile</option> takes precedence over <option>apiKey</option>.
+          {option}`apiKeyFile` takes precedence over {option}`apiKey`.
         '';
       };
 
@@ -51,7 +51,7 @@ in {
         type = types.str;
         default = "";
         example = "http://127.0.0.1/server-status";
-        description = ''
+        description = lib.mdDoc ''
           The Apache status page URL. If provided, Longview will
           gather statistics from this location. This requires Apache
           mod_status to be loaded and enabled.
@@ -62,7 +62,7 @@ in {
         type = types.str;
         default = "";
         example = "http://127.0.0.1/nginx_status";
-        description = ''
+        description = lib.mdDoc ''
           The Nginx status page URL. Longview will gather statistics
           from this URL. This requires the Nginx stub_status module to
           be enabled and configured at the given location.
@@ -72,7 +72,7 @@ in {
       mysqlUser = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           The user for connecting to the MySQL database. If provided,
           Longview will connect to MySQL and collect statistics about
           queries, etc. This user does not need to have been granted
@@ -83,10 +83,10 @@ in {
       mysqlPassword = mkOption {
         type = types.str;
         default = "";
-        description = ''
-          The password corresponding to <option>mysqlUser</option>.
+        description = lib.mdDoc ''
+          The password corresponding to {option}`mysqlUser`.
           Warning: this is stored in cleartext in the Nix store!
-          Use <option>mysqlPasswordFile</option> instead.
+          Use {option}`mysqlPasswordFile` instead.
         '';
       };
 
@@ -94,8 +94,8 @@ in {
         type = types.nullOr types.path;
         default = null;
         example = "/run/keys/dbpassword";
-        description = ''
-          A file containing the password corresponding to <option>mysqlUser</option>.
+        description = lib.mdDoc ''
+          A file containing the password corresponding to {option}`mysqlUser`.
         '';
       };
 
diff --git a/nixos/modules/services/monitoring/mackerel-agent.nix b/nixos/modules/services/monitoring/mackerel-agent.nix
index aeb6247abd8..4185cd76c4e 100644
--- a/nixos/modules/services/monitoring/mackerel-agent.nix
+++ b/nixos/modules/services/monitoring/mackerel-agent.nix
@@ -7,33 +7,33 @@ let
   settingsFmt = pkgs.formats.toml {};
 in {
   options.services.mackerel-agent = {
-    enable = mkEnableOption "mackerel.io agent";
+    enable = mkEnableOption (lib.mdDoc "mackerel.io agent");
 
     # the upstream package runs as root, but doesn't seem to be strictly
     # necessary for basic functionality
-    runAsRoot = mkEnableOption "Whether to run as root.";
+    runAsRoot = mkEnableOption (lib.mdDoc "Whether to run as root.");
 
-    autoRetirement = mkEnableOption ''
+    autoRetirement = mkEnableOption (lib.mdDoc ''
       Whether to automatically retire the host upon OS shutdown.
-    '';
+    '');
 
     apiKeyFile = mkOption {
       type = types.path;
       example = "/run/keys/mackerel-api-key";
-      description = ''
+      description = lib.mdDoc ''
         Path to file containing the Mackerel API key. The file should contain a
         single line of the following form:
 
-        <literallayout>apikey = "EXAMPLE_API_KEY"</literallayout>
+        `apikey = "EXAMPLE_API_KEY"`
       '';
     };
 
     settings = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Options for mackerel-agent.conf.
 
         Documentation:
-        <link xlink:href="https://mackerel.io/docs/entry/spec/agent"/>
+        <https://mackerel.io/docs/entry/spec/agent>
       '';
 
       default = {};
@@ -48,18 +48,18 @@ in {
         options.host_status = {
           on_start = mkOption {
             type = types.enum [ "working" "standby" "maintenance" "poweroff" ];
-            description = "Host status after agent startup.";
+            description = lib.mdDoc "Host status after agent startup.";
             default = "working";
           };
           on_stop = mkOption {
             type = types.enum [ "working" "standby" "maintenance" "poweroff" ];
-            description = "Host status after agent shutdown.";
+            description = lib.mdDoc "Host status after agent shutdown.";
             default = "poweroff";
           };
         };
 
         options.diagnostic =
-          mkEnableOption "Collect memory usage for the agent itself";
+          mkEnableOption (lib.mdDoc "Collect memory usage for the agent itself");
       };
     };
   };
diff --git a/nixos/modules/services/monitoring/metricbeat.nix b/nixos/modules/services/monitoring/metricbeat.nix
index e75039daa10..310c9d8ed50 100644
--- a/nixos/modules/services/monitoring/metricbeat.nix
+++ b/nixos/modules/services/monitoring/metricbeat.nix
@@ -19,30 +19,30 @@ in
 
     services.metricbeat = {
 
-      enable = mkEnableOption "metricbeat";
+      enable = mkEnableOption (lib.mdDoc "metricbeat");
 
       package = mkOption {
         type = types.package;
         default = pkgs.metricbeat;
         defaultText = literalExpression "pkgs.metricbeat";
         example = literalExpression "pkgs.metricbeat7";
-        description = ''
+        description = lib.mdDoc ''
           The metricbeat package to use
         '';
       };
 
       modules = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Metricbeat modules are responsible for reading metrics from the various sources.
 
-          This is like <literal>services.metricbeat.settings.metricbeat.modules</literal>,
+          This is like `services.metricbeat.settings.metricbeat.modules`,
           but structured as an attribute set. This has the benefit that multiple
           NixOS modules can contribute settings to a single metricbeat module.
 
-          A module can be specified multiple times by choosing a different <literal>&lt;name></literal>
-          for each, but setting <xref linkend="opt-services.metricbeat.modules._name_.module"/> to the same value.
+          A module can be specified multiple times by choosing a different `<name>`
+          for each, but setting [](#opt-services.metricbeat.modules._name_.module) to the same value.
 
-          See <link xlink:href="https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-modules.html"/>.
+          See <https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-modules.html>.
         '';
         default = {};
         type = types.attrsOf (types.submodule ({ name, ... }: {
@@ -51,11 +51,11 @@ in
             module = mkOption {
               type = types.str;
               default = name;
-              description = ''
+              description = lib.mdDoc ''
                 The name of the module.
 
-                Look for the value after <literal>module:</literal> on the individual
-                module pages linked from <link xlink:href="https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-modules.html"/>.
+                Look for the value after `module:` on the individual
+                module pages linked from <https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-modules.html>.
               '';
             };
           };
@@ -80,18 +80,18 @@ in
             name = mkOption {
               type = types.str;
               default = "";
-              description = ''
+              description = lib.mdDoc ''
                 Name of the beat. Defaults to the hostname.
-                See <link xlink:href="https://www.elastic.co/guide/en/beats/metricbeat/current/configuration-general-options.html#_name"/>.
+                See <https://www.elastic.co/guide/en/beats/metricbeat/current/configuration-general-options.html#_name>.
               '';
             };
 
             tags = mkOption {
               type = types.listOf types.str;
               default = [];
-              description = ''
+              description = lib.mdDoc ''
                 Tags to place on the shipped metrics.
-                See <link xlink:href="https://www.elastic.co/guide/en/beats/metricbeat/current/configuration-general-options.html#_tags_2"/>.
+                See <https://www.elastic.co/guide/en/beats/metricbeat/current/configuration-general-options.html#_tags_2>.
               '';
             };
 
@@ -99,17 +99,17 @@ in
               type = types.listOf settingsFormat.type;
               default = [];
               internal = true;
-              description = ''
-                The metric collecting modules. Use <xref linkend="opt-services.metricbeat.modules"/> instead.
+              description = lib.mdDoc ''
+                The metric collecting modules. Use [](#opt-services.metricbeat.modules) instead.
 
-                See <link xlink:href="https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-modules.html"/>.
+                See <https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-modules.html>.
               '';
             };
           };
         };
         default = {};
-        description = ''
-          Configuration for metricbeat. See <link xlink:href="https://www.elastic.co/guide/en/beats/metricbeat/current/configuring-howto-metricbeat.html"/> for supported values.
+        description = lib.mdDoc ''
+          Configuration for metricbeat. See <https://www.elastic.co/guide/en/beats/metricbeat/current/configuring-howto-metricbeat.html> for supported values.
         '';
       };
 
diff --git a/nixos/modules/services/monitoring/mimir.nix b/nixos/modules/services/monitoring/mimir.nix
new file mode 100644
index 00000000000..568066990f2
--- /dev/null
+++ b/nixos/modules/services/monitoring/mimir.nix
@@ -0,0 +1,67 @@
+{ config, lib, pkgs, ... }:
+
+let
+  inherit (lib) escapeShellArgs mkEnableOption mkIf mkOption types;
+
+  cfg = config.services.mimir;
+
+  settingsFormat = pkgs.formats.yaml {};
+in {
+  options.services.mimir = {
+    enable = mkEnableOption (lib.mdDoc "mimir");
+
+    configuration = mkOption {
+      type = (pkgs.formats.json {}).type;
+      default = {};
+      description = lib.mdDoc ''
+        Specify the configuration for Mimir in Nix.
+      '';
+    };
+
+    configFile = mkOption {
+      type = types.nullOr types.path;
+      default = null;
+      description = lib.mdDoc ''
+        Specify a configuration file that Mimir should use.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    # for mimirtool
+    environment.systemPackages = [ pkgs.mimir ];
+
+    assertions = [{
+      assertion = (
+        (cfg.configuration == {} -> cfg.configFile != null) &&
+        (cfg.configFile != null -> cfg.configuration == {})
+      );
+      message  = ''
+        Please specify either
+        'services.mimir.configuration' or
+        'services.mimir.configFile'.
+      '';
+    }];
+
+    systemd.services.mimir = {
+      description = "mimir Service Daemon";
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = let
+        conf = if cfg.configFile == null
+               then settingsFormat.generate "config.yaml" cfg.configuration
+               else cfg.configFile;
+      in
+      {
+        ExecStart = "${pkgs.mimir}/bin/mimir --config.file=${conf}";
+        DynamicUser = true;
+        Restart = "always";
+        ProtectSystem = "full";
+        DevicePolicy = "closed";
+        NoNewPrivileges = true;
+        WorkingDirectory = "/var/lib/mimir";
+        StateDirectory = "mimir";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/monitoring/monit.nix b/nixos/modules/services/monitoring/monit.nix
index 379ee967620..a22bbc9046b 100644
--- a/nixos/modules/services/monitoring/monit.nix
+++ b/nixos/modules/services/monitoring/monit.nix
@@ -9,12 +9,12 @@ in
 {
   options.services.monit = {
 
-    enable = mkEnableOption "Monit";
+    enable = mkEnableOption (lib.mdDoc "Monit");
 
     config = mkOption {
       type = types.lines;
       default = "";
-      description = "monitrc content";
+      description = lib.mdDoc "monitrc content";
     };
 
   };
diff --git a/nixos/modules/services/monitoring/munin.nix b/nixos/modules/services/monitoring/munin.nix
index 4fddb1e37e2..9461bd3f35b 100644
--- a/nixos/modules/services/monitoring/munin.nix
+++ b/nixos/modules/services/monitoring/munin.nix
@@ -138,29 +138,29 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Enable Munin Node agent. Munin node listens on 0.0.0.0 and
           by default accepts connections only from 127.0.0.1 for security reasons.
 
-          See <link xlink:href='http://guide.munin-monitoring.org/en/latest/architecture/index.html' />.
+          See <http://guide.munin-monitoring.org/en/latest/architecture/index.html>.
         '';
       };
 
       extraConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
-          <filename>munin-node.conf</filename> extra configuration. See
-          <link xlink:href='http://guide.munin-monitoring.org/en/latest/reference/munin-node.conf.html' />
+        description = lib.mdDoc ''
+          {file}`munin-node.conf` extra configuration. See
+          <http://guide.munin-monitoring.org/en/latest/reference/munin-node.conf.html>
         '';
       };
 
       extraPluginConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
-          <filename>plugin-conf.d</filename> extra plugin configuration. See
-          <link xlink:href='http://guide.munin-monitoring.org/en/latest/plugin/use.html' />
+        description = lib.mdDoc ''
+          {file}`plugin-conf.d` extra plugin configuration. See
+          <http://guide.munin-monitoring.org/en/latest/plugin/use.html>
         '';
         example = ''
           [fail2ban_*]
@@ -171,7 +171,7 @@ in
       extraPlugins = mkOption {
         default = {};
         type = with types; attrsOf path;
-        description = ''
+        description = lib.mdDoc ''
           Additional Munin plugins to activate. Keys are the name of the plugin
           symlink, values are the path to the underlying plugin script. You
           can use the same plugin script multiple times (e.g. for wildcard
@@ -179,15 +179,15 @@ in
 
           Note that these plugins do not participate in autoconfiguration. If
           you want to autoconfigure additional plugins, use
-          <option>services.munin-node.extraAutoPlugins</option>.
+          {option}`services.munin-node.extraAutoPlugins`.
 
           Plugins enabled in this manner take precedence over autoconfigured
           plugins.
 
           Plugins will be copied into the Nix store, and it will attempt to
           modify them to run properly by fixing hardcoded references to
-          <literal>/bin</literal>, <literal>/usr/bin</literal>,
-          <literal>/sbin</literal>, and <literal>/usr/sbin</literal>.
+          `/bin`, `/usr/bin`,
+          `/sbin`, and `/usr/sbin`.
         '';
         example = literalExpression ''
           {
@@ -201,24 +201,24 @@ in
       extraAutoPlugins = mkOption {
         default = [];
         type = with types; listOf path;
-        description = ''
+        description = lib.mdDoc ''
           Additional Munin plugins to autoconfigure, using
-          <literal>munin-node-configure --suggest</literal>. These should be
+          `munin-node-configure --suggest`. These should be
           the actual paths to the plugin files (or directories containing them),
           not just their names.
 
           If you want to manually enable individual plugins instead, use
-          <option>services.munin-node.extraPlugins</option>.
+          {option}`services.munin-node.extraPlugins`.
 
           Note that only plugins that have the 'autoconfig' capability will do
           anything if listed here, since plugins that cannot autoconfigure
           won't be automatically enabled by
-          <literal>munin-node-configure</literal>.
+          `munin-node-configure`.
 
           Plugins will be copied into the Nix store, and it will attempt to
           modify them to run properly by fixing hardcoded references to
-          <literal>/bin</literal>, <literal>/usr/bin</literal>,
-          <literal>/sbin</literal>, and <literal>/usr/sbin</literal>.
+          `/bin`, `/usr/bin`,
+          `/sbin`, and `/usr/sbin`.
         '';
         example = literalExpression ''
           [
@@ -234,14 +234,14 @@ in
         # NaNs in the output.
         default = [ "munin_stats" ];
         type = with types; listOf str;
-        description = ''
+        description = lib.mdDoc ''
           Munin plugins to disable, even if
-          <literal>munin-node-configure --suggest</literal> tries to enable
+          `munin-node-configure --suggest` tries to enable
           them. To disable a wildcard plugin, use an actual wildcard, as in
           the example.
 
           munin_stats is disabled by default as it tries to read
-          <literal>/var/log/munin/munin-update.log</literal> for timing
+          `/var/log/munin/munin-update.log` for timing
           information, and the NixOS build of Munin does not write this file.
         '';
         example = [ "diskstats" "zfs_usage_*" ];
@@ -253,12 +253,12 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Enable munin-cron. Takes care of all heavy lifting to collect data from
           nodes and draws graphs to html. Runs munin-update, munin-limits,
           munin-graphs and munin-html in that order.
 
-          HTML output is in <filename>/var/www/munin/</filename>, configure your
+          HTML output is in {file}`/var/www/munin/`, configure your
           favourite webserver to serve static files.
         '';
       };
@@ -266,11 +266,11 @@ in
       extraGlobalConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
-          <filename>munin.conf</filename> extra global configuration.
-          See <link xlink:href='http://guide.munin-monitoring.org/en/latest/reference/munin.conf.html' />.
+        description = lib.mdDoc ''
+          {file}`munin.conf` extra global configuration.
+          See <http://guide.munin-monitoring.org/en/latest/reference/munin.conf.html>.
           Useful to setup notifications, see
-          <link xlink:href='http://guide.munin-monitoring.org/en/latest/tutorial/alert.html' />
+          <http://guide.munin-monitoring.org/en/latest/tutorial/alert.html>
         '';
         example = ''
           contact.email.command mail -s "Munin notification for ''${var:host}" someone@example.com
@@ -280,10 +280,10 @@ in
       hosts = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Definitions of hosts of nodes to collect data from. Needs at least one
           host for cron to succeed. See
-          <link xlink:href='http://guide.munin-monitoring.org/en/latest/reference/munin.conf.html' />
+          <http://guide.munin-monitoring.org/en/latest/reference/munin.conf.html>
         '';
         example = literalExpression ''
           '''
@@ -296,7 +296,7 @@ in
       extraCSS = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Custom styling for the HTML that munin-cron generates. This will be
           appended to the CSS files used by munin-cron and will thus take
           precedence over the builtin styles.
diff --git a/nixos/modules/services/monitoring/nagios.nix b/nixos/modules/services/monitoring/nagios.nix
index 2c7f0ed1966..8feff22c118 100644
--- a/nixos/modules/services/monitoring/nagios.nix
+++ b/nixos/modules/services/monitoring/nagios.nix
@@ -88,34 +88,34 @@ in
 
   options = {
     services.nagios = {
-      enable = mkEnableOption "<link xlink:href='http://www.nagios.org/'>Nagios</link> to monitor your system or network.";
+      enable = mkEnableOption (lib.mdDoc ''[Nagios](http://www.nagios.org/) to monitor your system or network.'');
 
       objectDefs = mkOption {
-        description = "
+        description = lib.mdDoc ''
           A list of Nagios object configuration files that must define
           the hosts, host groups, services and contacts for the
           network that you want Nagios to monitor.
-        ";
+        '';
         type = types.listOf types.path;
         example = literalExpression "[ ./objects.cfg ]";
       };
 
       plugins = mkOption {
         type = types.listOf types.package;
-        default = with pkgs; [ monitoring-plugins ssmtp mailutils ];
-        defaultText = literalExpression "[pkgs.monitoring-plugins pkgs.ssmtp pkgs.mailutils]";
-        description = "
-          Packages to be added to the Nagios <envar>PATH</envar>.
+        default = with pkgs; [ monitoring-plugins msmtp mailutils ];
+        defaultText = literalExpression "[pkgs.monitoring-plugins pkgs.msmtp pkgs.mailutils]";
+        description = lib.mdDoc ''
+          Packages to be added to the Nagios {env}`PATH`.
           Typically used to add plugins, but can be anything.
-        ";
+        '';
       };
 
       mainConfigFile = mkOption {
         type = types.nullOr types.package;
         default = null;
-        description = "
+        description = lib.mdDoc ''
           If non-null, overrides the main configuration file of Nagios.
-        ";
+        '';
       };
 
       extraConfig = mkOption {
@@ -125,33 +125,33 @@ in
           debug_file = "/var/log/nagios/debug.log";
         };
         default = {};
-        description = "Configuration to add to /etc/nagios.cfg";
+        description = lib.mdDoc "Configuration to add to /etc/nagios.cfg";
       };
 
       validateConfig = mkOption {
         type = types.bool;
         default = pkgs.stdenv.hostPlatform == pkgs.stdenv.buildPlatform;
         defaultText = literalExpression "pkgs.stdenv.hostPlatform == pkgs.stdenv.buildPlatform";
-        description = "if true, the syntax of the nagios configuration file is checked at build time";
+        description = lib.mdDoc "if true, the syntax of the nagios configuration file is checked at build time";
       };
 
       cgiConfigFile = mkOption {
         type = types.package;
         default = nagiosCGICfgFile;
         defaultText = literalExpression "nagiosCGICfgFile";
-        description = "
+        description = lib.mdDoc ''
           Derivation for the configuration file of Nagios CGI scripts
           that can be used in web servers for running the Nagios web interface.
-        ";
+        '';
       };
 
       enableWebInterface = mkOption {
         type = types.bool;
         default = false;
-        description = "
+        description = lib.mdDoc ''
           Whether to enable the Nagios web interface.  You should also
-          enable Apache (<option>services.httpd.enable</option>).
-        ";
+          enable Apache ({option}`services.httpd.enable`).
+        '';
       };
 
       virtualHost = mkOption {
@@ -164,9 +164,9 @@ in
             sslServerKey = "/var/lib/acme/example.org/key.pem";
           }
         '';
-        description = ''
-          Apache configuration can be done by adapting <option>services.httpd.virtualHosts</option>.
-          See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
+        description = lib.mdDoc ''
+          Apache configuration can be done by adapting {option}`services.httpd.virtualHosts`.
+          See [](#opt-services.httpd.virtualHosts) for further information.
         '';
       };
     };
diff --git a/nixos/modules/services/monitoring/netdata.nix b/nixos/modules/services/monitoring/netdata.nix
index f528d183042..92c870bb23f 100644
--- a/nixos/modules/services/monitoring/netdata.nix
+++ b/nixos/modules/services/monitoring/netdata.nix
@@ -49,30 +49,30 @@ let
 in {
   options = {
     services.netdata = {
-      enable = mkEnableOption "netdata";
+      enable = mkEnableOption (lib.mdDoc "netdata");
 
       package = mkOption {
         type = types.package;
         default = pkgs.netdata;
         defaultText = literalExpression "pkgs.netdata";
-        description = "Netdata package to use.";
+        description = lib.mdDoc "Netdata package to use.";
       };
 
       user = mkOption {
         type = types.str;
         default = "netdata";
-        description = "User account under which netdata runs.";
+        description = lib.mdDoc "User account under which netdata runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "netdata";
-        description = "Group under which netdata runs.";
+        description = lib.mdDoc "Group under which netdata runs.";
       };
 
       configText = mkOption {
         type = types.nullOr types.lines;
-        description = "Verbatim netdata.conf, cannot be combined with config.";
+        description = lib.mdDoc "Verbatim netdata.conf, cannot be combined with config.";
         default = null;
         example = ''
           [global]
@@ -86,7 +86,7 @@ in {
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable python-based plugins
           '';
         };
@@ -101,7 +101,7 @@ in {
               ps.dnspython
             ]
           '';
-          description = ''
+          description = lib.mdDoc ''
             Extra python packages available at runtime
             to enable additional python plugins.
           '';
@@ -114,14 +114,14 @@ in {
         example = literalExpression ''
           [ "/path/to/plugins.d" ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra paths to add to the netdata global "plugins directory"
           option.  Useful for when you want to include your own
           collection scripts.
-          </para><para>
+
           Details about writing a custom netdata plugin are available at:
-          <link xlink:href="https://docs.netdata.cloud/collectors/plugins.d/"/>
-          </para><para>
+          <https://docs.netdata.cloud/collectors/plugins.d/>
+
           Cannot be combined with configText.
         '';
       };
@@ -129,7 +129,7 @@ in {
       config = mkOption {
         type = types.attrsOf types.attrs;
         default = {};
-        description = "netdata.conf configuration as nix attributes. cannot be combined with configText.";
+        description = lib.mdDoc "netdata.conf configuration as nix attributes. cannot be combined with configText.";
         example = literalExpression ''
           global = {
             "debug log" = "syslog";
@@ -142,7 +142,7 @@ in {
       configDir = mkOption {
         type = types.attrsOf types.path;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Complete netdata config directory except netdata.conf.
           The default configuration is merged with changes
           defined in this option.
@@ -162,11 +162,11 @@ in {
       enableAnalyticsReporting = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable reporting of anonymous usage statistics to Netdata Inc. via either
           Google Analytics (in versions prior to 1.29.4), or Netdata Inc.'s
           self-hosted PostHog (in versions 1.29.4 and later).
-          See: <link xlink:href="https://learn.netdata.cloud/docs/agent/anonymous-statistics"/>
+          See: <https://learn.netdata.cloud/docs/agent/anonymous-statistics>
         '';
       };
     };
@@ -186,7 +186,7 @@ in {
       description = "Real time performance monitoring";
       after = [ "network.target" ];
       wantedBy = [ "multi-user.target" ];
-      path = (with pkgs; [ curl gawk iproute2 which procps ])
+      path = (with pkgs; [ curl gawk iproute2 which procps bash ])
         ++ lib.optional cfg.python.enable (pkgs.python3.withPackages cfg.python.extraPackages)
         ++ lib.optional config.virtualisation.libvirtd.enable (config.virtualisation.libvirtd.package);
       environment = {
@@ -201,6 +201,10 @@ in {
       serviceConfig = {
         ExecStart = "${cfg.package}/bin/netdata -P /run/netdata/netdata.pid -D -c /etc/netdata/netdata.conf";
         ExecReload = "${pkgs.util-linux}/bin/kill -s HUP -s USR1 -s USR2 $MAINPID";
+        ExecStartPost = pkgs.writeShellScript "wait-for-netdata-up" ''
+          while [ "$(${pkgs.netdata}/bin/netdatacli ping)" != pong ]; do sleep 0.5; done
+        '';
+
         TimeoutStopSec = 60;
         Restart = "on-failure";
         # User and group
diff --git a/nixos/modules/services/monitoring/parsedmarc.nix b/nixos/modules/services/monitoring/parsedmarc.nix
index ec71365ba3c..3540d91fc9f 100644
--- a/nixos/modules/services/monitoring/parsedmarc.nix
+++ b/nixos/modules/services/monitoring/parsedmarc.nix
@@ -3,32 +3,44 @@
 let
   cfg = config.services.parsedmarc;
   opt = options.services.parsedmarc;
-  ini = pkgs.formats.ini {};
+  isSecret = v: isAttrs v && v ? _secret && isString v._secret;
+  ini = pkgs.formats.ini {
+    mkKeyValue = lib.flip lib.generators.mkKeyValueDefault "=" rec {
+      mkValueString = v:
+        if isInt           v then toString v
+        else if isString   v then v
+        else if true  ==   v then "True"
+        else if false ==   v then "False"
+        else if isSecret   v then hashString "sha256" v._secret
+        else throw "unsupported type ${typeOf v}: ${(lib.generators.toPretty {}) v}";
+    };
+  };
+  inherit (builtins) elem isAttrs isString isInt isList typeOf hashString;
 in
 {
   options.services.parsedmarc = {
 
-    enable = lib.mkEnableOption ''
+    enable = lib.mkEnableOption (lib.mdDoc ''
       parsedmarc, a DMARC report monitoring service
-    '';
+    '');
 
     provision = {
       localMail = {
         enable = lib.mkOption {
           type = lib.types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether Postfix and Dovecot should be set up to receive
             mail locally. parsedmarc will be configured to watch the
             local inbox as the automatically created user specified in
-            <xref linkend="opt-services.parsedmarc.provision.localMail.recipientName" />
+            [](#opt-services.parsedmarc.provision.localMail.recipientName)
           '';
         };
 
         recipientName = lib.mkOption {
           type = lib.types.str;
           default = "dmarc";
-          description = ''
+          description = lib.mdDoc ''
             The DMARC mail recipient name, i.e. the name part of the
             email address which receives DMARC reports.
 
@@ -42,7 +54,7 @@ in
           default = config.networking.fqdn;
           defaultText = lib.literalExpression "config.networking.fqdn";
           example = "monitoring.example.com";
-          description = ''
+          description = lib.mdDoc ''
             The hostname to use when configuring Postfix.
 
             Should correspond to the host's fully qualified domain
@@ -56,15 +68,13 @@ in
       geoIp = lib.mkOption {
         type = lib.types.bool;
         default = true;
-        description = ''
-          Whether to enable and configure the <link
-          linkend="opt-services.geoipupdate.enable">geoipupdate</link>
+        description = lib.mdDoc ''
+          Whether to enable and configure the [geoipupdate](#opt-services.geoipupdate.enable)
           service to automatically fetch GeoIP databases. Not crucial,
           but recommended for full functionality.
 
-          To finish the setup, you need to manually set the <xref
-          linkend="opt-services.geoipupdate.settings.AccountID" /> and
-          <xref linkend="opt-services.geoipupdate.settings.LicenseKey" />
+          To finish the setup, you need to manually set the [](#opt-services.geoipupdate.settings.AccountID) and
+          [](#opt-services.geoipupdate.settings.LicenseKey)
           options.
         '';
       };
@@ -72,7 +82,7 @@ in
       elasticsearch = lib.mkOption {
         type = lib.types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to set up and use a local instance of Elasticsearch.
         '';
       };
@@ -85,11 +95,11 @@ in
             config.${opt.provision.elasticsearch} && config.${options.services.grafana.enable}
           '';
           apply = x: x && cfg.provision.elasticsearch;
-          description = ''
+          description = lib.mdDoc ''
             Whether the automatically provisioned Elasticsearch
             instance should be added as a grafana datasource. Has no
             effect unless
-            <xref linkend="opt-services.parsedmarc.provision.elasticsearch" />
+            [](#opt-services.parsedmarc.provision.elasticsearch)
             is also enabled.
           '';
         };
@@ -98,7 +108,7 @@ in
           type = lib.types.bool;
           default = config.services.grafana.enable;
           defaultText = lib.literalExpression "config.services.grafana.enable";
-          description = ''
+          description = lib.mdDoc ''
             Whether the official parsedmarc grafana dashboard should
             be provisioned to the local grafana instance.
           '';
@@ -107,11 +117,35 @@ in
     };
 
     settings = lib.mkOption {
-      description = ''
+      example = lib.literalExpression ''
+        {
+          imap = {
+            host = "imap.example.com";
+            user = "alice@example.com";
+            password = { _secret = "/run/keys/imap_password" };
+            watch = true;
+          };
+          splunk_hec = {
+            url = "https://splunkhec.example.com";
+            token = { _secret = "/run/keys/splunk_token" };
+            index = "email";
+          };
+        }
+      '';
+      description = lib.mdDoc ''
         Configuration parameters to set in
-        <filename>parsedmarc.ini</filename>. For a full list of
+        {file}`parsedmarc.ini`. For a full list of
         available parameters, see
-        <link xlink:href="https://domainaware.github.io/parsedmarc/#configuration-file" />.
+        <https://domainaware.github.io/parsedmarc/#configuration-file>.
+
+        Settings containing secret data should be set to an attribute
+        set containing the attribute `_secret` - a
+        string pointing to a file containing the value the option
+        should be set to. See the example to get a better picture of
+        this: in the resulting {file}`parsedmarc.ini`
+        file, the `splunk_hec.token` key will be set
+        to the contents of the
+        {file}`/run/keys/splunk_token` file.
       '';
 
       type = lib.types.submodule {
@@ -122,7 +156,7 @@ in
             save_aggregate = lib.mkOption {
               type = lib.types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Save aggregate report data to Elasticsearch and/or Splunk.
               '';
             };
@@ -130,7 +164,7 @@ in
             save_forensic = lib.mkOption {
               type = lib.types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Save forensic report data to Elasticsearch and/or Splunk.
               '';
             };
@@ -140,7 +174,7 @@ in
             host = lib.mkOption {
               type = lib.types.str;
               default = "localhost";
-              description = ''
+              description = lib.mdDoc ''
                 The IMAP server hostname or IP address.
               '';
             };
@@ -148,7 +182,7 @@ in
             port = lib.mkOption {
               type = lib.types.port;
               default = 993;
-              description = ''
+              description = lib.mdDoc ''
                 The IMAP server port.
               '';
             };
@@ -156,7 +190,7 @@ in
             ssl = lib.mkOption {
               type = lib.types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Use an encrypted SSL/TLS connection.
               '';
             };
@@ -164,23 +198,29 @@ in
             user = lib.mkOption {
               type = with lib.types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The IMAP server username.
               '';
             };
 
             password = lib.mkOption {
-              type = with lib.types; nullOr path;
+              type = with lib.types; nullOr (either path (attrsOf path));
               default = null;
-              description = ''
-                The path to a file containing the IMAP server password.
+              description = lib.mdDoc ''
+                The IMAP server password.
+
+                Always handled as a secret whether the value is
+                wrapped in a `{ _secret = ...; }`
+                attrset or not (refer to [](#opt-services.parsedmarc.settings) for
+                details).
               '';
+              apply = x: if isAttrs x || x == null then x else { _secret = x; };
             };
 
             watch = lib.mkOption {
               type = lib.types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Use the IMAP IDLE command to process messages as they arrive.
               '';
             };
@@ -188,7 +228,7 @@ in
             delete = lib.mkOption {
               type = lib.types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 Delete messages after processing them, instead of archiving them.
               '';
             };
@@ -198,7 +238,7 @@ in
             host = lib.mkOption {
               type = with lib.types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The SMTP server hostname or IP address.
               '';
             };
@@ -206,7 +246,7 @@ in
             port = lib.mkOption {
               type = with lib.types; nullOr port;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The SMTP server port.
               '';
             };
@@ -214,7 +254,7 @@ in
             ssl = lib.mkOption {
               type = with lib.types; nullOr bool;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Use an encrypted SSL/TLS connection.
               '';
             };
@@ -222,24 +262,30 @@ in
             user = lib.mkOption {
               type = with lib.types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The SMTP server username.
               '';
             };
 
             password = lib.mkOption {
-              type = with lib.types; nullOr path;
+              type = with lib.types; nullOr (either path (attrsOf path));
               default = null;
-              description = ''
-                The path to a file containing the SMTP server password.
+              description = lib.mdDoc ''
+                The SMTP server password.
+
+                Always handled as a secret whether the value is
+                wrapped in a `{ _secret = ...; }`
+                attrset or not (refer to [](#opt-services.parsedmarc.settings) for
+                details).
               '';
+              apply = x: if isAttrs x || x == null then x else { _secret = x; };
             };
 
             from = lib.mkOption {
               type = with lib.types; nullOr str;
               default = null;
-              description = ''
-                The <literal>From</literal> address to use for the
+              description = lib.mdDoc ''
+                The `From` address to use for the
                 outgoing mail.
               '';
             };
@@ -247,7 +293,7 @@ in
             to = lib.mkOption {
               type = with lib.types; nullOr (listOf str);
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The addresses to send outgoing mail to.
               '';
             };
@@ -258,7 +304,7 @@ in
               default = [];
               type = with lib.types; listOf str;
               apply = x: if x == [] then null else lib.concatStringsSep "," x;
-              description = ''
+              description = lib.mdDoc ''
                 A list of Elasticsearch hosts to push parsed reports
                 to.
               '';
@@ -267,25 +313,31 @@ in
             user = lib.mkOption {
               type = with lib.types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Username to use when connecting to Elasticsearch, if
                 required.
               '';
             };
 
             password = lib.mkOption {
-              type = with lib.types; nullOr path;
+              type = with lib.types; nullOr (either path (attrsOf path));
               default = null;
-              description = ''
-                The path to a file containing the password to use when
-                connecting to Elasticsearch, if required.
+              description = lib.mdDoc ''
+                The password to use when connecting to Elasticsearch,
+                if required.
+
+                Always handled as a secret whether the value is
+                wrapped in a `{ _secret = ...; }`
+                attrset or not (refer to [](#opt-services.parsedmarc.settings) for
+                details).
               '';
+              apply = x: if isAttrs x || x == null then x else { _secret = x; };
             };
 
             ssl = lib.mkOption {
               type = lib.types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 Whether to use an encrypted SSL/TLS connection.
               '';
             };
@@ -293,69 +345,12 @@ in
             cert_path = lib.mkOption {
               type = lib.types.path;
               default = "/etc/ssl/certs/ca-certificates.crt";
-              description = ''
+              description = lib.mdDoc ''
                 The path to a TLS certificate bundle used to verify
                 the server's certificate.
               '';
             };
           };
-
-          kafka = {
-            hosts = lib.mkOption {
-              default = [];
-              type = with lib.types; listOf str;
-              apply = x: if x == [] then null else lib.concatStringsSep "," x;
-              description = ''
-                A list of Apache Kafka hosts to publish parsed reports
-                to.
-              '';
-            };
-
-            user = lib.mkOption {
-              type = with lib.types; nullOr str;
-              default = null;
-              description = ''
-                Username to use when connecting to Kafka, if
-                required.
-              '';
-            };
-
-            password = lib.mkOption {
-              type = with lib.types; nullOr path;
-              default = null;
-              description = ''
-                The path to a file containing the password to use when
-                connecting to Kafka, if required.
-              '';
-            };
-
-            ssl = lib.mkOption {
-              type = with lib.types; nullOr bool;
-              default = null;
-              description = ''
-                Whether to use an encrypted SSL/TLS connection.
-              '';
-            };
-
-            aggregate_topic = lib.mkOption {
-              type = with lib.types; nullOr str;
-              default = null;
-              example = "aggregate";
-              description = ''
-                The Kafka topic to publish aggregate reports on.
-              '';
-            };
-
-            forensic_topic = lib.mkOption {
-              type = with lib.types; nullOr str;
-              default = null;
-              example = "forensic";
-              description = ''
-                The Kafka topic to publish forensic reports on.
-              '';
-            };
-          };
-
         };
 
       };
@@ -404,21 +399,14 @@ in
         enable = cfg.provision.grafana.datasource || cfg.provision.grafana.dashboard;
         datasources =
           let
-            pkgVer = lib.getVersion config.services.elasticsearch.package;
-            esVersion =
-              if lib.versionOlder pkgVer "7" then
-                "60"
-              else if lib.versionOlder pkgVer "8" then
-                "70"
-              else
-                throw "When provisioning parsedmarc grafana datasources: unknown Elasticsearch version.";
+            esVersion = lib.getVersion config.services.elasticsearch.package;
           in
             lib.mkIf cfg.provision.grafana.datasource [
               {
                 name = "dmarc-ag";
                 type = "elasticsearch";
                 access = "proxy";
-                url = "localhost:9200";
+                url = "http://localhost:9200";
                 jsonData = {
                   timeField = "date_range";
                   inherit esVersion;
@@ -428,7 +416,7 @@ in
                 name = "dmarc-fo";
                 type = "elasticsearch";
                 access = "proxy";
-                url = "localhost:9200";
+                url = "http://localhost:9200";
                 jsonData = {
                   timeField = "date_range";
                   inherit esVersion;
@@ -467,12 +455,17 @@ in
         # lists, empty attrsets and null. This makes it possible to
         # list interesting options in `settings` without them always
         # ending up in the resulting config.
-        filteredConfig = lib.converge (lib.filterAttrsRecursive (_: v: ! builtins.elem v [ null [] {} ])) cfg.settings;
+        filteredConfig = lib.converge (lib.filterAttrsRecursive (_: v: ! elem v [ null [] {} ])) cfg.settings;
+
+        # Extract secrets (attributes set to an attrset with a
+        # "_secret" key) from the settings and generate the commands
+        # to run to perform the secret replacements.
+        secretPaths = lib.catAttrs "_secret" (lib.collect isSecret filteredConfig);
         parsedmarcConfig = ini.generate "parsedmarc.ini" filteredConfig;
-        mkSecretReplacement = file:
-          lib.optionalString (file != null) ''
-            replace-secret '${file}' '${file}' /run/parsedmarc/parsedmarc.ini
-          '';
+        mkSecretReplacement = file: ''
+          replace-secret ${lib.escapeShellArgs [ (hashString "sha256" file) file "/run/parsedmarc/parsedmarc.ini" ]}
+        '';
+        secretReplacements = lib.concatMapStrings mkSecretReplacement secretPaths;
       in
         {
           wantedBy = [ "multi-user.target" ];
@@ -487,10 +480,7 @@ in
                 umask u=rwx,g=,o=
                 cp ${parsedmarcConfig} /run/parsedmarc/parsedmarc.ini
                 chown parsedmarc:parsedmarc /run/parsedmarc/parsedmarc.ini
-                ${mkSecretReplacement cfg.settings.smtp.password}
-                ${mkSecretReplacement cfg.settings.imap.password}
-                ${mkSecretReplacement cfg.settings.elasticsearch.password}
-                ${mkSecretReplacement cfg.settings.kafka.password}
+                ${secretReplacements}
               '' + lib.optionalString cfg.provision.localMail.enable ''
                 openssl rand -hex 64 >/run/parsedmarc/dmarc_user_passwd
                 replace-secret '@imap-password@' '/run/parsedmarc/dmarc_user_passwd' /run/parsedmarc/parsedmarc.ini
@@ -504,7 +494,7 @@ in
             Group = "parsedmarc";
             DynamicUser = true;
             RuntimeDirectory = "parsedmarc";
-            RuntimeDirectoryMode = 0700;
+            RuntimeDirectoryMode = "0700";
             CapabilityBoundingSet = "";
             PrivateDevices = true;
             PrivateMounts = true;
diff --git a/nixos/modules/services/monitoring/prometheus/alertmanager.nix b/nixos/modules/services/monitoring/prometheus/alertmanager.nix
index 1f396634ae0..ee2533ef121 100644
--- a/nixos/modules/services/monitoring/prometheus/alertmanager.nix
+++ b/nixos/modules/services/monitoring/prometheus/alertmanager.nix
@@ -40,13 +40,13 @@ in {
 
   options = {
     services.prometheus.alertmanager = {
-      enable = mkEnableOption "Prometheus Alertmanager";
+      enable = mkEnableOption (lib.mdDoc "Prometheus Alertmanager");
 
       package = mkOption {
         type = types.package;
         default = pkgs.prometheus-alertmanager;
         defaultText = literalExpression "pkgs.alertmanager";
-        description = ''
+        description = lib.mdDoc ''
           Package that should be used for alertmanager.
         '';
       };
@@ -54,7 +54,7 @@ in {
       configuration = mkOption {
         type = types.nullOr types.attrs;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Alertmanager configuration as nix attribute set.
         '';
       };
@@ -62,7 +62,7 @@ in {
       configText = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Alertmanager configuration as YAML text. If non-null, this option
           defines the text that is written to alertmanager.yml. If null, the
           contents of alertmanager.yml is generated from the structured config
@@ -73,7 +73,7 @@ in {
       logFormat = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           If set use a syslog logger or JSON logging.
         '';
       };
@@ -81,7 +81,7 @@ in {
       logLevel = mkOption {
         type = types.enum ["debug" "info" "warn" "error" "fatal"];
         default = "warn";
-        description = ''
+        description = lib.mdDoc ''
           Only log messages with the given severity or above.
         '';
       };
@@ -89,7 +89,7 @@ in {
       webExternalUrl = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The URL under which Alertmanager is externally reachable (for example, if Alertmanager is served via a reverse proxy).
           Used for generating relative and absolute links back to Alertmanager itself.
           If the URL has a path portion, it will be used to prefix all HTTP endoints served by Alertmanager.
@@ -100,7 +100,7 @@ in {
       listenAddress = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Address to listen on for the web interface and API. Empty string will listen on all interfaces.
           "localhost" will listen on 127.0.0.1 (but not ::1).
         '';
@@ -109,7 +109,7 @@ in {
       port = mkOption {
         type = types.int;
         default = 9093;
-        description = ''
+        description = lib.mdDoc ''
           Port to listen on for the web interface and API.
         '';
       };
@@ -117,7 +117,7 @@ in {
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open port in firewall for incoming connections.
         '';
       };
@@ -125,7 +125,7 @@ in {
       clusterPeers = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Initial peers for HA cluster.
         '';
       };
@@ -133,7 +133,7 @@ in {
       extraFlags = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Extra commandline options when launching the Alertmanager.
         '';
       };
@@ -142,11 +142,11 @@ in {
         type = types.nullOr types.path;
         default = null;
         example = "/root/alertmanager.env";
-        description = ''
+        description = lib.mdDoc ''
           File to load as environment file. Environment variables
           from this file will be interpolated into the config file
           using envsubst with this syntax:
-          <literal>$ENVIRONMENT ''${VARIABLE}</literal>
+          `$ENVIRONMENT ''${VARIABLE}`
         '';
       };
     };
diff --git a/nixos/modules/services/monitoring/prometheus/default.nix b/nixos/modules/services/monitoring/prometheus/default.nix
index f563861b61c..f6bae8f9e96 100644
--- a/nixos/modules/services/monitoring/prometheus/default.nix
+++ b/nixos/modules/services/monitoring/prometheus/default.nix
@@ -3,7 +3,11 @@
 with lib;
 
 let
+  json = pkgs.formats.json { };
   cfg = config.services.prometheus;
+  checkConfigEnabled =
+    (lib.isBool cfg.checkConfig && cfg.checkConfig)
+      || cfg.checkConfig == "syntax-only";
 
   workingDir = "/var/lib/" + cfg.stateDir;
 
@@ -26,7 +30,7 @@ let
 
   # a wrapper that verifies that the configuration is valid
   promtoolCheck = what: name: file:
-    if cfg.checkConfig then
+    if checkConfigEnabled then
       pkgs.runCommandLocal
         "${name}-${replaceStrings [" "] [""] what}-checked"
         { buildInputs = [ cfg.package ]; } ''
@@ -34,13 +38,7 @@ let
         promtool ${what} $out
       '' else file;
 
-  # Pretty-print JSON to a file
-  writePrettyJSON = name: x:
-    pkgs.runCommandLocal name { } ''
-      echo '${builtins.toJSON x}' | ${pkgs.jq}/bin/jq . > $out
-    '';
-
-  generatedPrometheusYml = writePrettyJSON "prometheus.yml" promConfig;
+  generatedPrometheusYml = json.generate "prometheus.yml" promConfig;
 
   # This becomes the main config file for Prometheus
   promConfig = {
@@ -63,7 +61,7 @@ let
           pkgs.writeText "prometheus.yml" cfg.configText
         else generatedPrometheusYml;
     in
-    promtoolCheck "check config" "prometheus.yml" yml;
+    promtoolCheck "check config ${lib.optionalString (cfg.checkConfig == "syntax-only") "--syntax-only"}" "prometheus.yml" yml;
 
   cmdlineArgs = cfg.extraFlags ++ [
     "--storage.tsdb.path=${workingDir}/data/"
@@ -74,7 +72,6 @@ let
     }"
     "--web.listen-address=${cfg.listenAddress}:${builtins.toString cfg.port}"
     "--alertmanager.notification-queue-capacity=${toString cfg.alertmanagerNotificationQueueCapacity}"
-    "--alertmanager.timeout=${toString cfg.alertmanagerTimeout}s"
   ] ++ optional (cfg.webExternalUrl != null) "--web.external-url=${cfg.webExternalUrl}"
     ++ optional (cfg.retentionTime != null) "--storage.tsdb.retention.time=${cfg.retentionTime}";
 
@@ -102,14 +99,14 @@ let
 
   mkDefOpt = type: defaultStr: description: mkOpt type (description + ''
 
-    Defaults to <literal>${defaultStr}</literal> in prometheus
-    when set to <literal>null</literal>.
+    Defaults to ````${defaultStr}```` in prometheus
+    when set to `null`.
   '');
 
   mkOpt = type: description: mkOption {
     type = types.nullOr type;
     default = null;
-    inherit description;
+    description = lib.mdDoc description;
   };
 
   mkSdConfigModule = extraOptions: types.submodule {
@@ -187,7 +184,7 @@ let
     options = {
       username = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           HTTP username
         '';
       };
@@ -254,13 +251,13 @@ let
       authorization = mkOption {
         type = types.nullOr types.attrs;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Sets the `Authorization` header on every scrape request with the configured credentials.
         '';
       };
       job_name = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The job name assigned to scraped metrics by default.
         '';
       };
@@ -291,7 +288,7 @@ let
 
         If honor_labels is set to "false", label conflicts are
         resolved by renaming conflicting labels in the scraped data
-        to "exported_&lt;original-label&gt;" (for example
+        to "exported_\<original-label\>" (for example
         "exported_instance", "exported_job") and then attaching
         server-side labels. This is useful for use cases such as
         federation, where all labels specified in the target should
@@ -302,10 +299,10 @@ let
         honor_timestamps controls whether Prometheus respects the timestamps present
         in scraped data.
 
-        If honor_timestamps is set to <literal>true</literal>, the timestamps of the metrics exposed
+        If honor_timestamps is set to `true`, the timestamps of the metrics exposed
         by the target will be used.
 
-        If honor_timestamps is set to <literal>false</literal>, the timestamps of the metrics exposed
+        If honor_timestamps is set to `false`, the timestamps of the metrics exposed
         by the target will be ignored.
       '';
 
@@ -326,13 +323,13 @@ let
       bearer_token = mkOpt types.str ''
         Sets the `Authorization` header on every scrape request with
         the configured bearer token. It is mutually exclusive with
-        <option>bearer_token_file</option>.
+        {option}`bearer_token_file`.
       '';
 
       bearer_token_file = mkOpt types.str ''
         Sets the `Authorization` header on every scrape request with
         the bearer token read from the configured file. It is mutually
-        exclusive with <option>bearer_token</option>.
+        exclusive with {option}`bearer_token`.
       '';
 
       tls_config = mkOpt promTypes.tls_config ''
@@ -382,9 +379,8 @@ let
       gce_sd_configs = mkOpt (types.listOf promTypes.gce_sd_config) ''
         List of Google Compute Engine service discovery configurations.
 
-        See <link
-        xlink:href="https://prometheus.io/docs/prometheus/latest/configuration/configuration/#gce_sd_config">the
-        relevant Prometheus configuration docs</link> for more detail.
+        See [the relevant Prometheus configuration docs](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#gce_sd_config)
+        for more detail.
       '';
 
       hetzner_sd_configs = mkOpt (types.listOf promTypes.hetzner_sd_config) ''
@@ -516,7 +512,7 @@ let
 
       subscription_id = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The subscription ID.
         '';
       };
@@ -595,7 +591,7 @@ let
 
     allow_stale = mkOpt types.bool ''
       Allow stale Consul results
-      (see <link xlink:href="https://www.consul.io/api/index.html#consistency-modes"/>).
+      (see <https://www.consul.io/api/index.html#consistency-modes>).
 
       Will reduce load on Consul.
     '';
@@ -621,7 +617,7 @@ let
   mkDockerSdConfigModule = extraOptions: mkSdConfigModule ({
     host = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Address of the Docker daemon.
       '';
     };
@@ -636,16 +632,16 @@ let
         options = {
           name = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               Name of the filter. The available filters are listed in the upstream documentation:
-              Services: <link xlink:href="https://docs.docker.com/engine/api/v1.40/#operation/ServiceList"/>
-              Tasks: <link xlink:href="https://docs.docker.com/engine/api/v1.40/#operation/TaskList"/>
-              Nodes: <link xlink:href="https://docs.docker.com/engine/api/v1.40/#operation/NodeList"/>
+              Services: <https://docs.docker.com/engine/api/v1.40/#operation/ServiceList>
+              Tasks: <https://docs.docker.com/engine/api/v1.40/#operation/TaskList>
+              Nodes: <https://docs.docker.com/engine/api/v1.40/#operation/NodeList>
             '';
           };
           values = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               Value for the filter.
             '';
           };
@@ -668,7 +664,7 @@ let
   promTypes.dockerswarm_sd_config = mkDockerSdConfigModule {
     role = mkOption {
       type = types.enum [ "services" "tasks" "nodes" ];
-      description = ''
+      description = lib.mdDoc ''
         Role of the targets to retrieve. Must be `services`, `tasks`, or `nodes`.
       '';
     };
@@ -678,7 +674,7 @@ let
     options = {
       names = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           A list of DNS SRV record names to be queried.
         '';
       };
@@ -701,7 +697,7 @@ let
     options = {
       region = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The AWS Region. If blank, the region from the instance metadata is used.
         '';
       };
@@ -711,12 +707,12 @@ let
 
       access_key = mkOpt types.str ''
         The AWS API key id. If blank, the environment variable
-        <literal>AWS_ACCESS_KEY_ID</literal> is used.
+        `AWS_ACCESS_KEY_ID` is used.
       '';
 
       secret_key = mkOpt types.str ''
         The AWS API key secret. If blank, the environment variable
-         <literal>AWS_SECRET_ACCESS_KEY</literal> is used.
+         `AWS_SECRET_ACCESS_KEY` is used.
       '';
 
       profile = mkOpt types.str ''
@@ -742,8 +738,8 @@ let
           options = {
             name = mkOption {
               type = types.str;
-              description = ''
-                See <link xlink:href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html">this list</link>
+              description = lib.mdDoc ''
+                See [this list](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html)
                 for the available filters.
               '';
             };
@@ -751,7 +747,7 @@ let
             values = mkOption {
               type = types.listOf types.str;
               default = [ ];
-              description = ''
+              description = lib.mdDoc ''
                 Value of the filter.
               '';
             };
@@ -765,7 +761,7 @@ let
   promTypes.eureka_sd_config = mkSdConfigModule {
     server = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The URL to connect to the Eureka server.
       '';
     };
@@ -775,7 +771,7 @@ let
     options = {
       files = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Patterns for files from which target groups are extracted. Refer
           to the Prometheus documentation for permitted filename patterns
           and formats.
@@ -794,14 +790,14 @@ let
       # required configuration values for `gce_sd_config`.
       project = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The GCP Project.
         '';
       };
 
       zone = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The zone of the scrape targets. If you need multiple zones use multiple
           gce_sd_configs.
         '';
@@ -810,9 +806,7 @@ let
       filter = mkOpt types.str ''
         Filter can be used optionally to filter the instance list by other
         criteria Syntax of this filter string is described here in the filter
-        query parameter section: <link
-        xlink:href="https://cloud.google.com/compute/docs/reference/latest/instances/list"
-        />.
+        query parameter section: <https://cloud.google.com/compute/docs/reference/latest/instances/list>.
       '';
 
       refresh_interval = mkDefOpt types.str "60s" ''
@@ -828,7 +822,7 @@ let
         The tag separator used to separate concatenated GCE instance network tags.
 
         See the GCP documentation on network tags for more information:
-        <link xlink:href="https://cloud.google.com/vpc/docs/add-remove-network-tags" />
+        <https://cloud.google.com/vpc/docs/add-remove-network-tags>
       '';
     };
   };
@@ -836,9 +830,9 @@ let
   promTypes.hetzner_sd_config = mkSdConfigModule {
     role = mkOption {
       type = types.enum [ "robot" "hcloud" ];
-      description = ''
+      description = lib.mdDoc ''
         The Hetzner role of entities that should be discovered.
-        One of <literal>robot</literal> or <literal>hcloud</literal>.
+        One of `robot` or `hcloud`.
       '';
     };
 
@@ -855,7 +849,7 @@ let
     options = {
       url = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           URL from which the targets are fetched.
         '';
       };
@@ -892,7 +886,7 @@ let
 
     role = mkOption {
       type = types.enum [ "endpoints" "service" "pod" "node" "ingress" ];
-      description = ''
+      description = lib.mdDoc ''
         The Kubernetes role of entities that should be discovered.
         One of endpoints, service, pod, node, or ingress.
       '';
@@ -923,7 +917,7 @@ let
             options = {
               role = mkOption {
                 type = types.str;
-                description = ''
+                description = lib.mdDoc ''
                   Selector role
                 '';
               };
@@ -957,7 +951,7 @@ let
   promTypes.kuma_sd_config = mkSdConfigModule {
     server = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Address of the Kuma Control Plane's MADS xDS server.
       '';
     };
@@ -982,11 +976,11 @@ let
       '';
 
       access_key = mkOpt types.str ''
-        The AWS API keys. If blank, the environment variable <literal>AWS_ACCESS_KEY_ID</literal> is used.
+        The AWS API keys. If blank, the environment variable `AWS_ACCESS_KEY_ID` is used.
       '';
 
       secret_key = mkOpt types.str ''
-        The AWS API keys. If blank, the environment variable <literal>AWS_SECRET_ACCESS_KEY</literal> is used.
+        The AWS API keys. If blank, the environment variable `AWS_SECRET_ACCESS_KEY` is used.
       '';
 
       profile = mkOpt types.str ''
@@ -1025,7 +1019,7 @@ let
   promTypes.marathon_sd_config = mkSdConfigModule {
     servers = mkOption {
       type = types.listOf types.str;
-      description = ''
+      description = lib.mdDoc ''
         List of URLs to be used to contact Marathon servers. You need to provide at least one server URL.
       '';
     };
@@ -1036,14 +1030,14 @@ let
 
     auth_token = mkOpt types.str ''
       Optional authentication information for token-based authentication:
-      <link xlink:href="https://docs.mesosphere.com/1.11/security/ent/iam-api/#passing-an-authentication-token" />
-      It is mutually exclusive with <literal>auth_token_file</literal> and other authentication mechanisms.
+      <https://docs.mesosphere.com/1.11/security/ent/iam-api/#passing-an-authentication-token>
+      It is mutually exclusive with `auth_token_file` and other authentication mechanisms.
     '';
 
     auth_token_file = mkOpt types.str ''
       Optional authentication information for token-based authentication:
-      <link xlink:href="https://docs.mesosphere.com/1.11/security/ent/iam-api/#passing-an-authentication-token" />
-      It is mutually exclusive with <literal>auth_token</literal> and other authentication mechanisms.
+      <https://docs.mesosphere.com/1.11/security/ent/iam-api/#passing-an-authentication-token>
+      It is mutually exclusive with `auth_token` and other authentication mechanisms.
     '';
   };
 
@@ -1051,14 +1045,14 @@ let
     options = {
       servers = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The Zookeeper servers.
         '';
       };
 
       paths = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Paths can point to a single service, or the root of a tree of services.
         '';
       };
@@ -1100,14 +1094,14 @@ let
       {
         role = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             The OpenStack role of entities that should be discovered.
           '';
         };
 
         region = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             The OpenStack Region.
           '';
         };
@@ -1168,14 +1162,14 @@ let
   promTypes.puppetdb_sd_config = mkSdConfigModule {
     url = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The URL of the PuppetDB root query endpoint.
       '';
     };
 
     query = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Puppet Query Language (PQL) query. Only resources are supported.
         https://puppet.com/docs/puppetdb/latest/api/query/v4/pql.html
       '';
@@ -1204,7 +1198,7 @@ let
     options = {
       access_key = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Access key to use. https://console.scaleway.com/project/credentials
         '';
       };
@@ -1221,14 +1215,14 @@ let
 
       project_id = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Project ID of the targets.
         '';
       };
 
       role = mkOption {
         type = types.enum [ "instance" "baremetal" ];
-        description = ''
+        description = lib.mdDoc ''
           Role of the targets to retrieve. Must be `instance` or `baremetal`.
         '';
       };
@@ -1278,7 +1272,7 @@ let
     options = {
       account = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The account to use for discovering new targets.
         '';
       };
@@ -1291,21 +1285,21 @@ let
 
       dns_suffix = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The DNS suffix which should be applied to target.
         '';
       };
 
       endpoint = mkOption {
         type = types.str;
-        description = ''
-          The Triton discovery endpoint (e.g. <literal>cmon.us-east-3b.triton.zone</literal>). This is
+        description = lib.mdDoc ''
+          The Triton discovery endpoint (e.g. `cmon.us-east-3b.triton.zone`). This is
           often the same value as dns_suffix.
         '';
       };
 
       groups = mkOpt (types.listOf types.str) ''
-        A list of groups for which targets are retrieved, only supported when targeting the <literal>container</literal> role.
+        A list of groups for which targets are retrieved, only supported when targeting the `container` role.
         If omitted all containers owned by the requesting account are scraped.
       '';
 
@@ -1330,21 +1324,21 @@ let
   promTypes.uyuni_sd_config = mkSdConfigModule {
     server = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The URL to connect to the Uyuni server.
       '';
     };
 
     username = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Credentials are used to authenticate the requests to Uyuni API.
       '';
     };
 
     password = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Credentials are used to authenticate the requests to Uyuni API.
       '';
     };
@@ -1366,14 +1360,14 @@ let
     options = {
       targets = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The targets specified by the target group.
         '';
       };
       labels = mkOption {
         type = types.attrsOf types.str;
         default = { };
-        description = ''
+        description = lib.mdDoc ''
           Labels assigned to all metrics scraped from the targets.
         '';
       };
@@ -1429,7 +1423,7 @@ let
     options = {
       url = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           ServerName extension to indicate the name of the server.
           http://tools.ietf.org/html/rfc4366#section-3.1
         '';
@@ -1515,7 +1509,7 @@ let
     options = {
       url = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           ServerName extension to indicate the name of the server.
           http://tools.ietf.org/html/rfc4366#section-3.1
         '';
@@ -1563,23 +1557,19 @@ in
     (mkRenamedOptionModule [ "services" "prometheus2" ] [ "services" "prometheus" ])
     (mkRemovedOptionModule [ "services" "prometheus" "environmentFile" ]
       "It has been removed since it was causing issues (https://github.com/NixOS/nixpkgs/issues/126083) and Prometheus now has native support for secret files, i.e. `basic_auth.password_file` and `authorization.credentials_file`.")
+    (mkRemovedOptionModule [ "services" "prometheus" "alertmanagerTimeout" ]
+      "Deprecated upstream and no longer had any effect")
   ];
 
   options.services.prometheus = {
 
-    enable = mkOption {
-      type = types.bool;
-      default = false;
-      description = ''
-        Enable the Prometheus monitoring daemon.
-      '';
-    };
+    enable = mkEnableOption (lib.mdDoc "Prometheus monitoring daemon");
 
     package = mkOption {
       type = types.package;
       default = pkgs.prometheus;
       defaultText = literalExpression "pkgs.prometheus";
-      description = ''
+      description = lib.mdDoc ''
         The prometheus package that should be used.
       '';
     };
@@ -1587,7 +1577,7 @@ in
     port = mkOption {
       type = types.port;
       default = 9090;
-      description = ''
+      description = lib.mdDoc ''
         Port to listen on.
       '';
     };
@@ -1595,7 +1585,7 @@ in
     listenAddress = mkOption {
       type = types.str;
       default = "0.0.0.0";
-      description = ''
+      description = lib.mdDoc ''
         Address to listen on for the web interface, API, and telemetry.
       '';
     };
@@ -1603,8 +1593,8 @@ in
     stateDir = mkOption {
       type = types.str;
       default = "prometheus2";
-      description = ''
-        Directory below <literal>/var/lib</literal> to store Prometheus metrics data.
+      description = lib.mdDoc ''
+        Directory below `/var/lib` to store Prometheus metrics data.
         This directory will be created automatically using systemd's StateDirectory mechanism.
       '';
     };
@@ -1612,7 +1602,7 @@ in
     extraFlags = mkOption {
       type = types.listOf types.str;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         Extra commandline options when launching Prometheus.
       '';
     };
@@ -1620,11 +1610,11 @@ in
     enableReload = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Reload prometheus when configuration file changes (instead of restart).
 
         The following property holds: switching to a configuration
-        (<literal>switch-to-configuration</literal>) that changes the prometheus
+        (`switch-to-configuration`) that changes the prometheus
         configuration only finishes successully when prometheus has finished
         loading the new configuration.
       '';
@@ -1633,7 +1623,7 @@ in
     configText = mkOption {
       type = types.nullOr types.lines;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         If non-null, this option defines the text that is written to
         prometheus.yml. If null, the contents of prometheus.yml is generated
         from the structured config options.
@@ -1643,7 +1633,7 @@ in
     globalConfig = mkOption {
       type = promTypes.globalConfig;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Parameters that are valid in all  configuration contexts. They
         also serve as defaults for other configuration sections
       '';
@@ -1652,25 +1642,25 @@ in
     remoteRead = mkOption {
       type = types.listOf promTypes.remote_read;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         Parameters of the endpoints to query from.
-        See <link xlink:href="https://prometheus.io/docs/prometheus/latest/configuration/configuration/#remote_read">the official documentation</link> for more information.
+        See [the official documentation](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#remote_read) for more information.
       '';
     };
 
     remoteWrite = mkOption {
       type = types.listOf promTypes.remote_write;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         Parameters of the endpoints to send samples to.
-        See <link xlink:href="https://prometheus.io/docs/prometheus/latest/configuration/configuration/#remote_write">the official documentation</link> for more information.
+        See [the official documentation](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#remote_write) for more information.
       '';
     };
 
     rules = mkOption {
       type = types.listOf types.str;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         Alerting and/or Recording rules to evaluate at runtime.
       '';
     };
@@ -1678,7 +1668,7 @@ in
     ruleFiles = mkOption {
       type = types.listOf types.path;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         Any additional rules files to include in this configuration.
       '';
     };
@@ -1686,7 +1676,7 @@ in
     scrapeConfigs = mkOption {
       type = types.listOf promTypes.scrape_config;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         A list of scrape configurations.
       '';
     };
@@ -1705,49 +1695,44 @@ in
         } ]
       '';
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         A list of alertmanagers to send alerts to.
-        See <link xlink:href="https://prometheus.io/docs/prometheus/latest/configuration/configuration/#alertmanager_config">the official documentation</link> for more information.
+        See [the official documentation](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#alertmanager_config) for more information.
       '';
     };
 
     alertmanagerNotificationQueueCapacity = mkOption {
       type = types.int;
       default = 10000;
-      description = ''
+      description = lib.mdDoc ''
         The capacity of the queue for pending alert manager notifications.
       '';
     };
 
-    alertmanagerTimeout = mkOption {
-      type = types.int;
-      default = 10;
-      description = ''
-        Alert manager HTTP API timeout (in seconds).
-      '';
-    };
-
     webExternalUrl = mkOption {
       type = types.nullOr types.str;
       default = null;
       example = "https://example.com/";
-      description = ''
+      description = lib.mdDoc ''
         The URL under which Prometheus is externally reachable (for example,
         if Prometheus is served via a reverse proxy).
       '';
     };
 
     checkConfig = mkOption {
-      type = types.bool;
+      type = with types; either bool (enum [ "syntax-only" ]);
       default = true;
-      description = ''
-        Check configuration with <literal>promtool
-        check</literal>. The call to <literal>promtool</literal> is
-        subject to sandboxing by Nix. When credentials are stored in
-        external files (<literal>password_file</literal>,
-        <literal>bearer_token_file</literal>, etc), they will not be
-        visible to <literal>promtool</literal> and it will report
-        errors, despite a correct configuration.
+      example = "syntax-only";
+      description = lib.mdDoc ''
+        Check configuration with `promtool check`. The call to `promtool` is
+        subject to sandboxing by Nix.
+
+        If you use credentials stored in external files
+        (`password_file`, `bearer_token_file`, etc),
+        they will not be visible to `promtool`
+        and it will report errors, despite a correct configuration.
+        To resolve this, you may set this option to `"syntax-only"`
+        in order to only syntax check the Prometheus configuration.
       '';
     };
 
@@ -1755,7 +1740,7 @@ in
       type = types.nullOr types.str;
       default = null;
       example = "15d";
-      description = ''
+      description = lib.mdDoc ''
         How long to retain samples in storage.
       '';
     };
@@ -1805,6 +1790,33 @@ in
         WorkingDirectory = workingDir;
         StateDirectory = cfg.stateDir;
         StateDirectoryMode = "0700";
+        # Hardening
+        AmbientCapabilities = lib.mkIf (cfg.port < 1024) [ "CAP_NET_BIND_SERVICE" ];
+        CapabilityBoundingSet = if (cfg.port < 1024) then [ "CAP_NET_BIND_SERVICE" ] else [ "" ];
+        DeviceAllow = [ "/dev/null rw" ];
+        DevicePolicy = "strict";
+        LockPersonality = true;
+        MemoryDenyWriteExecute = true;
+        NoNewPrivileges = true;
+        PrivateDevices = true;
+        PrivateTmp = true;
+        PrivateUsers = true;
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectProc = "invisible";
+        ProtectSystem = "full";
+        RemoveIPC = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        RestrictSUIDSGID = true;
+        SystemCallArchitectures = "native";
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
       };
     };
     # prometheus-config-reload will activate after prometheus. However, what we
diff --git a/nixos/modules/services/monitoring/prometheus/exporters.nix b/nixos/modules/services/monitoring/prometheus/exporters.nix
index 41302d6d3ce..8826d80a70c 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters.nix
@@ -36,6 +36,7 @@ let
     "fastly"
     "fritzbox"
     "influxdb"
+    "ipmi"
     "json"
     "jitsi"
     "kea"
@@ -72,40 +73,42 @@ let
     "unbound"
     "unifi"
     "unifi-poller"
+    "v2ray"
     "varnish"
     "wireguard"
     "flow"
+    "zfs"
   ] (name:
     import (./. + "/exporters/${name}.nix") { inherit config lib pkgs options; }
   );
 
   mkExporterOpts = ({ name, port }: {
-    enable = mkEnableOption "the prometheus ${name} exporter";
+    enable = mkEnableOption (lib.mdDoc "the prometheus ${name} exporter");
     port = mkOption {
       type = types.port;
       default = port;
-      description = ''
+      description = lib.mdDoc ''
         Port to listen on.
       '';
     };
     listenAddress = mkOption {
       type = types.str;
       default = "0.0.0.0";
-      description = ''
+      description = lib.mdDoc ''
         Address to listen on.
       '';
     };
     extraFlags = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Extra commandline options to pass to the ${name} exporter.
       '';
     };
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Open port in firewall for incoming connections.
       '';
     };
@@ -115,23 +118,23 @@ let
       example = literalExpression ''
         "-i eth0 -p tcp -m tcp --dport ${toString port}"
       '';
-      description = ''
+      description = lib.mdDoc ''
         Specify a filter for iptables to use when
-        <option>services.prometheus.exporters.${name}.openFirewall</option>
-        is true. It is used as `ip46tables -I nixos-fw <option>firewallFilter</option> -j nixos-fw-accept`.
+        {option}`services.prometheus.exporters.${name}.openFirewall`
+        is true. It is used as `ip46tables -I nixos-fw firewallFilter -j nixos-fw-accept`.
       '';
     };
     user = mkOption {
       type = types.str;
       default = "${name}-exporter";
-      description = ''
+      description = lib.mdDoc ''
         User name under which the ${name} exporter shall be run.
       '';
     };
     group = mkOption {
       type = types.str;
       default = "${name}-exporter";
-      description = ''
+      description = lib.mdDoc ''
         Group under which the ${name} exporter shall be run.
       '';
     };
@@ -194,7 +197,7 @@ let
         serviceConfig.LockPersonality = true;
         serviceConfig.MemoryDenyWriteExecute = true;
         serviceConfig.NoNewPrivileges = true;
-        serviceConfig.PrivateDevices = true;
+        serviceConfig.PrivateDevices = mkDefault true;
         serviceConfig.ProtectClock = mkDefault true;
         serviceConfig.ProtectControlGroups = true;
         serviceConfig.ProtectHome = true;
@@ -227,7 +230,7 @@ in
     type = types.submodule {
       options = (mkSubModules);
     };
-    description = "Prometheus exporter configuration";
+    description = lib.mdDoc "Prometheus exporter configuration";
     default = {};
     example = literalExpression ''
       {
@@ -242,6 +245,22 @@ in
 
   config = mkMerge ([{
     assertions = [ {
+      assertion = cfg.ipmi.enable -> (cfg.ipmi.configFile != null) -> (
+        !(lib.hasPrefix "/tmp/" cfg.ipmi.configFile)
+      );
+      message = ''
+        Config file specified in `services.prometheus.exporters.ipmi.configFile' must
+          not reside within /tmp - it won't be visible to the systemd service.
+      '';
+    } {
+      assertion = cfg.ipmi.enable -> (cfg.ipmi.webConfigFile != null) -> (
+        !(lib.hasPrefix "/tmp/" cfg.ipmi.webConfigFile)
+      );
+      message = ''
+        Config file specified in `services.prometheus.exporters.ipmi.webConfigFile' must
+          not reside within /tmp - it won't be visible to the systemd service.
+      '';
+    } {
       assertion = cfg.snmp.enable -> (
         (cfg.snmp.configurationPath == null) != (cfg.snmp.configuration == null)
       );
diff --git a/nixos/modules/services/monitoring/prometheus/exporters.xml b/nixos/modules/services/monitoring/prometheus/exporters.xml
index c2d4b05996a..1df88bb61a1 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters.xml
+++ b/nixos/modules/services/monitoring/prometheus/exporters.xml
@@ -19,6 +19,7 @@
 <programlisting>
   services.prometheus.exporters.node = {
     enable = true;
+    port = 9100;
     enabledCollectors = [
       "logind"
       "systemd"
@@ -42,6 +43,26 @@
    <link xlink:href="https://nixos.org/nixos/options.html#prometheus.exporters">available
    options</link>.
   </para>
+
+  <para>
+    Prometheus can now be configured to consume the metrics produced by the exporter:
+    <programlisting>
+    services.prometheus = {
+      # ...
+
+      scrapeConfigs = [
+        {
+          job_name = "node";
+          static_configs = [{
+            targets = [ "localhost:${toString config.services.prometheus.exporters.node.port}" ];
+          }];
+        }
+      ];
+
+      # ...
+    }
+    </programlisting>
+  </para>
  </section>
  <section xml:id="module-services-prometheus-exporters-new-exporter">
   <title>Adding a new exporter</title>
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/apcupsd.nix b/nixos/modules/services/monitoring/prometheus/exporters/apcupsd.nix
index 57c35a742c5..a8a9f84ea8e 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/apcupsd.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/apcupsd.nix
@@ -11,7 +11,7 @@ in
     apcupsdAddress = mkOption {
       type = types.str;
       default = ":3551";
-      description = ''
+      description = lib.mdDoc ''
         Address of the apcupsd Network Information Server (NIS).
       '';
     };
@@ -19,7 +19,7 @@ in
     apcupsdNetwork = mkOption {
       type = types.enum ["tcp" "tcp4" "tcp6"];
       default = "tcp";
-      description = ''
+      description = lib.mdDoc ''
         Network of the apcupsd Network Information Server (NIS): one of "tcp", "tcp4", or "tcp6".
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/artifactory.nix b/nixos/modules/services/monitoring/prometheus/exporters/artifactory.nix
index 2adcecc728b..bc67fe59b3b 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/artifactory.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/artifactory.nix
@@ -11,14 +11,14 @@ in
     scrapeUri = mkOption {
       type = types.str;
       default = "http://localhost:8081/artifactory";
-      description = ''
+      description = lib.mdDoc ''
         URI on which to scrape JFrog Artifactory.
       '';
     };
 
     artiUsername = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Username for authentication against JFrog Artifactory API.
       '';
     };
@@ -26,7 +26,7 @@ in
     artiPassword = mkOption {
       type = types.str;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Password for authentication against JFrog Artifactory API.
         One of the password or access token needs to be set.
       '';
@@ -35,7 +35,7 @@ in
     artiAccessToken = mkOption {
       type = types.str;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Access token for authentication against JFrog Artifactory API.
         One of the password or access token needs to be set.
       '';
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/bind.nix b/nixos/modules/services/monitoring/prometheus/exporters/bind.nix
index 16c2920751d..bd2003f0650 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/bind.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/bind.nix
@@ -11,28 +11,28 @@ in
     bindURI = mkOption {
       type = types.str;
       default = "http://localhost:8053/";
-      description = ''
+      description = lib.mdDoc ''
         HTTP XML API address of an Bind server.
       '';
     };
     bindTimeout = mkOption {
       type = types.str;
       default = "10s";
-      description = ''
+      description = lib.mdDoc ''
         Timeout for trying to get stats from Bind.
       '';
     };
     bindVersion = mkOption {
       type = types.enum [ "xml.v2" "xml.v3" "auto" ];
       default = "auto";
-      description = ''
+      description = lib.mdDoc ''
         BIND statistics version. Can be detected automatically.
       '';
     };
     bindGroups = mkOption {
       type = types.listOf (types.enum [ "server" "view" "tasks" ]);
       default = [ "server" "view" ];
-      description = ''
+      description = lib.mdDoc ''
         List of statistics to collect. Available: [server, view, tasks]
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/bird.nix b/nixos/modules/services/monitoring/prometheus/exporters/bird.nix
index 1ef264fc86e..5f6c36f4c56 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/bird.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/bird.nix
@@ -11,21 +11,21 @@ in
     birdVersion = mkOption {
       type = types.enum [ 1 2 ];
       default = 2;
-      description = ''
+      description = lib.mdDoc ''
         Specifies whether BIRD1 or BIRD2 is in use.
       '';
     };
     birdSocket = mkOption {
       type = types.path;
-      default = "/var/run/bird.ctl";
-      description = ''
+      default = "/run/bird/bird.ctl";
+      description = lib.mdDoc ''
         Path to BIRD2 (or BIRD1 v4) socket.
       '';
     };
     newMetricFormat = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Enable the new more-generic metric format.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/bitcoin.nix b/nixos/modules/services/monitoring/prometheus/exporters/bitcoin.nix
index 43721f70b49..330d5412644 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/bitcoin.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/bitcoin.nix
@@ -11,14 +11,14 @@ in
     rpcUser = mkOption {
       type = types.str;
       default = "bitcoinrpc";
-      description = ''
+      description = lib.mdDoc ''
         RPC user name.
       '';
     };
 
     rpcPasswordFile = mkOption {
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         File containing RPC password.
       '';
     };
@@ -26,7 +26,7 @@ in
     rpcScheme = mkOption {
       type = types.enum [ "http" "https" ];
       default = "http";
-      description = ''
+      description = lib.mdDoc ''
         Whether to connect to bitcoind over http or https.
       '';
     };
@@ -34,7 +34,7 @@ in
     rpcHost = mkOption {
       type = types.str;
       default = "localhost";
-      description = ''
+      description = lib.mdDoc ''
         RPC host.
       '';
     };
@@ -42,7 +42,7 @@ in
     rpcPort = mkOption {
       type = types.port;
       default = 8332;
-      description = ''
+      description = lib.mdDoc ''
         RPC port number.
       '';
     };
@@ -50,7 +50,7 @@ in
     refreshSeconds = mkOption {
       type = types.ints.unsigned;
       default = 300;
-      description = ''
+      description = lib.mdDoc ''
         How often to ask bitcoind for metrics.
       '';
     };
@@ -58,7 +58,7 @@ in
     extraEnv = mkOption {
       type = types.attrsOf types.str;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         Extra environment variables for the exporter.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/blackbox.nix b/nixos/modules/services/monitoring/prometheus/exporters/blackbox.nix
index fe8d905da3f..66eaed51d2e 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/blackbox.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/blackbox.nix
@@ -35,14 +35,14 @@ in {
   extraOpts = {
     configFile = mkOption {
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Path to configuration file.
       '';
     };
     enableConfigCheck = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to run a correctness check for the configuration file. This depends
         on the configuration file residing in the nix-store. Paths passed as string will
         be copied to the store.
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/buildkite-agent.nix b/nixos/modules/services/monitoring/prometheus/exporters/buildkite-agent.nix
index e9be39608fc..0515b72b13f 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/buildkite-agent.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/buildkite-agent.nix
@@ -11,7 +11,7 @@ in
     tokenPath = mkOption {
       type = types.nullOr types.path;
       apply = final: if final == null then null else toString final;
-      description = ''
+      description = lib.mdDoc ''
         The token from your Buildkite "Agents" page.
 
         A run-time path to the token file, which is supposed to be provisioned
@@ -22,14 +22,14 @@ in
       type = types.str;
       default = "30s";
       example = "1min";
-      description = ''
+      description = lib.mdDoc ''
         How often to update metrics.
       '';
     };
     endpoint = mkOption {
       type = types.str;
       default = "https://agent.buildkite.com/v3";
-      description = ''
+      description = lib.mdDoc ''
         The Buildkite Agent API endpoint.
       '';
     };
@@ -37,7 +37,7 @@ in
       type = with types; nullOr (listOf str);
       default = null;
       example = literalExpression ''[ "my-queue1" "my-queue2" ]'';
-      description = ''
+      description = lib.mdDoc ''
         Which specific queues to process.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/collectd.nix b/nixos/modules/services/monitoring/prometheus/exporters/collectd.nix
index a7f4d3e096f..0c2de683ecf 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/collectd.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/collectd.nix
@@ -9,24 +9,24 @@ in
   port = 9103;
   extraOpts = {
     collectdBinary = {
-      enable = mkEnableOption "collectd binary protocol receiver";
+      enable = mkEnableOption (lib.mdDoc "collectd binary protocol receiver");
 
       authFile = mkOption {
         default = null;
         type = types.nullOr types.path;
-        description = "File mapping user names to pre-shared keys (passwords).";
+        description = lib.mdDoc "File mapping user names to pre-shared keys (passwords).";
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 25826;
-        description = "Network address on which to accept collectd binary network packets.";
+        description = lib.mdDoc "Network address on which to accept collectd binary network packets.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           Address to listen on for binary network packets.
           '';
       };
@@ -34,7 +34,7 @@ in
       securityLevel = mkOption {
         type = types.enum ["None" "Sign" "Encrypt"];
         default = "None";
-        description = ''
+        description = lib.mdDoc ''
           Minimum required security level for accepted packets.
         '';
       };
@@ -44,7 +44,7 @@ in
       type = types.enum [ "logfmt" "json" ];
       default = "logfmt";
       example = "json";
-      description = ''
+      description = lib.mdDoc ''
         Set the log format.
       '';
     };
@@ -52,7 +52,7 @@ in
     logLevel = mkOption {
       type = types.enum ["debug" "info" "warn" "error" "fatal"];
       default = "info";
-      description = ''
+      description = lib.mdDoc ''
         Only log messages with the given severity or above.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/dmarc.nix b/nixos/modules/services/monitoring/prometheus/exporters/dmarc.nix
index 330610a15d9..437cece588a 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/dmarc.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/dmarc.nix
@@ -24,28 +24,28 @@ in {
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           Hostname of IMAP server to connect to.
         '';
       };
       port = mkOption {
         type = types.port;
         default = 993;
-        description = ''
+        description = lib.mdDoc ''
           Port of the IMAP server to connect to.
         '';
       };
       username = mkOption {
         type = types.str;
         example = "postmaster@example.org";
-        description = ''
+        description = lib.mdDoc ''
           Login username for the IMAP connection.
         '';
       };
       passwordFile = mkOption {
         type = types.str;
         example = "/run/secrets/dovecot_pw";
-        description = ''
+        description = lib.mdDoc ''
           File containing the login password for the IMAP connection.
         '';
       };
@@ -54,21 +54,21 @@ in {
       inbox = mkOption {
         type = types.str;
         default = "INBOX";
-        description = ''
+        description = lib.mdDoc ''
           IMAP mailbox that is checked for incoming DMARC aggregate reports
         '';
       };
       done = mkOption {
         type = types.str;
         default = "Archive";
-        description = ''
+        description = lib.mdDoc ''
           IMAP mailbox that successfully processed reports are moved to.
         '';
       };
       error = mkOption {
         type = types.str;
         default = "Invalid";
-        description = ''
+        description = lib.mdDoc ''
           IMAP mailbox that emails are moved to that could not be processed.
         '';
       };
@@ -76,7 +76,7 @@ in {
     pollIntervalSeconds = mkOption {
       type = types.ints.unsigned;
       default = 60;
-      description = ''
+      description = lib.mdDoc ''
         How often to poll the IMAP server in seconds.
       '';
     };
@@ -84,7 +84,7 @@ in {
       type = types.ints.unsigned;
       default = 604800;
       defaultText = "7 days (in seconds)";
-      description = ''
+      description = lib.mdDoc ''
         How long individual report IDs will be remembered to avoid
         counting double delivered reports twice.
       '';
@@ -92,8 +92,8 @@ in {
     debug = mkOption {
       type = types.bool;
       default = false;
-      description = ''
-        Whether to declare enable <literal>--debug</literal>.
+      description = lib.mdDoc ''
+        Whether to declare enable `--debug`.
       '';
     };
   };
@@ -108,7 +108,7 @@ in {
           -i ${pkgs.writeText "dmarc-exporter.json.template" json} \
           -o ''${STATE_DIRECTORY}/dmarc-exporter.json
 
-        exec ${pkgs.prometheus-dmarc-exporter}/bin/prometheus-dmarc-exporter \
+        exec ${pkgs.dmarc-metrics-exporter}/bin/dmarc-metrics-exporter \
           --configuration /var/lib/prometheus-dmarc-exporter/dmarc-exporter.json \
           ${optionalString cfg.debug "--debug"}
       ''}";
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/dnsmasq.nix b/nixos/modules/services/monitoring/prometheus/exporters/dnsmasq.nix
index 68afba21d64..ece42a34cb0 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/dnsmasq.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/dnsmasq.nix
@@ -11,7 +11,7 @@ in
     dnsmasqListenAddress = mkOption {
       type = types.str;
       default = "localhost:53";
-      description = ''
+      description = lib.mdDoc ''
         Address on which dnsmasq listens.
       '';
     };
@@ -19,8 +19,8 @@ in
       type = types.path;
       default = "/var/lib/misc/dnsmasq.leases";
       example = "/var/lib/dnsmasq/dnsmasq.leases";
-      description = ''
-        Path to the <literal>dnsmasq.leases</literal> file.
+      description = lib.mdDoc ''
+        Path to the `dnsmasq.leases` file.
       '';
     };
   };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/dovecot.nix b/nixos/modules/services/monitoring/prometheus/exporters/dovecot.nix
index 092ac6fea7d..6fb438353a4 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/dovecot.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/dovecot.nix
@@ -11,7 +11,7 @@ in
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
@@ -19,24 +19,24 @@ in
       type = types.path;
       default = "/var/run/dovecot/stats";
       example = "/var/run/dovecot2/old-stats";
-      description = ''
+      description = lib.mdDoc ''
         Path under which the stats socket is placed.
         The user/group under which the exporter runs,
         should be able to access the socket in order
         to scrape the metrics successfully.
 
         Please keep in mind that the stats module has changed in
-        <link xlink:href="https://wiki2.dovecot.org/Upgrading/2.3">Dovecot 2.3+</link> which
-        is not <link xlink:href="https://github.com/kumina/dovecot_exporter/issues/8">compatible with this exporter</link>.
+        [Dovecot 2.3+](https://wiki2.dovecot.org/Upgrading/2.3) which
+        is not [compatible with this exporter](https://github.com/kumina/dovecot_exporter/issues/8).
 
         The following extra config has to be passed to Dovecot to ensure that recent versions
         work with this exporter:
-        <programlisting>
+        ```
         {
-          <xref linkend="opt-services.prometheus.exporters.dovecot.enable" /> = true;
-          <xref linkend="opt-services.prometheus.exporters.dovecot.socketPath" /> = "/var/run/dovecot2/old-stats";
-          <xref linkend="opt-services.dovecot2.mailPlugins.globally.enable" /> = [ "old_stats" ];
-          <xref linkend="opt-services.dovecot2.extraConfig" /> = '''
+          services.prometheus.exporters.dovecot.enable = true;
+          services.prometheus.exporters.dovecot.socketPath = "/var/run/dovecot2/old-stats";
+          services.dovecot2.mailPlugins.globally.enable = [ "old_stats" ];
+          services.dovecot2.extraConfig = '''
             service old-stats {
               unix_listener old-stats {
                 user = dovecot-exporter
@@ -60,14 +60,14 @@ in
             }
           ''';
         }
-        </programlisting>
+        ```
       '';
     };
     scopes = mkOption {
       type = types.listOf types.str;
       default = [ "user" ];
       example = [ "user" "global" ];
-      description = ''
+      description = lib.mdDoc ''
         Stats scopes to query.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/fastly.nix b/nixos/modules/services/monitoring/prometheus/exporters/fastly.nix
index 55a61c4949e..36409caccf2 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/fastly.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/fastly.nix
@@ -7,14 +7,14 @@ in
 {
   port = 9118;
   extraOpts = {
-    debug = mkEnableOption "Debug logging mode for fastly-exporter";
+    debug = mkEnableOption (lib.mdDoc "Debug logging mode for fastly-exporter");
 
     configFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Path to a fastly-exporter configuration file.
-        Example one can be generated with <literal>fastly-exporter --config-file-example</literal>.
+        Example one can be generated with `fastly-exporter --config-file-example`.
       '';
       example = "./fastly-exporter-config.txt";
     };
@@ -22,7 +22,7 @@ in
     tokenPath = mkOption {
       type = types.nullOr types.path;
       apply = final: if final == null then null else toString final;
-      description = ''
+      description = lib.mdDoc ''
         A run-time path to the token file, which is supposed to be provisioned
         outside of Nix store.
       '';
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/flow.nix b/nixos/modules/services/monitoring/prometheus/exporters/flow.nix
index b85e5461f21..81099aaf170 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/flow.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/flow.nix
@@ -10,19 +10,19 @@ in {
     brokers = mkOption {
       type = types.listOf types.str;
       example = literalExpression ''[ "kafka.example.org:19092" ]'';
-      description = "List of Kafka brokers to connect to.";
+      description = lib.mdDoc "List of Kafka brokers to connect to.";
     };
 
     asn = mkOption {
       type = types.ints.positive;
       example = 65542;
-      description = "The ASN being monitored.";
+      description = lib.mdDoc "The ASN being monitored.";
     };
 
     partitions = mkOption {
       type = types.listOf types.int;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         The number of the partitions to consume, none means all.
       '';
     };
@@ -30,7 +30,7 @@ in {
     topic = mkOption {
       type = types.str;
       example = "pmacct.acct";
-      description = "The Kafka topic to consume from.";
+      description = lib.mdDoc "The Kafka topic to consume from.";
     };
   };
 
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/fritzbox.nix b/nixos/modules/services/monitoring/prometheus/exporters/fritzbox.nix
index 9526597b8c9..dc53d21406f 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/fritzbox.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/fritzbox.nix
@@ -11,7 +11,7 @@ in
     gatewayAddress = mkOption {
       type = types.str;
       default = "fritz.box";
-      description = ''
+      description = lib.mdDoc ''
         The hostname or IP of the FRITZ!Box.
       '';
     };
@@ -19,7 +19,7 @@ in
     gatewayPort = mkOption {
       type = types.int;
       default = 49000;
-      description = ''
+      description = lib.mdDoc ''
         The port of the FRITZ!Box UPnP service.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/influxdb.nix b/nixos/modules/services/monitoring/prometheus/exporters/influxdb.nix
index ba45173e946..61c0c08d225 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/influxdb.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/influxdb.nix
@@ -12,13 +12,13 @@ in
       type = types.str;
       default = "5m";
       example = "10m";
-      description = "How long a sample is valid for";
+      description = lib.mdDoc "How long a sample is valid for";
     };
     udpBindAddress = mkOption {
       type = types.str;
       default = ":9122";
       example = "192.0.2.1:9122";
-      description = "Address on which to listen for udp packets";
+      description = lib.mdDoc "Address on which to listen for udp packets";
     };
   };
   serviceOpts = {
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/ipmi.nix b/nixos/modules/services/monitoring/prometheus/exporters/ipmi.nix
new file mode 100644
index 00000000000..55c4f4aa482
--- /dev/null
+++ b/nixos/modules/services/monitoring/prometheus/exporters/ipmi.nix
@@ -0,0 +1,41 @@
+{ config, lib, pkgs, options }:
+
+with lib;
+
+let
+  logPrefix = "services.prometheus.exporter.ipmi";
+  cfg = config.services.prometheus.exporters.ipmi;
+in {
+  port = 9290;
+
+  extraOpts = {
+    configFile = mkOption {
+      type = types.nullOr types.path;
+      default = null;
+      description = lib.mdDoc ''
+        Path to configuration file.
+      '';
+    };
+
+    webConfigFile = mkOption {
+      type = types.nullOr types.path;
+      default = null;
+      description = lib.mdDoc ''
+        Path to configuration file that can enable TLS or authentication.
+      '';
+    };
+  };
+
+  serviceOpts.serviceConfig = {
+    ExecStart = with cfg; concatStringsSep " " ([
+      "${pkgs.prometheus-ipmi-exporter}/bin/ipmi_exporter"
+      "--web.listen-address ${listenAddress}:${toString port}"
+    ] ++ optionals (cfg.webConfigFile != null) [
+      "--web.config.file ${escapeShellArg cfg.webConfigFile}"
+    ] ++ optionals (cfg.configFile != null) [
+      "--config.file ${escapeShellArg cfg.configFile}"
+    ] ++ extraFlags);
+
+    ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
+  };
+}
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/jitsi.nix b/nixos/modules/services/monitoring/prometheus/exporters/jitsi.nix
index c93a8f98e55..02460271860 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/jitsi.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/jitsi.nix
@@ -11,7 +11,7 @@ in
     url = mkOption {
       type = types.str;
       default = "http://localhost:8080/colibri/stats";
-      description = ''
+      description = lib.mdDoc ''
         Jitsi Videobridge metrics URL to monitor.
         This is usually /colibri/stats on port 8080 of the jitsi videobridge host.
       '';
@@ -20,7 +20,7 @@ in
       type = types.str;
       default = "30s";
       example = "1min";
-      description = ''
+      description = lib.mdDoc ''
         How often to scrape new data
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/json.nix b/nixos/modules/services/monitoring/prometheus/exporters/json.nix
index 1800da69a25..473f3a7e47e 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/json.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/json.nix
@@ -10,7 +10,7 @@ in
   extraOpts = {
     configFile = mkOption {
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Path to configuration file.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/kea.nix b/nixos/modules/services/monitoring/prometheus/exporters/kea.nix
index 27aeb909624..ed33c72f644 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/kea.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/kea.nix
@@ -19,19 +19,23 @@ in {
           "/run/kea/kea-dhcp6.socket"
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         Paths to kea control sockets
       '';
     };
   };
   serviceOpts = {
+    after = [
+      "kea-dhcp4-server.service"
+      "kea-dhcp6-server.service"
+    ];
     serviceConfig = {
       User = "kea";
       ExecStart = ''
         ${pkgs.prometheus-kea-exporter}/bin/kea-exporter \
           --address ${cfg.listenAddress} \
           --port ${toString cfg.port} \
-          ${concatStringsSep " \\n" cfg.controlSocketPaths}
+          ${concatStringsSep " " cfg.controlSocketPaths}
       '';
       SupplementaryGroups = [ "kea" ];
       RestrictAddressFamilies = [
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/knot.nix b/nixos/modules/services/monitoring/prometheus/exporters/knot.nix
index 29e543f1013..a73425b37da 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/knot.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/knot.nix
@@ -11,24 +11,23 @@ in {
       type = types.str;
       default = "${pkgs.knot-dns.out}/lib/libknot.so";
       defaultText = literalExpression ''"''${pkgs.knot-dns.out}/lib/libknot.so"'';
-      description = ''
-        Path to the library of <package>knot-dns</package>.
+      description = lib.mdDoc ''
+        Path to the library of `knot-dns`.
       '';
     };
 
     knotSocketPath = mkOption {
       type = types.str;
       default = "/run/knot/knot.sock";
-      description = ''
-        Socket path of <citerefentry><refentrytitle>knotd</refentrytitle>
-        <manvolnum>8</manvolnum></citerefentry>.
+      description = lib.mdDoc ''
+        Socket path of {manpage}`knotd(8)`.
       '';
     };
 
     knotSocketTimeout = mkOption {
       type = types.int;
       default = 2000;
-      description = ''
+      description = lib.mdDoc ''
         Timeout in seconds.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/lnd.nix b/nixos/modules/services/monitoring/prometheus/exporters/lnd.nix
index 35f97202057..9f914b1dc14 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/lnd.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/lnd.nix
@@ -11,21 +11,21 @@ in
     lndHost = mkOption {
       type = types.str;
       default = "localhost:10009";
-      description = ''
+      description = lib.mdDoc ''
         lnd instance gRPC address:port.
       '';
     };
 
     lndTlsPath = mkOption {
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Path to lnd TLS certificate.
       '';
     };
 
     lndMacaroonDir = mkOption {
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Path to lnd macaroons.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/mail.nix b/nixos/modules/services/monitoring/prometheus/exporters/mail.nix
index 956bd96aa45..15079f5841f 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/mail.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/mail.nix
@@ -5,6 +5,8 @@ with lib;
 let
   cfg = config.services.prometheus.exporters.mail;
 
+  configFile = if cfg.configuration != null then configurationFile else (escapeShellArg cfg.configFile);
+
   configurationFile = pkgs.writeText "prometheus-mail-exporter.conf" (builtins.toJSON (
     # removes the _module attribute, null values and converts attrNames to lowercase
     mapAttrs' (name: value:
@@ -20,41 +22,41 @@ let
   serverOptions.options = {
     name = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Value for label 'configname' which will be added to all metrics.
       '';
     };
     server = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Hostname of the server that should be probed.
       '';
     };
     port = mkOption {
-      type = types.int;
+      type = types.port;
       example = 587;
-      description = ''
+      description = lib.mdDoc ''
         Port to use for SMTP.
       '';
     };
     from = mkOption {
       type = types.str;
       example = "exporteruser@domain.tld";
-      description = ''
+      description = lib.mdDoc ''
         Content of 'From' Header for probing mails.
       '';
     };
     to = mkOption {
       type = types.str;
       example = "exporteruser@domain.tld";
-      description = ''
+      description = lib.mdDoc ''
         Content of 'To' Header for probing mails.
       '';
     };
     detectionDir = mkOption {
       type = types.path;
       example = "/var/spool/mail/exporteruser/new";
-      description = ''
+      description = lib.mdDoc ''
         Directory in which new mails for the exporter user are placed.
         Note that this needs to exist when the exporter starts.
       '';
@@ -63,14 +65,14 @@ let
       type = types.nullOr types.str;
       default = null;
       example = "exporteruser@domain.tld";
-      description = ''
+      description = lib.mdDoc ''
         Username to use for SMTP authentication.
       '';
     };
     passphrase = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Password to use for SMTP authentication.
       '';
     };
@@ -80,20 +82,20 @@ let
     monitoringInterval = mkOption {
       type = types.str;
       example = "10s";
-      description = ''
+      description = lib.mdDoc ''
         Time interval between two probe attempts.
       '';
     };
     mailCheckTimeout = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Timeout until mails are considered "didn't make it".
       '';
     };
     disableFileDeletion = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Disables the exporter's function to delete probing mails.
       '';
     };
@@ -110,17 +112,16 @@ let
           detectionDir = "/path/to/Maildir/new";
         } ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         List of servers that should be probed.
 
-        <emphasis>Note:</emphasis> if your mailserver has <citerefentry>
-        <refentrytitle>rspamd</refentrytitle><manvolnum>8</manvolnum></citerefentry> configured,
+        *Note:* if your mailserver has {manpage}`rspamd(8)` configured,
         it can happen that emails from this exporter are marked as spam.
 
         It's possible to work around the issue with a config like this:
-        <programlisting>
+        ```
         {
-          <link linkend="opt-services.rspamd.locals._name_.text">services.rspamd.locals."multimap.conf".text</link> = '''
+          services.rspamd.locals."multimap.conf".text = '''
             ALLOWLIST_PROMETHEUS {
               filter = "email:domain:tld";
               type = "from";
@@ -129,7 +130,7 @@ let
             }
           ''';
         }
-        </programlisting>
+        ```
       '';
     };
   };
@@ -137,24 +138,31 @@ in
 {
   port = 9225;
   extraOpts = {
+    environmentFile = mkOption {
+      type = types.nullOr types.str;
+      default = null;
+      description = lib.mdDoc ''
+        File containing env-vars to be substituted into the exporter's config.
+      '';
+    };
     configFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Specify the mailexporter configuration file to use.
       '';
     };
     configuration = mkOption {
       type = types.nullOr (types.submodule exporterOptions);
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Specify the mailexporter configuration file to use.
       '';
     };
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
@@ -162,13 +170,19 @@ in
   serviceOpts = {
     serviceConfig = {
       DynamicUser = false;
+      EnvironmentFile = mkIf (cfg.environmentFile != null) [ cfg.environmentFile ];
+      RuntimeDirectory = "prometheus-mail-exporter";
+      ExecStartPre = [
+        "${pkgs.writeShellScript "subst-secrets-mail-exporter" ''
+          umask 0077
+          ${pkgs.envsubst}/bin/envsubst -i ${configFile} -o ''${RUNTIME_DIRECTORY}/mail-exporter.json
+        ''}"
+      ];
       ExecStart = ''
         ${pkgs.prometheus-mail-exporter}/bin/mailexporter \
           --web.listen-address ${cfg.listenAddress}:${toString cfg.port} \
           --web.telemetry-path ${cfg.telemetryPath} \
-          --config.file ${
-            if cfg.configuration != null then configurationFile else (escapeShellArg cfg.configFile)
-          } \
+          --config.file ''${RUNTIME_DIRECTORY}/mail-exporter.json \
           ${concatStringsSep " \\\n  " cfg.extraFlags}
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/mikrotik.nix b/nixos/modules/services/monitoring/prometheus/exporters/mikrotik.nix
index 8f9536b702a..54dab4b5581 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/mikrotik.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/mikrotik.nix
@@ -11,9 +11,9 @@ in
     configFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Path to a mikrotik exporter configuration file. Mutually exclusive with
-        <option>configuration</option> option.
+        {option}`configuration` option.
       '';
       example = literalExpression "./mikrotik.yml";
     };
@@ -21,11 +21,11 @@ in
     configuration = mkOption {
       type = types.nullOr types.attrs;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Mikrotik exporter configuration as nix attribute set. Mutually exclusive with
-        <option>configFile</option> option.
+        {option}`configFile` option.
 
-        See <link xlink:href="https://github.com/nshttpd/mikrotik-exporter/blob/master/README.md"/>
+        See <https://github.com/nshttpd/mikrotik-exporter/blob/master/README.md>
         for the description of the configuration file format.
       '';
       example = literalExpression ''
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/minio.nix b/nixos/modules/services/monitoring/prometheus/exporters/minio.nix
index d6dd62f871b..82cc3fc314f 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/minio.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/minio.nix
@@ -11,7 +11,7 @@ in
     minioAddress = mkOption {
       type = types.str;
       example = "https://10.0.0.1:9000";
-      description = ''
+      description = lib.mdDoc ''
         The URL of the minio server.
         Use HTTPS if Minio accepts secure connections only.
         By default this connects to the local minio server if enabled.
@@ -21,28 +21,28 @@ in
     minioAccessKey = mkOption {
       type = types.str;
       example = "yourMinioAccessKey";
-      description = ''
+      description = lib.mdDoc ''
         The value of the Minio access key.
         It is required in order to connect to the server.
         By default this uses the one from the local minio server if enabled
-        and <literal>config.services.minio.accessKey</literal>.
+        and `config.services.minio.accessKey`.
       '';
     };
 
     minioAccessSecret = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The value of the Minio access secret.
         It is required in order to connect to the server.
         By default this uses the one from the local minio server if enabled
-        and <literal>config.services.minio.secretKey</literal>.
+        and `config.services.minio.secretKey`.
       '';
     };
 
     minioBucketStats = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Collect statistics about the buckets and files in buckets.
         It requires more computation, use it carefully in case of large buckets..
       '';
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/modemmanager.nix b/nixos/modules/services/monitoring/prometheus/exporters/modemmanager.nix
index afd03f6c270..222ea3e5384 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/modemmanager.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/modemmanager.nix
@@ -11,7 +11,7 @@ in
     refreshRate = mkOption {
       type = types.str;
       default = "5s";
-      description = ''
+      description = lib.mdDoc ''
         How frequently ModemManager will refresh the extended signal quality
         information for each modem. The duration should be specified in seconds
         ("5s"), minutes ("1m"), or hours ("1h").
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/nextcloud.nix b/nixos/modules/services/monitoring/prometheus/exporters/nextcloud.nix
index ce7125bf5a8..7808c8861a7 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/nextcloud.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/nextcloud.nix
@@ -11,16 +11,16 @@ in
     url = mkOption {
       type = types.str;
       example = "https://domain.tld";
-      description = ''
+      description = lib.mdDoc ''
         URL to the Nextcloud serverinfo page.
         Adding the path to the serverinfo API is optional, it defaults
-        to <literal>/ocs/v2.php/apps/serverinfo/api/v1/info</literal>.
+        to `/ocs/v2.php/apps/serverinfo/api/v1/info`.
       '';
     };
     username = mkOption {
       type = types.str;
       default = "nextcloud-exporter";
-      description = ''
+      description = lib.mdDoc ''
         Username for connecting to Nextcloud.
         Note that this account needs to have admin privileges in Nextcloud.
       '';
@@ -28,7 +28,7 @@ in
     passwordFile = mkOption {
       type = types.path;
       example = "/path/to/password-file";
-      description = ''
+      description = lib.mdDoc ''
         File containing the password for connecting to Nextcloud.
         Make sure that this file is readable by the exporter user.
       '';
@@ -36,7 +36,7 @@ in
     timeout = mkOption {
       type = types.str;
       default = "5s";
-      description = ''
+      description = lib.mdDoc ''
         Timeout for getting server info document.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/nginx.nix b/nixos/modules/services/monitoring/prometheus/exporters/nginx.nix
index 6f69f5919d1..3158e71f046 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/nginx.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/nginx.nix
@@ -11,7 +11,7 @@ in
     scrapeUri = mkOption {
       type = types.str;
       default = "http://localhost/nginx_status";
-      description = ''
+      description = lib.mdDoc ''
         Address to access the nginx status page.
         Can be enabled with services.nginx.statusPage = true.
       '';
@@ -19,14 +19,14 @@ in
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
     sslVerify = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to perform certificate verification for https.
       '';
     };
@@ -37,7 +37,7 @@ in
         "label1=value1"
         "label2=value2"
       ];
-      description = ''
+      description = lib.mdDoc ''
         A list of constant labels that will be used in every metric.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/nginxlog.nix b/nixos/modules/services/monitoring/prometheus/exporters/nginxlog.nix
index 8c1f552d58a..9e507423c7d 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/nginxlog.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/nginxlog.nix
@@ -10,7 +10,7 @@ in {
     settings = mkOption {
       type = types.attrs;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         All settings of nginxlog expressed as an Nix attrset.
 
         Check the official documentation for the corresponding YAML
@@ -24,7 +24,7 @@ in {
     metricsEndpoint = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/node.nix b/nixos/modules/services/monitoring/prometheus/exporters/node.nix
index 5e5fc7cd552..dd8602e2c63 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/node.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/node.nix
@@ -4,6 +4,8 @@ with lib;
 
 let
   cfg = config.services.prometheus.exporters.node;
+  collectorIsEnabled = final: any (collector: (final == collector)) cfg.enabledCollectors;
+  collectorIsDisabled = final: any (collector: (final == collector)) cfg.disabledCollectors;
 in
 {
   port = 9100;
@@ -12,7 +14,7 @@ in
       type = types.listOf types.str;
       default = [];
       example = [ "systemd" ];
-      description = ''
+      description = lib.mdDoc ''
         Collectors to enable. The collectors listed here are enabled in addition to the default ones.
       '';
     };
@@ -20,7 +22,7 @@ in
       type = types.listOf types.str;
       default = [];
       example = [ "timex" ];
-      description = ''
+      description = lib.mdDoc ''
         Collectors to disable which are enabled by default.
       '';
     };
@@ -35,15 +37,17 @@ in
           ${concatMapStringsSep " " (x: "--no-collector." + x) cfg.disabledCollectors} \
           --web.listen-address ${cfg.listenAddress}:${toString cfg.port} ${concatStringsSep " " cfg.extraFlags}
       '';
-      RestrictAddressFamilies = optionals (any (collector: (collector == "logind" || collector == "systemd")) cfg.enabledCollectors) [
+      RestrictAddressFamilies = optionals (collectorIsEnabled "logind" || collectorIsEnabled "systemd") [
         # needs access to dbus via unix sockets (logind/systemd)
         "AF_UNIX"
-      ] ++ optionals (any (collector: (collector == "network_route" || collector == "wifi")) cfg.enabledCollectors) [
+      ] ++ optionals (collectorIsEnabled "network_route" || collectorIsEnabled "wifi" || ! collectorIsDisabled "netdev") [
         # needs netlink sockets for wireless collector
         "AF_NETLINK"
       ];
       # The timex collector needs to access clock APIs
-      ProtectClock = any (collector: collector == "timex") cfg.disabledCollectors;
+      ProtectClock = collectorIsDisabled "timex";
+      # Allow space monitoring under /home
+      ProtectHome = true;
     };
   };
 }
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/openldap.nix b/nixos/modules/services/monitoring/prometheus/exporters/openldap.nix
index 888611ee6fa..aee3ae5bb2d 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/openldap.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/openldap.nix
@@ -10,37 +10,37 @@ in {
     ldapCredentialFile = mkOption {
       type = types.path;
       example = "/run/keys/ldap_pass";
-      description = ''
+      description = lib.mdDoc ''
         Environment file to contain the credentials to authenticate against
-        <package>openldap</package>.
+        `openldap`.
 
         The file should look like this:
-        <programlisting>
+        ```
         ---
         ldapUser: "cn=monitoring,cn=Monitor"
         ldapPass: "secret"
-        </programlisting>
+        ```
       '';
     };
     protocol = mkOption {
       default = "tcp";
       example = "udp";
       type = types.str;
-      description = ''
-        Which protocol to use to connect against <package>openldap</package>.
+      description = lib.mdDoc ''
+        Which protocol to use to connect against `openldap`.
       '';
     };
     ldapAddr = mkOption {
       default = "localhost:389";
       type = types.str;
-      description = ''
-        Address of the <package>openldap</package>-instance.
+      description = lib.mdDoc ''
+        Address of the `openldap`-instance.
       '';
     };
     metricsPath = mkOption {
       default = "/metrics";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         URL path where metrics should be exposed.
       '';
     };
@@ -48,7 +48,7 @@ in {
       default = "30s";
       type = types.str;
       example = "1m";
-      description = ''
+      description = lib.mdDoc ''
         Scrape interval of the exporter.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/openvpn.nix b/nixos/modules/services/monitoring/prometheus/exporters/openvpn.nix
index a97a753ebc3..5b54dad9980 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/openvpn.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/openvpn.nix
@@ -9,15 +9,15 @@ in {
   extraOpts = {
     statusPaths = mkOption {
       type = types.listOf types.str;
-      description = ''
+      description = lib.mdDoc ''
         Paths to OpenVPN status files. Please configure the OpenVPN option
-        <literal>status</literal> accordingly.
+        `status` accordingly.
       '';
     };
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/pihole.nix b/nixos/modules/services/monitoring/prometheus/exporters/pihole.nix
index 4bc27ebc32f..537d72e85c8 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/pihole.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/pihole.nix
@@ -12,7 +12,7 @@ in
       type = types.str;
       default = "";
       example = "580a770cb40511eb85290242ac130003580a770cb40511eb85290242ac130003";
-      description = ''
+      description = lib.mdDoc ''
         pi-hole API token which can be used instead of a password
       '';
     };
@@ -20,7 +20,7 @@ in
       type = types.str;
       default = "10s";
       example = "30s";
-      description = ''
+      description = lib.mdDoc ''
         How often to scrape new data
       '';
     };
@@ -28,7 +28,7 @@ in
       type = types.str;
       default = "";
       example = "password";
-      description = ''
+      description = lib.mdDoc ''
         The password to login into pihole. An api token can be used instead.
       '';
     };
@@ -36,7 +36,7 @@ in
       type = types.str;
       default = "pihole";
       example = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         Hostname or address where to find the pihole webinterface
       '';
     };
@@ -44,7 +44,7 @@ in
       type = types.port;
       default = 80;
       example = 443;
-      description = ''
+      description = lib.mdDoc ''
         The port pihole webinterface is reachable on
       '';
     };
@@ -52,7 +52,7 @@ in
       type = types.enum [ "http" "https" ];
       default = "http";
       example = "https";
-      description = ''
+      description = lib.mdDoc ''
         The protocol which is used to connect to pihole
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/postfix.nix b/nixos/modules/services/monitoring/prometheus/exporters/postfix.nix
index 4d3c1fa267e..9f402b12311 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/postfix.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/postfix.nix
@@ -10,17 +10,17 @@ in
   extraOpts = {
     group = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Group under which the postfix exporter shall be run.
         It should match the group that is allowed to access the
-        <literal>showq</literal> socket in the <literal>queue/public/</literal> directory.
-        Defaults to <literal>services.postfix.setgidGroup</literal> when postfix is enabled.
+        `showq` socket in the `queue/public/` directory.
+        Defaults to `services.postfix.setgidGroup` when postfix is enabled.
       '';
     };
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
@@ -28,7 +28,7 @@ in
       type = types.path;
       default = "/var/log/postfix_exporter_input.log";
       example = "/var/log/mail.log";
-      description = ''
+      description = lib.mdDoc ''
         Path where Postfix writes log entries.
         This file will be truncated by this exporter!
       '';
@@ -37,7 +37,7 @@ in
       type = types.path;
       default = "/var/lib/postfix/queue/public/showq";
       example = "/var/spool/postfix/public/showq";
-      description = ''
+      description = lib.mdDoc ''
         Path where Postfix places its showq socket.
       '';
     };
@@ -45,40 +45,42 @@ in
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable reading metrics from the systemd journal instead of from a logfile
         '';
       };
       unit = mkOption {
         type = types.str;
         default = "postfix.service";
-        description = ''
+        description = lib.mdDoc ''
           Name of the postfix systemd unit.
         '';
       };
       slice = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Name of the postfix systemd slice.
-          This overrides the <option>systemd.unit</option>.
+          This overrides the {option}`systemd.unit`.
         '';
       };
       journalPath = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to the systemd journal.
         '';
       };
     };
   };
   serviceOpts = {
+    after = mkIf cfg.systemd.enable [ cfg.systemd.unit ];
     serviceConfig = {
       DynamicUser = false;
       # By default, each prometheus exporter only gets AF_INET & AF_INET6,
       # but AF_UNIX is needed to read from the `showq`-socket.
       RestrictAddressFamilies = [ "AF_UNIX" ];
+      SupplementaryGroups = mkIf cfg.systemd.enable [ "systemd-journal" ];
       ExecStart = ''
         ${pkgs.prometheus-postfix-exporter}/bin/postfix_exporter \
           --web.listen-address ${cfg.listenAddress}:${toString cfg.port} \
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/postgres.nix b/nixos/modules/services/monitoring/prometheus/exporters/postgres.nix
index 3f9a32ef399..755d771ecdf 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/postgres.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/postgres.nix
@@ -11,7 +11,7 @@ in
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
@@ -19,14 +19,14 @@ in
       type = types.str;
       default = "user=postgres database=postgres host=/run/postgresql sslmode=disable";
       example = "postgresql://username:password@localhost:5432/postgres?sslmode=disable";
-      description = ''
+      description = lib.mdDoc ''
         Accepts PostgreSQL URI form and key=value form arguments.
       '';
     };
     runAsLocalSuperUser = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to run the exporter as the local 'postgres' super user.
       '';
     };
@@ -36,10 +36,8 @@ in
       type = types.nullOr types.path;
       default = null;
       example = "/root/prometheus-postgres-exporter.env";
-      description = ''
-        Environment file as defined in <citerefentry>
-        <refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum>
-        </citerefentry>.
+      description = lib.mdDoc ''
+        Environment file as defined in {manpage}`systemd.exec(5)`.
 
         Secrets may be passed to the service without adding them to the
         world-readable Nix store, by specifying placeholder variables as
@@ -48,7 +46,7 @@ in
 
         Environment variables from this file will be interpolated into the
         config file using envsubst with this syntax:
-        <literal>$ENVIRONMENT ''${VARIABLE}</literal>
+        `$ENVIRONMENT ''${VARIABLE}`
 
         The main use is to set the DATA_SOURCE_NAME that contains the
         postgres password
@@ -56,10 +54,10 @@ in
         note that contents from this file will override dataSourceName
         if you have set it from nix.
 
-        <programlisting>
+        ```
           # Content of the environment file
           DATA_SOURCE_NAME=postgresql://username:password@localhost:5432/postgres?sslmode=disable
-        </programlisting>
+        ```
 
         Note that this file needs to be available on the host on which
         this exporter is running.
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/process.nix b/nixos/modules/services/monitoring/prometheus/exporters/process.nix
index 1e9c402fb55..278d6cd7807 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/process.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/process.nix
@@ -18,11 +18,11 @@ in
           { name = "{{.Matches.Wrapped}} {{ .Matches.Args }}"; cmdline = [ "^/nix/store[^ ]*/(?P<Wrapped>[^ /]*) (?P<Args>.*)" ]; }
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         All settings expressed as an Nix attrset.
 
         Check the official documentation for the corresponding YAML
-        settings that can all be used here: <link xlink:href="https://github.com/ncabatoff/process-exporter" />
+        settings that can all be used here: <https://github.com/ncabatoff/process-exporter>
       '';
     };
   };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/pve.nix b/nixos/modules/services/monitoring/prometheus/exporters/pve.nix
index ef708414c95..e02acad3ecd 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/pve.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/pve.nix
@@ -10,7 +10,7 @@ let
     text = "default:";
   };
 
-  computedConfigFile = "${if cfg.configFile == null then emptyConfigFile else cfg.configFile}";
+  computedConfigFile = if cfg.configFile == null then emptyConfigFile else cfg.configFile;
 in
 {
   port = 9221;
@@ -20,7 +20,7 @@ in
       default = pkgs.prometheus-pve-exporter;
       defaultText = literalExpression "pkgs.prometheus-pve-exporter";
       example = literalExpression "pkgs.prometheus-pve-exporter";
-      description = ''
+      description = lib.mdDoc ''
         The package to use for prometheus-pve-exporter
       '';
     };
@@ -29,7 +29,7 @@ in
       type = with types; nullOr path;
       default = null;
       example = "/etc/prometheus-pve-exporter/pve.env";
-      description = ''
+      description = lib.mdDoc ''
         Path to the service's environment file. This path can either be a computed path in /nix/store or a path in the local filesystem.
 
         The environment file should NOT be stored in /nix/store as it contains passwords and/or keys in plain text.
@@ -42,7 +42,7 @@ in
       type = with types; nullOr path;
       default = null;
       example = "/etc/prometheus-pve-exporter/pve.yml";
-      description = ''
+      description = lib.mdDoc ''
         Path to the service's config file. This path can either be a computed path in /nix/store or a path in the local filesystem.
 
         The config file should NOT be stored in /nix/store as it will contain passwords and/or keys in plain text.
@@ -57,42 +57,42 @@ in
       status = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Collect Node/VM/CT status
         '';
       };
       version = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Collect PVE version info
         '';
       };
       node = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Collect PVE node info
         '';
       };
       cluster = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Collect PVE cluster info
         '';
       };
       resources = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Collect PVE resources info
         '';
       };
       config = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Collect PVE onboot status
         '';
       };
@@ -100,6 +100,8 @@ in
   };
   serviceOpts = {
     serviceConfig = {
+      DynamicUser = cfg.environmentFile == null;
+      LoadCredential = "configFile:${computedConfigFile}";
       ExecStart = ''
         ${cfg.package}/bin/pve_exporter \
           --${if cfg.collectors.status == true then "" else "no-"}collector.status \
@@ -108,11 +110,11 @@ in
           --${if cfg.collectors.cluster == true then "" else "no-"}collector.cluster \
           --${if cfg.collectors.resources == true then "" else "no-"}collector.resources \
           --${if cfg.collectors.config == true then "" else "no-"}collector.config \
-          ${computedConfigFile} \
+          %d/configFile \
           ${toString cfg.port} ${cfg.listenAddress}
       '';
     } // optionalAttrs (cfg.environmentFile != null) {
-          EnvironmentFile = cfg.environmentFile;
+      EnvironmentFile = cfg.environmentFile;
     };
   };
 }
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/py-air-control.nix b/nixos/modules/services/monitoring/prometheus/exporters/py-air-control.nix
index d9ab99221d9..f03b3c4df91 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/py-air-control.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/py-air-control.nix
@@ -14,14 +14,14 @@ in
     deviceHostname = mkOption {
       type = types.str;
       example = "192.168.1.123";
-      description = ''
+      description = lib.mdDoc ''
         The hostname of the air purification device from which to scrape the metrics.
       '';
     };
     protocol = mkOption {
       type = types.str;
       default = "http";
-      description = ''
+      description = lib.mdDoc ''
         The protocol to use when communicating with the air purification device.
         Available: [http, coap, plain_coap]
       '';
@@ -29,8 +29,8 @@ in
     stateDir = mkOption {
       type = types.str;
       default = "prometheus-py-air-control-exporter";
-      description = ''
-        Directory below <literal>/var/lib</literal> to store runtime data.
+      description = lib.mdDoc ''
+        Directory below `/var/lib` to store runtime data.
         This directory will be created automatically using systemd's StateDirectory mechanism.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/rspamd.nix b/nixos/modules/services/monitoring/prometheus/exporters/rspamd.nix
index ed985751e42..0b48827f43f 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/rspamd.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/rspamd.nix
@@ -69,7 +69,7 @@ in
           custom_label = "some_value";
         }
       '';
-      description = "Set of labels added to each metric.";
+      description = lib.mdDoc "Set of labels added to each metric.";
     };
   };
   serviceOpts.serviceConfig.ExecStart = ''
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/rtl_433.nix b/nixos/modules/services/monitoring/prometheus/exporters/rtl_433.nix
index ef829a1b7d0..1f7235cb783 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/rtl_433.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/rtl_433.nix
@@ -12,15 +12,15 @@ in
         options = {
           name = lib.mkOption {
             type = str;
-            description = "Name to match.";
+            description = lib.mdDoc "Name to match.";
           };
           "${field}" = lib.mkOption {
             type = int;
-            inherit description;
+            description = lib.mdDoc description;
           };
           location = lib.mkOption {
             type = str;
-            description = "Location to match.";
+            description = lib.mdDoc "Location to match.";
           };
         };
       });
@@ -30,9 +30,9 @@ in
       type = lib.types.str;
       default = "-C si";
       example = "-C si -R 19";
-      description = ''
+      description = lib.mdDoc ''
         Flags passed verbatim to rtl_433 binary.
-        Having <literal>-C si</literal> (the default) is recommended since only Celsius temperatures are parsed.
+        Having `-C si` (the default) is recommended since only Celsius temperatures are parsed.
       '';
     };
     channels = lib.mkOption {
@@ -41,7 +41,7 @@ in
       example = [
         { name = "Acurite"; channel = 6543; location = "Kitchen"; }
       ];
-      description = ''
+      description = lib.mdDoc ''
         List of channel matchers to export.
       '';
     };
@@ -51,7 +51,7 @@ in
       example = [
         { name = "Nexus"; id = 1; location = "Bedroom"; }
       ];
-      description = ''
+      description = lib.mdDoc ''
         List of ID matchers to export.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/script.nix b/nixos/modules/services/monitoring/prometheus/exporters/script.nix
index a805a0ad335..eab0e1d8a6b 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/script.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/script.nix
@@ -15,18 +15,18 @@ in
           name = mkOption {
             type = str;
             example = "sleep";
-            description = "Name of the script.";
+            description = lib.mdDoc "Name of the script.";
           };
           script = mkOption {
             type = str;
             example = "sleep 5";
-            description = "Shell script to execute when metrics are requested.";
+            description = lib.mdDoc "Shell script to execute when metrics are requested.";
           };
           timeout = mkOption {
             type = nullOr int;
             default = null;
             example = 60;
-            description = "Optional timeout for the script in seconds.";
+            description = lib.mdDoc "Optional timeout for the script in seconds.";
           };
         };
       });
@@ -37,11 +37,11 @@ in
           ];
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         All settings expressed as an Nix attrset.
 
         Check the official documentation for the corresponding YAML
-        settings that can all be used here: <link xlink:href="https://github.com/adhocteam/script_exporter#sample-configuration" />
+        settings that can all be used here: <https://github.com/adhocteam/script_exporter#sample-configuration>
       '';
     };
   };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/smartctl.nix b/nixos/modules/services/monitoring/prometheus/exporters/smartctl.nix
index bac98364538..df424ede606 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/smartctl.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/smartctl.nix
@@ -24,7 +24,7 @@ in {
       example = literalExpression ''
         [ "/dev/sda", "/dev/nvme0n1" ];
       '';
-      description = ''
+      description = lib.mdDoc ''
         Paths to the disks that will be monitored. Will autodiscover
         all disks if none given.
       '';
@@ -33,7 +33,7 @@ in {
       type = types.str;
       default = "60s";
       example = "2m";
-      description = ''
+      description = lib.mdDoc ''
         Interval that limits how often a disk can be queried.
       '';
     };
@@ -50,7 +50,7 @@ in {
         "CAP_SYS_ADMIN"
       ];
       DevicePolicy = "closed";
-      DeviceAllow = lib.mkOverride 100 (
+      DeviceAllow = lib.mkOverride 50 (
         if cfg.devices != [] then
           cfg.devices
         else [
@@ -66,10 +66,7 @@ in {
       ProtectProc = "invisible";
       ProcSubset = "pid";
       SupplementaryGroups = [ "disk" ];
-      SystemCallFilter = [
-        "@system-service"
-        "~@privileged @resources"
-      ];
+      SystemCallFilter = [ "@system-service" "~@privileged" ];
     };
   };
 }
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/smokeping.nix b/nixos/modules/services/monitoring/prometheus/exporters/smokeping.nix
index 0181c341a7e..459f5842f54 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/smokeping.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/smokeping.nix
@@ -17,27 +17,27 @@ in
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
     pingInterval = mkOption {
       type = goDuration;
       default = "1s";
-      description = ''
+      description = lib.mdDoc ''
         Interval between pings.
       '';
     };
     buckets = mkOption {
       type = types.commas;
       default = "5e-05,0.0001,0.0002,0.0004,0.0008,0.0016,0.0032,0.0064,0.0128,0.0256,0.0512,0.1024,0.2048,0.4096,0.8192,1.6384,3.2768,6.5536,13.1072,26.2144";
-      description = ''
+      description = lib.mdDoc ''
         List of buckets to use for the response duration histogram.
       '';
     };
     hosts = mkOption {
       type = with types; listOf str;
-      description = ''
+      description = lib.mdDoc ''
         List of endpoints to probe.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/snmp.nix b/nixos/modules/services/monitoring/prometheus/exporters/snmp.nix
index de42663e67f..edc6e4b5022 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/snmp.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/snmp.nix
@@ -11,7 +11,7 @@ in
     configurationPath = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Path to a snmp exporter configuration file. Mutually exclusive with 'configuration' option.
       '';
       example = literalExpression "./snmp.yml";
@@ -20,7 +20,7 @@ in
     configuration = mkOption {
       type = types.nullOr types.attrs;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Snmp exporter configuration as nix attribute set. Mutually exclusive with 'configurationPath' option.
       '';
       example = {
@@ -36,7 +36,7 @@ in
     logFormat = mkOption {
       type = types.enum ["logfmt" "json"];
       default = "logfmt";
-      description = ''
+      description = lib.mdDoc ''
         Output format of log messages.
       '';
     };
@@ -44,7 +44,7 @@ in
     logLevel = mkOption {
       type = types.enum ["debug" "info" "warn" "error"];
       default = "info";
-      description = ''
+      description = lib.mdDoc ''
         Only log messages with the given severity or above.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/sql.nix b/nixos/modules/services/monitoring/prometheus/exporters/sql.nix
index 3496fd9541f..678bc348679 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/sql.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/sql.nix
@@ -7,7 +7,7 @@ let
       jobs = mkOption {
         type = attrsOf (submodule jobOptions);
         default = { };
-        description = "An attrset of metrics scraping jobs to run.";
+        description = lib.mdDoc "An attrset of metrics scraping jobs to run.";
       };
     };
   };
@@ -15,23 +15,23 @@ let
     options = with types; {
       interval = mkOption {
         type = str;
-        description = ''
+        description = lib.mdDoc ''
           How often to run this job, specified in
-          <link xlink:href="https://golang.org/pkg/time/#ParseDuration">Go duration</link> format.
+          [Go duration](https://golang.org/pkg/time/#ParseDuration) format.
         '';
       };
       connections = mkOption {
         type = listOf str;
-        description = "A list of connection strings of the SQL servers to scrape metrics from";
+        description = lib.mdDoc "A list of connection strings of the SQL servers to scrape metrics from";
       };
       startupSql = mkOption {
         type = listOf str;
         default = [];
-        description = "A list of SQL statements to execute once after making a connection.";
+        description = lib.mdDoc "A list of SQL statements to execute once after making a connection.";
       };
       queries = mkOption {
         type = attrsOf (submodule queryOptions);
-        description = "SQL queries to run.";
+        description = lib.mdDoc "SQL queries to run.";
       };
     };
   };
@@ -40,20 +40,20 @@ let
       help = mkOption {
         type = nullOr str;
         default = null;
-        description = "A human-readable description of this metric.";
+        description = lib.mdDoc "A human-readable description of this metric.";
       };
       labels = mkOption {
         type = listOf str;
         default = [ ];
-        description = "A set of columns that will be used as Prometheus labels.";
+        description = lib.mdDoc "A set of columns that will be used as Prometheus labels.";
       };
       query = mkOption {
         type = str;
-        description = "The SQL query to run.";
+        description = lib.mdDoc "The SQL query to run.";
       };
       values = mkOption {
         type = listOf str;
-        description = "A set of columns that will be used as values of this metric.";
+        description = lib.mdDoc "A set of columns that will be used as values of this metric.";
       };
     };
   };
@@ -77,14 +77,14 @@ in
     configFile = mkOption {
       type = with types; nullOr path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Path to configuration file.
       '';
     };
     configuration = mkOption {
       type = with types; nullOr (submodule cfgOptions);
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Exporter configuration as nix attribute set. Mutually exclusive with 'configFile' option.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/surfboard.nix b/nixos/modules/services/monitoring/prometheus/exporters/surfboard.nix
index 81c5c70ed93..b1d6760b40b 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/surfboard.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/surfboard.nix
@@ -11,7 +11,7 @@ in
     modemAddress = mkOption {
       type = types.str;
       default = "192.168.100.1";
-      description = ''
+      description = lib.mdDoc ''
         The hostname or IP of the cable modem.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/tor.nix b/nixos/modules/services/monitoring/prometheus/exporters/tor.nix
index 36c473677ef..7a9167110a2 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/tor.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/tor.nix
@@ -11,15 +11,15 @@ in
     torControlAddress = mkOption {
       type = types.str;
       default = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         Tor control IP address or hostname.
       '';
     };
 
     torControlPort = mkOption {
-      type = types.int;
+      type = types.port;
       default = 9051;
-      description = ''
+      description = lib.mdDoc ''
         Tor control port.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/unbound.nix b/nixos/modules/services/monitoring/prometheus/exporters/unbound.nix
index cf0efddd340..f52d92a73d5 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/unbound.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/unbound.nix
@@ -12,7 +12,7 @@ in
       # TODO: add shm when upstream implemented it
       type = types.enum [ "tcp" "uds" ];
       default = "uds";
-      description = ''
+      description = lib.mdDoc ''
         Which methods the exporter uses to get the information from unbound.
       '';
     };
@@ -20,7 +20,7 @@ in
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
@@ -29,7 +29,7 @@ in
       type = types.nullOr types.str;
       default = null;
       example = "/run/unbound/unbound.socket";
-      description = ''
+      description = lib.mdDoc ''
         Path to the unbound socket for uds mode or the control interface port for tcp mode.
 
         Example:
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/unifi-poller.nix b/nixos/modules/services/monitoring/prometheus/exporters/unifi-poller.nix
index 394e6e201f0..35de31df88e 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/unifi-poller.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/unifi-poller.nix
@@ -9,10 +9,12 @@ let
     poller = { inherit (cfg.log) debug quiet; };
     unifi = { inherit (cfg) controllers; };
     influxdb.disable = true;
+    datadog.disable = true; # workaround for https://github.com/unpoller/unpoller/issues/442
     prometheus = {
       http_listen = "${cfg.listenAddress}:${toString cfg.port}";
       report_errors = cfg.log.prometheusErrors;
     };
+    inherit (cfg) loki;
   });
 
 in {
@@ -20,15 +22,16 @@ in {
 
   extraOpts = {
     inherit (options.services.unifi-poller.unifi) controllers;
+    inherit (options.services.unifi-poller) loki;
     log = {
-      debug = mkEnableOption "debug logging including line numbers, high resolution timestamps, per-device logs.";
-      quiet = mkEnableOption "startup and error logs only.";
-      prometheusErrors = mkEnableOption "emitting errors to prometheus.";
+      debug = mkEnableOption (lib.mdDoc "debug logging including line numbers, high resolution timestamps, per-device logs.");
+      quiet = mkEnableOption (lib.mdDoc "startup and error logs only.");
+      prometheusErrors = mkEnableOption (lib.mdDoc "emitting errors to prometheus.");
     };
   };
 
   serviceOpts.serviceConfig = {
-    ExecStart = "${pkgs.unifi-poller}/bin/unifi-poller --config ${configFile}";
+    ExecStart = "${pkgs.unifi-poller}/bin/unpoller --config ${configFile}";
     DynamicUser = false;
   };
 }
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/unifi.nix b/nixos/modules/services/monitoring/prometheus/exporters/unifi.nix
index 8d0e8764001..70f26d9783b 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/unifi.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/unifi.nix
@@ -11,7 +11,7 @@ in
     unifiAddress = mkOption {
       type = types.str;
       example = "https://10.0.0.1:8443";
-      description = ''
+      description = lib.mdDoc ''
         URL of the UniFi Controller API.
       '';
     };
@@ -19,7 +19,7 @@ in
     unifiInsecure = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         If enabled skip the verification of the TLS certificate of the UniFi Controller API.
         Use with caution.
       '';
@@ -28,14 +28,14 @@ in
     unifiUsername = mkOption {
       type = types.str;
       example = "ReadOnlyUser";
-      description = ''
+      description = lib.mdDoc ''
         username for authentication against UniFi Controller API.
       '';
     };
 
     unifiPassword = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Password for authentication against UniFi Controller API.
       '';
     };
@@ -44,7 +44,7 @@ in
       type = types.str;
       default = "5s";
       example = "2m";
-      description = ''
+      description = lib.mdDoc ''
         Timeout including unit for UniFi Controller API requests.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/v2ray.nix b/nixos/modules/services/monitoring/prometheus/exporters/v2ray.nix
new file mode 100644
index 00000000000..a019157c664
--- /dev/null
+++ b/nixos/modules/services/monitoring/prometheus/exporters/v2ray.nix
@@ -0,0 +1,29 @@
+{ config, lib, pkgs, options }:
+
+with lib;
+
+let
+  cfg = config.services.prometheus.exporters.v2ray;
+in
+{
+  port = 9299;
+  extraOpts = {
+    v2rayEndpoint = mkOption {
+      type = types.str;
+      default = "127.0.0.1:54321";
+      description = lib.mdDoc ''
+        v2ray grpc api endpoint
+      '';
+    };
+  };
+  serviceOpts = {
+    serviceConfig = {
+      ExecStart = ''
+        ${pkgs.prometheus-v2ray-exporter}/bin/v2ray-exporter \
+          --v2ray-endpoint ${cfg.v2rayEndpoint} \
+          --listen ${cfg.listenAddress}:${toString cfg.port} \
+          ${concatStringsSep " \\\n  " cfg.extraFlags}
+      '';
+    };
+  };
+}
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/varnish.nix b/nixos/modules/services/monitoring/prometheus/exporters/varnish.nix
index ede6028933a..a7e5b41dffc 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/varnish.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/varnish.nix
@@ -11,35 +11,35 @@ in
     noExit = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Do not exit server on Varnish scrape errors.
       '';
     };
     withGoMetrics = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Export go runtime and http handler metrics.
       '';
     };
     verbose = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable verbose logging.
       '';
     };
     raw = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable raw stdout logging without timestamps.
       '';
     };
     varnishStatPath = mkOption {
       type = types.str;
       default = "varnishstat";
-      description = ''
+      description = lib.mdDoc ''
         Path to varnishstat.
       '';
     };
@@ -47,21 +47,21 @@ in
       type = types.nullOr types.str;
       default = config.services.varnish.stateDir;
       defaultText = lib.literalExpression "config.services.varnish.stateDir";
-      description = ''
+      description = lib.mdDoc ''
         varnishstat -n value.
       '';
     };
     healthPath = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose healthcheck. Disabled unless configured.
       '';
     };
     telemetryPath = mkOption {
       type = types.str;
       default = "/metrics";
-      description = ''
+      description = lib.mdDoc ''
         Path under which to expose metrics.
       '';
     };
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/wireguard.nix b/nixos/modules/services/monitoring/prometheus/exporters/wireguard.nix
index d4aa69629ec..c98dcd9f64b 100644
--- a/nixos/modules/services/monitoring/prometheus/exporters/wireguard.nix
+++ b/nixos/modules/services/monitoring/prometheus/exporters/wireguard.nix
@@ -11,19 +11,19 @@ in {
     ({ options.warnings = options.warnings; options.assertions = options.assertions; })
   ];
   extraOpts = {
-    verbose = mkEnableOption "Verbose logging mode for prometheus-wireguard-exporter";
+    verbose = mkEnableOption (lib.mdDoc "Verbose logging mode for prometheus-wireguard-exporter");
 
     wireguardConfig = mkOption {
       type = with types; nullOr (either path str);
       default = null;
 
-      description = ''
+      description = lib.mdDoc ''
         Path to the Wireguard Config to
-        <link xlink:href="https://github.com/MindFlavor/prometheus_wireguard_exporter/tree/2.0.0#usage">add the peer's name to the stats of a peer</link>.
+        [add the peer's name to the stats of a peer](https://github.com/MindFlavor/prometheus_wireguard_exporter/tree/2.0.0#usage).
 
-        Please note that <literal>networking.wg-quick</literal> is required for this feature
-        as <literal>networking.wireguard</literal> uses
-        <citerefentry><refentrytitle>wg</refentrytitle><manvolnum>8</manvolnum></citerefentry>
+        Please note that `networking.wg-quick` is required for this feature
+        as `networking.wireguard` uses
+        {manpage}`wg(8)`
         to set the peers up.
       '';
     };
@@ -31,18 +31,18 @@ in {
     singleSubnetPerField = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         By default, all allowed IPs and subnets are comma-separated in the
-        <literal>allowed_ips</literal> field. With this option enabled,
-        a single IP and subnet will be listed in fields like <literal>allowed_ip_0</literal>,
-        <literal>allowed_ip_1</literal> and so on.
+        `allowed_ips` field. With this option enabled,
+        a single IP and subnet will be listed in fields like `allowed_ip_0`,
+        `allowed_ip_1` and so on.
       '';
     };
 
     withRemoteIp = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether or not the remote IP of a WireGuard peer should be exposed via prometheus.
       '';
     };
@@ -57,9 +57,9 @@ in {
         ${pkgs.prometheus-wireguard-exporter}/bin/prometheus_wireguard_exporter \
           -p ${toString cfg.port} \
           -l ${cfg.listenAddress} \
-          ${optionalString cfg.verbose "-v"} \
-          ${optionalString cfg.singleSubnetPerField "-s"} \
-          ${optionalString cfg.withRemoteIp "-r"} \
+          ${optionalString cfg.verbose "-v true"} \
+          ${optionalString cfg.singleSubnetPerField "-s true"} \
+          ${optionalString cfg.withRemoteIp "-r true"} \
           ${optionalString (cfg.wireguardConfig != null) "-n ${escapeShellArg cfg.wireguardConfig}"}
       '';
       RestrictAddressFamilies = [
diff --git a/nixos/modules/services/monitoring/prometheus/exporters/zfs.nix b/nixos/modules/services/monitoring/prometheus/exporters/zfs.nix
new file mode 100644
index 00000000000..ff12a52d49a
--- /dev/null
+++ b/nixos/modules/services/monitoring/prometheus/exporters/zfs.nix
@@ -0,0 +1,44 @@
+{ config, lib, pkgs, options }:
+
+with lib;
+
+let
+  cfg = config.services.prometheus.exporters.zfs;
+in
+{
+  port = 9134;
+
+  extraOpts = {
+    telemetryPath = mkOption {
+      type = types.str;
+      default = "/metrics";
+      description = lib.mdDoc ''
+        Path under which to expose metrics.
+      '';
+    };
+
+    pools = mkOption {
+      type = with types; nullOr (listOf str);
+      default = [ ];
+      description = lib.mdDoc ''
+        Name of the pool(s) to collect, repeat for multiple pools (default: all pools).
+      '';
+    };
+  };
+
+  serviceOpts = {
+    # needs zpool
+    path = [ config.boot.zfs.package ];
+    serviceConfig = {
+      ExecStart = ''
+        ${pkgs.prometheus-zfs-exporter}/bin/zfs_exporter \
+          --web.listen-address ${cfg.listenAddress}:${toString cfg.port} \
+          --web.telemetry-path ${cfg.telemetryPath} \
+          ${concatMapStringsSep " " (x: "--pool=${x}") cfg.pools} \
+          ${concatStringsSep " \\\n  " cfg.extraFlags}
+      '';
+      ProtectClock = false;
+      PrivateDevices = false;
+    };
+  };
+}
diff --git a/nixos/modules/services/monitoring/prometheus/pushgateway.nix b/nixos/modules/services/monitoring/prometheus/pushgateway.nix
index 01b99376243..f5c114c9275 100644
--- a/nixos/modules/services/monitoring/prometheus/pushgateway.nix
+++ b/nixos/modules/services/monitoring/prometheus/pushgateway.nix
@@ -21,13 +21,13 @@ let
 in {
   options = {
     services.prometheus.pushgateway = {
-      enable = mkEnableOption "Prometheus Pushgateway";
+      enable = mkEnableOption (lib.mdDoc "Prometheus Pushgateway");
 
       package = mkOption {
         type = types.package;
         default = pkgs.prometheus-pushgateway;
         defaultText = literalExpression "pkgs.prometheus-pushgateway";
-        description = ''
+        description = lib.mdDoc ''
           Package that should be used for the prometheus pushgateway.
         '';
       };
@@ -35,27 +35,27 @@ in {
       web.listen-address = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Address to listen on for the web interface, API and telemetry.
 
-          <literal>null</literal> will default to <literal>:9091</literal>.
+          `null` will default to `:9091`.
         '';
       };
 
       web.telemetry-path = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path under which to expose metrics.
 
-          <literal>null</literal> will default to <literal>/metrics</literal>.
+          `null` will default to `/metrics`.
         '';
       };
 
       web.external-url = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The URL under which Pushgateway is externally reachable.
         '';
       };
@@ -63,11 +63,11 @@ in {
       web.route-prefix = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Prefix for the internal routes of web endpoints.
 
           Defaults to the path of
-          <option>services.prometheus.pushgateway.web.external-url</option>.
+          {option}`services.prometheus.pushgateway.web.external-url`.
         '';
       };
 
@@ -75,20 +75,20 @@ in {
         type = types.nullOr types.str;
         default = null;
         example = "10m";
-        description = ''
+        description = lib.mdDoc ''
           The minimum interval at which to write out the persistence file.
 
-          <literal>null</literal> will default to <literal>5m</literal>.
+          `null` will default to `5m`.
         '';
       };
 
       log.level = mkOption {
         type = types.nullOr (types.enum ["debug" "info" "warn" "error" "fatal"]);
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Only log messages with the given severity or above.
 
-          <literal>null</literal> will default to <literal>info</literal>.
+          `null` will default to `info`.
         '';
       };
 
@@ -96,17 +96,17 @@ in {
         type = types.nullOr types.str;
         default = null;
         example = "logger:syslog?appname=bob&local=7";
-        description = ''
+        description = lib.mdDoc ''
           Set the log target and format.
 
-          <literal>null</literal> will default to <literal>logger:stderr</literal>.
+          `null` will default to `logger:stderr`.
         '';
       };
 
       extraFlags = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Extra commandline options when launching the Pushgateway.
         '';
       };
@@ -114,26 +114,26 @@ in {
       persistMetrics = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to persist metrics to a file.
 
           When enabled metrics will be saved to a file called
-          <literal>metrics</literal> in the directory
-          <literal>/var/lib/pushgateway</literal>. The directory below
-          <literal>/var/lib</literal> can be set using
-          <option>services.prometheus.pushgateway.stateDir</option>.
+          `metrics` in the directory
+          `/var/lib/pushgateway`. The directory below
+          `/var/lib` can be set using
+          {option}`services.prometheus.pushgateway.stateDir`.
         '';
       };
 
       stateDir = mkOption {
         type = types.str;
         default = "pushgateway";
-        description = ''
-          Directory below <literal>/var/lib</literal> to store metrics.
+        description = lib.mdDoc ''
+          Directory below `/var/lib` to store metrics.
 
           This directory will be created automatically using systemd's
           StateDirectory mechanism when
-          <option>services.prometheus.pushgateway.persistMetrics</option>
+          {option}`services.prometheus.pushgateway.persistMetrics`
           is enabled.
         '';
       };
diff --git a/nixos/modules/services/monitoring/prometheus/sachet.nix b/nixos/modules/services/monitoring/prometheus/sachet.nix
new file mode 100644
index 00000000000..c908d599bd4
--- /dev/null
+++ b/nixos/modules/services/monitoring/prometheus/sachet.nix
@@ -0,0 +1,88 @@
+{ config, pkgs, lib, ... }:
+
+with lib;
+
+let
+  cfg = config.services.prometheus.sachet;
+  configFile = pkgs.writeText "sachet.yml" (builtins.toJSON cfg.configuration);
+in
+{
+  options = {
+    services.prometheus.sachet = {
+      enable = mkEnableOption (lib.mdDoc "Sachet, an SMS alerting tool for the Prometheus Alertmanager");
+
+      configuration = mkOption {
+        type = types.nullOr types.attrs;
+        default = null;
+        example = literalExpression ''
+          {
+            providers = {
+              twilio = {
+                # environment variables gets expanded at runtime
+                account_sid = "$TWILIO_ACCOUNT";
+                auth_token = "$TWILIO_TOKEN";
+              };
+            };
+            templates = [ ./some-template.tmpl ];
+            receivers = [{
+              name = "pager";
+              provider = "twilio";
+              to = [ "+33123456789" ];
+              text = "{{ template \"message\" . }}";
+            }];
+          }
+        '';
+        description = lib.mdDoc ''
+          Sachet's configuration as a nix attribute set.
+        '';
+      };
+
+      address = mkOption {
+        type = types.str;
+        default = "localhost";
+        description = lib.mdDoc ''
+          The address Sachet will listen to.
+        '';
+      };
+
+      port = mkOption {
+        type = types.port;
+        default = 9876;
+        description = lib.mdDoc ''
+          The port Sachet will listen to.
+        '';
+      };
+
+    };
+  };
+
+  config = mkIf cfg.enable {
+    assertions = singleton {
+      assertion = cfg.configuration != null;
+      message = "Cannot enable Sachet without a configuration.";
+    };
+
+    systemd.services.sachet = {
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" "network-online.target" ];
+      script = ''
+        ${pkgs.envsubst}/bin/envsubst -i "${configFile}" > /tmp/sachet.yaml
+        exec ${pkgs.prometheus-sachet}/bin/sachet -config /tmp/sachet.yaml -listen-address ${cfg.address}:${builtins.toString cfg.port}
+      '';
+
+      serviceConfig = {
+        Restart = "always";
+
+        ProtectSystem = "strict";
+        ProtectHome = true;
+        ProtectKernelTunables = true;
+        ProtectKernelModules = true;
+        ProtectControlGroups = true;
+
+        DynamicUser = true;
+        PrivateTmp = true;
+        WorkingDirectory = "/tmp/";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/monitoring/prometheus/xmpp-alerts.nix b/nixos/modules/services/monitoring/prometheus/xmpp-alerts.nix
index 980c93c9c47..4545ca37d27 100644
--- a/nixos/modules/services/monitoring/prometheus/xmpp-alerts.nix
+++ b/nixos/modules/services/monitoring/prometheus/xmpp-alerts.nix
@@ -15,15 +15,15 @@ in
   ];
 
   options.services.prometheus.xmpp-alerts = {
-    enable = mkEnableOption "XMPP Web hook service for Alertmanager";
+    enable = mkEnableOption (lib.mdDoc "XMPP Web hook service for Alertmanager");
 
     settings = mkOption {
       type = settingsFormat.type;
       default = {};
 
-      description = ''
+      description = lib.mdDoc ''
         Configuration for prometheus xmpp-alerts, see
-        <link xlink:href="https://github.com/jelmer/prometheus-xmpp-alerts/blob/master/xmpp-alerts.yml.example"/>
+        <https://github.com/jelmer/prometheus-xmpp-alerts/blob/master/xmpp-alerts.yml.example>
         for supported values.
       '';
     };
diff --git a/nixos/modules/services/monitoring/riemann-dash.nix b/nixos/modules/services/monitoring/riemann-dash.nix
index 16eb8300850..1ca8af14e77 100644
--- a/nixos/modules/services/monitoring/riemann-dash.nix
+++ b/nixos/modules/services/monitoring/riemann-dash.nix
@@ -26,20 +26,20 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the riemann-dash dashboard daemon.
         '';
       };
       config = mkOption {
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Contents added to the end of the riemann-dash configuration file.
         '';
       };
       dataDir = mkOption {
         type = types.str;
         default = "/var/riemann-dash";
-        description = ''
+        description = lib.mdDoc ''
           Location of the riemann-base dir. The dashboard configuration file is
           is stored to this directory. The directory is created automatically on
           service start, and owner is set to the riemanndash user.
diff --git a/nixos/modules/services/monitoring/riemann-tools.nix b/nixos/modules/services/monitoring/riemann-tools.nix
index 86a11694e7b..28821267b4f 100644
--- a/nixos/modules/services/monitoring/riemann-tools.nix
+++ b/nixos/modules/services/monitoring/riemann-tools.nix
@@ -23,21 +23,21 @@ in {
       enableHealth = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the riemann-health daemon.
         '';
       };
       riemannHost = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = ''
+        description = lib.mdDoc ''
           Address of the host riemann node. Defaults to localhost.
         '';
       };
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of commandline-switches forwarded to a riemann-tool.
           See for example `riemann-health --help` for available options.
         '';
diff --git a/nixos/modules/services/monitoring/riemann.nix b/nixos/modules/services/monitoring/riemann.nix
index 13d2b1cc060..7ab8af85ed7 100644
--- a/nixos/modules/services/monitoring/riemann.nix
+++ b/nixos/modules/services/monitoring/riemann.nix
@@ -27,16 +27,11 @@ in {
   options = {
 
     services.riemann = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Enable the Riemann network monitoring daemon.
-        '';
-      };
+      enable = mkEnableOption (lib.mdDoc "Riemann network monitoring daemon");
+
       config = mkOption {
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Contents of the Riemann configuration file. For more complicated
           config you should use configFile.
         '';
@@ -44,17 +39,17 @@ in {
       configFiles = mkOption {
         type = with types; listOf path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Extra files containing Riemann configuration. These files will be
           loaded at runtime by Riemann (with Clojure's
-          <literal>load-file</literal> function) at the end of the
+          `load-file` function) at the end of the
           configuration if you use the config option, this is ignored if you
           use configFile.
         '';
       };
       configFile = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           A Riemann config file. Any files in the same directory as this file
           will be added to the classpath by Riemann.
         '';
@@ -62,14 +57,14 @@ in {
       extraClasspathEntries = mkOption {
         type = with types; listOf str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Extra entries added to the Java classpath when running Riemann.
         '';
       };
       extraJavaOpts = mkOption {
         type = with types; listOf str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Extra Java options used when launching Riemann.
         '';
       };
diff --git a/nixos/modules/services/monitoring/scollector.nix b/nixos/modules/services/monitoring/scollector.nix
index 6a6fe110f94..48be309c959 100644
--- a/nixos/modules/services/monitoring/scollector.nix
+++ b/nixos/modules/services/monitoring/scollector.nix
@@ -35,7 +35,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run scollector.
         '';
       };
@@ -44,7 +44,7 @@ in {
         type = types.package;
         default = pkgs.scollector;
         defaultText = literalExpression "pkgs.scollector";
-        description = ''
+        description = lib.mdDoc ''
           scollector binary to use.
         '';
       };
@@ -52,7 +52,7 @@ in {
       user = mkOption {
         type = types.str;
         default = "scollector";
-        description = ''
+        description = lib.mdDoc ''
           User account under which scollector runs.
         '';
       };
@@ -60,7 +60,7 @@ in {
       group = mkOption {
         type = types.str;
         default = "scollector";
-        description = ''
+        description = lib.mdDoc ''
           Group account under which scollector runs.
         '';
       };
@@ -68,7 +68,7 @@ in {
       bosunHost = mkOption {
         type = types.str;
         default = "localhost:8070";
-        description = ''
+        description = lib.mdDoc ''
           Host and port of the bosun server that will store the collected
           data.
         '';
@@ -78,7 +78,7 @@ in {
         type = with types; attrsOf (listOf path);
         default = {};
         example = literalExpression ''{ "0" = [ "''${postgresStats}/bin/collect-stats" ]; }'';
-        description = ''
+        description = lib.mdDoc ''
           An attribute set mapping the frequency of collection to a list of
           binaries that should be executed at that frequency. You can use "0"
           to run a binary forever.
@@ -89,7 +89,7 @@ in {
         type = with types; listOf str;
         default = [];
         example = [ "-d" ];
-        description = ''
+        description = lib.mdDoc ''
           Extra scollector command line options
         '';
       };
@@ -97,7 +97,7 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra scollector configuration added to the end of scollector.toml
         '';
       };
diff --git a/nixos/modules/services/monitoring/smartd.nix b/nixos/modules/services/monitoring/smartd.nix
index 6d39cc3e4e6..1e654cad5dd 100644
--- a/nixos/modules/services/monitoring/smartd.nix
+++ b/nixos/modules/services/monitoring/smartd.nix
@@ -4,8 +4,7 @@ with lib;
 
 let
 
-  host = config.networking.hostName or "unknown"
-       + optionalString (config.networking.domain != null) ".${config.networking.domain}";
+  host = config.networking.fqdnOrHostName;
 
   cfg = config.services.smartd;
   opt = options.services.smartd;
@@ -72,14 +71,14 @@ let
       device = mkOption {
         example = "/dev/sda";
         type = types.str;
-        description = "Location of the device.";
+        description = lib.mdDoc "Location of the device.";
       };
 
       options = mkOption {
         default = "";
         example = "-d sat";
         type = types.separatedString " ";
-        description = "Options that determine how smartd monitors the device.";
+        description = lib.mdDoc "Options that determine how smartd monitors the device.";
       };
 
     };
@@ -95,17 +94,17 @@ in
 
     services.smartd = {
 
-      enable = mkEnableOption "smartd daemon from <literal>smartmontools</literal> package";
+      enable = mkEnableOption (lib.mdDoc "smartd daemon from `smartmontools` package");
 
       autodetect = mkOption {
         default = true;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whenever smartd should monitor all devices connected to the
           machine at the time it's being started (the default).
 
           Set to false to monitor the devices listed in
-          <option>services.smartd.devices</option> only.
+          {option}`services.smartd.devices` only.
         '';
       };
 
@@ -113,11 +112,11 @@ in
         default = [];
         type = types.listOf types.str;
         example = ["-A /var/log/smartd/" "--interval=3600"];
-        description = ''
-          Extra command-line options passed to the <literal>smartd</literal>
+        description = lib.mdDoc ''
+          Extra command-line options passed to the `smartd`
           daemon on startup.
 
-          (See <literal>man 8 smartd</literal>.)
+          (See `man 8 smartd`.)
         '';
       };
 
@@ -128,33 +127,33 @@ in
             default = config.services.mail.sendmailSetuidWrapper != null;
             defaultText = literalExpression "config.services.mail.sendmailSetuidWrapper != null";
             type = types.bool;
-            description = "Whenever to send e-mail notifications.";
+            description = lib.mdDoc "Whenever to send e-mail notifications.";
           };
 
           sender = mkOption {
             default = "root";
             example = "example@domain.tld";
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               Sender of the notification messages.
-              Acts as the value of <literal>email</literal> in the emails' <literal>From: ... </literal> field.
+              Acts as the value of `email` in the emails' `From: ...` field.
             '';
           };
 
           recipient = mkOption {
             default = "root";
             type = types.str;
-            description = "Recipient of the notification messages.";
+            description = lib.mdDoc "Recipient of the notification messages.";
           };
 
           mailer = mkOption {
             default = "/run/wrappers/bin/sendmail";
             type = types.path;
-            description = ''
+            description = lib.mdDoc ''
               Sendmail-compatible binary to be used to send the messages.
 
               You should probably enable
-              <option>services.postfix</option> or some other MTA for
+              {option}`services.postfix` or some other MTA for
               this to work.
             '';
           };
@@ -164,7 +163,7 @@ in
           enable = mkOption {
             default = true;
             type = types.bool;
-            description = "Whenever to send wall notifications to all users.";
+            description = lib.mdDoc "Whenever to send wall notifications to all users.";
           };
         };
 
@@ -173,21 +172,21 @@ in
             default = config.services.xserver.enable;
             defaultText = literalExpression "config.services.xserver.enable";
             type = types.bool;
-            description = "Whenever to send X11 xmessage notifications.";
+            description = lib.mdDoc "Whenever to send X11 xmessage notifications.";
           };
 
           display = mkOption {
             default = ":${toString config.services.xserver.display}";
             defaultText = literalExpression ''":''${toString config.services.xserver.display}"'';
             type = types.str;
-            description = "DISPLAY to send X11 notifications to.";
+            description = lib.mdDoc "DISPLAY to send X11 notifications to.";
           };
         };
 
         test = mkOption {
           default = false;
           type = types.bool;
-          description = "Whenever to send a test notification on startup.";
+          description = lib.mdDoc "Whenever to send a test notification on startup.";
         };
 
       };
@@ -197,12 +196,12 @@ in
           default = "-a";
           type = types.separatedString " ";
           example = "-a -o on -s (S/../.././02|L/../../7/04)";
-          description = ''
+          description = lib.mdDoc ''
             Common default options for explicitly monitored (listed in
-            <option>services.smartd.devices</option>) devices.
+            {option}`services.smartd.devices`) devices.
 
             The default value turns on monitoring of all the things (see
-            <literal>man 5 smartd.conf</literal>).
+            `man 5 smartd.conf`).
 
             The example also turns on SMART Automatic Offline Testing on
             startup, and schedules short self-tests daily, and long
@@ -214,8 +213,8 @@ in
           default = cfg.defaults.monitored;
           defaultText = literalExpression "config.${opt.defaults.monitored}";
           type = types.separatedString " ";
-          description = ''
-            Like <option>services.smartd.defaults.monitored</option>, but for the
+          description = lib.mdDoc ''
+            Like {option}`services.smartd.defaults.monitored`, but for the
             autodetected devices.
           '';
         };
@@ -225,7 +224,7 @@ in
         default = [];
         example = [ { device = "/dev/sda"; } { device = "/dev/sdb"; options = "-d sat"; } ];
         type = with types; listOf (submodule smartdDeviceOpts);
-        description = "List of devices to monitor.";
+        description = lib.mdDoc "List of devices to monitor.";
       };
 
     };
diff --git a/nixos/modules/services/monitoring/statsd.nix b/nixos/modules/services/monitoring/statsd.nix
index 30b2916a992..bbc1c7146a8 100644
--- a/nixos/modules/services/monitoring/statsd.nix
+++ b/nixos/modules/services/monitoring/statsd.nix
@@ -56,34 +56,34 @@ in
 
   options.services.statsd = {
 
-    enable = mkEnableOption "statsd";
+    enable = mkEnableOption (lib.mdDoc "statsd");
 
     listenAddress = mkOption {
-      description = "Address that statsd listens on over UDP";
+      description = lib.mdDoc "Address that statsd listens on over UDP";
       default = "127.0.0.1";
       type = types.str;
     };
 
     port = mkOption {
-      description = "Port that stats listens for messages on over UDP";
+      description = lib.mdDoc "Port that stats listens for messages on over UDP";
       default = 8125;
       type = types.int;
     };
 
     mgmt_address = mkOption {
-      description = "Address to run management TCP interface on";
+      description = lib.mdDoc "Address to run management TCP interface on";
       default = "127.0.0.1";
       type = types.str;
     };
 
     mgmt_port = mkOption {
-      description = "Port to run the management TCP interface on";
+      description = lib.mdDoc "Port to run the management TCP interface on";
       default = 8126;
       type = types.int;
     };
 
     backends = mkOption {
-      description = "List of backends statsd will use for data persistence";
+      description = lib.mdDoc "List of backends statsd will use for data persistence";
       default = [];
       example = [
         "graphite"
@@ -97,19 +97,19 @@ in
     };
 
     graphiteHost = mkOption {
-      description = "Hostname or IP of Graphite server";
+      description = lib.mdDoc "Hostname or IP of Graphite server";
       default = null;
       type = types.nullOr types.str;
     };
 
     graphitePort = mkOption {
-      description = "Port of Graphite server (i.e. carbon-cache).";
+      description = lib.mdDoc "Port of Graphite server (i.e. carbon-cache).";
       default = null;
       type = types.nullOr types.int;
     };
 
     extraConfig = mkOption {
-      description = "Extra configuration options for statsd";
+      description = lib.mdDoc "Extra configuration options for statsd";
       default = "";
       type = types.nullOr types.str;
     };
diff --git a/nixos/modules/services/monitoring/sysstat.nix b/nixos/modules/services/monitoring/sysstat.nix
index ca2cff82723..5468fc3aa45 100644
--- a/nixos/modules/services/monitoring/sysstat.nix
+++ b/nixos/modules/services/monitoring/sysstat.nix
@@ -5,12 +5,12 @@ let
 in {
   options = {
     services.sysstat = {
-      enable = mkEnableOption "sar system activity collection";
+      enable = mkEnableOption (lib.mdDoc "sar system activity collection");
 
       collect-frequency = mkOption {
         type = types.str;
         default = "*:00/10";
-        description = ''
+        description = lib.mdDoc ''
           OnCalendar specification for sysstat-collect
         '';
       };
@@ -18,7 +18,7 @@ in {
       collect-args = mkOption {
         type = types.str;
         default = "1 1";
-        description = ''
+        description = lib.mdDoc ''
           Arguments to pass sa1 when collecting statistics
         '';
       };
diff --git a/nixos/modules/services/monitoring/teamviewer.nix b/nixos/modules/services/monitoring/teamviewer.nix
index e2271e571c4..9b127831794 100644
--- a/nixos/modules/services/monitoring/teamviewer.nix
+++ b/nixos/modules/services/monitoring/teamviewer.nix
@@ -14,7 +14,7 @@ in
 
   options = {
 
-    services.teamviewer.enable = mkEnableOption "TeamViewer daemon";
+    services.teamviewer.enable = mkEnableOption (lib.mdDoc "TeamViewer daemon");
 
   };
 
@@ -30,7 +30,7 @@ in
       description = "TeamViewer remote control daemon";
 
       wantedBy = [ "multi-user.target" ];
-      after = [ "NetworkManager-wait-online.service" "network.target" "dbus.service" ];
+      after = [ "network-online.target" "network.target" "dbus.service" ];
       requires = [ "dbus.service" ];
       preStart = "mkdir -pv /var/lib/teamviewer /var/log/teamviewer";
 
diff --git a/nixos/modules/services/monitoring/telegraf.nix b/nixos/modules/services/monitoring/telegraf.nix
index 13aae58d0f3..913e599c189 100644
--- a/nixos/modules/services/monitoring/telegraf.nix
+++ b/nixos/modules/services/monitoring/telegraf.nix
@@ -11,12 +11,12 @@ in {
   ###### interface
   options = {
     services.telegraf = {
-      enable = mkEnableOption "telegraf server";
+      enable = mkEnableOption (lib.mdDoc "telegraf server");
 
       package = mkOption {
         default = pkgs.telegraf;
         defaultText = literalExpression "pkgs.telegraf";
-        description = "Which telegraf derivation to use";
+        description = lib.mdDoc "Which telegraf derivation to use";
         type = types.package;
       };
 
@@ -24,17 +24,17 @@ in {
         type = types.listOf types.path;
         default = [];
         example = [ "/run/keys/telegraf.env" ];
-        description = ''
+        description = lib.mdDoc ''
           File to load as environment file. Environment variables from this file
           will be interpolated into the config file using envsubst with this
-          syntax: <literal>$ENVIRONMENT</literal> or <literal>''${VARIABLE}</literal>.
+          syntax: `$ENVIRONMENT` or `''${VARIABLE}`.
           This is useful to avoid putting secrets into the nix store.
         '';
       };
 
       extraConfig = mkOption {
         default = {};
-        description = "Extra configuration options for telegraf";
+        description = lib.mdDoc "Extra configuration options for telegraf";
         type = settingsFormat.type;
         example = {
           outputs.influxdb = {
diff --git a/nixos/modules/services/monitoring/thanos.nix b/nixos/modules/services/monitoring/thanos.nix
index 9e93d8dbb0e..41462da4ff4 100644
--- a/nixos/modules/services/monitoring/thanos.nix
+++ b/nixos/modules/services/monitoring/thanos.nix
@@ -8,7 +8,7 @@ let
   nullOpt = type: description: mkOption {
     type = types.nullOr type;
     default = null;
-    inherit description;
+    description = lib.mdDoc description;
   };
 
   optionToArgs = opt: v  : optional (v != null)  ''--${opt}="${toString v}"'';
@@ -18,8 +18,8 @@ let
 
   mkParamDef = type: default: description: mkParam type (description + ''
 
-    Defaults to <literal>${toString default}</literal> in Thanos
-    when set to <literal>null</literal>.
+    Defaults to `${toString default}` in Thanos
+    when set to `null`.
   '');
 
   mkParam = type: description: {
@@ -32,7 +32,7 @@ let
     option = mkOption {
       type = types.bool;
       default = false;
-      inherit description;
+      description = lib.mdDoc description;
     };
   };
 
@@ -41,7 +41,7 @@ let
     option = mkOption {
       type = types.listOf types.str;
       default = [];
-      inherit description;
+      description = lib.mdDoc description;
     };
   };
 
@@ -50,7 +50,7 @@ let
     option = mkOption {
       type = types.attrsOf types.str;
       default = {};
-      inherit description;
+      description = lib.mdDoc description;
     };
   };
 
@@ -59,7 +59,7 @@ let
     option = mkOption {
       type = types.str;
       inherit default;
-      inherit description;
+      description = lib.mdDoc description;
     };
   };
 
@@ -83,14 +83,14 @@ let
   mkArgumentsOption = cmd: mkOption {
     type = types.listOf types.str;
     default = argumentsOf cmd;
-    defaultText = literalDocBook ''
-      calculated from <literal>config.services.thanos.${cmd}</literal>
+    defaultText = literalMD ''
+      calculated from `config.services.thanos.${cmd}`
     '';
-    description = ''
-      Arguments to the <literal>thanos ${cmd}</literal> command.
+    description = lib.mdDoc ''
+      Arguments to the `thanos ${cmd}` command.
 
       Defaults to a list of arguments formed by converting the structured
-      options of <option>services.thanos.${cmd}</option> to a list of arguments.
+      options of {option}`services.thanos.${cmd}` to a list of arguments.
 
       Overriding this option will cause none of the structured options to have
       any effect. So only set this if you know what you're doing!
@@ -127,10 +127,10 @@ let
             if config.services.thanos.<cmd>.tracing.config == null then null
             else toString (toYAML "tracing.yaml" config.services.thanos.<cmd>.tracing.config);
           '';
-          description = ''
+          description = lib.mdDoc ''
             Path to YAML file that contains tracing configuration.
 
-            See format details: <link xlink:href="https://thanos.io/tracing.md/#configuration"/>
+            See format details: <https://thanos.io/tracing.md/#configuration>
           '';
         };
       };
@@ -141,13 +141,13 @@ let
           option = nullOpt types.attrs ''
             Tracing configuration.
 
-            When not <literal>null</literal> the attribute set gets converted to
+            When not `null` the attribute set gets converted to
             a YAML file and stored in the Nix store. The option
-            <option>tracing.config-file</option> will default to its path.
+            {option}`tracing.config-file` will default to its path.
 
-            If <option>tracing.config-file</option> is set this option has no effect.
+            If {option}`tracing.config-file` is set this option has no effect.
 
-            See format details: <link xlink:href="https://thanos.io/tracing.md/#configuration"/>
+            See format details: <https://thanos.io/tracing.md/#configuration>
           '';
         };
     };
@@ -155,11 +155,11 @@ let
     common = cfg: params.log // params.tracing cfg // {
 
       http-address = mkParamDef types.str "0.0.0.0:10902" ''
-        Listen <literal>host:port</literal> for HTTP endpoints.
+        Listen `host:port` for HTTP endpoints.
       '';
 
       grpc-address = mkParamDef types.str "0.0.0.0:10901" ''
-        Listen <literal>ip:port</literal> address for gRPC endpoints (StoreAPI).
+        Listen `ip:port` address for gRPC endpoints (StoreAPI).
 
         Make sure this address is routable from other components.
       '';
@@ -192,10 +192,10 @@ let
             if config.services.thanos.<cmd>.objstore.config == null then null
             else toString (toYAML "objstore.yaml" config.services.thanos.<cmd>.objstore.config);
           '';
-          description = ''
+          description = lib.mdDoc ''
             Path to YAML file that contains object store configuration.
 
-            See format details: <link xlink:href="https://thanos.io/storage.md/#configuration"/>
+            See format details: <https://thanos.io/storage.md/#configuration>
           '';
         };
       };
@@ -206,13 +206,13 @@ let
           option = nullOpt types.attrs ''
             Object store configuration.
 
-            When not <literal>null</literal> the attribute set gets converted to
+            When not `null` the attribute set gets converted to
             a YAML file and stored in the Nix store. The option
-            <option>objstore.config-file</option> will default to its path.
+            {option}`objstore.config-file` will default to its path.
 
-            If <option>objstore.config-file</option> is set this option has no effect.
+            If {option}`objstore.config-file` is set this option has no effect.
 
-            See format details: <link xlink:href="https://thanos.io/storage.md/#configuration"/>
+            See format details: <https://thanos.io/storage.md/#configuration>
           '';
         };
     };
@@ -231,7 +231,7 @@ let
           type = types.str;
           default = "/var/lib/${config.services.prometheus.stateDir}/data";
           defaultText = literalExpression ''"/var/lib/''${config.services.prometheus.stateDir}/data"'';
-          description = ''
+          description = lib.mdDoc ''
             Data directory of TSDB.
           '';
         };
@@ -254,7 +254,7 @@ let
     store = params.common cfg.store // params.objstore cfg.store // {
 
       stateDir = mkStateDirParam "data-dir" "thanos-store" ''
-        Data directory relative to <literal>/var/lib</literal>
+        Data directory relative to `/var/lib`
         in which to cache remote blocks.
       '';
 
@@ -269,7 +269,7 @@ let
       store.grpc.series-sample-limit = mkParamDef types.int 0 ''
         Maximum amount of samples returned via a single Series call.
 
-        <literal>0</literal> means no limit.
+        `0` means no limit.
 
         NOTE: for efficiency we take 120 as the number of samples in chunk (it
         cannot be bigger than that), so the actual number of samples might be
@@ -327,14 +327,14 @@ let
 
       grpc-client-server-name = mkParam types.str ''
         Server name to verify the hostname on the returned gRPC certificates.
-        See <link xlink:href="https://tools.ietf.org/html/rfc4366#section-3.1"/>
+        See <https://tools.ietf.org/html/rfc4366#section-3.1>
       '';
 
       web.route-prefix = mkParam types.str ''
         Prefix for API and UI endpoints.
 
         This allows thanos UI to be served on a sub-path. This option is
-        analogous to <option>web.route-prefix</option> of Promethus.
+        analogous to {option}`web.route-prefix` of Promethus.
       '';
 
       web.external-prefix = mkParam types.str ''
@@ -342,7 +342,7 @@ let
         interface.
 
         Actual endpoints are still served on / or the
-        <option>web.route-prefix</option>. This allows thanos UI to be served
+        {option}`web.route-prefix`. This allows thanos UI to be served
         behind a reverse proxy that strips a URL sub-path.
       '';
 
@@ -351,15 +351,15 @@ let
         redirects.
 
         This option is ignored if the option
-        <literal>web.external-prefix</literal> is set.
+        `web.external-prefix` is set.
 
         Security risk: enable this option only if a reverse proxy in front of
         thanos is resetting the header.
 
-        The setting <literal>web.prefix-header="X-Forwarded-Prefix"</literal>
+        The setting `web.prefix-header="X-Forwarded-Prefix"`
         can be useful, for example, if Thanos UI is served via Traefik reverse
-        proxy with <literal>PathPrefixStrip</literal> option enabled, which
-        sends the stripped prefix value in <literal>X-Forwarded-Prefix</literal>
+        proxy with `PathPrefixStrip` option enabled, which
+        sends the stripped prefix value in `X-Forwarded-Prefix`
         header. This allows thanos UI to be served on a sub-path.
       '';
 
@@ -376,7 +376,7 @@ let
         deduplicated.
 
         Still you will be able to query without deduplication using
-        <literal>dedup=false</literal> parameter.
+        `dedup=false` parameter.
       '';
 
       selector-labels = mkAttrsParam "selector-label" ''
@@ -386,8 +386,8 @@ let
       store.addresses = mkListParam "store" ''
         Addresses of statically configured store API servers.
 
-        The scheme may be prefixed with <literal>dns+</literal> or
-        <literal>dnssrv+</literal> to detect store API servers through
+        The scheme may be prefixed with `dns+` or
+        `dnssrv+` to detect store API servers through
         respective DNS lookups.
       '';
 
@@ -411,12 +411,12 @@ let
       query.auto-downsampling = mkFlagParam ''
         Enable automatic adjustment (step / 5) to what source of data should
         be used in store gateways if no
-        <literal>max_source_resolution</literal> param is specified.
+        `max_source_resolution` param is specified.
       '';
 
       query.partial-response = mkFlagParam ''
         Enable partial response for queries if no
-        <literal>partial_response</literal> param is specified.
+        `partial_response` param is specified.
       '';
 
       query.default-evaluation-interval = mkParamDef types.str "1m" ''
@@ -426,7 +426,7 @@ let
       store.response-timeout = mkParamDef types.str "0ms" ''
         If a Store doesn't send any data in this specified duration then a
         Store will be ignored and partial data will be returned if it's
-        enabled. <literal>0</literal> disables timeout.
+        enabled. `0` disables timeout.
       '';
     };
 
@@ -440,7 +440,7 @@ let
       '';
 
       stateDir = mkStateDirParam "data-dir" "thanos-rule" ''
-        Data directory relative to <literal>/var/lib</literal>.
+        Data directory relative to `/var/lib`.
       '';
 
       rule-files = mkListParam "rule-file" ''
@@ -464,9 +464,9 @@ let
 
         Ruler claims success if push to at least one alertmanager from
         discovered succeeds. The scheme may be prefixed with
-        <literal>dns+</literal> or <literal>dnssrv+</literal> to detect
+        `dns+` or `dnssrv+` to detect
         Alertmanager IPs through respective DNS lookups. The port defaults to
-        <literal>9093</literal> or the SRV record's value. The URL path is
+        `9093` or the SRV record's value. The URL path is
         used as a prefix for the regular Alertmanager API path.
       '';
 
@@ -491,7 +491,7 @@ let
 
         This allows thanos UI to be served on a sub-path.
 
-        This option is analogous to <literal>--web.route-prefix</literal> of Promethus.
+        This option is analogous to `--web.route-prefix` of Promethus.
       '';
 
       web.external-prefix = mkParam types.str ''
@@ -499,7 +499,7 @@ let
         interface.
 
         Actual endpoints are still served on / or the
-        <option>web.route-prefix</option>. This allows thanos UI to be served
+        {option}`web.route-prefix`. This allows thanos UI to be served
         behind a reverse proxy that strips a URL sub-path.
       '';
 
@@ -508,23 +508,23 @@ let
         redirects.
 
         This option is ignored if the option
-        <option>web.external-prefix</option> is set.
+        {option}`web.external-prefix` is set.
 
         Security risk: enable this option only if a reverse proxy in front of
         thanos is resetting the header.
 
-        The header <literal>X-Forwarded-Prefix</literal> can be useful, for
+        The header `X-Forwarded-Prefix` can be useful, for
         example, if Thanos UI is served via Traefik reverse proxy with
-        <literal>PathPrefixStrip</literal> option enabled, which sends the
-        stripped prefix value in <literal>X-Forwarded-Prefix</literal>
+        `PathPrefixStrip` option enabled, which sends the
+        stripped prefix value in `X-Forwarded-Prefix`
         header. This allows thanos UI to be served on a sub-path.
       '';
 
       query.addresses = mkListParam "query" ''
         Addresses of statically configured query API servers.
 
-        The scheme may be prefixed with <literal>dns+</literal> or
-        <literal>dnssrv+</literal> to detect query API servers through
+        The scheme may be prefixed with `dns+` or
+        `dnssrv+` to detect query API servers through
         respective DNS lookups.
       '';
 
@@ -545,11 +545,11 @@ let
     compact = params.log // params.tracing cfg.compact // params.objstore cfg.compact // {
 
       http-address = mkParamDef types.str "0.0.0.0:10902" ''
-        Listen <literal>host:port</literal> for HTTP endpoints.
+        Listen `host:port` for HTTP endpoints.
       '';
 
       stateDir = mkStateDirParam "data-dir" "thanos-compact" ''
-        Data directory relative to <literal>/var/lib</literal>
+        Data directory relative to `/var/lib`
         in which to cache blocks and process compactions.
       '';
 
@@ -562,28 +562,28 @@ let
       retention.resolution-raw = mkParamDef types.str "0d" ''
         How long to retain raw samples in bucket.
 
-        <literal>0d</literal> - disables this retention
+        `0d` - disables this retention
       '';
 
       retention.resolution-5m = mkParamDef types.str "0d" ''
         How long to retain samples of resolution 1 (5 minutes) in bucket.
 
-        <literal>0d</literal> - disables this retention
+        `0d` - disables this retention
       '';
 
       retention.resolution-1h = mkParamDef types.str "0d" ''
         How long to retain samples of resolution 2 (1 hour) in bucket.
 
-        <literal>0d</literal> - disables this retention
+        `0d` - disables this retention
       '';
 
       startAt = {
         toArgs = _opt: startAt: flagToArgs "wait" (startAt == null);
         option = nullOpt types.str ''
-          When this option is set to a <literal>systemd.time</literal>
+          When this option is set to a `systemd.time`
           specification the Thanos compactor will run at the specified period.
 
-          When this option is <literal>null</literal> the Thanos compactor service
+          When this option is `null` the Thanos compactor service
           will run continuously. So it will not exit after all compactions have
           been processed but wait for new work.
         '';
@@ -609,7 +609,7 @@ let
     downsample = params.log // params.tracing cfg.downsample // params.objstore cfg.downsample // {
 
       stateDir = mkStateDirParam "data-dir" "thanos-downsample" ''
-        Data directory relative to <literal>/var/lib</literal>
+        Data directory relative to `/var/lib`
         in which to cache blocks and process downsamplings.
       '';
 
@@ -622,7 +622,7 @@ let
       '';
 
       stateDir = mkStateDirParam "tsdb.path" "thanos-receive" ''
-        Data directory relative to <literal>/var/lib</literal> of TSDB.
+        Data directory relative to `/var/lib` of TSDB.
       '';
 
       labels = mkAttrsParam "labels" ''
@@ -635,7 +635,7 @@ let
       tsdb.retention = mkParamDef types.str "15d" ''
         How long to retain raw samples on local storage.
 
-        <literal>0d</literal> - disables this retention
+        `0d` - disables this retention
       '';
     };
 
@@ -660,53 +660,53 @@ in {
       type = types.package;
       default = pkgs.thanos;
       defaultText = literalExpression "pkgs.thanos";
-      description = ''
+      description = lib.mdDoc ''
         The thanos package that should be used.
       '';
     };
 
     sidecar = paramsToOptions params.sidecar // {
       enable = mkEnableOption
-        "the Thanos sidecar for Prometheus server";
+        (lib.mdDoc "the Thanos sidecar for Prometheus server");
       arguments = mkArgumentsOption "sidecar";
     };
 
     store = paramsToOptions params.store // {
       enable = mkEnableOption
-        "the Thanos store node giving access to blocks in a bucket provider.";
+        (lib.mdDoc "the Thanos store node giving access to blocks in a bucket provider.");
       arguments = mkArgumentsOption "store";
     };
 
     query = paramsToOptions params.query // {
       enable = mkEnableOption
-        ("the Thanos query node exposing PromQL enabled Query API " +
-         "with data retrieved from multiple store nodes");
+        (lib.mdDoc ("the Thanos query node exposing PromQL enabled Query API " +
+         "with data retrieved from multiple store nodes"));
       arguments = mkArgumentsOption "query";
     };
 
     rule = paramsToOptions params.rule // {
       enable = mkEnableOption
-        ("the Thanos ruler service which evaluates Prometheus rules against" +
-        " given Query nodes, exposing Store API and storing old blocks in bucket");
+        (lib.mdDoc ("the Thanos ruler service which evaluates Prometheus rules against" +
+        " given Query nodes, exposing Store API and storing old blocks in bucket"));
       arguments = mkArgumentsOption "rule";
     };
 
     compact = paramsToOptions params.compact // {
       enable = mkEnableOption
-        "the Thanos compactor which continuously compacts blocks in an object store bucket";
+        (lib.mdDoc "the Thanos compactor which continuously compacts blocks in an object store bucket");
       arguments = mkArgumentsOption "compact";
     };
 
     downsample = paramsToOptions params.downsample // {
       enable = mkEnableOption
-        "the Thanos downsampler which continuously downsamples blocks in an object store bucket";
+        (lib.mdDoc "the Thanos downsampler which continuously downsamples blocks in an object store bucket");
       arguments = mkArgumentsOption "downsample";
     };
 
     receive = paramsToOptions params.receive // {
       enable = mkEnableOption
-        ("the Thanos receiver which accept Prometheus remote write API requests " +
-         "and write to local tsdb (EXPERIMENTAL, this may change drastically without notice)");
+        (lib.mdDoc ("the Thanos receiver which accept Prometheus remote write API requests " +
+         "and write to local tsdb (EXPERIMENTAL, this may change drastically without notice)"));
       arguments = mkArgumentsOption "receive";
     };
   };
diff --git a/nixos/modules/services/monitoring/tremor-rs.nix b/nixos/modules/services/monitoring/tremor-rs.nix
new file mode 100644
index 00000000000..213e8a47486
--- /dev/null
+++ b/nixos/modules/services/monitoring/tremor-rs.nix
@@ -0,0 +1,129 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let
+
+  cfg = config.services.tremor-rs;
+
+  loggerSettingsFormat = pkgs.formats.yaml { };
+  loggerConfigFile = loggerSettingsFormat.generate "logger.yaml" cfg.loggerSettings;
+in {
+
+  options = {
+    services.tremor-rs = {
+      enable = lib.mkEnableOption (lib.mdDoc "Tremor event- or stream-processing system");
+
+      troyFileList = mkOption {
+        type = types.listOf types.path;
+        default = [];
+        description = lib.mdDoc "List of troy files to load.";
+      };
+
+      tremorLibDir = mkOption {
+        type = types.path;
+        default = "";
+        description = lib.mdDoc "Directory where to find /lib containing tremor script files";
+      };
+
+      host = mkOption {
+        type = types.str;
+        default = "127.0.0.1";
+        description = lib.mdDoc "The host tremor should be listening on";
+      };
+
+      port = mkOption {
+        type = types.port;
+        default = 9898;
+        description = lib.mdDoc "the port tremor should be listening on";
+      };
+
+      loggerSettings = mkOption {
+        description = lib.mdDoc "Tremor logger configuration";
+        default = {};
+        type = loggerSettingsFormat.type;
+
+        example = {
+          refresh_rate = "30 seconds";
+          appenders.stdout.kind = "console";
+          root = {
+            level = "warn";
+            appenders = [ "stdout" ];
+          };
+          loggers = {
+            tremor_runtime = {
+              level = "debug";
+              appenders = [ "stdout" ];
+              additive = false;
+            };
+            tremor = {
+              level = "debug";
+              appenders = [ "stdout" ];
+              additive = false;
+            };
+          };
+        };
+
+        defaultText = literalExpression ''
+          {
+            refresh_rate = "30 seconds";
+            appenders.stdout.kind = "console";
+            root = {
+              level = "warn";
+              appenders = [ "stdout" ];
+            };
+            loggers = {
+              tremor_runtime = {
+                level = "debug";
+                appenders = [ "stdout" ];
+                additive = false;
+              };
+              tremor = {
+                level = "debug";
+                appenders = [ "stdout" ];
+                additive = false;
+              };
+            };
+          }
+        '';
+
+      };
+    };
+  };
+
+  config = mkIf (cfg.enable) {
+
+    environment.systemPackages = [ pkgs.tremor-rs ] ;
+
+    systemd.services.tremor-rs = {
+      description = "Tremor event- or stream-processing system";
+      wantedBy = [ "multi-user.target" ];
+      requires = [ "network-online.target" ];
+      after = [ "network-online.target" ];
+
+      environment.TREMOR_PATH = "${pkgs.tremor-rs}/lib:${cfg.tremorLibDir}";
+
+      serviceConfig = {
+        ExecStart = "${pkgs.tremor-rs}/bin/tremor --logger-config ${loggerConfigFile} server run ${concatStringsSep " " cfg.troyFileList} --api-host ${cfg.host}:${toString cfg.port}";
+        DynamicUser = true;
+        Restart = "always";
+        NoNewPrivileges = true;
+        PrivateTmp = true;
+        ProtectHome = true;
+        ProtectClock = true;
+        ProtectProc = "noaccess";
+        ProcSubset = "pid";
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectControlGroups = true;
+        ProtectHostname = true;
+        RestrictSUIDSGID = true;
+        RestrictRealtime = true;
+        RestrictNamespaces = true;
+        LockPersonality = true;
+        RemoveIPC = true;
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/monitoring/tuptime.nix b/nixos/modules/services/monitoring/tuptime.nix
index de80282559a..d97e408bce3 100644
--- a/nixos/modules/services/monitoring/tuptime.nix
+++ b/nixos/modules/services/monitoring/tuptime.nix
@@ -10,19 +10,19 @@ in {
 
   options.services.tuptime = {
 
-    enable = mkEnableOption "the total uptime service";
+    enable = mkEnableOption (lib.mdDoc "the total uptime service");
 
     timer = {
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to regularly log uptime to detect bad shutdowns.";
+        description = lib.mdDoc "Whether to regularly log uptime to detect bad shutdowns.";
       };
 
       period = mkOption {
         type = types.str;
         default = "*:0/5";
-        description = "systemd calendar event";
+        description = lib.mdDoc "systemd calendar event";
       };
     };
   };
@@ -45,7 +45,7 @@ in {
       services = {
 
         tuptime = {
-          description = "the total uptime service";
+          description = "The total uptime service";
           documentation = [ "man:tuptime(1)" ];
           after = [ "time-sync.target" ];
           wantedBy = [ "multi-user.target" ];
@@ -59,10 +59,9 @@ in {
           };
         };
 
-        tuptime-oneshot = mkIf cfg.timer.enable {
-          description = "the tuptime scheduled execution unit";
+        tuptime-sync = mkIf cfg.timer.enable {
+          description = "Tuptime scheduled sync service";
           serviceConfig = {
-            StateDirectory = "tuptime";
             Type = "oneshot";
             User = "_tuptime";
             ExecStart = "${pkgs.tuptime}/bin/tuptime -x";
@@ -70,8 +69,8 @@ in {
         };
       };
 
-      timers.tuptime = mkIf cfg.timer.enable {
-        description = "the tuptime scheduled execution timer";
+      timers.tuptime-sync = mkIf cfg.timer.enable {
+        description = "Tuptime scheduled sync timer";
         # this timer should be started if the service is started
         # even if the timer was previously stopped
         wantedBy = [ "tuptime.service" "timers.target" ];
@@ -80,7 +79,7 @@ in {
         timerConfig = {
           OnBootSec = "1min";
           OnCalendar = cfg.timer.period;
-          Unit = "tuptime-oneshot.service";
+          Unit = "tuptime-sync.service";
         };
       };
     };
diff --git a/nixos/modules/services/monitoring/unifi-poller.nix b/nixos/modules/services/monitoring/unifi-poller.nix
index cca4a0e7207..b30e28a3ecc 100644
--- a/nixos/modules/services/monitoring/unifi-poller.nix
+++ b/nixos/modules/services/monitoring/unifi-poller.nix
@@ -11,13 +11,13 @@ let
 
 in {
   options.services.unifi-poller = {
-    enable = mkEnableOption "unifi-poller";
+    enable = mkEnableOption (lib.mdDoc "unifi-poller");
 
     poller = {
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Turns on line numbers, microsecond logging, and a per-device log.
           This may be noisy if you have a lot of devices. It adds one line per device.
         '';
@@ -25,14 +25,14 @@ in {
       quiet = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Turns off per-interval logs. Only startup and error logs will be emitted.
         '';
       };
       plugins = mkOption {
         type = with types; listOf str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Load additional plugins.
         '';
       };
@@ -42,21 +42,21 @@ in {
       disable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to disable the prometheus ouput plugin.
         '';
       };
       http_listen = mkOption {
         type = types.str;
         default = "[::]:9130";
-        description = ''
+        description = lib.mdDoc ''
           Bind the prometheus exporter to this IP or hostname.
         '';
       };
       report_errors = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to report errors.
         '';
       };
@@ -66,21 +66,21 @@ in {
       disable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to disable the influxdb ouput plugin.
         '';
       };
       url = mkOption {
         type = types.str;
         default = "http://127.0.0.1:8086";
-        description = ''
+        description = lib.mdDoc ''
           URL of the influxdb host.
         '';
       };
       user = mkOption {
         type = types.str;
         default = "unifipoller";
-        description = ''
+        description = lib.mdDoc ''
           Username for the influxdb.
         '';
       };
@@ -88,7 +88,7 @@ in {
         type = types.path;
         default = pkgs.writeText "unifi-poller-influxdb-default.password" "unifipoller";
         defaultText = literalExpression "unifi-poller-influxdb-default.password";
-        description = ''
+        description = lib.mdDoc ''
           Path of a file containing the password for influxdb.
           This file needs to be readable by the unifi-poller user.
         '';
@@ -97,21 +97,21 @@ in {
       db = mkOption {
         type = types.str;
         default = "unifi";
-        description = ''
+        description = lib.mdDoc ''
           Database name. Database should exist.
         '';
       };
       verify_ssl = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Verify the influxdb's certificate.
         '';
       };
       interval = mkOption {
         type = types.str;
         default = "30s";
-        description = ''
+        description = lib.mdDoc ''
           Setting this lower than the Unifi controller's refresh
           interval may lead to zeroes in your database.
         '';
@@ -122,14 +122,14 @@ in {
       url = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           URL of the Loki host.
         '';
       };
       user = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Username for Loki.
         '';
       };
@@ -137,7 +137,7 @@ in {
         type = types.path;
         default = pkgs.writeText "unifi-poller-loki-default.password" "";
         defaultText = "unifi-poller-influxdb-default.password";
-        description = ''
+        description = lib.mdDoc ''
           Path of a file containing the password for Loki.
           This file needs to be readable by the unifi-poller user.
         '';
@@ -146,28 +146,28 @@ in {
       verify_ssl = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Verify Loki's certificate.
         '';
       };
       tenant_id = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Tenant ID to use in Loki.
         '';
       };
       interval = mkOption {
         type = types.str;
         default = "2m";
-        description = ''
+        description = lib.mdDoc ''
           How often the events are polled and pushed to Loki.
         '';
       };
       timeout = mkOption {
         type = types.str;
         default = "10s";
-        description = ''
+        description = lib.mdDoc ''
           Should be increased in case of timeout errors.
         '';
       };
@@ -178,7 +178,7 @@ in {
         user = mkOption {
           type = types.str;
           default = "unifi";
-          description = ''
+          description = lib.mdDoc ''
             Unifi service user name.
           '';
         };
@@ -186,7 +186,7 @@ in {
           type = types.path;
           default = pkgs.writeText "unifi-poller-unifi-default.password" "unifi";
           defaultText = literalExpression "unifi-poller-unifi-default.password";
-          description = ''
+          description = lib.mdDoc ''
             Path of a file containing the password for the unifi service user.
             This file needs to be readable by the unifi-poller user.
           '';
@@ -195,14 +195,14 @@ in {
         url = mkOption {
           type = types.str;
           default = "https://unifi:8443";
-          description = ''
+          description = lib.mdDoc ''
             URL of the Unifi controller.
           '';
         };
         sites = mkOption {
           type = with types; either (enum [ "default" "all" ]) (listOf str);
           default = "all";
-          description = ''
+          description = lib.mdDoc ''
             List of site names for which statistics should be exported.
             Or the string "default" for the default site or the string "all" for all sites.
           '';
@@ -211,35 +211,35 @@ in {
         save_ids = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Collect and save data from the intrusion detection system to influxdb and Loki.
           '';
         };
         save_events = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Collect and save data from UniFi events to influxdb and Loki.
           '';
         };
         save_alarms = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Collect and save data from UniFi alarms to influxdb and Loki.
           '';
         };
         save_anomalies = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Collect and save data from UniFi anomalies to influxdb and Loki.
           '';
         };
         save_dpi = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Collect and save data from deep packet inspection.
             Adds around 150 data points and impacts performance.
           '';
@@ -247,14 +247,14 @@ in {
         save_sites = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Collect and save site data.
           '';
         };
         hash_pii = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Hash, with md5, client names and MAC addresses. This attempts
             to protect personally identifiable information.
           '';
@@ -262,7 +262,7 @@ in {
         verify_ssl = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Verify the Unifi controller's certificate.
           '';
         };
@@ -272,7 +272,7 @@ in {
       dynamic = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Let prometheus select which controller to poll when scraping.
           Use with default credentials. See unifi-poller wiki for more.
         '';
@@ -283,7 +283,7 @@ in {
       controllers = mkOption {
         type = with types; listOf (submodule { options = controllerOptions; });
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of Unifi controllers to poll. Use defaults if empty.
         '';
         apply = map (flip removeAttrs [ "_module" ]);
diff --git a/nixos/modules/services/monitoring/ups.nix b/nixos/modules/services/monitoring/ups.nix
index ae5097c5442..c7abaeb2973 100644
--- a/nixos/modules/services/monitoring/ups.nix
+++ b/nixos/modules/services/monitoring/ups.nix
@@ -16,7 +16,7 @@ let
       # /nix/store/nut/share/driver.list
       driver = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specify the program to run to talk to this UPS.  apcsmart,
           bestups, and sec are some examples.
         '';
@@ -24,7 +24,7 @@ let
 
       port = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The serial port to which your UPS is connected.  /dev/ttyS0 is
           usually the first port on Linux boxes, for example.
         '';
@@ -33,7 +33,7 @@ let
       shutdownOrder = mkOption {
         default = 0;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           When you have multiple UPSes on your system, you usually need to
           turn them off in a certain order.  upsdrvctl shuts down all the
           0s, then the 1s, 2s, and so on.  To exclude a UPS from the
@@ -44,7 +44,7 @@ let
       maxStartDelay = mkOption {
         default = null;
         type = types.uniq (types.nullOr types.int);
-        description = ''
+        description = lib.mdDoc ''
           This can be set as a global variable above your first UPS
           definition and it can also be set in a UPS section.  This value
           controls how long upsdrvctl will wait for the driver to finish
@@ -56,7 +56,7 @@ let
       description = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Description of the UPS.
         '';
       };
@@ -64,7 +64,7 @@ let
       directives = mkOption {
         default = [];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           List of configuration directives for this UPS.
         '';
       };
@@ -72,7 +72,7 @@ let
       summary = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Lines which would be added inside ups.conf for handling this UPS.
         '';
       };
@@ -106,7 +106,7 @@ in
       enable = mkOption {
         default = false;
         type = with types; bool;
-        description = ''
+        description = lib.mdDoc ''
           Enables support for Power Devices, such as Uninterruptible Power
           Supplies, Power Distribution Units and Solar Controllers.
         '';
@@ -116,7 +116,7 @@ in
       mode = mkOption {
         default = "standalone";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The MODE determines which part of the NUT is to be started, and
           which configuration files must be modified.
 
@@ -143,7 +143,7 @@ in
       schedulerRules = mkOption {
         example = "/etc/nixos/upssched.conf";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           File which contains the rules to handle UPS events.
         '';
       };
@@ -152,7 +152,7 @@ in
       maxStartDelay = mkOption {
         default = 45;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           This can be set as a global variable above your first UPS
           definition and it can also be set in a UPS section.  This value
           controls how long upsdrvctl will wait for the driver to finish
@@ -164,7 +164,7 @@ in
       ups = mkOption {
         default = {};
         # see nut/etc/ups.conf.sample
-        description = ''
+        description = lib.mdDoc ''
           This is where you configure all the UPSes that this system will be
           monitoring directly.  These are usually attached to serial ports,
           but USB devices are also supported.
diff --git a/nixos/modules/services/monitoring/uptime-kuma.nix b/nixos/modules/services/monitoring/uptime-kuma.nix
new file mode 100644
index 00000000000..3a6091de679
--- /dev/null
+++ b/nixos/modules/services/monitoring/uptime-kuma.nix
@@ -0,0 +1,76 @@
+{ config, pkgs, lib, ... }:
+
+with lib;
+
+let
+  cfg = config.services.uptime-kuma;
+in
+{
+
+  options = {
+    services.uptime-kuma = {
+      enable = mkEnableOption (mdDoc "Uptime Kuma, this assumes a reverse proxy to be set.");
+
+      package = mkOption {
+        type = types.package;
+        example = literalExpression "pkgs.uptime-kuma";
+        default = pkgs.uptime-kuma;
+        defaultText = "pkgs.uptime-kuma";
+        description = lib.mdDoc "Uptime Kuma package to use.";
+      };
+
+      settings = lib.mkOption {
+        type =
+          lib.types.submodule { freeformType = with lib.types; attrsOf str; };
+        default = { };
+        example = {
+          PORT = "4000";
+          NODE_EXTRA_CA_CERTS = "/etc/ssl/certs/ca-certificates.crt";
+        };
+        description = lib.mdDoc ''
+          Additional configuration for Uptime Kuma, see
+          <https://github.com/louislam/uptime-kuma/wiki/Environment-Variables">
+          for supported values.
+        '';
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    services.uptime-kuma.settings = {
+      DATA_DIR = "/var/lib/uptime-kuma/";
+      NODE_ENV = mkDefault "production";
+    };
+
+    systemd.services.uptime-kuma = {
+      description = "Uptime Kuma";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+      environment = cfg.settings;
+      serviceConfig = {
+        Type = "simple";
+        StateDirectory = "uptime-kuma";
+        DynamicUser = true;
+        ExecStart = "${cfg.package}/bin/uptime-kuma-server";
+        Restart = "on-failure";
+        ProtectHome = true;
+        ProtectSystem = "strict";
+        PrivateTmp = true;
+        PrivateDevices = true;
+        ProtectHostname = true;
+        ProtectClock = true;
+        ProtectKernelTunables = true;
+        ProtectKernelModules = true;
+        ProtectKernelLogs = true;
+        ProtectControlGroups = true;
+        NoNewPrivileges = true;
+        RestrictRealtime = true;
+        RestrictSUIDSGID = true;
+        RemoveIPC = true;
+        PrivateMounts = true;
+      };
+    };
+  };
+}
+
diff --git a/nixos/modules/services/monitoring/uptime.nix b/nixos/modules/services/monitoring/uptime.nix
index 79b86be6cc7..7bf9e593c95 100644
--- a/nixos/modules/services/monitoring/uptime.nix
+++ b/nixos/modules/services/monitoring/uptime.nix
@@ -26,7 +26,7 @@ let
 in {
   options.services.uptime = {
     configFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The uptime configuration file
 
         If mongodb: server != localhost, please set usesRemoteMongo = true
@@ -44,22 +44,22 @@ in {
     };
 
     usesRemoteMongo = mkOption {
-      description = "Whether the configuration file specifies a remote mongo instance";
+      description = lib.mdDoc "Whether the configuration file specifies a remote mongo instance";
 
       default = false;
 
       type = types.bool;
     };
 
-    enableWebService = mkEnableOption "the uptime monitoring program web service";
+    enableWebService = mkEnableOption (lib.mdDoc "the uptime monitoring program web service");
 
-    enableSeparateMonitoringService = mkEnableOption "the uptime monitoring service" // {
+    enableSeparateMonitoringService = mkEnableOption (lib.mdDoc "the uptime monitoring service") // {
       default = cfg.enableWebService;
       defaultText = literalExpression "config.${opt.enableWebService}";
     };
 
     nodeEnv = mkOption {
-      description = "The node environment to run in (development, production, etc.)";
+      description = lib.mdDoc "The node environment to run in (development, production, etc.)";
 
       type = types.str;
 
diff --git a/nixos/modules/services/monitoring/vmagent.nix b/nixos/modules/services/monitoring/vmagent.nix
new file mode 100644
index 00000000000..c793bb07319
--- /dev/null
+++ b/nixos/modules/services/monitoring/vmagent.nix
@@ -0,0 +1,100 @@
+{ config, pkgs, lib, ... }:
+with lib;
+let
+  cfg = config.services.vmagent;
+  settingsFormat = pkgs.formats.json { };
+in {
+  options.services.vmagent = {
+    enable = mkEnableOption (lib.mdDoc "vmagent");
+
+    user = mkOption {
+      default = "vmagent";
+      type = types.str;
+      description = lib.mdDoc ''
+        User account under which vmagent runs.
+      '';
+    };
+
+    group = mkOption {
+      type = types.str;
+      default = "vmagent";
+      description = lib.mdDoc ''
+        Group under which vmagent runs.
+      '';
+    };
+
+    package = mkOption {
+      default = pkgs.vmagent;
+      defaultText = lib.literalMD "pkgs.vmagent";
+      type = types.package;
+      description = lib.mdDoc ''
+        vmagent package to use.
+      '';
+    };
+
+    dataDir = mkOption {
+      type = types.str;
+      default = "/var/lib/vmagent";
+      description = lib.mdDoc ''
+        The directory where vmagent stores its data files.
+      '';
+    };
+
+    remoteWriteUrl = mkOption {
+      default = "http://localhost:8428/api/v1/write";
+      type = types.str;
+      description = lib.mdDoc ''
+        The storage endpoint such as VictoriaMetrics
+      '';
+    };
+
+    prometheusConfig = mkOption {
+      type = lib.types.submodule { freeformType = settingsFormat.type; };
+      description = lib.mdDoc ''
+        Config for prometheus style metrics
+      '';
+    };
+
+    openFirewall = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Whether to open the firewall for the default ports.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    users.groups = mkIf (cfg.group == "vmagent") { vmagent = { }; };
+
+    users.users = mkIf (cfg.user == "vmagent") {
+      vmagent = {
+        group = cfg.group;
+        description = "vmagent daemon user";
+        home = cfg.dataDir;
+        isSystemUser = true;
+      };
+    };
+
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ 8429 ];
+
+    systemd.services.vmagent = let
+      prometheusConfig = settingsFormat.generate "prometheusConfig.yaml" cfg.prometheusConfig;
+    in {
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+      description = "vmagent system service";
+      serviceConfig = {
+        User = cfg.user;
+        Group = cfg.group;
+        Type = "simple";
+        Restart = "on-failure";
+        WorkingDirectory = cfg.dataDir;
+        ExecStart = "${cfg.package}/bin/vmagent -remoteWrite.url=${cfg.remoteWriteUrl} -promscrape.config=${prometheusConfig}";
+      };
+    };
+
+    systemd.tmpfiles.rules =
+      [ "d '${cfg.dataDir}' 0755 ${cfg.user} ${cfg.group} -" ];
+  };
+}
diff --git a/nixos/modules/services/monitoring/vnstat.nix b/nixos/modules/services/monitoring/vnstat.nix
index 5e19c399568..a498962ae57 100644
--- a/nixos/modules/services/monitoring/vnstat.nix
+++ b/nixos/modules/services/monitoring/vnstat.nix
@@ -6,7 +6,7 @@ let
   cfg = config.services.vnstat;
 in {
   options.services.vnstat = {
-    enable = mkEnableOption "update of network usage statistics via vnstatd";
+    enable = mkEnableOption (lib.mdDoc "update of network usage statistics via vnstatd");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/monitoring/zabbix-agent.nix b/nixos/modules/services/monitoring/zabbix-agent.nix
index c48b973f1ef..b497ecbcdb6 100644
--- a/nixos/modules/services/monitoring/zabbix-agent.nix
+++ b/nixos/modules/services/monitoring/zabbix-agent.nix
@@ -29,13 +29,13 @@ in
   options = {
 
     services.zabbixAgent = {
-      enable = mkEnableOption "the Zabbix Agent";
+      enable = mkEnableOption (lib.mdDoc "the Zabbix Agent");
 
       package = mkOption {
         type = types.package;
         default = pkgs.zabbix.agent;
         defaultText = literalExpression "pkgs.zabbix.agent";
-        description = "The Zabbix package to use.";
+        description = lib.mdDoc "The Zabbix package to use.";
       };
 
       extraPackages = mkOption {
@@ -43,15 +43,15 @@ in
         default = with pkgs; [ nettools ];
         defaultText = literalExpression "with pkgs; [ nettools ]";
         example = literalExpression "with pkgs; [ nettools mysql ]";
-        description = ''
-          Packages to be added to the Zabbix <envar>PATH</envar>.
+        description = lib.mdDoc ''
+          Packages to be added to the Zabbix {env}`PATH`.
           Typically used to add executables for scripts, but can be anything.
         '';
       };
 
       modules = mkOption {
         type = types.attrsOf types.package;
-        description = "A set of modules to load.";
+        description = lib.mdDoc "A set of modules to load.";
         default = {};
         example = literalExpression ''
           {
@@ -71,7 +71,7 @@ in
 
       server = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The IP address or hostname of the Zabbix server to connect to.
         '';
       };
@@ -80,7 +80,7 @@ in
         ip = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = ''
+          description = lib.mdDoc ''
             List of comma delimited IP addresses that the agent should listen on.
           '';
         };
@@ -88,7 +88,7 @@ in
         port = mkOption {
           type = types.port;
           default = 10050;
-          description = ''
+          description = lib.mdDoc ''
             Agent will listen on this port for connections from the server.
           '';
         };
@@ -97,7 +97,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for the Zabbix Agent.
         '';
       };
@@ -105,9 +105,9 @@ in
       settings = mkOption {
         type = with types; attrsOf (oneOf [ int str (listOf str) ]);
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Zabbix Agent configuration. Refer to
-          <link xlink:href="https://www.zabbix.com/documentation/current/manual/appendix/config/zabbix_agentd"/>
+          <https://www.zabbix.com/documentation/current/manual/appendix/config/zabbix_agentd>
           for details on supported values.
         '';
         example = {
diff --git a/nixos/modules/services/monitoring/zabbix-proxy.nix b/nixos/modules/services/monitoring/zabbix-proxy.nix
index 0ebd7bcff83..e7e353f3660 100644
--- a/nixos/modules/services/monitoring/zabbix-proxy.nix
+++ b/nixos/modules/services/monitoring/zabbix-proxy.nix
@@ -38,11 +38,11 @@ in
   options = {
 
     services.zabbixProxy = {
-      enable = mkEnableOption "the Zabbix Proxy";
+      enable = mkEnableOption (lib.mdDoc "the Zabbix Proxy");
 
       server = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The IP address or hostname of the Zabbix server to connect to.
           '';
         };
@@ -54,22 +54,22 @@ in
           else if cfg.database.type == "pgsql" then pkgs.zabbix.proxy-pgsql
           else pkgs.zabbix.proxy-sqlite;
         defaultText = literalExpression "pkgs.zabbix.proxy-pgsql";
-        description = "The Zabbix package to use.";
+        description = lib.mdDoc "The Zabbix package to use.";
       };
 
       extraPackages = mkOption {
         type = types.listOf types.package;
         default = with pkgs; [ nettools nmap traceroute ];
         defaultText = literalExpression "[ nettools nmap traceroute ]";
-        description = ''
-          Packages to be added to the Zabbix <envar>PATH</envar>.
+        description = lib.mdDoc ''
+          Packages to be added to the Zabbix {env}`PATH`.
           Typically used to add executables for scripts, but can be anything.
         '';
       };
 
       modules = mkOption {
         type = types.attrsOf types.package;
-        description = "A set of modules to load.";
+        description = lib.mdDoc "A set of modules to load.";
         default = {};
         example = literalExpression ''
           {
@@ -92,13 +92,13 @@ in
           type = types.enum [ "mysql" "pgsql" "sqlite" ];
           example = "mysql";
           default = "pgsql";
-          description = "Database engine to use.";
+          description = lib.mdDoc "Database engine to use.";
         };
 
         host = mkOption {
           type = types.str;
           default = "localhost";
-          description = "Database host address.";
+          description = lib.mdDoc "Database host address.";
         };
 
         port = mkOption {
@@ -109,29 +109,29 @@ in
             then config.${options.services.mysql.port}
             else config.${options.services.postgresql.port}
           '';
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = mkOption {
           type = types.str;
           default = if cfg.database.type == "sqlite" then "${stateDir}/zabbix.db" else "zabbix";
           defaultText = literalExpression "zabbix";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = mkOption {
           type = types.str;
           default = "zabbix";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/zabbix-dbpassword";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
 
@@ -139,13 +139,13 @@ in
           type = types.nullOr types.path;
           default = null;
           example = "/run/postgresql";
-          description = "Path to the unix socket file to use for authentication.";
+          description = lib.mdDoc "Path to the unix socket file to use for authentication.";
         };
 
         createLocally = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether to create a local database automatically.";
+          description = lib.mdDoc "Whether to create a local database automatically.";
         };
       };
 
@@ -153,7 +153,7 @@ in
         ip = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = ''
+          description = lib.mdDoc ''
             List of comma delimited IP addresses that the trapper should listen on.
             Trapper will listen on all network interfaces if this parameter is missing.
           '';
@@ -162,7 +162,7 @@ in
         port = mkOption {
           type = types.port;
           default = 10051;
-          description = ''
+          description = lib.mdDoc ''
             Listen port for trapper.
           '';
         };
@@ -171,7 +171,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for the Zabbix Proxy.
         '';
       };
@@ -179,9 +179,9 @@ in
       settings = mkOption {
         type = with types; attrsOf (oneOf [ int str (listOf str) ]);
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Zabbix Proxy configuration. Refer to
-          <link xlink:href="https://www.zabbix.com/documentation/current/manual/appendix/config/zabbix_proxy"/>
+          <https://www.zabbix.com/documentation/current/manual/appendix/config/zabbix_proxy>
           for details on supported values.
         '';
         example = {
diff --git a/nixos/modules/services/monitoring/zabbix-server.nix b/nixos/modules/services/monitoring/zabbix-server.nix
index 9f960517a81..2b50280e396 100644
--- a/nixos/modules/services/monitoring/zabbix-server.nix
+++ b/nixos/modules/services/monitoring/zabbix-server.nix
@@ -40,28 +40,28 @@ in
   options = {
 
     services.zabbixServer = {
-      enable = mkEnableOption "the Zabbix Server";
+      enable = mkEnableOption (lib.mdDoc "the Zabbix Server");
 
       package = mkOption {
         type = types.package;
         default = if cfg.database.type == "mysql" then pkgs.zabbix.server-mysql else pkgs.zabbix.server-pgsql;
         defaultText = literalExpression "pkgs.zabbix.server-pgsql";
-        description = "The Zabbix package to use.";
+        description = lib.mdDoc "The Zabbix package to use.";
       };
 
       extraPackages = mkOption {
         type = types.listOf types.package;
         default = with pkgs; [ nettools nmap traceroute ];
         defaultText = literalExpression "[ nettools nmap traceroute ]";
-        description = ''
-          Packages to be added to the Zabbix <envar>PATH</envar>.
+        description = lib.mdDoc ''
+          Packages to be added to the Zabbix {env}`PATH`.
           Typically used to add executables for scripts, but can be anything.
         '';
       };
 
       modules = mkOption {
         type = types.attrsOf types.package;
-        description = "A set of modules to load.";
+        description = lib.mdDoc "A set of modules to load.";
         default = {};
         example = literalExpression ''
           {
@@ -84,45 +84,45 @@ in
           type = types.enum [ "mysql" "pgsql" ];
           example = "mysql";
           default = "pgsql";
-          description = "Database engine to use.";
+          description = lib.mdDoc "Database engine to use.";
         };
 
         host = mkOption {
           type = types.str;
           default = "localhost";
-          description = "Database host address.";
+          description = lib.mdDoc "Database host address.";
         };
 
         port = mkOption {
-          type = types.int;
+          type = types.port;
           default = if cfg.database.type == "mysql" then mysql.port else pgsql.port;
           defaultText = literalExpression ''
             if config.${opt.database.type} == "mysql"
             then config.${options.services.mysql.port}
             else config.${options.services.postgresql.port}
           '';
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = mkOption {
           type = types.str;
           default = "zabbix";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = mkOption {
           type = types.str;
           default = "zabbix";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/zabbix-dbpassword";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
 
@@ -130,13 +130,13 @@ in
           type = types.nullOr types.path;
           default = null;
           example = "/run/postgresql";
-          description = "Path to the unix socket file to use for authentication.";
+          description = lib.mdDoc "Path to the unix socket file to use for authentication.";
         };
 
         createLocally = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether to create a local database automatically.";
+          description = lib.mdDoc "Whether to create a local database automatically.";
         };
       };
 
@@ -144,7 +144,7 @@ in
         ip = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = ''
+          description = lib.mdDoc ''
             List of comma delimited IP addresses that the trapper should listen on.
             Trapper will listen on all network interfaces if this parameter is missing.
           '';
@@ -153,7 +153,7 @@ in
         port = mkOption {
           type = types.port;
           default = 10051;
-          description = ''
+          description = lib.mdDoc ''
             Listen port for trapper.
           '';
         };
@@ -162,7 +162,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for the Zabbix Server.
         '';
       };
@@ -170,9 +170,9 @@ in
       settings = mkOption {
         type = with types; attrsOf (oneOf [ int str (listOf str) ]);
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Zabbix Server configuration. Refer to
-          <link xlink:href="https://www.zabbix.com/documentation/current/manual/appendix/config/zabbix_server"/>
+          <https://www.zabbix.com/documentation/current/manual/appendix/config/zabbix_server>
           for details on supported values.
         '';
         example = {
diff --git a/nixos/modules/services/network-filesystems/cachefilesd.nix b/nixos/modules/services/network-filesystems/cachefilesd.nix
index 229c9665419..da5a79a062c 100644
--- a/nixos/modules/services/network-filesystems/cachefilesd.nix
+++ b/nixos/modules/services/network-filesystems/cachefilesd.nix
@@ -20,20 +20,20 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable cachefilesd network filesystems caching daemon.";
+        description = lib.mdDoc "Whether to enable cachefilesd network filesystems caching daemon.";
       };
 
       cacheDir = mkOption {
         type = types.str;
         default = "/var/cache/fscache";
-        description = "Directory to contain filesystem cache.";
+        description = lib.mdDoc "Directory to contain filesystem cache.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
         example = "brun 10%";
-        description = "Additional configuration file entries. See cachefilesd.conf(5) for more information.";
+        description = lib.mdDoc "Additional configuration file entries. See cachefilesd.conf(5) for more information.";
       };
 
     };
diff --git a/nixos/modules/services/network-filesystems/ceph.nix b/nixos/modules/services/network-filesystems/ceph.nix
index 7a1444decaf..22d58f29cb8 100644
--- a/nixos/modules/services/network-filesystems/ceph.nix
+++ b/nixos/modules/services/network-filesystems/ceph.nix
@@ -72,7 +72,7 @@ in
   options.services.ceph = {
     # Ceph has a monolithic configuration file but different sections for
     # each daemon, a separate client section and a global section
-    enable = mkEnableOption "Ceph global configuration";
+    enable = mkEnableOption (lib.mdDoc "Ceph global configuration");
 
     global = {
       fsid = mkOption {
@@ -80,7 +80,7 @@ in
         example = ''
           433a2193-4f8a-47a0-95d2-209d7ca2cca5
         '';
-        description = ''
+        description = lib.mdDoc ''
           Filesystem ID, a generated uuid, its must be generated and set before
           attempting to start a cluster
         '';
@@ -89,7 +89,7 @@ in
       clusterName = mkOption {
         type = types.str;
         default = "ceph";
-        description = ''
+        description = lib.mdDoc ''
           Name of cluster
         '';
       };
@@ -98,7 +98,7 @@ in
         type = types.path;
         default = "${pkgs.ceph.lib}/lib/ceph/mgr";
         defaultText = literalExpression ''"''${pkgs.ceph.lib}/lib/ceph/mgr"'';
-        description = ''
+        description = lib.mdDoc ''
           Path at which to find ceph-mgr modules.
         '';
       };
@@ -109,7 +109,7 @@ in
         example = ''
           node0, node1, node2
         '';
-        description = ''
+        description = lib.mdDoc ''
           List of hosts that will be used as monitors at startup.
         '';
       };
@@ -120,7 +120,7 @@ in
         example = ''
           10.10.0.1, 10.10.0.2, 10.10.0.3
         '';
-        description = ''
+        description = lib.mdDoc ''
           List of hostname shortnames/IP addresses of the initial monitors.
         '';
       };
@@ -128,7 +128,7 @@ in
       maxOpenFiles = mkOption {
         type = types.int;
         default = 131072;
-        description = ''
+        description = lib.mdDoc ''
           Max open files for each OSD daemon.
         '';
       };
@@ -136,7 +136,7 @@ in
       authClusterRequired = mkOption {
         type = types.enum [ "cephx" "none" ];
         default = "cephx";
-        description = ''
+        description = lib.mdDoc ''
           Enables requiring daemons to authenticate with eachother in the cluster.
         '';
       };
@@ -144,7 +144,7 @@ in
       authServiceRequired = mkOption {
         type = types.enum [ "cephx" "none" ];
         default = "cephx";
-        description = ''
+        description = lib.mdDoc ''
           Enables requiring clients to authenticate with the cluster to access services in the cluster (e.g. radosgw, mds or osd).
         '';
       };
@@ -152,7 +152,7 @@ in
       authClientRequired = mkOption {
         type = types.enum [ "cephx" "none" ];
         default = "cephx";
-        description = ''
+        description = lib.mdDoc ''
           Enables requiring the cluster to authenticate itself to the client.
         '';
       };
@@ -163,7 +163,7 @@ in
         example = ''
           10.20.0.0/24, 192.168.1.0/24
         '';
-        description = ''
+        description = lib.mdDoc ''
           A comma-separated list of subnets that will be used as public networks in the cluster.
         '';
       };
@@ -174,7 +174,7 @@ in
         example = ''
           10.10.0.0/24, 192.168.0.0/24
         '';
-        description = ''
+        description = lib.mdDoc ''
           A comma-separated list of subnets that will be used as cluster networks in the cluster.
         '';
       };
@@ -183,7 +183,7 @@ in
         type = with types; nullOr path;
         default = "${pkgs.mailcap}/etc/mime.types";
         defaultText = literalExpression ''"''${pkgs.mailcap}/etc/mime.types"'';
-        description = ''
+        description = lib.mdDoc ''
           Path to mime types used by radosgw.
         '';
       };
@@ -195,18 +195,18 @@ in
       example = {
         "ms bind ipv6" = "true";
       };
-      description = ''
+      description = lib.mdDoc ''
         Extra configuration to add to the global section. Use for setting values that are common for all daemons in the cluster.
       '';
     };
 
     mgr = {
-      enable = mkEnableOption "Ceph MGR daemon";
+      enable = mkEnableOption (lib.mdDoc "Ceph MGR daemon");
       daemons = mkOption {
         type = with types; listOf str;
         default = [];
         example = [ "name1" "name2" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of names for manager daemons that should have a service created. The names correspond
           to the id part in ceph i.e. [ "name1" ] would result in mgr.name1
         '';
@@ -214,19 +214,19 @@ in
       extraConfig = mkOption {
         type = with types; attrsOf str;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to add to the global section for manager daemons.
         '';
       };
     };
 
     mon = {
-      enable = mkEnableOption "Ceph MON daemon";
+      enable = mkEnableOption (lib.mdDoc "Ceph MON daemon");
       daemons = mkOption {
         type = with types; listOf str;
         default = [];
         example = [ "name1" "name2" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of monitor daemons that should have a service created. The names correspond
           to the id part in ceph i.e. [ "name1" ] would result in mon.name1
         '';
@@ -234,19 +234,19 @@ in
       extraConfig = mkOption {
         type = with types; attrsOf str;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to add to the monitor section.
         '';
       };
     };
 
     osd = {
-      enable = mkEnableOption "Ceph OSD daemon";
+      enable = mkEnableOption (lib.mdDoc "Ceph OSD daemon");
       daemons = mkOption {
         type = with types; listOf str;
         default = [];
         example = [ "name1" "name2" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of OSD daemons that should have a service created. The names correspond
           to the id part in ceph i.e. [ "name1" ] would result in osd.name1
         '';
@@ -262,19 +262,19 @@ in
           "osd pool default pgp num" = "200";
           "osd crush chooseleaf type" = "1";
         };
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to add to the OSD section.
         '';
       };
     };
 
     mds = {
-      enable = mkEnableOption "Ceph MDS daemon";
+      enable = mkEnableOption (lib.mdDoc "Ceph MDS daemon");
       daemons = mkOption {
         type = with types; listOf str;
         default = [];
         example = [ "name1" "name2" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of metadata service daemons that should have a service created. The names correspond
           to the id part in ceph i.e. [ "name1" ] would result in mds.name1
         '';
@@ -282,19 +282,19 @@ in
       extraConfig = mkOption {
         type = with types; attrsOf str;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to add to the MDS section.
         '';
       };
     };
 
     rgw = {
-      enable = mkEnableOption "Ceph RadosGW daemon";
+      enable = mkEnableOption (lib.mdDoc "Ceph RadosGW daemon");
       daemons = mkOption {
         type = with types; listOf str;
         default = [];
         example = [ "name1" "name2" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of rados gateway daemons that should have a service created. The names correspond
           to the id part in ceph i.e. [ "name1" ] would result in client.name1, radosgw daemons
           aren't daemons to cluster in the sense that OSD, MGR or MON daemons are. They are simply
@@ -304,7 +304,7 @@ in
     };
 
     client = {
-      enable = mkEnableOption "Ceph client configuration";
+      enable = mkEnableOption (lib.mdDoc "Ceph client configuration");
       extraConfig = mkOption {
         type = with types; attrsOf (attrsOf str);
         default = {};
@@ -315,7 +315,7 @@ in
             "client.radosgw.node0" = { "some config option" = "true"; };
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration to add to the client section. Configuration for rados gateways
           would be added here, with their own sections, see example.
         '';
diff --git a/nixos/modules/services/network-filesystems/davfs2.nix b/nixos/modules/services/network-filesystems/davfs2.nix
index 8cf314fe63a..8024cfba08b 100644
--- a/nixos/modules/services/network-filesystems/davfs2.nix
+++ b/nixos/modules/services/network-filesystems/davfs2.nix
@@ -15,7 +15,7 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable davfs2.
       '';
     };
@@ -23,7 +23,7 @@ in
     davUser = mkOption {
       type = types.str;
       default = "davfs2";
-      description = ''
+      description = lib.mdDoc ''
         When invoked by root the mount.davfs daemon will run as this user.
         Value must be given as name, not as numerical id.
       '';
@@ -32,7 +32,7 @@ in
     davGroup = mkOption {
       type = types.str;
       default = "davfs2";
-      description = ''
+      description = lib.mdDoc ''
         The group of the running mount.davfs daemon. Ordinary users must be
         member of this group in order to mount a davfs2 file system. Value must
         be given as name, not as numerical id.
@@ -47,7 +47,7 @@ in
         proxy foo.bar:8080
         use_locks 0
       '';
-      description = ''
+      description = lib.mdDoc ''
         Extra lines appended to the configuration of davfs2.
       ''  ;
     };
diff --git a/nixos/modules/services/network-filesystems/diod.nix b/nixos/modules/services/network-filesystems/diod.nix
index 063bae6ddb1..541b4ffd6b4 100644
--- a/nixos/modules/services/network-filesystems/diod.nix
+++ b/nixos/modules/services/network-filesystems/diod.nix
@@ -26,13 +26,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the diod 9P file server.";
+        description = lib.mdDoc "Whether to enable the diod 9P file server.";
       };
 
       listen = mkOption {
         type = types.listOf types.str;
         default = [ "0.0.0.0:564" ];
-        description = ''
+        description = lib.mdDoc ''
           [ "IP:PORT" [,"IP:PORT",...] ]
           List the interfaces and ports that diod should listen on.
         '';
@@ -41,7 +41,7 @@ in
       exports = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List the file systems that clients will be allowed to mount. All paths should
           be fully qualified. The exports table can include two types of element:
           a string element (as above),
@@ -57,7 +57,7 @@ in
       exportall = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Export all file systems listed in /proc/mounts. If new file systems are mounted
           after diod has started, they will become immediately mountable. If there is a
           duplicate entry for a file system in the exports list, any options listed in
@@ -68,7 +68,7 @@ in
       exportopts = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Establish a default set of export options. These are overridden, not appended
           to, by opts attributes in an "exports" entry.
         '';
@@ -77,7 +77,7 @@ in
       nwthreads = mkOption {
         type = types.int;
         default = 16;
-        description = ''
+        description = lib.mdDoc ''
           Sets the (fixed) number of worker threads created to handle 9P
           requests for a unique aname.
         '';
@@ -86,7 +86,7 @@ in
       authRequired = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Allow clients to connect without authentication, i.e. without a valid MUNGE credential.
         '';
       };
@@ -94,7 +94,7 @@ in
       userdb = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           This option disables password/group lookups. It allows any uid to attach and
           assumes gid=uid, and supplementary groups contain only the primary gid.
         '';
@@ -103,7 +103,7 @@ in
       allsquash = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Remap all users to "nobody". The attaching user need not be present in the
           password file.
         '';
@@ -112,7 +112,7 @@ in
       squashuser = mkOption {
         type = types.str;
         default = "nobody";
-        description = ''
+        description = lib.mdDoc ''
           Change the squash user. The squash user must be present in the password file.
         '';
       };
@@ -120,7 +120,7 @@ in
       logdest = mkOption {
         type = types.str;
         default = "syslog:daemon:err";
-        description = ''
+        description = lib.mdDoc ''
           Set the destination for logging.
           The value has the form of "syslog:facility:level" or "filename".
         '';
@@ -130,7 +130,7 @@ in
       statfsPassthru = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           This option configures statfs to return the host file system's type
           rather than V9FS_MAGIC.
         '';
@@ -139,7 +139,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Extra configuration options for diod.conf.";
+        description = lib.mdDoc "Extra configuration options for diod.conf.";
       };
     };
   };
diff --git a/nixos/modules/services/network-filesystems/drbd.nix b/nixos/modules/services/network-filesystems/drbd.nix
index c730e0b34e9..e74ed391d48 100644
--- a/nixos/modules/services/network-filesystems/drbd.nix
+++ b/nixos/modules/services/network-filesystems/drbd.nix
@@ -15,7 +15,7 @@ let cfg = config.services.drbd; in
     services.drbd.enable = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable support for DRBD, the Distributed Replicated
         Block Device.
       '';
@@ -24,8 +24,8 @@ let cfg = config.services.drbd; in
     services.drbd.config = mkOption {
       default = "";
       type = types.lines;
-      description = ''
-        Contents of the <filename>drbd.conf</filename> configuration file.
+      description = lib.mdDoc ''
+        Contents of the {file}`drbd.conf` configuration file.
       '';
     };
 
diff --git a/nixos/modules/services/network-filesystems/glusterfs.nix b/nixos/modules/services/network-filesystems/glusterfs.nix
index 38be098de5d..5c3e197b687 100644
--- a/nixos/modules/services/network-filesystems/glusterfs.nix
+++ b/nixos/modules/services/network-filesystems/glusterfs.nix
@@ -33,17 +33,17 @@ in
 
     services.glusterfs = {
 
-      enable = mkEnableOption "GlusterFS Daemon";
+      enable = mkEnableOption (lib.mdDoc "GlusterFS Daemon");
 
       logLevel = mkOption {
         type = types.enum ["DEBUG" "INFO" "WARNING" "ERROR" "CRITICAL" "TRACE" "NONE"];
-        description = "Log level used by the GlusterFS daemon";
+        description = lib.mdDoc "Log level used by the GlusterFS daemon";
         default = "INFO";
       };
 
       useRpcbind = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Enable use of rpcbind. This is required for Gluster's NFS functionality.
 
           You may want to turn it off to reduce the attack surface for DDoS reflection attacks.
@@ -56,13 +56,13 @@ in
 
       enableGlustereventsd = mkOption {
         type = types.bool;
-        description = "Whether to enable the GlusterFS Events Daemon";
+        description = lib.mdDoc "Whether to enable the GlusterFS Events Daemon";
         default = true;
       };
 
       killMode = mkOption {
         type = types.enum ["control-group" "process" "mixed" "none"];
-        description = ''
+        description = lib.mdDoc ''
           The systemd KillMode to use for glusterd.
 
           glusterd spawns other daemons like gsyncd.
@@ -79,7 +79,7 @@ in
 
       stopKillTimeout = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The systemd TimeoutStopSec to use.
 
           After this time after having been asked to shut down, glusterd
@@ -94,17 +94,17 @@ in
 
       extraFlags = mkOption {
         type = types.listOf types.str;
-        description = "Extra flags passed to the GlusterFS daemon";
+        description = lib.mdDoc "Extra flags passed to the GlusterFS daemon";
         default = [];
       };
 
       tlsSettings = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Make the server communicate via TLS.
           This means it will only connect to other gluster
           servers having certificates signed by the same CA.
 
-          Enabling this will create a file <filename>/var/lib/glusterd/secure-access</filename>.
+          Enabling this will create a file {file}`/var/lib/glusterd/secure-access`.
           Disabling will delete this file again.
 
           See also: https://gluster.readthedocs.io/en/latest/Administrator%20Guide/SSL/
@@ -114,17 +114,17 @@ in
           options = {
             tlsKeyPath = mkOption {
               type = types.str;
-              description = "Path to the private key used for TLS.";
+              description = lib.mdDoc "Path to the private key used for TLS.";
             };
 
             tlsPem = mkOption {
               type = types.path;
-              description = "Path to the certificate used for TLS.";
+              description = lib.mdDoc "Path to the certificate used for TLS.";
             };
 
             caCert = mkOption {
               type = types.path;
-              description = "Path certificate authority used to sign the cluster certificates.";
+              description = lib.mdDoc "Path certificate authority used to sign the cluster certificates.";
             };
           };
         });
@@ -159,9 +159,10 @@ in
         install -m 0755 -d /var/log/glusterfs
       ''
       # The copying of hooks is due to upstream bug https://bugzilla.redhat.com/show_bug.cgi?id=1452761
+      # Excludes one hook due to missing SELinux binaries.
       + ''
         mkdir -p /var/lib/glusterd/hooks/
-        ${rsync}/bin/rsync -a ${glusterfs}/var/lib/glusterd/hooks/ /var/lib/glusterd/hooks/
+        ${rsync}/bin/rsync -a --exclude="S10selinux-label-brick.sh" ${glusterfs}/var/lib/glusterd/hooks/ /var/lib/glusterd/hooks/
 
         ${tlsCmd}
       ''
diff --git a/nixos/modules/services/network-filesystems/kbfs.nix b/nixos/modules/services/network-filesystems/kbfs.nix
index a43ac656f66..33ff283d5e8 100644
--- a/nixos/modules/services/network-filesystems/kbfs.nix
+++ b/nixos/modules/services/network-filesystems/kbfs.nix
@@ -15,15 +15,15 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to mount the Keybase filesystem.";
+        description = lib.mdDoc "Whether to mount the Keybase filesystem.";
       };
 
       enableRedirector = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Keybase root redirector service, allowing
-          any user to access KBFS files via <literal>/keybase</literal>,
+          any user to access KBFS files via `/keybase`,
           which will show different contents depending on the requester.
         '';
       };
@@ -32,7 +32,7 @@ in {
         type = types.str;
         default = "%h/keybase";
         example = "/keybase";
-        description = "Mountpoint for the Keybase filesystem.";
+        description = lib.mdDoc "Mountpoint for the Keybase filesystem.";
       };
 
       extraFlags = mkOption {
@@ -42,7 +42,7 @@ in {
           "-label kbfs"
           "-mount-type normal"
         ];
-        description = ''
+        description = lib.mdDoc ''
           Additional flags to pass to the Keybase filesystem on launch.
         '';
       };
diff --git a/nixos/modules/services/network-filesystems/ipfs.nix b/nixos/modules/services/network-filesystems/kubo.nix
index 7e96179b3ca..51e1282db41 100644
--- a/nixos/modules/services/network-filesystems/ipfs.nix
+++ b/nixos/modules/services/network-filesystems/kubo.nix
@@ -1,10 +1,11 @@
-{ config, lib, pkgs, options, utils, ... }:
+{ config, lib, pkgs, utils, ... }:
 with lib;
 let
-  cfg = config.services.ipfs;
-  opt = options.services.ipfs;
+  cfg = config.services.kubo;
 
-  ipfsFlags = utils.escapeSystemdExecArgs (
+  settingsFormat = pkgs.formats.json {};
+
+  kuboFlags = utils.escapeSystemdExecArgs (
     optional cfg.autoMount "--mount" ++
     optional cfg.enableGC "--enable-gc" ++
     optional (cfg.serviceFdlimit != null) "--manage-fdlimit=false" ++
@@ -51,27 +52,27 @@ in
 
   options = {
 
-    services.ipfs = {
+    services.kubo = {
 
-      enable = mkEnableOption "Interplanetary File System (WARNING: may cause severe network degredation)";
+      enable = mkEnableOption (lib.mdDoc "Interplanetary File System (WARNING: may cause severe network degredation)");
 
       package = mkOption {
         type = types.package;
-        default = pkgs.ipfs;
-        defaultText = literalExpression "pkgs.ipfs";
-        description = "Which IPFS package to use.";
+        default = pkgs.kubo;
+        defaultText = literalExpression "pkgs.kubo";
+        description = lib.mdDoc "Which Kubo package to use.";
       };
 
       user = mkOption {
         type = types.str;
         default = "ipfs";
-        description = "User under which the IPFS daemon runs";
+        description = lib.mdDoc "User under which the Kubo daemon runs";
       };
 
       group = mkOption {
         type = types.str;
         default = "ipfs";
-        description = "Group under which the IPFS daemon runs";
+        description = lib.mdDoc "Group under which the Kubo daemon runs";
       };
 
       dataDir = mkOption {
@@ -85,79 +86,83 @@ in
           then "/var/lib/ipfs"
           else "/var/lib/ipfs/.ipfs"
         '';
-        description = "The data dir for IPFS";
+        description = lib.mdDoc "The data dir for Kubo";
       };
 
       defaultMode = mkOption {
         type = types.enum [ "online" "offline" "norouting" ];
         default = "online";
-        description = "systemd service that is enabled by default";
+        description = lib.mdDoc "systemd service that is enabled by default";
       };
 
       autoMount = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether IPFS should try to mount /ipfs and /ipns at startup.";
+        description = lib.mdDoc "Whether Kubo should try to mount /ipfs and /ipns at startup.";
       };
 
       autoMigrate = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether IPFS should try to run the fs-repo-migration at startup.";
+        description = lib.mdDoc "Whether Kubo should try to run the fs-repo-migration at startup.";
       };
 
       ipfsMountDir = mkOption {
         type = types.str;
         default = "/ipfs";
-        description = "Where to mount the IPFS namespace to";
+        description = lib.mdDoc "Where to mount the IPFS namespace to";
       };
 
       ipnsMountDir = mkOption {
         type = types.str;
         default = "/ipns";
-        description = "Where to mount the IPNS namespace to";
-      };
-
-      gatewayAddress = mkOption {
-        type = types.str;
-        default = "/ip4/127.0.0.1/tcp/8080";
-        description = "Where the IPFS Gateway can be reached";
-      };
-
-      apiAddress = mkOption {
-        type = types.str;
-        default = "/ip4/127.0.0.1/tcp/5001";
-        description = "Where IPFS exposes its API to";
-      };
-
-      swarmAddress = mkOption {
-        type = types.listOf types.str;
-        default = [
-          "/ip4/0.0.0.0/tcp/4001"
-          "/ip6/::/tcp/4001"
-          "/ip4/0.0.0.0/udp/4001/quic"
-          "/ip6/::/udp/4001/quic"
-        ];
-        description = "Where IPFS listens for incoming p2p connections";
+        description = lib.mdDoc "Where to mount the IPNS namespace to";
       };
 
       enableGC = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable automatic garbage collection";
+        description = lib.mdDoc "Whether to enable automatic garbage collection";
       };
 
       emptyRepo = mkOption {
         type = types.bool;
         default = false;
-        description = "If set to true, the repo won't be initialized with help files";
+        description = lib.mdDoc "If set to true, the repo won't be initialized with help files";
       };
 
-      extraConfig = mkOption {
-        type = types.attrs;
-        description = ''
-          Attrset of daemon configuration to set using <command>ipfs config</command>, every time the daemon starts.
-          These are applied last, so may override configuration set by other options in this module.
+      settings = mkOption {
+        type = lib.types.submodule {
+          freeformType = settingsFormat.type;
+
+          options = {
+            Addresses.API = mkOption {
+              type = types.str;
+              default = "/ip4/127.0.0.1/tcp/5001";
+              description = lib.mdDoc "Where Kubo exposes its API to";
+            };
+
+            Addresses.Gateway = mkOption {
+              type = types.str;
+              default = "/ip4/127.0.0.1/tcp/8080";
+              description = lib.mdDoc "Where the IPFS Gateway can be reached";
+            };
+
+            Addresses.Swarm = mkOption {
+              type = types.listOf types.str;
+              default = [
+                "/ip4/0.0.0.0/tcp/4001"
+                "/ip6/::/tcp/4001"
+                "/ip4/0.0.0.0/udp/4001/quic"
+                "/ip6/::/udp/4001/quic"
+              ];
+              description = lib.mdDoc "Where Kubo listens for incoming p2p connections";
+            };
+          };
+        };
+        description = lib.mdDoc ''
+          Attrset of daemon configuration to set using {command}`ipfs config`, every time the daemon starts.
+          See [https://github.com/ipfs/kubo/blob/master/docs/config.md](https://github.com/ipfs/kubo/blob/master/docs/config.md) for reference.
           Keep in mind that this configuration is stateful; i.e., unsetting anything in here does not reset the value to the default!
         '';
         default = { };
@@ -175,14 +180,14 @@ in
 
       extraFlags = mkOption {
         type = types.listOf types.str;
-        description = "Extra flags passed to the IPFS daemon";
+        description = lib.mdDoc "Extra flags passed to the Kubo daemon";
         default = [ ];
       };
 
       localDiscovery = mkOption {
         type = types.bool;
-        description = ''Whether to enable local discovery for the ipfs daemon.
-          This will allow ipfs to scan ports on your local network. Some hosting services will ban you if you do this.
+        description = lib.mdDoc ''Whether to enable local discovery for the Kubo daemon.
+          This will allow Kubo to scan ports on your local network. Some hosting services will ban you if you do this.
         '';
         default = false;
       };
@@ -190,14 +195,14 @@ in
       serviceFdlimit = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = "The fdlimit for the IPFS systemd unit or <literal>null</literal> to have the daemon attempt to manage it";
+        description = lib.mdDoc "The fdlimit for the Kubo systemd unit or `null` to have the daemon attempt to manage it";
         example = 64 * 1024;
       };
 
       startWhenNeeded = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to use socket activation to start IPFS when needed.";
+        description = lib.mdDoc "Whether to use socket activation to start Kubo when needed.";
       };
 
     };
@@ -224,7 +229,7 @@ in
         uid = config.ids.uids.ipfs;
         description = "IPFS daemon user";
         packages = [
-          pkgs.ipfs-migrator
+          pkgs.kubo-migrator
         ];
       };
     };
@@ -245,6 +250,12 @@ in
       then [ cfg.package.systemd_unit ]
       else [ cfg.package.systemd_unit_hardened ];
 
+    services.kubo.settings = mkIf cfg.autoMount {
+      Mounts.FuseAllowOther = lib.mkDefault true;
+      Mounts.IPFS = lib.mkDefault cfg.ipfsMountDir;
+      Mounts.IPNS = lib.mkDefault cfg.ipnsMountDir;
+    };
+
     systemd.services.ipfs = {
       path = [ "/run/wrappers" cfg.package ];
       environment.IPFS_PATH = cfg.dataDir;
@@ -255,32 +266,24 @@ in
         else
           # After an unclean shutdown this file may exist which will cause the config command to attempt to talk to the daemon. This will hang forever if systemd is holding our sockets open.
           rm -vf "$IPFS_PATH/api"
-
-          ipfs --offline config profile apply ${profile}
-        fi
-      '' + optionalString cfg.autoMount ''
-        ipfs --offline config Mounts.FuseAllowOther --json true
-        ipfs --offline config Mounts.IPFS ${cfg.ipfsMountDir}
-        ipfs --offline config Mounts.IPNS ${cfg.ipnsMountDir}
       '' + optionalString cfg.autoMigrate ''
-        ${pkgs.ipfs-migrator}/bin/fs-repo-migrations -to '${cfg.package.repoVersion}' -y
+        ${pkgs.kubo-migrator}/bin/fs-repo-migrations -to '${cfg.package.repoVersion}' -y
+      '' + ''
+          ipfs --offline config profile apply ${profile} >/dev/null
+        fi
       '' + ''
         ipfs --offline config show \
-          | ${pkgs.jq}/bin/jq '. * $extraConfig' --argjson extraConfig ${
-              escapeShellArg (builtins.toJSON ({
-                Addresses.API = cfg.apiAddress;
-                Addresses.Gateway = cfg.gatewayAddress;
-                Addresses.Swarm = cfg.swarmAddress;
-              } // cfg.extraConfig))
+          | ${pkgs.jq}/bin/jq '. * $settings' --argjson settings ${
+              escapeShellArg (builtins.toJSON cfg.settings)
             } \
           | ipfs --offline config replace -
       '';
       serviceConfig = {
-        ExecStart = [ "" "${cfg.package}/bin/ipfs daemon ${ipfsFlags}" ];
+        ExecStart = [ "" "${cfg.package}/bin/ipfs daemon ${kuboFlags}" ];
         User = cfg.user;
         Group = cfg.group;
         StateDirectory = "";
-        ReadWritePaths = [ "" cfg.dataDir ];
+        ReadWritePaths = optionals (!cfg.autoMount) [ "" cfg.dataDir ];
       } // optionalAttrs (cfg.serviceFdlimit != null) { LimitNOFILE = cfg.serviceFdlimit; };
     } // optionalAttrs (!cfg.startWhenNeeded) {
       wantedBy = [ "default.target" ];
@@ -291,12 +294,12 @@ in
       socketConfig = {
         ListenStream =
           let
-            fromCfg = multiaddrToListenStream cfg.gatewayAddress;
+            fromCfg = multiaddrToListenStream cfg.settings.Addresses.Gateway;
           in
           [ "" ] ++ lib.optional (fromCfg != null) fromCfg;
         ListenDatagram =
           let
-            fromCfg = multiaddrToListenDatagram cfg.gatewayAddress;
+            fromCfg = multiaddrToListenDatagram cfg.settings.Addresses.Gateway;
           in
           [ "" ] ++ lib.optional (fromCfg != null) fromCfg;
       };
@@ -308,10 +311,40 @@ in
       # in the multiaddr.
       socketConfig.ListenStream =
         let
-          fromCfg = multiaddrToListenStream cfg.apiAddress;
+          fromCfg = multiaddrToListenStream cfg.settings.Addresses.API;
         in
         [ "" "%t/ipfs.sock" ] ++ lib.optional (fromCfg != null) fromCfg;
     };
+  };
 
+  meta = {
+    maintainers = with lib.maintainers; [ Luflosi ];
   };
+
+  imports = [
+    (mkRenamedOptionModule [ "services" "ipfs" "enable" ] [ "services" "kubo" "enable" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "package" ] [ "services" "kubo" "package" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "user" ] [ "services" "kubo" "user" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "group" ] [ "services" "kubo" "group" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "dataDir" ] [ "services" "kubo" "dataDir" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "defaultMode" ] [ "services" "kubo" "defaultMode" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "autoMount" ] [ "services" "kubo" "autoMount" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "autoMigrate" ] [ "services" "kubo" "autoMigrate" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "ipfsMountDir" ] [ "services" "kubo" "ipfsMountDir" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "ipnsMountDir" ] [ "services" "kubo" "ipnsMountDir" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "gatewayAddress" ] [ "services" "kubo" "settings" "Addresses" "Gateway" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "apiAddress" ] [ "services" "kubo" "settings" "Addresses" "API" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "swarmAddress" ] [ "services" "kubo" "settings" "Addresses" "Swarm" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "enableGC" ] [ "services" "kubo" "enableGC" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "emptyRepo" ] [ "services" "kubo" "emptyRepo" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "extraConfig" ] [ "services" "kubo" "settings" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "extraFlags" ] [ "services" "kubo" "extraFlags" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "localDiscovery" ] [ "services" "kubo" "localDiscovery" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "serviceFdlimit" ] [ "services" "kubo" "serviceFdlimit" ])
+    (mkRenamedOptionModule [ "services" "ipfs" "startWhenNeeded" ] [ "services" "kubo" "startWhenNeeded" ])
+    (mkRenamedOptionModule [ "services" "kubo" "extraConfig" ] [ "services" "kubo" "settings" ])
+    (mkRenamedOptionModule [ "services" "kubo" "gatewayAddress" ] [ "services" "kubo" "settings" "Addresses" "Gateway" ])
+    (mkRenamedOptionModule [ "services" "kubo" "apiAddress" ] [ "services" "kubo" "settings" "Addresses" "API" ])
+    (mkRenamedOptionModule [ "services" "kubo" "swarmAddress" ] [ "services" "kubo" "settings" "Addresses" "Swarm" ])
+  ];
 }
diff --git a/nixos/modules/services/network-filesystems/litestream/default.nix b/nixos/modules/services/network-filesystems/litestream/default.nix
index 51eb920d778..884ffa50e7c 100644
--- a/nixos/modules/services/network-filesystems/litestream/default.nix
+++ b/nixos/modules/services/network-filesystems/litestream/default.nix
@@ -8,18 +8,18 @@ let
 in
 {
   options.services.litestream = {
-    enable = mkEnableOption "litestream";
+    enable = mkEnableOption (lib.mdDoc "litestream");
 
     package = mkOption {
-      description = "Package to use.";
+      description = lib.mdDoc "Package to use.";
       default = pkgs.litestream;
       defaultText = literalExpression "pkgs.litestream";
       type = types.package;
     };
 
     settings = mkOption {
-      description = ''
-        See the <link xlink:href="https://litestream.io/reference/config/">documentation</link>.
+      description = lib.mdDoc ''
+        See the [documentation](https://litestream.io/reference/config/).
       '';
       type = settingsFormat.type;
       example = {
@@ -40,10 +40,8 @@ in
       type = types.nullOr types.path;
       default = null;
       example = "/run/secrets/litestream";
-      description = ''
-        Environment file as defined in <citerefentry>
-        <refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum>
-        </citerefentry>.
+      description = lib.mdDoc ''
+        Environment file as defined in {manpage}`systemd.exec(5)`.
 
         Secrets may be passed to the service without adding them to the
         world-readable Nix store, by specifying placeholder variables as
@@ -56,11 +54,11 @@ in
         variable values. If no value is set then it will be replaced with an
         empty string.
 
-        <programlisting>
+        ```
           # Content of the environment file
           LITESTREAM_ACCESS_KEY_ID=AKIAxxxxxxxxxxxxxxxx
           LITESTREAM_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxx
-        </programlisting>
+        ```
 
         Note that this file needs to be available on the host on which
         this exporter is running.
diff --git a/nixos/modules/services/network-filesystems/litestream/litestream.xml b/nixos/modules/services/network-filesystems/litestream/litestream.xml
index 598f9be8cf6..8f5597bb689 100644
--- a/nixos/modules/services/network-filesystems/litestream/litestream.xml
+++ b/nixos/modules/services/network-filesystems/litestream/litestream.xml
@@ -15,7 +15,7 @@
   <para>
    Litestream service is managed by a dedicated user named <literal>litestream</literal>
    which needs permission to the database file. Here's an example config which gives
-   required permissions to access <link linkend="opt-services.grafana.database.path">
+   required permissions to access <link linkend="opt-services.grafana.settings.database.path">
    grafana database</link>:
 <programlisting>
 { pkgs, ... }:
diff --git a/nixos/modules/services/network-filesystems/moosefs.nix b/nixos/modules/services/network-filesystems/moosefs.nix
index 88b2ada37e7..c9a5a43ebcd 100644
--- a/nixos/modules/services/network-filesystems/moosefs.nix
+++ b/nixos/modules/services/network-filesystems/moosefs.nix
@@ -75,26 +75,26 @@ in {
       masterHost = mkOption {
         type = types.str;
         default = null;
-        description = "IP or DNS name of master host.";
+        description = lib.mdDoc "IP or DNS name of master host.";
       };
 
       runAsUser = mkOption {
         type = types.bool;
         default = true;
         example = true;
-        description = "Run daemons as user moosefs instead of root.";
+        description = lib.mdDoc "Run daemons as user moosefs instead of root.";
       };
 
-      client.enable = mkEnableOption "Moosefs client.";
+      client.enable = mkEnableOption (lib.mdDoc "Moosefs client.");
 
       master = {
         enable = mkOption {
           type = types.bool;
-          description = ''
+          description = lib.mdDoc ''
             Enable Moosefs master daemon.
 
-            You need to run <literal>mfsmaster-init</literal> on a freshly installed master server to
-            initialize the <literal>DATA_PATH</literal> direcory.
+            You need to run `mfsmaster-init` on a freshly installed master server to
+            initialize the `DATA_PATH` direcory.
           '';
           default = false;
         };
@@ -102,7 +102,7 @@ in {
         exports = mkOption {
           type = with types; listOf str;
           default = null;
-          description = "Paths to export (see mfsexports.cfg).";
+          description = lib.mdDoc "Paths to export (see mfsexports.cfg).";
           example = [
             "* / rw,alldirs,admin,maproot=0:0"
             "* . rw"
@@ -111,7 +111,7 @@ in {
 
         openFirewall = mkOption {
           type = types.bool;
-          description = "Whether to automatically open the necessary ports in the firewall.";
+          description = lib.mdDoc "Whether to automatically open the necessary ports in the firewall.";
           default = false;
         };
 
@@ -122,16 +122,16 @@ in {
             options.DATA_PATH = mkOption {
               type = types.str;
               default = "/var/lib/mfs";
-              description = "Data storage directory.";
+              description = lib.mdDoc "Data storage directory.";
             };
           };
 
-          description = "Contents of config file (mfsmaster.cfg).";
+          description = lib.mdDoc "Contents of config file (mfsmaster.cfg).";
         };
       };
 
       metalogger = {
-        enable = mkEnableOption "Moosefs metalogger daemon.";
+        enable = mkEnableOption (lib.mdDoc "Moosefs metalogger daemon.");
 
         settings = mkOption {
           type = types.submodule {
@@ -140,27 +140,27 @@ in {
             options.DATA_PATH = mkOption {
               type = types.str;
               default = "/var/lib/mfs";
-              description = "Data storage directory";
+              description = lib.mdDoc "Data storage directory";
             };
           };
 
-          description = "Contents of metalogger config file (mfsmetalogger.cfg).";
+          description = lib.mdDoc "Contents of metalogger config file (mfsmetalogger.cfg).";
         };
       };
 
       chunkserver = {
-        enable = mkEnableOption "Moosefs chunkserver daemon.";
+        enable = mkEnableOption (lib.mdDoc "Moosefs chunkserver daemon.");
 
         openFirewall = mkOption {
           type = types.bool;
-          description = "Whether to automatically open the necessary ports in the firewall.";
+          description = lib.mdDoc "Whether to automatically open the necessary ports in the firewall.";
           default = false;
         };
 
         hdds = mkOption {
           type = with types; listOf str;
           default =  null;
-          description = "Mount points to be used by chunkserver for storage (see mfshdd.cfg).";
+          description = lib.mdDoc "Mount points to be used by chunkserver for storage (see mfshdd.cfg).";
           example = [ "/mnt/hdd1" ];
         };
 
@@ -171,11 +171,11 @@ in {
             options.DATA_PATH = mkOption {
               type = types.str;
               default = "/var/lib/mfs";
-              description = "Directory for lock file.";
+              description = lib.mdDoc "Directory for lock file.";
             };
           };
 
-          description = "Contents of chunkserver config file (mfschunkserver.cfg).";
+          description = lib.mdDoc "Contents of chunkserver config file (mfschunkserver.cfg).";
         };
       };
     };
diff --git a/nixos/modules/services/network-filesystems/netatalk.nix b/nixos/modules/services/network-filesystems/netatalk.nix
index 06a36eb30c2..a40f68557c0 100644
--- a/nixos/modules/services/network-filesystems/netatalk.nix
+++ b/nixos/modules/services/network-filesystems/netatalk.nix
@@ -10,12 +10,12 @@ in {
   options = {
     services.netatalk = {
 
-      enable = mkEnableOption "the Netatalk AFP fileserver";
+      enable = mkEnableOption (lib.mdDoc "the Netatalk AFP fileserver");
 
       port = mkOption {
         type = types.port;
         default = 548;
-        description = "TCP port to be used for AFP.";
+        description = lib.mdDoc "TCP port to be used for AFP.";
       };
 
       settings = mkOption {
@@ -32,20 +32,18 @@ in {
             "read only" = true;
           };
         };
-        description = ''
+        description = lib.mdDoc ''
           Configuration for Netatalk. See
-          <citerefentry><refentrytitle>afp.conf</refentrytitle>
-          <manvolnum>5</manvolnum></citerefentry>.
+          {manpage}`afp.conf(5)`.
         '';
       };
 
       extmap = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           File name extension mappings.
-          See <citerefentry><refentrytitle>extmap.conf</refentrytitle>
-          <manvolnum>5</manvolnum></citerefentry>. for more information.
+          See {manpage}`extmap.conf(5)`. for more information.
         '';
       };
 
diff --git a/nixos/modules/services/network-filesystems/nfsd.nix b/nixos/modules/services/network-filesystems/nfsd.nix
index 1b62bfa8203..c9e1cbcbbda 100644
--- a/nixos/modules/services/network-filesystems/nfsd.nix
+++ b/nixos/modules/services/network-filesystems/nfsd.nix
@@ -26,7 +26,7 @@ in
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable the kernel's NFS server.
           '';
         };
@@ -34,7 +34,7 @@ in
         extraNfsdConfig = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Extra configuration options for the [nfsd] section of /etc/nfs.conf.
           '';
         };
@@ -42,28 +42,26 @@ in
         exports = mkOption {
           type = types.lines;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Contents of the /etc/exports file.  See
-            <citerefentry><refentrytitle>exports</refentrytitle>
-            <manvolnum>5</manvolnum></citerefentry> for the format.
+            {manpage}`exports(5)` for the format.
           '';
         };
 
         hostName = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Hostname or address on which NFS requests will be accepted.
-            Default is all.  See the <option>-H</option> option in
-            <citerefentry><refentrytitle>nfsd</refentrytitle>
-            <manvolnum>8</manvolnum></citerefentry>.
+            Default is all.  See the {option}`-H` option in
+            {manpage}`nfsd(8)`.
           '';
         };
 
         nproc = mkOption {
           type = types.int;
           default = 8;
-          description = ''
+          description = lib.mdDoc ''
             Number of NFS server threads.  Defaults to the recommended value of 8.
           '';
         };
@@ -71,14 +69,14 @@ in
         createMountPoints = mkOption {
           type = types.bool;
           default = false;
-          description = "Whether to create the mount points in the exports file at startup time.";
+          description = lib.mdDoc "Whether to create the mount points in the exports file at startup time.";
         };
 
         mountdPort = mkOption {
           type = types.nullOr types.int;
           default = null;
           example = 4002;
-          description = ''
+          description = lib.mdDoc ''
             Use fixed port for rpc.mountd, useful if server is behind firewall.
           '';
         };
@@ -87,9 +85,9 @@ in
           type = types.nullOr types.int;
           default = null;
           example = 4001;
-          description = ''
+          description = lib.mdDoc ''
             Use a fixed port for the NFS lock manager kernel module
-            (<literal>lockd/nlockmgr</literal>).  This is useful if the
+            (`lockd/nlockmgr`).  This is useful if the
             NFS server is behind a firewall.
           '';
         };
@@ -98,8 +96,8 @@ in
           type = types.nullOr types.int;
           default = null;
           example = 4000;
-          description = ''
-            Use a fixed port for <command>rpc.statd</command>. This is
+          description = lib.mdDoc ''
+            Use a fixed port for {command}`rpc.statd`. This is
             useful if the NFS server is behind a firewall.
           '';
         };
diff --git a/nixos/modules/services/network-filesystems/openafs/client.nix b/nixos/modules/services/network-filesystems/openafs/client.nix
index c8cc5052c2a..bb0fee087e6 100644
--- a/nixos/modules/services/network-filesystems/openafs/client.nix
+++ b/nixos/modules/services/network-filesystems/openafs/client.nix
@@ -33,29 +33,29 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = "Whether to enable the OpenAFS client.";
+        description = lib.mdDoc "Whether to enable the OpenAFS client.";
       };
 
       afsdb = mkOption {
         default = true;
         type = types.bool;
-        description = "Resolve cells via AFSDB DNS records.";
+        description = lib.mdDoc "Resolve cells via AFSDB DNS records.";
       };
 
       cellName = mkOption {
         default = "";
         type = types.str;
-        description = "Cell name.";
+        description = lib.mdDoc "Cell name.";
         example = "grand.central.org";
       };
 
       cellServDB = mkOption {
         default = [];
         type = with types; listOf (submodule { options = cellServDBConfig; });
-        description = ''
+        description = lib.mdDoc ''
           This cell's database server records, added to the global
           CellServDB. See CellServDB(5) man page for syntax. Ignored when
-          <literal>afsdb</literal> is set to <literal>true</literal>.
+          `afsdb` is set to `true`.
         '';
         example = [
           { ip = "1.2.3.4"; dnsname = "first.afsdb.server.dns.fqdn.org"; }
@@ -67,15 +67,15 @@ in
         blocks = mkOption {
           default = 100000;
           type = types.int;
-          description = "Cache size in 1KB blocks.";
+          description = lib.mdDoc "Cache size in 1KB blocks.";
         };
 
         chunksize = mkOption {
           default = 0;
           type = types.ints.between 0 30;
-          description = ''
+          description = lib.mdDoc ''
             Size of each cache chunk given in powers of
-            2. <literal>0</literal> resets the chunk size to its default
+            2. `0` resets the chunk size to its default
             values (13 (8 KB) for memcache, 18-20 (256 KB to 1 MB) for
             diskcache). Maximum value is 30. Important performance
             parameter. Set to higher values when dealing with large files.
@@ -85,13 +85,13 @@ in
         directory = mkOption {
           default = "/var/cache/openafs";
           type = types.str;
-          description = "Cache directory.";
+          description = lib.mdDoc "Cache directory.";
         };
 
         diskless = mkOption {
           default = false;
           type = types.bool;
-          description = ''
+          description = lib.mdDoc ''
             Use in-memory cache for diskless machines. Has no real
             performance benefit anymore.
           '';
@@ -101,13 +101,13 @@ in
       crypt = mkOption {
         default = true;
         type = types.bool;
-        description = "Whether to enable (weak) protocol encryption.";
+        description = lib.mdDoc "Whether to enable (weak) protocol encryption.";
       };
 
       daemons = mkOption {
         default = 2;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Number of daemons to serve user requests. Numbers higher than 6
           usually do no increase performance. Default is sufficient for up
           to five concurrent users.
@@ -117,9 +117,9 @@ in
       fakestat = mkOption {
         default = false;
         type = types.bool;
-        description = ''
-          Return fake data on stat() calls. If <literal>true</literal>,
-          always do so. If <literal>false</literal>, only do so for
+        description = lib.mdDoc ''
+          Return fake data on stat() calls. If `true`,
+          always do so. If `false`, only do so for
           cross-cell mounts (as these are potentially expensive).
         '';
       };
@@ -127,9 +127,9 @@ in
       inumcalc = mkOption {
         default = "compat";
         type = types.strMatching "compat|md5";
-        description = ''
-          Inode calculation method. <literal>compat</literal> is
-          computationally less expensive, but <literal>md5</literal> greatly
+        description = lib.mdDoc ''
+          Inode calculation method. `compat` is
+          computationally less expensive, but `md5` greatly
           reduces the likelihood of inode collisions in larger scenarios
           involving multiple cells mounted into one AFS space.
         '';
@@ -138,9 +138,9 @@ in
       mountPoint = mkOption {
         default = "/afs";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Mountpoint of the AFS file tree, conventionally
-          <literal>/afs</literal>. When set to a different value, only
+          `/afs`. When set to a different value, only
           cross-cells that use the same value can be accessed.
         '';
       };
@@ -150,28 +150,28 @@ in
           default = config.boot.kernelPackages.openafs;
           defaultText = literalExpression "config.boot.kernelPackages.openafs";
           type = types.package;
-          description = "OpenAFS kernel module package. MUST match the userland package!";
+          description = lib.mdDoc "OpenAFS kernel module package. MUST match the userland package!";
         };
         programs = mkOption {
           default = getBin pkgs.openafs;
           defaultText = literalExpression "getBin pkgs.openafs";
           type = types.package;
-          description = "OpenAFS programs package. MUST match the kernel module package!";
+          description = lib.mdDoc "OpenAFS programs package. MUST match the kernel module package!";
         };
       };
 
       sparse = mkOption {
         default = true;
         type = types.bool;
-        description = "Minimal cell list in /afs.";
+        description = lib.mdDoc "Minimal cell list in /afs.";
       };
 
       startDisconnected = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Start up in disconnected mode.  You need to execute
-          <literal>fs disco online</literal> (as root) to switch to
+          `fs disco online` (as root) to switch to
           connected mode. Useful for roaming devices.
         '';
       };
diff --git a/nixos/modules/services/network-filesystems/openafs/lib.nix b/nixos/modules/services/network-filesystems/openafs/lib.nix
index e068ee761c2..80628f4dfaf 100644
--- a/nixos/modules/services/network-filesystems/openafs/lib.nix
+++ b/nixos/modules/services/network-filesystems/openafs/lib.nix
@@ -17,13 +17,13 @@ in {
       type = types.str;
       default = "";
       example = "1.2.3.4";
-      description = "IP Address of a database server";
+      description = lib.mdDoc "IP Address of a database server";
     };
     dnsname = mkOption {
       type = types.str;
       default = "";
       example = "afs.example.org";
-      description = "DNS full-qualified domain name of a database server";
+      description = lib.mdDoc "DNS full-qualified domain name of a database server";
     };
   };
 
diff --git a/nixos/modules/services/network-filesystems/openafs/server.nix b/nixos/modules/services/network-filesystems/openafs/server.nix
index 9c974335def..1c615d3bfb6 100644
--- a/nixos/modules/services/network-filesystems/openafs/server.nix
+++ b/nixos/modules/services/network-filesystems/openafs/server.nix
@@ -49,13 +49,13 @@ in {
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the OpenAFS server. An OpenAFS server needs a
           complex setup. So, be aware that enabling this service and setting
           some options does not give you a turn-key-ready solution. You need
           at least a running Kerberos 5 setup, as OpenAFS relies on it for
           authentication. See the Guide "QuickStartUnix" coming with
-          <literal>pkgs.openafs.doc</literal> for complete setup
+          `pkgs.openafs.doc` for complete setup
           instructions.
         '';
       };
@@ -63,27 +63,27 @@ in {
       advertisedAddresses = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "List of IP addresses this server is advertised under. See NetInfo(5)";
+        description = lib.mdDoc "List of IP addresses this server is advertised under. See NetInfo(5)";
       };
 
       cellName = mkOption {
         default = "";
         type = types.str;
-        description = "Cell name, this server will serve.";
+        description = lib.mdDoc "Cell name, this server will serve.";
         example = "grand.central.org";
       };
 
       cellServDB = mkOption {
         default = [];
         type = with types; listOf (submodule [ { options = cellServDBConfig;} ]);
-        description = "Definition of all cell-local database server machines.";
+        description = lib.mdDoc "Definition of all cell-local database server machines.";
       };
 
       package = mkOption {
         default = pkgs.openafs.server or pkgs.openafs;
         defaultText = literalExpression "pkgs.openafs.server or pkgs.openafs";
         type = types.package;
-        description = "OpenAFS package for the server binaries";
+        description = lib.mdDoc "OpenAFS package for the server binaries";
       };
 
       roles = {
@@ -91,33 +91,33 @@ in {
           enable = mkOption {
             default = true;
             type = types.bool;
-            description = "Fileserver role, serves files and volumes from its local storage.";
+            description = lib.mdDoc "Fileserver role, serves files and volumes from its local storage.";
           };
 
           fileserverArgs = mkOption {
             default = "-vattachpar 128 -vhashsize 11 -L -rxpck 400 -cb 1000000";
             type = types.str;
-            description = "Arguments to the dafileserver process. See its man page.";
+            description = lib.mdDoc "Arguments to the dafileserver process. See its man page.";
           };
 
           volserverArgs = mkOption {
             default = "";
             type = types.str;
-            description = "Arguments to the davolserver process. See its man page.";
+            description = lib.mdDoc "Arguments to the davolserver process. See its man page.";
             example = "-sync never";
           };
 
           salvageserverArgs = mkOption {
             default = "";
             type = types.str;
-            description = "Arguments to the salvageserver process. See its man page.";
+            description = lib.mdDoc "Arguments to the salvageserver process. See its man page.";
             example = "-showlog";
           };
 
           salvagerArgs = mkOption {
             default = "";
             type = types.str;
-            description = "Arguments to the dasalvager process. See its man page.";
+            description = lib.mdDoc "Arguments to the dasalvager process. See its man page.";
             example = "-showlog -showmounts";
           };
         };
@@ -126,10 +126,10 @@ in {
           enable = mkOption {
             default = true;
             type = types.bool;
-            description = ''
+            description = lib.mdDoc ''
               Database server role, maintains the Volume Location Database,
               Protection Database (and Backup Database, see
-              <literal>backup</literal> role). There can be multiple
+              `backup` role). There can be multiple
               servers in the database role for replication, which then need
               reliable network connection to each other.
 
@@ -141,14 +141,14 @@ in {
           vlserverArgs = mkOption {
             default = "";
             type = types.str;
-            description = "Arguments to the vlserver process. See its man page.";
+            description = lib.mdDoc "Arguments to the vlserver process. See its man page.";
             example = "-rxbind";
           };
 
           ptserverArgs = mkOption {
             default = "";
             type = types.str;
-            description = "Arguments to the ptserver process. See its man page.";
+            description = lib.mdDoc "Arguments to the ptserver process. See its man page.";
             example = "-restricted -default_access S---- S-M---";
           };
         };
@@ -157,9 +157,9 @@ in {
           enable = mkOption {
             default = false;
             type = types.bool;
-            description = ''
+            description = lib.mdDoc ''
               Backup server role. Use in conjunction with the
-              <literal>database</literal> role to maintain the Backup
+              `database` role to maintain the Backup
               Database. Normally only used in conjunction with tape storage
               or IBM's Tivoli Storage Manager.
             '';
@@ -168,14 +168,14 @@ in {
           buserverArgs = mkOption {
             default = "";
             type = types.str;
-            description = "Arguments to the buserver process. See its man page.";
+            description = lib.mdDoc "Arguments to the buserver process. See its man page.";
             example = "-p 8";
           };
 
           cellServDB = mkOption {
             default = [];
             type = with types; listOf (submodule [ { options = cellServDBConfig;} ]);
-            description = ''
+            description = lib.mdDoc ''
               Definition of all cell-local backup database server machines.
               Use this when your cell uses less backup database servers than
               other database server machines.
@@ -187,7 +187,7 @@ in {
       dottedPrincipals= mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, allow principal names containing (.) dots. Enabling
           this has security implications!
         '';
@@ -196,11 +196,11 @@ in {
       udpPacketSize = mkOption {
         default = 1310720;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           UDP packet size to use in Bytes. Higher values can speed up
           communications. The default of 1 MB is a sufficient in most
           cases. Make sure to increase the kernel's UDP buffer size
-          accordingly via <literal>net.core(w|r|opt)mem_max</literal>
+          accordingly via `net.core(w|r|opt)mem_max`
           sysctl.
         '';
       };
diff --git a/nixos/modules/services/network-filesystems/orangefs/client.nix b/nixos/modules/services/network-filesystems/orangefs/client.nix
index 36ea5af2168..471e17970ae 100644
--- a/nixos/modules/services/network-filesystems/orangefs/client.nix
+++ b/nixos/modules/services/network-filesystems/orangefs/client.nix
@@ -10,18 +10,18 @@ in {
 
   options = {
     services.orangefs.client = {
-      enable = mkEnableOption "OrangeFS client daemon";
+      enable = mkEnableOption (lib.mdDoc "OrangeFS client daemon");
 
       extraOptions = mkOption {
         type = with types; listOf str;
         default = [];
-        description = "Extra command line options for pvfs2-client.";
+        description = lib.mdDoc "Extra command line options for pvfs2-client.";
       };
 
       fileSystems = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The orangefs file systems to be mounted.
-          This option is prefered over using <option>fileSystems</option> directly since
+          This option is prefered over using {option}`fileSystems` directly since
           the pvfs client service needs to be running for it to be mounted.
         '';
 
@@ -36,19 +36,19 @@ in {
             mountPoint = mkOption {
               type = types.str;
               default = "/orangefs";
-              description = "Mount point.";
+              description = lib.mdDoc "Mount point.";
             };
 
             options = mkOption {
               type = with types; listOf str;
               default = [];
-              description = "Mount options";
+              description = lib.mdDoc "Mount options";
             };
 
             target = mkOption {
               type = types.str;
               example = "tcp://server:3334/orangefs";
-              description = "Target URL";
+              description = lib.mdDoc "Target URL";
             };
           };
         }));
diff --git a/nixos/modules/services/network-filesystems/orangefs/server.nix b/nixos/modules/services/network-filesystems/orangefs/server.nix
index 621c2fe8f78..8e6838c0467 100644
--- a/nixos/modules/services/network-filesystems/orangefs/server.nix
+++ b/nixos/modules/services/network-filesystems/orangefs/server.nix
@@ -74,45 +74,45 @@ in {
 
   options = {
     services.orangefs.server = {
-      enable = mkEnableOption "OrangeFS server";
+      enable = mkEnableOption (lib.mdDoc "OrangeFS server");
 
       logType = mkOption {
         type = with types; enum [ "file" "syslog" ];
         default = "syslog";
-        description = "Destination for log messages.";
+        description = lib.mdDoc "Destination for log messages.";
       };
 
       dataStorageSpace = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "/data/storage";
-        description = "Directory for data storage.";
+        description = lib.mdDoc "Directory for data storage.";
       };
 
       metadataStorageSpace = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "/data/meta";
-        description = "Directory for meta data storage.";
+        description = lib.mdDoc "Directory for meta data storage.";
       };
 
       BMIModules = mkOption {
         type = with types; listOf str;
         default = [ "bmi_tcp" ];
         example = [ "bmi_tcp" "bmi_ib"];
-        description = "List of BMI modules to load.";
+        description = lib.mdDoc "List of BMI modules to load.";
       };
 
       extraDefaults = mkOption {
         type = types.lines;
         default = "";
-        description = "Extra config for <literal>&lt;Defaults&gt;</literal> section.";
+        description = lib.mdDoc "Extra config for `<Defaults>` section.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Extra config for the global section.";
+        description = lib.mdDoc "Extra config for the global section.";
       };
 
       servers = mkOption {
@@ -122,12 +122,12 @@ in {
           node1 = "tcp://node1:3334";
           node2 = "tcp://node2:3334";
         };
-        description = "URLs for storage server including port. The attribute names define the server alias.";
+        description = lib.mdDoc "URLs for storage server including port. The attribute names define the server alias.";
       };
 
       fileSystems = mkOption {
-        description = ''
-          These options will create the <literal>&lt;FileSystem&gt;</literal> sections of config file.
+        description = lib.mdDoc ''
+          These options will create the `<FileSystem>` sections of config file.
         '';
         default = { orangefs = {}; };
         example = literalExpression ''
@@ -146,37 +146,37 @@ in {
             id = mkOption {
               type = types.int;
               default = 1;
-              description = "File system ID (must be unique within configuration).";
+              description = lib.mdDoc "File system ID (must be unique within configuration).";
             };
 
             rootHandle = mkOption {
               type = types.int;
               default = 3;
-              description = "File system root ID.";
+              description = lib.mdDoc "File system root ID.";
             };
 
             extraConfig = mkOption {
               type = types.lines;
               default = "";
-              description = "Extra config for <literal>&lt;FileSystem&gt;</literal> section.";
+              description = lib.mdDoc "Extra config for `<FileSystem>` section.";
             };
 
             troveSyncMeta = mkOption {
               type = types.bool;
               default = true;
-              description = "Sync meta data.";
+              description = lib.mdDoc "Sync meta data.";
             };
 
             troveSyncData = mkOption {
               type = types.bool;
               default = false;
-              description = "Sync data.";
+              description = lib.mdDoc "Sync data.";
             };
 
             extraStorageHints = mkOption {
               type = types.lines;
               default = "";
-              description = "Extra config for <literal>&lt;StorageHints&gt;</literal> section.";
+              description = lib.mdDoc "Extra config for `<StorageHints>` section.";
             };
           };
         }));
diff --git a/nixos/modules/services/network-filesystems/rsyncd.nix b/nixos/modules/services/network-filesystems/rsyncd.nix
index e72f9b54cd6..c9d7475395f 100644
--- a/nixos/modules/services/network-filesystems/rsyncd.nix
+++ b/nixos/modules/services/network-filesystems/rsyncd.nix
@@ -10,12 +10,12 @@ in {
   options = {
     services.rsyncd = {
 
-      enable = mkEnableOption "the rsync daemon";
+      enable = mkEnableOption (lib.mdDoc "the rsync daemon");
 
       port = mkOption {
         default = 873;
         type = types.port;
-        description = "TCP port the daemon will listen on.";
+        description = lib.mdDoc "TCP port the daemon will listen on.";
       };
 
       settings = mkOption {
@@ -39,10 +39,9 @@ in {
             "secrets file" = "/etc/rsyncd.secrets";
           };
         };
-        description = ''
+        description = lib.mdDoc ''
           Configuration for rsyncd. See
-          <citerefentry><refentrytitle>rsyncd.conf</refentrytitle>
-          <manvolnum>5</manvolnum></citerefentry>.
+          {manpage}`rsyncd.conf(5)`.
         '';
       };
 
@@ -50,7 +49,7 @@ in {
         default = false;
         type = types.bool;
         description =
-          "If enabled Rsync will be socket-activated rather than run persistently.";
+          lib.mdDoc "If enabled Rsync will be socket-activated rather than run persistently.";
       };
 
     };
diff --git a/nixos/modules/services/network-filesystems/samba-wsdd.nix b/nixos/modules/services/network-filesystems/samba-wsdd.nix
index 800ef448d37..24407f05de6 100644
--- a/nixos/modules/services/network-filesystems/samba-wsdd.nix
+++ b/nixos/modules/services/network-filesystems/samba-wsdd.nix
@@ -8,61 +8,61 @@ let
 in {
   options = {
     services.samba-wsdd = {
-      enable = mkEnableOption ''
-        Enable Web Services Dynamic Discovery host daemon. This enables (Samba) hosts, like your local NAS device,
+      enable = mkEnableOption (lib.mdDoc ''
+        Web Services Dynamic Discovery host daemon. This enables (Samba) hosts, like your local NAS device,
         to be found by Web Service Discovery Clients like Windows.
-        <note>
-          <para>If you use the firewall consider adding the following:</para>
-          <programlisting>
+
+        ::: {.note}
+        If you use the firewall consider adding the following:
+
             networking.firewall.allowedTCPPorts = [ 5357 ];
             networking.firewall.allowedUDPPorts = [ 3702 ];
-          </programlisting>
-        </note>
-      '';
+        :::
+      '');
       interface = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "eth0";
-        description = "Interface or address to use.";
+        description = lib.mdDoc "Interface or address to use.";
       };
       hoplimit = mkOption {
         type = types.nullOr types.int;
         default = null;
         example = 2;
-        description = "Hop limit for multicast packets (default = 1).";
+        description = lib.mdDoc "Hop limit for multicast packets (default = 1).";
       };
       workgroup = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "HOME";
-        description = "Set workgroup name (default WORKGROUP).";
+        description = lib.mdDoc "Set workgroup name (default WORKGROUP).";
       };
       hostname = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "FILESERVER";
-        description = "Override (NetBIOS) hostname to be used (default hostname).";
+        description = lib.mdDoc "Override (NetBIOS) hostname to be used (default hostname).";
       };
       domain = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "Set domain name (disables workgroup).";
+        description = lib.mdDoc "Set domain name (disables workgroup).";
       };
       discovery = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable discovery operation mode.";
+        description = lib.mdDoc "Enable discovery operation mode.";
       };
       listen = mkOption {
         type = types.str;
         default = "/run/wsdd/wsdd.sock";
-        description = "Listen on path or localhost port in discovery mode.";
+        description = lib.mdDoc "Listen on path or localhost port in discovery mode.";
       };
       extraOptions = mkOption {
         type = types.listOf types.str;
         default = [ "--shortlog" ];
         example = [ "--verbose" "--no-http" "--ipv4only" "--no-host" ];
-        description = "Additional wsdd options.";
+        description = lib.mdDoc "Additional wsdd options.";
       };
     };
   };
diff --git a/nixos/modules/services/network-filesystems/samba.nix b/nixos/modules/services/network-filesystems/samba.nix
index 992f948e8cd..1310a374abd 100644
--- a/nixos/modules/services/network-filesystems/samba.nix
+++ b/nixos/modules/services/network-filesystems/samba.nix
@@ -80,23 +80,22 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Samba, which provides file and print
           services to Windows clients through the SMB/CIFS protocol.
 
-          <note>
-            <para>If you use the firewall consider adding the following:</para>
-          <programlisting>
-            services.samba.openFirewall = true;
-          </programlisting>
-          </note>
+          ::: {.note}
+          If you use the firewall consider adding the following:
+
+              services.samba.openFirewall = true;
+          :::
         '';
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to automatically open the necessary ports in the firewall.
         '';
       };
@@ -104,7 +103,7 @@ in
       enableNmbd = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Samba's nmbd, which replies to NetBIOS over IP name
           service requests. It also participates in the browsing protocols
           which make up the Windows "Network Neighborhood" view.
@@ -114,7 +113,7 @@ in
       enableWinbindd = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Samba's winbindd, which provides a number of services
           to the Name Service Switch capability found in most modern C libraries,
           to arbitrary applications via PAM and ntlm_auth and to Samba itself.
@@ -126,7 +125,7 @@ in
         default = pkgs.samba;
         defaultText = literalExpression "pkgs.samba";
         example = literalExpression "pkgs.samba4Full";
-        description = ''
+        description = lib.mdDoc ''
           Defines which package should be used for the samba server.
         '';
       };
@@ -134,7 +133,7 @@ in
       invalidUsers = mkOption {
         type = types.listOf types.str;
         default = [ "root" ];
-        description = ''
+        description = lib.mdDoc ''
           List of users who are denied to login via Samba.
         '';
       };
@@ -142,7 +141,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Additional global section and extra section lines go in here.
         '';
         example = ''
@@ -154,7 +153,7 @@ in
       configText = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Verbatim contents of smb.conf. If null (default), use the
           autogenerated file from NixOS instead.
         '';
@@ -163,13 +162,13 @@ in
       securityType = mkOption {
         type = types.str;
         default = "user";
-        description = "Samba security type";
+        description = lib.mdDoc "Samba security type";
       };
 
       nsswins = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the WINS NSS (Name Service Switch) plug-in.
           Enabling it allows applications to resolve WINS/NetBIOS names (a.k.a.
           Windows machine names) by transparently querying the winbindd daemon.
@@ -178,9 +177,9 @@ in
 
       shares = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           A set describing shared resources.
-          See <command>man smb.conf</command> for options.
+          See {command}`man smb.conf` for options.
         '';
         type = types.attrsOf (types.attrsOf types.unspecified);
         example = literalExpression ''
diff --git a/nixos/modules/services/network-filesystems/tahoe.nix b/nixos/modules/services/network-filesystems/tahoe.nix
index 5426463dffa..4213f437f4b 100644
--- a/nixos/modules/services/network-filesystems/tahoe.nix
+++ b/nixos/modules/services/network-filesystems/tahoe.nix
@@ -12,21 +12,21 @@ in
           options = {
             nickname = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The nickname of this Tahoe introducer.
               '';
             };
             tub.port = mkOption {
               default = 3458;
               type = types.int;
-              description = ''
+              description = lib.mdDoc ''
                 The port on which the introducer will listen.
               '';
             };
             tub.location = mkOption {
               default = null;
               type = types.nullOr types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The external location that the introducer should listen on.
 
                 If specified, the port should be included.
@@ -36,13 +36,13 @@ in
               default = pkgs.tahoelafs;
               defaultText = literalExpression "pkgs.tahoelafs";
               type = types.package;
-              description = ''
+              description = lib.mdDoc ''
                 The package to use for the Tahoe LAFS daemon.
               '';
             };
           };
         });
-        description = ''
+        description = lib.mdDoc ''
           The Tahoe introducers.
         '';
       };
@@ -52,14 +52,14 @@ in
           options = {
             nickname = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The nickname of this Tahoe node.
               '';
             };
             tub.port = mkOption {
               default = 3457;
               type = types.int;
-              description = ''
+              description = lib.mdDoc ''
                 The port on which the tub will listen.
 
                 This is the correct setting to tweak if you want Tahoe's storage
@@ -69,7 +69,7 @@ in
             tub.location = mkOption {
               default = null;
               type = types.nullOr types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The external location that the node should listen on.
 
                 This is the setting to tweak if there are multiple interfaces
@@ -81,7 +81,7 @@ in
             web.port = mkOption {
               default = 3456;
               type = types.int;
-              description = ''
+              description = lib.mdDoc ''
                 The port on which the Web server will listen.
 
                 This is the correct setting to tweak if you want Tahoe's WUI to
@@ -91,7 +91,7 @@ in
             client.introducer = mkOption {
               default = null;
               type = types.nullOr types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The furl for a Tahoe introducer node.
 
                 Like all furls, keep this safe and don't share it.
@@ -100,7 +100,7 @@ in
             client.helper = mkOption {
               default = null;
               type = types.nullOr types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The furl for a Tahoe helper node.
 
                 Like all furls, keep this safe and don't share it.
@@ -109,14 +109,14 @@ in
             client.shares.needed = mkOption {
               default = 3;
               type = types.int;
-              description = ''
+              description = lib.mdDoc ''
                 The number of shares required to reconstitute a file.
               '';
             };
             client.shares.happy = mkOption {
               default = 7;
               type = types.int;
-              description = ''
+              description = lib.mdDoc ''
                 The number of distinct storage nodes required to store
                 a file.
               '';
@@ -124,24 +124,24 @@ in
             client.shares.total = mkOption {
               default = 10;
               type = types.int;
-              description = ''
+              description = lib.mdDoc ''
                 The number of shares required to store a file.
               '';
             };
-            storage.enable = mkEnableOption "storage service";
+            storage.enable = mkEnableOption (lib.mdDoc "storage service");
             storage.reservedSpace = mkOption {
               default = "1G";
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The amount of filesystem space to not use for storage.
               '';
             };
-            helper.enable = mkEnableOption "helper service";
-            sftpd.enable = mkEnableOption "SFTP service";
+            helper.enable = mkEnableOption (lib.mdDoc "helper service");
+            sftpd.enable = mkEnableOption (lib.mdDoc "SFTP service");
             sftpd.port = mkOption {
               default = null;
               type = types.nullOr types.int;
-              description = ''
+              description = lib.mdDoc ''
                 The port on which the SFTP server will listen.
 
                 This is the correct setting to tweak if you want Tahoe's SFTP
@@ -151,28 +151,28 @@ in
             sftpd.hostPublicKeyFile = mkOption {
               default = null;
               type = types.nullOr types.path;
-              description = ''
+              description = lib.mdDoc ''
                 Path to the SSH host public key.
               '';
             };
             sftpd.hostPrivateKeyFile = mkOption {
               default = null;
               type = types.nullOr types.path;
-              description = ''
+              description = lib.mdDoc ''
                 Path to the SSH host private key.
               '';
             };
             sftpd.accounts.file = mkOption {
               default = null;
               type = types.nullOr types.path;
-              description = ''
+              description = lib.mdDoc ''
                 Path to the accounts file.
               '';
             };
             sftpd.accounts.url = mkOption {
               default = null;
               type = types.nullOr types.str;
-              description = ''
+              description = lib.mdDoc ''
                 URL of the accounts server.
               '';
             };
@@ -180,13 +180,13 @@ in
               default = pkgs.tahoelafs;
               defaultText = literalExpression "pkgs.tahoelafs";
               type = types.package;
-              description = ''
+              description = lib.mdDoc ''
                 The package to use for the Tahoe LAFS daemon.
               '';
             };
           };
         });
-        description = ''
+        description = lib.mdDoc ''
           The Tahoe nodes.
         '';
       };
diff --git a/nixos/modules/services/network-filesystems/u9fs.nix b/nixos/modules/services/network-filesystems/u9fs.nix
index 77961b78cad..d6968b2cb82 100644
--- a/nixos/modules/services/network-filesystems/u9fs.nix
+++ b/nixos/modules/services/network-filesystems/u9fs.nix
@@ -14,16 +14,16 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to run the u9fs 9P server for Unix.";
+        description = lib.mdDoc "Whether to run the u9fs 9P server for Unix.";
       };
 
       listenStreams = mkOption {
         type = types.listOf types.str;
         default = [ "564" ];
         example = [ "192.168.16.1:564" ];
-        description = ''
+        description = lib.mdDoc ''
           Sockets to listen for clients on.
-          See <command>man 5 systemd.socket</command> for socket syntax.
+          See {command}`man 5 systemd.socket` for socket syntax.
         '';
       };
 
@@ -31,7 +31,7 @@ in
         type = types.str;
         default = "nobody";
         description =
-          "User to run u9fs under.";
+          lib.mdDoc "User to run u9fs under.";
       };
 
       extraArgs = mkOption {
@@ -39,9 +39,9 @@ in
         default = "";
         example = "-a none";
         description =
-          ''
+          lib.mdDoc ''
             Extra arguments to pass on invocation,
-            see <command>man 4 u9fs</command>
+            see {command}`man 4 u9fs`
           '';
       };
 
diff --git a/nixos/modules/services/network-filesystems/webdav-server-rs.nix b/nixos/modules/services/network-filesystems/webdav-server-rs.nix
index 1c5c299cb67..9ea30411181 100644
--- a/nixos/modules/services/network-filesystems/webdav-server-rs.nix
+++ b/nixos/modules/services/network-filesystems/webdav-server-rs.nix
@@ -14,27 +14,27 @@ in
 {
   options = {
     services.webdav-server-rs = {
-      enable = mkEnableOption "WebDAV server";
+      enable = mkEnableOption (lib.mdDoc "WebDAV server");
 
       user = mkOption {
         type = types.str;
         default = "webdav";
-        description = "User to run under when setuid is not enabled.";
+        description = lib.mdDoc "User to run under when setuid is not enabled.";
       };
 
       group = mkOption {
         type = types.str;
         default = "webdav";
-        description = "Group to run under when setuid is not enabled.";
+        description = lib.mdDoc "Group to run under when setuid is not enabled.";
       };
 
       settings = mkOption {
         type = format.type;
         default = { };
-        description = ''
+        description = lib.mdDoc ''
           Attrset that is converted and passed as config file. Available
           options can be found at
-          <link xlink:href="https://github.com/miquels/webdav-server-rs/blob/master/webdav-server.toml">here</link>.
+          [here](https://github.com/miquels/webdav-server-rs/blob/master/webdav-server.toml).
         '';
         example = literalExpression ''
           {
@@ -73,7 +73,7 @@ in
         type = types.path;
         default = format.generate "webdav-server.toml" settings;
         defaultText = "Config file generated from services.webdav-server-rs.settings";
-        description = ''
+        description = lib.mdDoc ''
           Path to config file. If this option is set, it will override any
           configuration done in services.webdav-server-rs.settings.
         '';
diff --git a/nixos/modules/services/network-filesystems/webdav.nix b/nixos/modules/services/network-filesystems/webdav.nix
index a810af40fd4..a384e58c96b 100644
--- a/nixos/modules/services/network-filesystems/webdav.nix
+++ b/nixos/modules/services/network-filesystems/webdav.nix
@@ -8,32 +8,32 @@ in
 {
   options = {
     services.webdav = {
-      enable = mkEnableOption "WebDAV server";
+      enable = mkEnableOption (lib.mdDoc "WebDAV server");
 
       user = mkOption {
         type = types.str;
         default = "webdav";
-        description = "User account under which WebDAV runs.";
+        description = lib.mdDoc "User account under which WebDAV runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "webdav";
-        description = "Group under which WebDAV runs.";
+        description = lib.mdDoc "Group under which WebDAV runs.";
       };
 
       settings = mkOption {
         type = format.type;
         default = { };
-        description = ''
+        description = lib.mdDoc ''
           Attrset that is converted and passed as config file. Available options
           can be found at
-          <link xlink:href="https://github.com/hacdias/webdav">here</link>.
+          [here](https://github.com/hacdias/webdav).
 
           This program supports reading username and password configuration
           from environment variables, so it's strongly recommended to store
           username and password in a separate
-          <link xlink:href="https://www.freedesktop.org/software/systemd/man/systemd.exec.html#EnvironmentFile=">EnvironmentFile</link>.
+          [EnvironmentFile](https://www.freedesktop.org/software/systemd/man/systemd.exec.html#EnvironmentFile=).
           This prevents adding secrets to the world-readable Nix store.
         '';
         example = literalExpression ''
@@ -57,7 +57,7 @@ in
         type = types.path;
         default = format.generate "webdav.yaml" cfg.settings;
         defaultText = "Config file generated from services.webdav.settings";
-        description = ''
+        description = lib.mdDoc ''
           Path to config file. If this option is set, it will override any
           configuration done in options.services.webdav.settings.
         '';
@@ -67,10 +67,8 @@ in
       environmentFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
-          Environment file as defined in <citerefentry>
-          <refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum>
-          </citerefentry>.
+        description = lib.mdDoc ''
+          Environment file as defined in {manpage}`systemd.exec(5)`.
         '';
       };
     };
diff --git a/nixos/modules/services/network-filesystems/xtreemfs.nix b/nixos/modules/services/network-filesystems/xtreemfs.nix
index fc072311578..926c3c3bd52 100644
--- a/nixos/modules/services/network-filesystems/xtreemfs.nix
+++ b/nixos/modules/services/network-filesystems/xtreemfs.nix
@@ -89,12 +89,12 @@ in
 
     services.xtreemfs = {
 
-      enable = mkEnableOption "XtreemFS";
+      enable = mkEnableOption (lib.mdDoc "XtreemFS");
 
       homeDir = mkOption {
         type = types.path;
         default = "/var/lib/xtreemfs";
-        description = ''
+        description = lib.mdDoc ''
           XtreemFS home dir for the xtreemfs user.
         '';
       };
@@ -103,7 +103,7 @@ in
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable XtreemFS DIR service.
           '';
         };
@@ -111,7 +111,7 @@ in
         uuid = mkOption {
           example = "eacb6bab-f444-4ebf-a06a-3f72d7465e40";
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             Must be set to a unique identifier, preferably a UUID according to
             RFC 4122. UUIDs can be generated with `uuidgen` command, found in
             the `util-linux` package.
@@ -120,7 +120,7 @@ in
         port = mkOption {
           default = 32638;
           type = types.port;
-          description = ''
+          description = lib.mdDoc ''
             The port to listen on for incoming connections (TCP).
           '';
         };
@@ -128,7 +128,7 @@ in
           type = types.str;
           example = "127.0.0.1";
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             If specified, it defines the interface to listen on. If not
             specified, the service will listen on all interfaces (any).
           '';
@@ -136,7 +136,7 @@ in
         httpPort = mkOption {
           default = 30638;
           type = types.port;
-          description = ''
+          description = lib.mdDoc ''
             Specifies the listen port for the HTTP service that returns the
             status page.
           '';
@@ -145,7 +145,7 @@ in
           type = types.enum [ "ASYNC" "SYNC_WRITE_METADATA" "SYNC_WRITE" "FDATASYNC" "FSYNC" ];
           default = "FSYNC";
           example = "FDATASYNC";
-          description = ''
+          description = lib.mdDoc ''
             The sync mode influences how operations are committed to the disk
             log before the operation is acknowledged to the caller.
 
@@ -173,14 +173,14 @@ in
             ssl.trusted_certs.pw = jks_passphrase
             ssl.trusted_certs.container = jks
           '';
-          description = ''
+          description = lib.mdDoc ''
             Configuration of XtreemFS DIR service.
             WARNING: configuration is saved as plaintext inside nix store.
             For more options: http://www.xtreemfs.org/xtfs-guide-1.5.1/index.html
           '';
         };
         replication = {
-          enable = mkEnableOption "XtreemFS DIR replication plugin";
+          enable = mkEnableOption (lib.mdDoc "XtreemFS DIR replication plugin");
           extraConfig = mkOption {
             type = types.lines;
             example = ''
@@ -215,7 +215,7 @@ in
 
               babudb.ssl.authenticationWithoutEncryption = false
             '';
-            description = ''
+            description = lib.mdDoc ''
               Configuration of XtreemFS DIR replication plugin.
               WARNING: configuration is saved as plaintext inside nix store.
               For more options: http://www.xtreemfs.org/xtfs-guide-1.5.1/index.html
@@ -228,7 +228,7 @@ in
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable XtreemFS MRC service.
           '';
         };
@@ -236,7 +236,7 @@ in
         uuid = mkOption {
           example = "eacb6bab-f444-4ebf-a06a-3f72d7465e41";
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             Must be set to a unique identifier, preferably a UUID according to
             RFC 4122. UUIDs can be generated with `uuidgen` command, found in
             the `util-linux` package.
@@ -245,7 +245,7 @@ in
         port = mkOption {
           default = 32636;
           type = types.port;
-          description = ''
+          description = lib.mdDoc ''
             The port to listen on for incoming connections (TCP).
           '';
         };
@@ -253,7 +253,7 @@ in
           example = "127.0.0.1";
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             If specified, it defines the interface to listen on. If not
             specified, the service will listen on all interfaces (any).
           '';
@@ -261,7 +261,7 @@ in
         httpPort = mkOption {
           default = 30636;
           type = types.port;
-          description = ''
+          description = lib.mdDoc ''
             Specifies the listen port for the HTTP service that returns the
             status page.
           '';
@@ -270,7 +270,7 @@ in
           default = "FSYNC";
           type = types.enum [ "ASYNC" "SYNC_WRITE_METADATA" "SYNC_WRITE" "FDATASYNC" "FSYNC" ];
           example = "FDATASYNC";
-          description = ''
+          description = lib.mdDoc ''
             The sync mode influences how operations are committed to the disk
             log before the operation is acknowledged to the caller.
 
@@ -316,14 +316,14 @@ in
             ssl.trusted_certs.pw = jks_passphrase
             ssl.trusted_certs.container = jks
           '';
-          description = ''
+          description = lib.mdDoc ''
             Configuration of XtreemFS MRC service.
             WARNING: configuration is saved as plaintext inside nix store.
             For more options: http://www.xtreemfs.org/xtfs-guide-1.5.1/index.html
           '';
         };
         replication = {
-          enable = mkEnableOption "XtreemFS MRC replication plugin";
+          enable = mkEnableOption (lib.mdDoc "XtreemFS MRC replication plugin");
           extraConfig = mkOption {
             type = types.lines;
             example = ''
@@ -358,7 +358,7 @@ in
 
               babudb.ssl.authenticationWithoutEncryption = false
             '';
-            description = ''
+            description = lib.mdDoc ''
               Configuration of XtreemFS MRC replication plugin.
               WARNING: configuration is saved as plaintext inside nix store.
               For more options: http://www.xtreemfs.org/xtfs-guide-1.5.1/index.html
@@ -371,7 +371,7 @@ in
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable XtreemFS OSD service.
           '';
         };
@@ -379,7 +379,7 @@ in
         uuid = mkOption {
           example = "eacb6bab-f444-4ebf-a06a-3f72d7465e42";
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             Must be set to a unique identifier, preferably a UUID according to
             RFC 4122. UUIDs can be generated with `uuidgen` command, found in
             the `util-linux` package.
@@ -388,7 +388,7 @@ in
         port = mkOption {
           default = 32640;
           type = types.port;
-          description = ''
+          description = lib.mdDoc ''
             The port to listen on for incoming connections (TCP and UDP).
           '';
         };
@@ -396,7 +396,7 @@ in
           example = "127.0.0.1";
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             If specified, it defines the interface to listen on. If not
             specified, the service will listen on all interfaces (any).
           '';
@@ -404,7 +404,7 @@ in
         httpPort = mkOption {
           default = 30640;
           type = types.port;
-          description = ''
+          description = lib.mdDoc ''
             Specifies the listen port for the HTTP service that returns the
             status page.
           '';
@@ -435,7 +435,7 @@ in
             ssl.trusted_certs.pw = jks_passphrase
             ssl.trusted_certs.container = jks
           '';
-          description = ''
+          description = lib.mdDoc ''
             Configuration of XtreemFS OSD service.
             WARNING: configuration is saved as plaintext inside nix store.
             For more options: http://www.xtreemfs.org/xtfs-guide-1.5.1/index.html
diff --git a/nixos/modules/services/network-filesystems/yandex-disk.nix b/nixos/modules/services/network-filesystems/yandex-disk.nix
index a5b1f9d4ab6..1078df0bed2 100644
--- a/nixos/modules/services/network-filesystems/yandex-disk.nix
+++ b/nixos/modules/services/network-filesystems/yandex-disk.nix
@@ -23,15 +23,15 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "
+        description = lib.mdDoc ''
           Whether to enable Yandex-disk client. See https://disk.yandex.ru/
-        ";
+        '';
       };
 
       username = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Your yandex.com login name.
         '';
       };
@@ -39,7 +39,7 @@ in
       password = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Your yandex.com password. Warning: it will be world-readable in /nix/store.
         '';
       };
@@ -47,7 +47,7 @@ in
       user = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           The user the yandex-disk daemon should run as.
         '';
       };
@@ -55,14 +55,14 @@ in
       directory = mkOption {
         type = types.path;
         default = "/home/Yandex.Disk";
-        description = "The directory to use for Yandex.Disk storage";
+        description = lib.mdDoc "The directory to use for Yandex.Disk storage";
       };
 
       excludes = mkOption {
         default = "";
         type = types.commas;
         example = "data,backup";
-        description = ''
+        description = lib.mdDoc ''
           Comma-separated list of directories which are excluded from synchronization.
         '';
       };
diff --git a/nixos/modules/services/networking/3proxy.nix b/nixos/modules/services/networking/3proxy.nix
index 326a8671fcc..e643ed94131 100644
--- a/nixos/modules/services/networking/3proxy.nix
+++ b/nixos/modules/services/networking/3proxy.nix
@@ -6,11 +6,11 @@ let
   optionalList = list: if list == [ ] then "*" else concatMapStringsSep "," toString list;
 in {
   options.services._3proxy = {
-    enable = mkEnableOption "3proxy";
+    enable = mkEnableOption (lib.mdDoc "3proxy");
     confFile = mkOption {
       type = types.path;
       example = "/var/lib/3proxy/3proxy.conf";
-      description = ''
+      description = lib.mdDoc ''
         Ignore all other 3proxy options and load configuration from this file.
       '';
     };
@@ -18,26 +18,26 @@ in {
       type = types.nullOr types.path;
       default = null;
       example = "/var/lib/3proxy/3proxy.passwd";
-      description = ''
+      description = lib.mdDoc ''
         Load users and passwords from this file.
 
         Example users file with plain-text passwords:
 
-        <literal>
+        ```
           test1:CL:password1
           test2:CL:password2
-        </literal>
+        ```
 
         Example users file with md5-crypted passwords:
 
-        <literal>
+        ```
           test1:CR:$1$tFkisVd2$1GA8JXkRmTXdLDytM/i3a1
           test2:CR:$1$rkpibm5J$Aq1.9VtYAn0JrqZ8M.1ME.
-        </literal>
+        ```
 
         You can generate md5-crypted passwords via https://unix4lyfe.org/crypt/
         Note that htpasswd tool generates incompatible md5-crypted passwords.
-        Consult <link xlink:href="https://github.com/z3APA3A/3proxy/wiki/How-To-(incomplete)#USERS">documentation</link> for more information.
+        Consult [documentation](https://github.com/z3APA3A/3proxy/wiki/How-To-%28incomplete%29#USERS) for more information.
       '';
     };
     services = mkOption {
@@ -55,42 +55,24 @@ in {
               "udppm"
             ];
             example = "proxy";
-            description = ''
+            description = lib.mdDoc ''
               Service type. The following values are valid:
 
-              <itemizedlist>
-                <listitem><para>
-                  <literal>"proxy"</literal>: HTTP/HTTPS proxy (default port 3128).
-                </para></listitem>
-                <listitem><para>
-                  <literal>"socks"</literal>: SOCKS 4/4.5/5 proxy (default port 1080).
-                </para></listitem>
-                <listitem><para>
-                  <literal>"pop3p"</literal>: POP3 proxy (default port 110).
-                </para></listitem>
-                <listitem><para>
-                  <literal>"ftppr"</literal>: FTP proxy (default port 21).
-                </para></listitem>
-                <listitem><para>
-                  <literal>"admin"</literal>: Web interface (default port 80).
-                </para></listitem>
-                <listitem><para>
-                  <literal>"dnspr"</literal>: Caching DNS proxy (default port 53).
-                </para></listitem>
-                <listitem><para>
-                  <literal>"tcppm"</literal>: TCP portmapper.
-                </para></listitem>
-                <listitem><para>
-                  <literal>"udppm"</literal>: UDP portmapper.
-                </para></listitem>
-              </itemizedlist>
+              - `"proxy"`: HTTP/HTTPS proxy (default port 3128).
+              - `"socks"`: SOCKS 4/4.5/5 proxy (default port 1080).
+              - `"pop3p"`: POP3 proxy (default port 110).
+              - `"ftppr"`: FTP proxy (default port 21).
+              - `"admin"`: Web interface (default port 80).
+              - `"dnspr"`: Caching DNS proxy (default port 53).
+              - `"tcppm"`: TCP portmapper.
+              - `"udppm"`: UDP portmapper.
             '';
           };
           bindAddress = mkOption {
             type = types.str;
             default = "[::]";
             example = "127.0.0.1";
-            description = ''
+            description = lib.mdDoc ''
               Address used for service.
             '';
           };
@@ -98,7 +80,7 @@ in {
             type = types.nullOr types.int;
             default = null;
             example = 3128;
-            description = ''
+            description = lib.mdDoc ''
               Override default port used for service.
             '';
           };
@@ -106,31 +88,23 @@ in {
             type = types.int;
             default = 100;
             example = 1000;
-            description = ''
+            description = lib.mdDoc ''
               Maximum number of simulationeous connections to this service.
             '';
           };
           auth = mkOption {
             type = types.listOf (types.enum [ "none" "iponly" "strong" ]);
             example = [ "iponly" "strong" ];
-            description = ''
+            description = lib.mdDoc ''
               Authentication type. The following values are valid:
 
-              <itemizedlist>
-                <listitem><para>
-                  <literal>"none"</literal>: disables both authentication and authorization. You can not use ACLs.
-                </para></listitem>
-                <listitem><para>
-                  <literal>"iponly"</literal>: specifies no authentication. ACLs authorization is used.
-                </para></listitem>
-                <listitem><para>
-                  <literal>"strong"</literal>: authentication by username/password. If user is not registered their access is denied regardless of ACLs.
-                </para></listitem>
-              </itemizedlist>
+              - `"none"`: disables both authentication and authorization. You can not use ACLs.
+              - `"iponly"`: specifies no authentication. ACLs authorization is used.
+              - `"strong"`: authentication by username/password. If user is not registered their access is denied regardless of ACLs.
 
               Double authentication is possible, e.g.
 
-              <literal>
+              ```
                 {
                   auth = [ "iponly" "strong" ];
                   acl = [
@@ -144,7 +118,7 @@ in {
                     }
                   ];
                 }
-              </literal>
+              ```
               In this example strong username authentication is not required to access 192.168.0.0/16.
             '';
           };
@@ -154,24 +128,18 @@ in {
                 rule = mkOption {
                   type = types.enum [ "allow" "deny" ];
                   example = "allow";
-                  description = ''
+                  description = lib.mdDoc ''
                     ACL rule. The following values are valid:
 
-                    <itemizedlist>
-                      <listitem><para>
-                        <literal>"allow"</literal>: connections allowed.
-                      </para></listitem>
-                      <listitem><para>
-                        <literal>"deny"</literal>: connections not allowed.
-                      </para></listitem>
-                    </itemizedlist>
+                    - `"allow"`: connections allowed.
+                    - `"deny"`: connections not allowed.
                   '';
                 };
                 users = mkOption {
                   type = types.listOf types.str;
                   default = [ ];
                   example = [ "user1" "user2" "user3" ];
-                  description = ''
+                  description = lib.mdDoc ''
                     List of users, use empty list for any.
                   '';
                 };
@@ -179,7 +147,7 @@ in {
                   type = types.listOf types.str;
                   default = [ ];
                   example = [ "127.0.0.1" "192.168.1.0/24" ];
-                  description = ''
+                  description = lib.mdDoc ''
                     List of source IP range, use empty list for any.
                   '';
                 };
@@ -187,10 +155,10 @@ in {
                   type = types.listOf types.str;
                   default = [ ];
                   example = [ "127.0.0.1" "192.168.1.0/24" ];
-                  description = ''
+                  description = lib.mdDoc ''
                     List of target IP ranges, use empty list for any.
                     May also contain host names instead of addresses.
-                    It's possible to use wildmask in the begginning and in the the end of hostname, e.g. *badsite.com or *badcontent*.
+                    It's possible to use wildmask in the begginning and in the the end of hostname, e.g. `*badsite.com` or `*badcontent*`.
                     Hostname is only checked if hostname presents in request.
                   '';
                 };
@@ -198,7 +166,7 @@ in {
                   type = types.listOf types.int;
                   default = [ ];
                   example = [ 80 443 ];
-                  description = ''
+                  description = lib.mdDoc ''
                     List of target ports, use empty list for any.
                   '';
                 };
@@ -220,7 +188,7 @@ in {
                 }
               ]
             '';
-            description = ''
+            description = lib.mdDoc ''
               Use this option to limit user access to resources.
             '';
           };
@@ -228,17 +196,17 @@ in {
             type = types.nullOr types.str;
             default = null;
             example = "-46";
-            description = ''
+            description = lib.mdDoc ''
               Extra arguments for service.
-              Consult "Options" section in <link xlink:href="https://github.com/z3APA3A/3proxy/wiki/3proxy.cfg">documentation</link> for available arguments.
+              Consult "Options" section in [documentation](https://github.com/z3APA3A/3proxy/wiki/3proxy.cfg) for available arguments.
             '';
           };
           extraConfig = mkOption {
             type = types.nullOr types.lines;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Extra configuration for service. Use this to configure things like bandwidth limiter or ACL-based redirection.
-              Consult <link xlink:href="https://github.com/z3APA3A/3proxy/wiki/3proxy.cfg">documentation</link> for available options.
+              Consult [documentation](https://github.com/z3APA3A/3proxy/wiki/3proxy.cfg) for available options.
             '';
           };
         };
@@ -266,14 +234,14 @@ in {
           }
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         Use this option to define 3proxy services.
       '';
     };
     denyPrivate = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to deny access to private IP ranges including loopback.
       '';
     };
@@ -290,7 +258,7 @@ in {
         "::1"
         "fc00::/7"
       ];
-      description = ''
+      description = lib.mdDoc ''
         What IP ranges to deny access when denyPrivate is set tu true.
       '';
     };
@@ -301,7 +269,7 @@ in {
             type = types.listOf types.str;
             default = [ ];
             example = [ "127.0.0.53" "192.168.1.3:5353/tcp" ];
-            description = ''
+            description = lib.mdDoc ''
               List of nameservers to use.
 
               Up to 5 nservers may be specified. If no nserver is configured,
@@ -311,12 +279,12 @@ in {
           nscache = mkOption {
             type = types.int;
             default = 65535;
-            description = "Set name cache size for IPv4.";
+            description = lib.mdDoc "Set name cache size for IPv4.";
           };
           nscache6 = mkOption {
             type = types.int;
             default = 65535;
-            description = "Set name cache size for IPv6.";
+            description = lib.mdDoc "Set name cache size for IPv6.";
           };
           nsrecord = mkOption {
             type = types.attrsOf types.str;
@@ -327,21 +295,21 @@ in {
                 "site.local" = "192.168.1.43";
               }
             '';
-            description = "Adds static nsrecords.";
+            description = lib.mdDoc "Adds static nsrecords.";
           };
         };
       };
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Use this option to configure name resolution and DNS caching.
       '';
     };
     extraConfig = mkOption {
       type = types.nullOr types.lines;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Extra configuration, appended to the 3proxy configuration file.
-        Consult <link xlink:href="https://github.com/z3APA3A/3proxy/wiki/3proxy.cfg">documentation</link> for available options.
+        Consult [documentation](https://github.com/z3APA3A/3proxy/wiki/3proxy.cfg) for available options.
       '';
     };
   };
diff --git a/nixos/modules/services/networking/adguardhome.nix b/nixos/modules/services/networking/adguardhome.nix
index 98ddf071608..bda99cb7942 100644
--- a/nixos/modules/services/networking/adguardhome.nix
+++ b/nixos/modules/services/networking/adguardhome.nix
@@ -12,41 +12,30 @@ let
     "--config /var/lib/AdGuardHome/AdGuardHome.yaml"
   ] ++ cfg.extraArgs);
 
-  baseConfig = {
-    bind_host = cfg.host;
-    bind_port = cfg.port;
-  };
-
   configFile = pkgs.writeTextFile {
     name = "AdGuardHome.yaml";
-    text = builtins.toJSON (recursiveUpdate cfg.settings baseConfig);
+    text = builtins.toJSON cfg.settings;
     checkPhase = "${pkgs.adguardhome}/bin/adguardhome -c $out --check-config";
   };
 
-in {
-  options.services.adguardhome = with types; {
-    enable = mkEnableOption "AdGuard Home network-wide ad blocker";
+in
+{
 
-    host = mkOption {
-      default = "0.0.0.0";
-      type = str;
-      description = ''
-        Host address to bind HTTP server to.
-      '';
-    };
+  imports =
+    let cfgPath = [ "services" "adguardhome" ];
+    in
+    [
+      (mkRenamedOptionModuleWith { sinceRelease = 2211; from = cfgPath ++ [ "host" ]; to = cfgPath ++ [ "settings" "bind_host" ]; })
+      (mkRenamedOptionModuleWith { sinceRelease = 2211; from = cfgPath ++ [ "port" ]; to = cfgPath ++ [ "settings" "bind_port" ]; })
+    ];
 
-    port = mkOption {
-      default = 3000;
-      type = port;
-      description = ''
-        Port to serve HTTP pages on.
-      '';
-    };
+  options.services.adguardhome = with types; {
+    enable = mkEnableOption (lib.mdDoc "AdGuard Home network-wide ad blocker");
 
     openFirewall = mkOption {
       default = false;
       type = bool;
-      description = ''
+      description = lib.mdDoc ''
         Open ports in the firewall for the AdGuard Home web interface. Does not
         open the port needed to access the DNS resolver.
       '';
@@ -55,32 +44,63 @@ in {
     mutableSettings = mkOption {
       default = true;
       type = bool;
-      description = ''
+      description = lib.mdDoc ''
         Allow changes made on the AdGuard Home web interface to persist between
         service restarts.
       '';
     };
 
     settings = mkOption {
-      type = (pkgs.formats.yaml { }).type;
-      default = { };
-      description = ''
+      default = null;
+      type = nullOr (submodule {
+        freeformType = (pkgs.formats.yaml { }).type;
+        options = {
+          schema_version = mkOption {
+            default = pkgs.adguardhome.schema_version;
+            defaultText = literalExpression "pkgs.adguardhome.schema_version";
+            type = int;
+            description = lib.mdDoc ''
+              Schema version for the configuration.
+              Defaults to the `schema_version` supplied by `pkgs.adguardhome`.
+            '';
+          };
+          bind_host = mkOption {
+            default = "0.0.0.0";
+            type = str;
+            description = lib.mdDoc ''
+              Host address to bind HTTP server to.
+            '';
+          };
+          bind_port = mkOption {
+            default = 3000;
+            type = port;
+            description = lib.mdDoc ''
+              Port to serve HTTP pages on.
+            '';
+          };
+        };
+      });
+      description = lib.mdDoc ''
         AdGuard Home configuration. Refer to
-        <link xlink:href="https://github.com/AdguardTeam/AdGuardHome/wiki/Configuration#configuration-file"/>
+        <https://github.com/AdguardTeam/AdGuardHome/wiki/Configuration#configuration-file>
         for details on supported values.
 
-        <note><para>
-          On start and if <option>mutableSettings</option> is <literal>true</literal>,
-          these options are merged into the configuration file on start, taking
-          precedence over configuration changes made on the web interface.
-        </para></note>
+        ::: {.note}
+        On start and if {option}`mutableSettings` is `true`,
+        these options are merged into the configuration file on start, taking
+        precedence over configuration changes made on the web interface.
+
+        Set this to `null` (default) for a non-declarative configuration without any
+        Nix-supplied values.
+        Declarative configurations are supplied with a default `schema_version`, `bind_host`, and `bind_port`.
+        :::
       '';
     };
 
     extraArgs = mkOption {
       default = [ ];
       type = listOf str;
-      description = ''
+      description = lib.mdDoc ''
         Extra command line parameters to be passed to the adguardhome binary.
       '';
     };
@@ -89,15 +109,15 @@ in {
   config = mkIf cfg.enable {
     assertions = [
       {
-        assertion = cfg.settings != { }
-          -> (hasAttrByPath [ "dns" "bind_host" ] cfg.settings)
+        assertion = cfg.settings != null -> cfg.mutableSettings
+          || (hasAttrByPath [ "dns" "bind_host" ] cfg.settings)
           || (hasAttrByPath [ "dns" "bind_hosts" ] cfg.settings);
         message =
           "AdGuard setting dns.bind_host or dns.bind_hosts needs to be configured for a minimal working configuration";
       }
       {
-        assertion = cfg.settings != { }
-          -> hasAttrByPath [ "dns" "bootstrap_dns" ] cfg.settings;
+        assertion = cfg.settings != null -> cfg.mutableSettings
+          || hasAttrByPath [ "dns" "bootstrap_dns" ] cfg.settings;
         message =
           "AdGuard setting dns.bootstrap_dns needs to be configured for a minimal working configuration";
       }
@@ -112,7 +132,7 @@ in {
         StartLimitBurst = 10;
       };
 
-      preStart = optionalString (cfg.settings != { }) ''
+      preStart = optionalString (cfg.settings != null) ''
         if    [ -e "$STATE_DIRECTORY/AdGuardHome.yaml" ] \
            && [ "${toString cfg.mutableSettings}" = "1" ]; then
           # Writing directly to AdGuardHome.yaml results in empty file
@@ -135,6 +155,6 @@ in {
       };
     };
 
-    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ];
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.settings.bind_port ];
   };
 }
diff --git a/nixos/modules/services/networking/amuled.nix b/nixos/modules/services/networking/amuled.nix
index aa72a047526..1cd54335819 100644
--- a/nixos/modules/services/networking/amuled.nix
+++ b/nixos/modules/services/networking/amuled.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run the AMule daemon. You need to manually run "amuled --ec-config" to configure the service for the first time.
         '';
       };
@@ -30,7 +30,7 @@ in
         defaultText = literalExpression ''
           "/home/''${config.${opt.user}}/"
         '';
-        description = ''
+        description = lib.mdDoc ''
           The directory holding configuration, incoming and temporary files.
         '';
       };
@@ -38,7 +38,7 @@ in
       user = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The user the AMule daemon should run as.
         '';
       };
diff --git a/nixos/modules/services/networking/antennas.nix b/nixos/modules/services/networking/antennas.nix
index ef98af22f20..c0e56890864 100644
--- a/nixos/modules/services/networking/antennas.nix
+++ b/nixos/modules/services/networking/antennas.nix
@@ -8,30 +8,30 @@ in
 {
   options = {
     services.antennas = {
-      enable = mkEnableOption "Antennas";
+      enable = mkEnableOption (lib.mdDoc "Antennas");
 
       tvheadendUrl = mkOption {
         type        = types.str;
         default     = "http://localhost:9981";
-        description = "URL of Tvheadend.";
+        description = lib.mdDoc "URL of Tvheadend.";
       };
 
       antennasUrl = mkOption {
         type        = types.str;
         default     = "http://127.0.0.1:5004";
-        description = "URL of Antennas.";
+        description = lib.mdDoc "URL of Antennas.";
       };
 
       tunerCount = mkOption {
         type        = types.int;
         default     = 6;
-        description = "Numbers of tuners in tvheadend.";
+        description = lib.mdDoc "Numbers of tuners in tvheadend.";
       };
 
       deviceUUID = mkOption {
         type        = types.str;
         default     = "2f70c0d7-90a3-4429-8275-cbeeee9cd605";
-        description = "Device tuner UUID. Change this if you are running multiple instances.";
+        description = lib.mdDoc "Device tuner UUID. Change this if you are running multiple instances.";
       };
     };
   };
diff --git a/nixos/modules/services/networking/aria2.nix b/nixos/modules/services/networking/aria2.nix
index 156fef14479..e848869cc0a 100644
--- a/nixos/modules/services/networking/aria2.nix
+++ b/nixos/modules/services/networking/aria2.nix
@@ -28,7 +28,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether or not to enable the headless Aria2 daemon service.
 
           Aria2 daemon can be controlled via the RPC interface using
@@ -41,7 +41,7 @@ in
       openPorts = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open listen and RPC ports found in listenPortRange and rpcListenPort
           options in the firewall.
         '';
@@ -49,26 +49,26 @@ in
       downloadDir = mkOption {
         type = types.path;
         default = downloadDir;
-        description = ''
+        description = lib.mdDoc ''
           Directory to store downloaded files.
         '';
       };
       listenPortRange = mkOption {
         type = types.listOf types.attrs;
         default = [ { from = 6881; to = 6999; } ];
-        description = ''
+        description = lib.mdDoc ''
           Set UDP listening port range used by DHT(IPv4, IPv6) and UDP tracker.
         '';
       };
       rpcListenPort = mkOption {
         type = types.int;
         default = 6800;
-        description = "Specify a port number for JSON-RPC/XML-RPC server to listen to. Possible Values: 1024-65535";
+        description = lib.mdDoc "Specify a port number for JSON-RPC/XML-RPC server to listen to. Possible Values: 1024-65535";
       };
       rpcSecret = mkOption {
         type = types.str;
         default = "aria2rpc";
-        description = ''
+        description = lib.mdDoc ''
           Set RPC secret authorization token.
           Read https://aria2.github.io/manual/en/html/aria2c.html#rpc-auth to know how this option value is used.
         '';
@@ -77,7 +77,7 @@ in
         type = types.separatedString " ";
         example = "--rpc-listen-all --remote-time=true";
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Additional arguments to be passed to Aria2.
         '';
       };
diff --git a/nixos/modules/services/networking/asterisk.nix b/nixos/modules/services/networking/asterisk.nix
index af091d55c01..5a1d03f0721 100644
--- a/nixos/modules/services/networking/asterisk.nix
+++ b/nixos/modules/services/networking/asterisk.nix
@@ -14,28 +14,9 @@ let
 
   # Add filecontents from files of useTheseDefaultConfFiles to confFiles, do not override
   defaultConfFiles = subtractLists (attrNames cfg.confFiles) cfg.useTheseDefaultConfFiles;
-  allConfFiles =
-    cfg.confFiles //
-    builtins.listToAttrs (map (x: { name = x;
-                                    value = builtins.readFile (cfg.package + "/etc/asterisk/" + x); })
-                              defaultConfFiles);
-
-  asteriskEtc = pkgs.stdenv.mkDerivation
-  ((mapAttrs' (name: value: nameValuePair
-        # Fudge the names to make bash happy
-        ((replaceChars ["."] ["_"] name) + "_")
-        (value)
-      ) allConfFiles) //
-  {
-    confFilesString = concatStringsSep " " (
-      attrNames allConfFiles
-    );
-
-    name = "asterisk-etc";
-
+  allConfFiles = {
     # Default asterisk.conf file
-    # (Notice that astetcdir will be set to the path of this derivation)
-    asteriskConf = ''
+    "asterisk.conf".text = ''
       [directories]
       astetcdir => /etc/asterisk
       astmoddir => ${cfg.package}/lib/asterisk/modules
@@ -48,43 +29,28 @@ let
       astrundir => /run/asterisk
       astlogdir => /var/log/asterisk
       astsbindir => ${cfg.package}/sbin
+      ${cfg.extraConfig}
     '';
-    extraConf = cfg.extraConfig;
 
     # Loading all modules by default is considered sensible by the authors of
     # "Asterisk: The Definitive Guide". Secure sites will likely want to
     # specify their own "modules.conf" in the confFiles option.
-    modulesConf = ''
+    "modules.conf".text = ''
       [modules]
       autoload=yes
     '';
 
     # Use syslog for logging so logs can be viewed with journalctl
-    loggerConf = ''
+    "logger.conf".text = ''
       [general]
 
       [logfiles]
       syslog.local0 => notice,warning,error
     '';
+  } //
+    mapAttrs (name: text: { inherit text; }) cfg.confFiles //
+    listToAttrs (map (x: nameValuePair x { source = cfg.package + "/etc/asterisk/" + x; }) defaultConfFiles);
 
-    buildCommand = ''
-      mkdir -p "$out"
-
-      # Create asterisk.conf, pointing astetcdir to the path of this derivation
-      echo "$asteriskConf" | sed "s|@out@|$out|g" > "$out"/asterisk.conf
-      echo "$extraConf" >> "$out"/asterisk.conf
-
-      echo "$modulesConf" > "$out"/modules.conf
-
-      echo "$loggerConf" > "$out"/logger.conf
-
-      # Config files specified in confFiles option override all other files
-      for i in $confFilesString; do
-        conf=$(echo "$i"_ | sed 's/\./_/g')
-        echo "''${!conf}" > "$out"/"$i"
-      done
-    '';
-  });
 in
 
 {
@@ -93,7 +59,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Asterisk PBX server.
         '';
       };
@@ -106,9 +72,9 @@ in
           verbose=3
           debug=3
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration options appended to the default
-          <literal>asterisk.conf</literal> file.
+          `asterisk.conf` file.
         '';
       };
 
@@ -161,19 +127,19 @@ in
               ''';
             }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Sets the content of config files (typically ending with
-          <literal>.conf</literal>) in the Asterisk configuration directory.
+          `.conf`) in the Asterisk configuration directory.
 
-          Note that if you want to change <literal>asterisk.conf</literal>, it
-          is preferable to use the <option>services.asterisk.extraConfig</option>
-          option over this option. If <literal>"asterisk.conf"</literal> is
-          specified with the <option>confFiles</option> option (not recommended),
-          you must be prepared to set your own <literal>astetcdir</literal>
+          Note that if you want to change `asterisk.conf`, it
+          is preferable to use the {option}`services.asterisk.extraConfig`
+          option over this option. If `"asterisk.conf"` is
+          specified with the {option}`confFiles` option (not recommended),
+          you must be prepared to set your own `astetcdir`
           path.
 
           See
-          <link xlink:href="http://www.asterisk.org/community/documentation"/>
+          <http://www.asterisk.org/community/documentation>
           for more examples of what is possible here.
         '';
       };
@@ -182,9 +148,9 @@ in
         default = [ "ari.conf" "acl.conf" "agents.conf" "amd.conf" "calendar.conf" "cdr.conf" "cdr_syslog.conf" "cdr_custom.conf" "cel.conf" "cel_custom.conf" "cli_aliases.conf" "confbridge.conf" "dundi.conf" "features.conf" "hep.conf" "iax.conf" "pjsip.conf" "pjsip_wizard.conf" "phone.conf" "phoneprov.conf" "queues.conf" "res_config_sqlite3.conf" "res_parking.conf" "statsd.conf" "udptl.conf" "unistim.conf" ];
         type = types.listOf types.str;
         example = [ "sip.conf" "dundi.conf" ];
-        description = ''Sets these config files to the default content. The default value for
+        description = lib.mdDoc ''Sets these config files to the default content. The default value for
           this option contains all necesscary files to avoid errors at startup.
-          This does not override settings via <option>services.asterisk.confFiles</option>.
+          This does not override settings via {option}`services.asterisk.confFiles`.
         '';
       };
 
@@ -193,7 +159,7 @@ in
         type = types.listOf types.str;
         example =
           [ "-vvvddd" "-e" "1024" ];
-        description = ''
+        description = lib.mdDoc ''
           Additional command line arguments to pass to Asterisk.
         '';
       };
@@ -201,7 +167,7 @@ in
         type = types.package;
         default = pkgs.asterisk;
         defaultText = literalExpression "pkgs.asterisk";
-        description = "The Asterisk package to use.";
+        description = lib.mdDoc "The Asterisk package to use.";
       };
     };
   };
@@ -209,7 +175,9 @@ in
   config = mkIf cfg.enable {
     environment.systemPackages = [ cfg.package ];
 
-    environment.etc.asterisk.source = asteriskEtc;
+    environment.etc = mapAttrs' (name: value:
+      nameValuePair "asterisk/${name}" value
+    ) allConfFiles;
 
     users.users.asterisk =
       { name = asteriskUser;
diff --git a/nixos/modules/services/networking/atftpd.nix b/nixos/modules/services/networking/atftpd.nix
index da5e305201f..e31b447e6c5 100644
--- a/nixos/modules/services/networking/atftpd.nix
+++ b/nixos/modules/services/networking/atftpd.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the atftpd TFTP server. By default, the server
           binds to address 0.0.0.0.
         '';
@@ -33,7 +33,7 @@ in
             "--verbose=7"
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra command line arguments to pass to atftp.
         '';
       };
@@ -41,7 +41,7 @@ in
       root = mkOption {
         default = "/srv/tftp";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Document root directory for the atftpd.
         '';
       };
diff --git a/nixos/modules/services/networking/autossh.nix b/nixos/modules/services/networking/autossh.nix
index 245f2bfc2cf..ed9c07d9a14 100644
--- a/nixos/modules/services/networking/autossh.nix
+++ b/nixos/modules/services/networking/autossh.nix
@@ -22,18 +22,18 @@ in
             name = mkOption {
               type = types.str;
               example = "socks-peer";
-              description = "Name of the local AutoSSH session";
+              description = lib.mdDoc "Name of the local AutoSSH session";
             };
             user = mkOption {
               type = types.str;
               example = "bill";
-              description = "Name of the user the AutoSSH session should run as";
+              description = lib.mdDoc "Name of the user the AutoSSH session should run as";
             };
             monitoringPort = mkOption {
               type = types.int;
               default = 0;
               example = 20000;
-              description = ''
+              description = lib.mdDoc ''
                 Port to be used by AutoSSH for peer monitoring. Note, that
                 AutoSSH also uses mport+1. Value of 0 disables the keep-alive
                 style monitoring
@@ -42,7 +42,7 @@ in
             extraArguments = mkOption {
               type = types.separatedString " ";
               example = "-N -D4343 bill@socks.example.net";
-              description = ''
+              description = lib.mdDoc ''
                 Arguments to be passed to AutoSSH and retransmitted to SSH
                 process. Some meaningful options include -N (don't run remote
                 command), -D (open SOCKS proxy on local port), -R (forward
@@ -54,7 +54,7 @@ in
         });
 
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of AutoSSH sessions to start as systemd services. Each service is
           named 'autossh-{session.name}'.
         '';
diff --git a/nixos/modules/services/networking/avahi-daemon.nix b/nixos/modules/services/networking/avahi-daemon.nix
index 50c4ffdedce..56113bd3459 100644
--- a/nixos/modules/services/networking/avahi-daemon.nix
+++ b/nixos/modules/services/networking/avahi-daemon.nix
@@ -43,7 +43,7 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to run the Avahi daemon, which allows Avahi clients
         to use Avahi's service discovery facilities and also allows
         the local machine to advertise its presence and services
@@ -55,16 +55,16 @@ in
       type = types.str;
       default = config.networking.hostName;
       defaultText = literalExpression "config.networking.hostName";
-      description = ''
+      description = lib.mdDoc ''
         Host name advertised on the LAN. If not set, avahi will use the value
-        of <option>config.networking.hostName</option>.
+        of {option}`config.networking.hostName`.
       '';
     };
 
     domainName = mkOption {
       type = types.str;
       default = "local";
-      description = ''
+      description = lib.mdDoc ''
         Domain name for all advertisements.
       '';
     };
@@ -73,7 +73,7 @@ in
       type = types.listOf types.str;
       default = [ ];
       example = [ "0pointer.de" "zeroconf.org" ];
-      description = ''
+      description = lib.mdDoc ''
         List of non-local DNS domains to be browsed.
       '';
     };
@@ -81,22 +81,22 @@ in
     ipv4 = mkOption {
       type = types.bool;
       default = true;
-      description = "Whether to use IPv4.";
+      description = lib.mdDoc "Whether to use IPv4.";
     };
 
     ipv6 = mkOption {
       type = types.bool;
       default = config.networking.enableIPv6;
       defaultText = literalExpression "config.networking.enableIPv6";
-      description = "Whether to use IPv6.";
+      description = lib.mdDoc "Whether to use IPv6.";
     };
 
     interfaces = mkOption {
       type = types.nullOr (types.listOf types.str);
       default = null;
-      description = ''
-        List of network interfaces that should be used by the <command>avahi-daemon</command>.
-        Other interfaces will be ignored. If <literal>null</literal>, all local interfaces
+      description = lib.mdDoc ''
+        List of network interfaces that should be used by the {command}`avahi-daemon`.
+        Other interfaces will be ignored. If `null`, all local interfaces
         except loopback and point-to-point will be used.
       '';
     };
@@ -104,7 +104,7 @@ in
     openFirewall = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to open the firewall for UDP port 5353.
       '';
     };
@@ -112,7 +112,7 @@ in
     allowPointToPoint = mkOption {
       type = types.bool;
       default = false;
-      description= ''
+      description= lib.mdDoc ''
         Whether to use POINTTOPOINT interfaces. Might make mDNS unreliable due to usually large
         latencies with such links and opens a potential security hole by allowing mDNS access from Internet
         connections.
@@ -122,13 +122,13 @@ in
     wideArea = mkOption {
       type = types.bool;
       default = true;
-      description = "Whether to enable wide-area service discovery.";
+      description = lib.mdDoc "Whether to enable wide-area service discovery.";
     };
 
     reflector = mkOption {
       type = types.bool;
       default = false;
-      description = "Reflect incoming mDNS requests to all allowed network interfaces.";
+      description = lib.mdDoc "Reflect incoming mDNS requests to all allowed network interfaces.";
     };
 
     extraServiceFiles = mkOption {
@@ -150,10 +150,9 @@ in
           ''';
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Specify custom service definitions which are placed in the avahi service directory.
-        See the <citerefentry><refentrytitle>avahi.service</refentrytitle>
-        <manvolnum>5</manvolnum></citerefentry> manpage for detailed information.
+        See the {manpage}`avahi.service(5)` manpage for detailed information.
       '';
     };
 
@@ -161,25 +160,25 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to allow publishing in general.";
+        description = lib.mdDoc "Whether to allow publishing in general.";
       };
 
       userServices = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to publish user services. Will set <literal>addresses=true</literal>.";
+        description = lib.mdDoc "Whether to publish user services. Will set `addresses=true`.";
       };
 
       addresses = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to register mDNS address records for all local IP addresses.";
+        description = lib.mdDoc "Whether to register mDNS address records for all local IP addresses.";
       };
 
       hinfo = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to register a mDNS HINFO record which contains information about the
           local operating system and CPU.
         '';
@@ -188,7 +187,7 @@ in
       workstation = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to register a service of type "_workstation._tcp" on the local LAN.
         '';
       };
@@ -196,14 +195,14 @@ in
       domain = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to announce the locally used domain name for browsing by other hosts.";
+        description = lib.mdDoc "Whether to announce the locally used domain name for browsing by other hosts.";
       };
     };
 
     nssmdns = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable the mDNS NSS (Name Service Switch) plug-in.
         Enabling it allows applications to resolve names in the `.local'
         domain by transparently querying the Avahi daemon.
@@ -213,7 +212,7 @@ in
     cacheEntriesMax = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Number of resource records to be cached per interface. Use 0 to
         disable caching. Avahi daemon defaults to 4096 if not set.
       '';
@@ -222,7 +221,7 @@ in
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra config to append to avahi-daemon.conf.
       '';
     };
diff --git a/nixos/modules/services/networking/babeld.nix b/nixos/modules/services/networking/babeld.nix
index aae6f1498a4..ff1ac6998ee 100644
--- a/nixos/modules/services/networking/babeld.nix
+++ b/nixos/modules/services/networking/babeld.nix
@@ -40,13 +40,13 @@ in
 
     services.babeld = {
 
-      enable = mkEnableOption "the babeld network routing daemon";
+      enable = mkEnableOption (lib.mdDoc "the babeld network routing daemon");
 
       interfaceDefaults = mkOption {
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           A set describing default parameters for babeld interfaces.
-          See <citerefentry><refentrytitle>babeld</refentrytitle><manvolnum>8</manvolnum></citerefentry> for options.
+          See {manpage}`babeld(8)` for options.
         '';
         type = types.nullOr (types.attrsOf types.unspecified);
         example =
@@ -58,9 +58,9 @@ in
 
       interfaces = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           A set describing babeld interfaces.
-          See <citerefentry><refentrytitle>babeld</refentrytitle><manvolnum>8</manvolnum></citerefentry> for options.
+          See {manpage}`babeld(8)` for options.
         '';
         type = types.attrsOf (types.attrsOf types.unspecified);
         example =
@@ -75,9 +75,9 @@ in
       extraConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Options that will be copied to babeld.conf.
-          See <citerefentry><refentrytitle>babeld</refentrytitle><manvolnum>8</manvolnum></citerefentry> for details.
+          See {manpage}`babeld(8)` for details.
         '';
       };
     };
diff --git a/nixos/modules/services/networking/bee-clef.nix b/nixos/modules/services/networking/bee-clef.nix
index 719714b2898..75e76f019a7 100644
--- a/nixos/modules/services/networking/bee-clef.nix
+++ b/nixos/modules/services/networking/bee-clef.nix
@@ -14,12 +14,12 @@ in {
 
   options = {
     services.bee-clef = {
-      enable = mkEnableOption "clef external signer instance for Ethereum Swarm Bee";
+      enable = mkEnableOption (lib.mdDoc "clef external signer instance for Ethereum Swarm Bee");
 
       dataDir = mkOption {
         type = types.nullOr types.str;
         default = "/var/lib/bee-clef";
-        description = ''
+        description = lib.mdDoc ''
           Data dir for bee-clef. Beware that some helper scripts may not work when changed!
           The service itself should work fine, though.
         '';
@@ -28,13 +28,13 @@ in {
       passwordFile = mkOption {
         type = types.nullOr types.str;
         default = "/var/lib/bee-clef/password";
-        description = "Password file for bee-clef.";
+        description = lib.mdDoc "Password file for bee-clef.";
       };
 
       user = mkOption {
         type = types.str;
         default = "bee-clef";
-        description = ''
+        description = lib.mdDoc ''
           User the bee-clef daemon should execute under.
         '';
       };
@@ -42,7 +42,7 @@ in {
       group = mkOption {
         type = types.str;
         default = "bee-clef";
-        description = ''
+        description = lib.mdDoc ''
           Group the bee-clef daemon should execute under.
         '';
       };
diff --git a/nixos/modules/services/networking/bee.nix b/nixos/modules/services/networking/bee.nix
index d6efade0630..add9861ebfc 100644
--- a/nixos/modules/services/networking/bee.nix
+++ b/nixos/modules/services/networking/bee.nix
@@ -15,21 +15,21 @@ in {
 
   options = {
     services.bee = {
-      enable = mkEnableOption "Ethereum Swarm Bee";
+      enable = mkEnableOption (lib.mdDoc "Ethereum Swarm Bee");
 
       package = mkOption {
         type = types.package;
         default = pkgs.bee;
         defaultText = literalExpression "pkgs.bee";
         example = literalExpression "pkgs.bee-unstable";
-        description = "The package providing the bee binary for the service.";
+        description = lib.mdDoc "The package providing the bee binary for the service.";
       };
 
       settings = mkOption {
         type = format.type;
-        description = ''
+        description = lib.mdDoc ''
           Ethereum Swarm Bee configuration. Refer to
-          <link xlink:href="https://gateway.ethswarm.org/bzz/docs.swarm.eth/docs/installation/configuration/"/>
+          <https://gateway.ethswarm.org/bzz/docs.swarm.eth/docs/installation/configuration/>
           for details on supported values.
         '';
       };
@@ -37,7 +37,7 @@ in {
       daemonNiceLevel = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Daemon process priority for bee.
           0 is the default Unix process priority, 19 is the lowest.
         '';
@@ -46,7 +46,7 @@ in {
       user = mkOption {
         type = types.str;
         default = "bee";
-        description = ''
+        description = lib.mdDoc ''
           User the bee binary should execute under.
         '';
       };
@@ -54,7 +54,7 @@ in {
       group = mkOption {
         type = types.str;
         default = "bee";
-        description = ''
+        description = lib.mdDoc ''
           Group the bee binary should execute under.
         '';
       };
diff --git a/nixos/modules/services/networking/biboumi.nix b/nixos/modules/services/networking/biboumi.nix
index 3f46b95eaf0..896a2350e3d 100644
--- a/nixos/modules/services/networking/biboumi.nix
+++ b/nixos/modules/services/networking/biboumi.nix
@@ -16,11 +16,11 @@ in
 {
   options = {
     services.biboumi = {
-      enable = mkEnableOption "the Biboumi XMPP gateway to IRC";
+      enable = mkEnableOption (lib.mdDoc "the Biboumi XMPP gateway to IRC");
 
       settings = mkOption {
-        description = ''
-          See <link xlink:href="https://lab.louiz.org/louiz/biboumi/blob/8.5/doc/biboumi.1.rst">biboumi 8.5</link>
+        description = lib.mdDoc ''
+          See [biboumi 8.5](https://lab.louiz.org/louiz/biboumi/blob/8.5/doc/biboumi.1.rst)
           for documentation.
         '';
         default = {};
@@ -34,7 +34,7 @@ in
             default = [];
             example = ["admin@example.org"];
             apply = concatStringsSep ":";
-            description = ''
+            description = lib.mdDoc ''
               The bare JID of the gateway administrator. This JID will have more
               privileges than other standard users, for example some administration
               ad-hoc commands will only be available to that JID.
@@ -43,7 +43,7 @@ in
           options.ca_file = mkOption {
             type = types.path;
             default = "/etc/ssl/certs/ca-certificates.crt";
-            description = ''
+            description = lib.mdDoc ''
               Specifies which file should be used as the list of trusted CA
               when negociating a TLS session.
             '';
@@ -51,7 +51,7 @@ in
           options.db_name = mkOption {
             type = with types; either path str;
             default = "${stateDir}/biboumi.sqlite";
-            description = ''
+            description = lib.mdDoc ''
               The name of the database to use.
             '';
             example = "postgresql://user:secret@localhost";
@@ -59,7 +59,7 @@ in
           options.hostname = mkOption {
             type = types.str;
             example = "biboumi.example.org";
-            description = ''
+            description = lib.mdDoc ''
               The hostname served by the XMPP gateway.
               This domain must be configured in the XMPP server
               as an external component.
@@ -69,34 +69,34 @@ in
             type = types.port;
             default = 113;
             example = 0;
-            description = ''
+            description = lib.mdDoc ''
               The TCP port on which to listen for identd queries.
             '';
           };
           options.log_level = mkOption {
             type = types.ints.between 0 3;
             default = 1;
-            description = ''
+            description = lib.mdDoc ''
               Indicate what type of log messages to write in the logs.
               0 is debug, 1 is info, 2 is warning, 3 is error.
             '';
           };
           options.password = mkOption {
             type = with types; nullOr str;
-            description = ''
+            description = lib.mdDoc ''
               The password used to authenticate the XMPP component to your XMPP server.
               This password must be configured in the XMPP server,
               associated with the external component on
-              <link linkend="opt-services.biboumi.settings.hostname">hostname</link>.
+              [hostname](#opt-services.biboumi.settings.hostname).
 
-              Set it to null and use <link linkend="opt-services.biboumi.credentialsFile">credentialsFile</link>
+              Set it to null and use [credentialsFile](#opt-services.biboumi.credentialsFile)
               if you do not want this password to go into the Nix store.
             '';
           };
           options.persistent_by_default = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Whether all rooms will be persistent by default:
               the value of the “persistent” option in the global configuration of each
               user will be “true”, but the value of each individual room will still
@@ -108,7 +108,7 @@ in
             type = types.path;
             default = "${pkgs.biboumi}/etc/biboumi";
             defaultText = literalExpression ''"''${pkgs.biboumi}/etc/biboumi"'';
-            description = ''
+            description = lib.mdDoc ''
               A directory that should contain the policy files,
               used to customize Botan’s behaviour
               when negociating the TLS connections with the IRC servers.
@@ -117,14 +117,14 @@ in
           options.port = mkOption {
             type = types.port;
             default = 5347;
-            description = ''
+            description = lib.mdDoc ''
               The TCP port to use to connect to the local XMPP component.
             '';
           };
           options.realname_customization = mkOption {
             type = types.bool;
             default = true;
-            description = ''
+            description = lib.mdDoc ''
               Whether the users will be able to use
               the ad-hoc commands that lets them configure
               their realname and username.
@@ -133,7 +133,7 @@ in
           options.realname_from_jid = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Whether the realname and username of each biboumi
               user will be extracted from their JID.
               Otherwise they will be set to the nick
@@ -143,7 +143,7 @@ in
           options.xmpp_server_ip = mkOption {
             type = types.str;
             default = "127.0.0.1";
-            description = ''
+            description = lib.mdDoc ''
               The IP address to connect to the XMPP server on.
               The connection to the XMPP server is unencrypted,
               so the biboumi instance and the server should
@@ -155,18 +155,18 @@ in
 
       credentialsFile = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to a configuration file to be merged with the settings.
           Beware not to surround "=" with spaces when setting biboumi's options in this file.
           Useful to merge a file which is better kept out of the Nix store
           because it contains sensible data like
-          <link linkend="opt-services.biboumi.settings.password">password</link>.
+          [password](#opt-services.biboumi.settings.password).
         '';
         default = "/dev/null";
         example = "/run/keys/biboumi.cfg";
       };
 
-      openFirewall = mkEnableOption "opening of the identd port in the firewall";
+      openFirewall = mkEnableOption (lib.mdDoc "opening of the identd port in the firewall");
     };
   };
 
diff --git a/nixos/modules/services/networking/bind.nix b/nixos/modules/services/networking/bind.nix
index 2045612ec05..f963e341546 100644
--- a/nixos/modules/services/networking/bind.nix
+++ b/nixos/modules/services/networking/bind.nix
@@ -17,28 +17,28 @@ let
       name = mkOption {
         type = types.str;
         default = name;
-        description = "Name of the zone.";
+        description = lib.mdDoc "Name of the zone.";
       };
       master = mkOption {
-        description = "Master=false means slave server";
+        description = lib.mdDoc "Master=false means slave server";
         type = types.bool;
       };
       file = mkOption {
         type = types.either types.str types.path;
-        description = "Zone file resource records contain columns of data, separated by whitespace, that define the record.";
+        description = lib.mdDoc "Zone file resource records contain columns of data, separated by whitespace, that define the record.";
       };
       masters = mkOption {
         type = types.listOf types.str;
-        description = "List of servers for inclusion in stub and secondary zones.";
+        description = lib.mdDoc "List of servers for inclusion in stub and secondary zones.";
       };
       slaves = mkOption {
         type = types.listOf types.str;
-        description = "Addresses who may request zone transfers.";
+        description = lib.mdDoc "Addresses who may request zone transfers.";
         default = [ ];
       };
       extraConfig = mkOption {
         type = types.str;
-        description = "Extra zone config to be appended at the end of the zone section.";
+        description = lib.mdDoc "Extra zone config to be appended at the end of the zone section.";
         default = "";
       };
     };
@@ -104,89 +104,89 @@ in
 
     services.bind = {
 
-      enable = mkEnableOption "BIND domain name server";
+      enable = mkEnableOption (lib.mdDoc "BIND domain name server");
 
 
       package = mkOption {
         type = types.package;
         default = pkgs.bind;
         defaultText = literalExpression "pkgs.bind";
-        description = "The BIND package to use.";
+        description = lib.mdDoc "The BIND package to use.";
       };
 
       cacheNetworks = mkOption {
         default = [ "127.0.0.0/24" ];
         type = types.listOf types.str;
-        description = "
+        description = lib.mdDoc ''
           What networks are allowed to use us as a resolver.  Note
           that this is for recursive queries -- all networks are
           allowed to query zones configured with the `zones` option.
           It is recommended that you limit cacheNetworks to avoid your
           server being used for DNS amplification attacks.
-        ";
+        '';
       };
 
       blockedNetworks = mkOption {
         default = [ ];
         type = types.listOf types.str;
-        description = "
+        description = lib.mdDoc ''
           What networks are just blocked.
-        ";
+        '';
       };
 
       ipv4Only = mkOption {
         default = false;
         type = types.bool;
-        description = "
+        description = lib.mdDoc ''
           Only use ipv4, even if the host supports ipv6.
-        ";
+        '';
       };
 
       forwarders = mkOption {
         default = config.networking.nameservers;
         defaultText = literalExpression "config.networking.nameservers";
         type = types.listOf types.str;
-        description = "
+        description = lib.mdDoc ''
           List of servers we should forward requests to.
-        ";
+        '';
       };
 
       forward = mkOption {
         default = "first";
         type = types.enum ["first" "only"];
-        description = "
+        description = lib.mdDoc ''
           Whether to forward 'first' (try forwarding but lookup directly if forwarding fails) or 'only'.
-        ";
+        '';
       };
 
       listenOn = mkOption {
         default = [ "any" ];
         type = types.listOf types.str;
-        description = "
+        description = lib.mdDoc ''
           Interfaces to listen on.
-        ";
+        '';
       };
 
       listenOnIpv6 = mkOption {
         default = [ "any" ];
         type = types.listOf types.str;
-        description = "
+        description = lib.mdDoc ''
           Ipv6 interfaces to listen on.
-        ";
+        '';
       };
 
       directory = mkOption {
         type = types.str;
         default = "/run/named";
-        description = "Working directory of BIND.";
+        description = lib.mdDoc "Working directory of BIND.";
       };
 
       zones = mkOption {
         default = [ ];
         type = with types; coercedTo (listOf attrs) bindZoneCoerce (attrsOf (types.submodule bindZoneOptions));
-        description = "
+        description = lib.mdDoc ''
           List of zones we claim authority over.
-        ";
+        '';
         example = {
           "example.com" = {
             master = false;
@@ -201,15 +201,15 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to the generated named configuration file.
-        ";
+        '';
       };
 
       extraOptions = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to the options section of the
           generated named configuration file.
         '';
@@ -219,10 +219,10 @@ in
         type = types.path;
         default = confFile;
         defaultText = literalExpression "confFile";
-        description = "
+        description = lib.mdDoc ''
           Overridable config file to use for named. By default, that
           generated by nixos.
-        ";
+        '';
       };
 
     };
diff --git a/nixos/modules/services/networking/bird-lg.nix b/nixos/modules/services/networking/bird-lg.nix
new file mode 100644
index 00000000000..11cfe3e7ec0
--- /dev/null
+++ b/nixos/modules/services/networking/bird-lg.nix
@@ -0,0 +1,269 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.bird-lg;
+in
+{
+  options = {
+    services.bird-lg = {
+      package = mkOption {
+        type = types.package;
+        default = pkgs.bird-lg;
+        defaultText = literalExpression "pkgs.bird-lg";
+        description = lib.mdDoc "The Bird Looking Glass package to use.";
+      };
+
+      user = mkOption {
+        type = types.str;
+        default = "bird-lg";
+        description = lib.mdDoc "User to run the service.";
+      };
+
+      group = mkOption {
+        type = types.str;
+        default = "bird-lg";
+        description = lib.mdDoc "Group to run the service.";
+      };
+
+      frontend = {
+        enable = mkEnableOption (lib.mdDoc "Bird Looking Glass Frontend Webserver");
+
+        listenAddress = mkOption {
+          type = types.str;
+          default = "127.0.0.1:5000";
+          description = lib.mdDoc "Address to listen on.";
+        };
+
+        proxyPort = mkOption {
+          type = types.port;
+          default = 8000;
+          description = lib.mdDoc "Port bird-lg-proxy is running on.";
+        };
+
+        domain = mkOption {
+          type = types.str;
+          default = "";
+          example = "dn42.lantian.pub";
+          description = lib.mdDoc "Server name domain suffixes.";
+        };
+
+        servers = mkOption {
+          type = types.listOf types.str;
+          default = [ ];
+          example = [ "gigsgigscloud" "hostdare" ];
+          description = lib.mdDoc "Server name prefixes.";
+        };
+
+        whois = mkOption {
+          type = types.str;
+          default = "whois.verisign-grs.com";
+          description = lib.mdDoc "Whois server for queries.";
+        };
+
+        dnsInterface = mkOption {
+          type = types.str;
+          default = "asn.cymru.com";
+          description = lib.mdDoc "DNS zone to query ASN information.";
+        };
+
+        bgpMapInfo = mkOption {
+          type = types.listOf types.str;
+          default = [ "asn" "as-name" "ASName" "descr" ];
+          description = lib.mdDoc "Information displayed in bgpmap.";
+        };
+
+        titleBrand = mkOption {
+          type = types.str;
+          default = "Bird-lg Go";
+          description = lib.mdDoc "Prefix of page titles in browser tabs.";
+        };
+
+        netSpecificMode = mkOption {
+          type = types.str;
+          default = "";
+          example = "dn42";
+          description = lib.mdDoc "Apply network-specific changes for some networks.";
+        };
+
+        protocolFilter = mkOption {
+          type = types.listOf types.str;
+          default = [ ];
+          example = [ "ospf" ];
+          description = lib.mdDoc "Information displayed in bgpmap.";
+        };
+
+        nameFilter = mkOption {
+          type = types.str;
+          default = "";
+          example = "^ospf";
+          description = lib.mdDoc "Protocol names to hide in summary tables (RE2 syntax),";
+        };
+
+        timeout = mkOption {
+          type = types.int;
+          default = 120;
+          description = lib.mdDoc "Time before request timed out, in seconds.";
+        };
+
+        navbar = {
+          brand = mkOption {
+            type = types.str;
+            default = "Bird-lg Go";
+            description = lib.mdDoc "Brand to show in the navigation bar .";
+          };
+
+          brandURL = mkOption {
+            type = types.str;
+            default = "/";
+            description = lib.mdDoc "URL of the brand to show in the navigation bar.";
+          };
+
+          allServers = mkOption {
+            type = types.str;
+            default = "ALL Servers";
+            description = lib.mdDoc "Text of 'All server' button in the navigation bar.";
+          };
+
+          allServersURL = mkOption {
+            type = types.str;
+            default = "all";
+            description = lib.mdDoc "URL of 'All servers' button.";
+          };
+        };
+
+        extraArgs = mkOption {
+          type = types.lines;
+          default = "";
+          description = lib.mdDoc ''
+            Extra parameters documented [here](https://github.com/xddxdd/bird-lg-go#frontend).
+          '';
+        };
+      };
+
+      proxy = {
+        enable = mkEnableOption (lib.mdDoc "Bird Looking Glass Proxy");
+
+        listenAddress = mkOption {
+          type = types.str;
+          default = "127.0.0.1:8000";
+          description = lib.mdDoc "Address to listen on.";
+        };
+
+        allowedIPs = mkOption {
+          type = types.listOf types.str;
+          default = [ ];
+          example = [ "192.168.25.52" "192.168.25.53" ];
+          description = lib.mdDoc "List of IPs to allow (default all allowed).";
+        };
+
+        birdSocket = mkOption {
+          type = types.str;
+          default = "/run/bird.ctl";
+          example = "/var/run/bird/bird.ctl";
+          description = lib.mdDoc "Bird control socket path.";
+        };
+
+        traceroute = {
+          binary = mkOption {
+            type = types.str;
+            default = "${pkgs.traceroute}/bin/traceroute";
+            defaultText = literalExpression ''"''${pkgs.traceroute}/bin/traceroute"'';
+            description = lib.mdDoc "Traceroute's binary path.";
+          };
+
+          rawOutput = mkOption {
+            type = types.bool;
+            default = false;
+            description = lib.mdDoc "Display traceroute output in raw format.";
+          };
+        };
+
+        extraArgs = mkOption {
+          type = types.lines;
+          default = "";
+          description = lib.mdDoc ''
+            Extra parameters documented [here](https://github.com/xddxdd/bird-lg-go#proxy).
+          '';
+        };
+      };
+    };
+  };
+
+  ###### implementation
+
+  config = {
+    systemd.services = {
+      bird-lg-frontend = mkIf cfg.frontend.enable {
+        enable = true;
+        after = [ "network.target" ];
+        wantedBy = [ "multi-user.target" ];
+        description = "Bird Looking Glass Frontend Webserver";
+        serviceConfig = {
+          Type = "simple";
+          Restart = "on-failure";
+          ProtectSystem = "full";
+          ProtectHome = "yes";
+          MemoryDenyWriteExecute = "yes";
+          User = cfg.user;
+          Group = cfg.group;
+        };
+        script = ''
+          ${cfg.package}/bin/frontend \
+            --servers ${concatStringsSep "," cfg.frontend.servers } \
+            --domain ${cfg.frontend.domain} \
+            --listen ${cfg.frontend.listenAddress} \
+            --proxy-port ${toString cfg.frontend.proxyPort} \
+            --whois ${cfg.frontend.whois} \
+            --dns-interface ${cfg.frontend.dnsInterface} \
+            --bgpmap-info ${concatStringsSep "," cfg.frontend.bgpMapInfo } \
+            --title-brand ${cfg.frontend.titleBrand} \
+            --navbar-brand ${cfg.frontend.navbar.brand} \
+            --navbar-brand-url ${cfg.frontend.navbar.brandURL} \
+            --navbar-all-servers ${cfg.frontend.navbar.allServers} \
+            --navbar-all-url ${cfg.frontend.navbar.allServersURL} \
+            --net-specific-mode ${cfg.frontend.netSpecificMode} \
+            --protocol-filter ${concatStringsSep "," cfg.frontend.protocolFilter } \
+            --name-filter ${cfg.frontend.nameFilter} \
+            --time-out ${toString cfg.frontend.timeout} \
+            ${cfg.frontend.extraArgs}
+        '';
+      };
+
+      bird-lg-proxy = mkIf cfg.proxy.enable {
+        enable = true;
+        after = [ "network.target" ];
+        wantedBy = [ "multi-user.target" ];
+        description = "Bird Looking Glass Proxy";
+        serviceConfig = {
+          Type = "simple";
+          Restart = "on-failure";
+          ProtectSystem = "full";
+          ProtectHome = "yes";
+          MemoryDenyWriteExecute = "yes";
+          User = cfg.user;
+          Group = cfg.group;
+        };
+        script = ''
+          ${cfg.package}/bin/proxy \
+          --allowed ${concatStringsSep "," cfg.proxy.allowedIPs } \
+          --bird ${cfg.proxy.birdSocket} \
+          --listen ${cfg.proxy.listenAddress} \
+          --traceroute_bin ${cfg.proxy.traceroute.binary}
+          --traceroute_raw ${boolToString cfg.proxy.traceroute.rawOutput}
+          ${cfg.proxy.extraArgs}
+        '';
+      };
+    };
+    users = mkIf (cfg.frontend.enable || cfg.proxy.enable) {
+      groups."bird-lg" = mkIf (cfg.group == "bird-lg") { };
+      users."bird-lg" = mkIf (cfg.user == "bird-lg") {
+        description = "Bird Looking Glass user";
+        extraGroups = lib.optionals (config.services.bird2.enable) [ "bird2" ];
+        group = cfg.group;
+        isSystemUser = true;
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/networking/bird.nix b/nixos/modules/services/networking/bird.nix
index 3049c4f2bce..77e0b3f8af9 100644
--- a/nixos/modules/services/networking/bird.nix
+++ b/nixos/modules/services/networking/bird.nix
@@ -10,21 +10,21 @@ in
   ###### interface
   options = {
     services.bird2 = {
-      enable = mkEnableOption "BIRD Internet Routing Daemon";
+      enable = mkEnableOption (lib.mdDoc "BIRD Internet Routing Daemon");
       config = mkOption {
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           BIRD Internet Routing Daemon configuration file.
-          <link xlink:href='http://bird.network.cz/'/>
+          <http://bird.network.cz/>
         '';
       };
       checkConfig = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether the config should be checked at build time.
           When the config can't be checked during build time, for example when it includes
-          other files, either disable this option or use <code>preCheckConfig</code> to create
+          other files, either disable this option or use `preCheckConfig` to create
           the included files before checking.
         '';
       };
@@ -34,9 +34,9 @@ in
         example = ''
           echo "cost 100;" > include.conf
         '';
-        description = ''
+        description = lib.mdDoc ''
           Commands to execute before the config file check. The file to be checked will be
-          available as <code>bird2.conf</code> in the current directory.
+          available as `bird2.conf` in the current directory.
 
           Files created with this option will not be available at service runtime, only during
           build time checking.
@@ -68,8 +68,7 @@ in
     systemd.services.bird2 = {
       description = "BIRD Internet Routing Daemon";
       wantedBy = [ "multi-user.target" ];
-      reloadIfChanged = true;
-      restartTriggers = [ config.environment.etc."bird/bird2.conf".source ];
+      reloadTriggers = [ config.environment.etc."bird/bird2.conf".source ];
       serviceConfig = {
         Type = "forking";
         Restart = "on-failure";
diff --git a/nixos/modules/services/networking/bitcoind.nix b/nixos/modules/services/networking/bitcoind.nix
index 80033d95860..6df809a8b76 100644
--- a/nixos/modules/services/networking/bitcoind.nix
+++ b/nixos/modules/services/networking/bitcoind.nix
@@ -11,19 +11,19 @@ let
       name = mkOption {
         type = types.str;
         example = "alice";
-        description = ''
+        description = lib.mdDoc ''
           Username for JSON-RPC connections.
         '';
       };
       passwordHMAC = mkOption {
         type = types.uniq (types.strMatching "[0-9a-f]+\\$[0-9a-f]{64}");
         example = "f7efda5c189b999524f151318c0c86$d5b51b3beffbc02b724e5d095828e0bc8b2456e9ac8757ae3211a5d9b16a22ae";
-        description = ''
+        description = lib.mdDoc ''
           Password HMAC-SHA-256 for JSON-RPC connections. Must be a string of the
-          format &lt;SALT-HEX&gt;$&lt;HMAC-HEX&gt;.
+          format \<SALT-HEX\>$\<HMAC-HEX\>.
 
           Tool (Python script) for HMAC generation is available here:
-          <link xlink:href="https://github.com/bitcoin/bitcoin/blob/master/share/rpcauth/rpcauth.py"/>
+          <https://github.com/bitcoin/bitcoin/blob/master/share/rpcauth/rpcauth.py>
         '';
       };
     };
@@ -35,20 +35,20 @@ let
   bitcoindOpts = { config, lib, name, ...}: {
     options = {
 
-      enable = mkEnableOption "Bitcoin daemon";
+      enable = mkEnableOption (lib.mdDoc "Bitcoin daemon");
 
       package = mkOption {
         type = types.package;
         default = pkgs.bitcoind;
         defaultText = literalExpression "pkgs.bitcoind";
-        description = "The package providing bitcoin binaries.";
+        description = lib.mdDoc "The package providing bitcoin binaries.";
       };
 
       configFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/var/lib/${name}/bitcoin.conf";
-        description = "The configuration file path to supply bitcoind.";
+        description = lib.mdDoc "The configuration file path to supply bitcoind.";
       };
 
       extraConfig = mkOption {
@@ -59,32 +59,32 @@ let
           rpcthreads=16
           logips=1
         '';
-        description = "Additional configurations to be appended to <filename>bitcoin.conf</filename>.";
+        description = lib.mdDoc "Additional configurations to be appended to {file}`bitcoin.conf`.";
       };
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/bitcoind-${name}";
-        description = "The data directory for bitcoind.";
+        description = lib.mdDoc "The data directory for bitcoind.";
       };
 
       user = mkOption {
         type = types.str;
         default = "bitcoind-${name}";
-        description = "The user as which to run bitcoind.";
+        description = lib.mdDoc "The user as which to run bitcoind.";
       };
 
       group = mkOption {
         type = types.str;
         default = config.user;
-        description = "The group as which to run bitcoind.";
+        description = lib.mdDoc "The group as which to run bitcoind.";
       };
 
       rpc = {
         port = mkOption {
           type = types.nullOr types.port;
           default = null;
-          description = "Override the default port on which to listen for JSON-RPC connections.";
+          description = lib.mdDoc "Override the default port on which to listen for JSON-RPC connections.";
         };
         users = mkOption {
           default = {};
@@ -95,33 +95,33 @@ let
             }
           '';
           type = types.attrsOf (types.submodule rpcUserOpts);
-          description = "RPC user information for JSON-RPC connnections.";
+          description = lib.mdDoc "RPC user information for JSON-RPC connnections.";
         };
       };
 
       pidFile = mkOption {
         type = types.path;
         default = "${config.dataDir}/bitcoind.pid";
-        description = "Location of bitcoind pid file.";
+        description = lib.mdDoc "Location of bitcoind pid file.";
       };
 
       testnet = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to use the testnet instead of mainnet.";
+        description = lib.mdDoc "Whether to use the testnet instead of mainnet.";
       };
 
       port = mkOption {
         type = types.nullOr types.port;
         default = null;
-        description = "Override the default port on which to listen for connections.";
+        description = lib.mdDoc "Override the default port on which to listen for connections.";
       };
 
       dbCache = mkOption {
         type = types.nullOr (types.ints.between 4 16384);
         default = null;
         example = 4000;
-        description = "Override the default database cache size in MiB.";
+        description = lib.mdDoc "Override the default database cache size in MiB.";
       };
 
       prune = mkOption {
@@ -132,7 +132,7 @@ let
         );
         default = null;
         example = 10000;
-        description = ''
+        description = lib.mdDoc ''
           Reduce storage requirements by enabling pruning (deleting) of old
           blocks. This allows the pruneblockchain RPC to be called to delete
           specific blocks, and enables automatic pruning of old blocks if a
@@ -147,7 +147,7 @@ let
       extraCmdlineOptions = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Extra command line options to pass to bitcoind.
           Run bitcoind --help to list all available options.
         '';
@@ -161,7 +161,7 @@ in
     services.bitcoind = mkOption {
       type = types.attrsOf (types.submodule bitcoindOpts);
       default = {};
-      description = "Specification of one or more bitcoind instances.";
+      description = lib.mdDoc "Specification of one or more bitcoind instances.";
     };
   };
 
@@ -204,7 +204,7 @@ in
         '';
       in {
         description = "Bitcoin daemon";
-        after = [ "network.target" ];
+        after = [ "network-online.target" ];
         wantedBy = [ "multi-user.target" ];
         serviceConfig = {
           User = cfg.user;
diff --git a/nixos/modules/services/networking/bitlbee.nix b/nixos/modules/services/networking/bitlbee.nix
index 8bf04e3a1a2..88c04597e2b 100644
--- a/nixos/modules/services/networking/bitlbee.nix
+++ b/nixos/modules/services/networking/bitlbee.nix
@@ -49,7 +49,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run the BitlBee IRC to other chat network gateway.
           Running it allows you to access the MSN, Jabber, Yahoo! and ICQ chat
           networks via an IRC client.
@@ -59,17 +59,17 @@ in
       interface = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = ''
-          The interface the BitlBee deamon will be listening to.  If `127.0.0.1',
-          only clients on the local host can connect to it; if `0.0.0.0', clients
+        description = lib.mdDoc ''
+          The interface the BitlBee deamon will be listening to.  If `127.0.0.1`,
+          only clients on the local host can connect to it; if `0.0.0.0`, clients
           can access it from any network interface.
         '';
       };
 
       portNumber = mkOption {
         default = 6667;
-        type = types.int;
-        description = ''
+        type = types.port;
+        description = lib.mdDoc ''
           Number of the port BitlBee will be listening to.
         '';
       };
@@ -77,7 +77,7 @@ in
       authBackend = mkOption {
         default = "storage";
         type = types.enum [ "storage" "pam" ];
-        description = ''
+        description = lib.mdDoc ''
           How users are authenticated
             storage -- save passwords internally
             pam -- Linux PAM authentication
@@ -87,7 +87,7 @@ in
       authMode = mkOption {
         default = "Open";
         type = types.enum [ "Open" "Closed" "Registered" ];
-        description = ''
+        description = lib.mdDoc ''
           The following authentication modes are available:
             Open -- Accept connections from anyone, use NickServ for user authentication.
             Closed -- Require authorization (using the PASS command during login) before allowing the user to connect at all.
@@ -98,7 +98,7 @@ in
       hostName = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Normally, BitlBee gets a hostname using getsockname(). If you have a nicer
           alias for your BitlBee daemon, you can set it here and BitlBee will identify
           itself with that name instead.
@@ -109,7 +109,7 @@ in
         type = types.listOf types.package;
         default = [];
         example = literalExpression "[ pkgs.bitlbee-facebook ]";
-        description = ''
+        description = lib.mdDoc ''
           The list of bitlbee plugins to install.
         '';
       };
@@ -118,7 +118,7 @@ in
         type = types.listOf types.package;
         default = [];
         example = literalExpression "[ pkgs.purple-matrix ]";
-        description = ''
+        description = lib.mdDoc ''
           The list of libpurple plugins to install.
         '';
       };
@@ -126,7 +126,7 @@ in
       configDir = mkOption {
         default = "/var/lib/bitlbee";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Specify an alternative directory to store all the per-user configuration
           files.
         '';
@@ -135,7 +135,7 @@ in
       protocols = mkOption {
         default = "";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           This option allows to remove the support of protocol, even if compiled
           in. If nothing is given, there are no restrictions.
         '';
@@ -144,7 +144,7 @@ in
       extraSettings = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Will be inserted in the Settings section of the config file.
         '';
       };
@@ -152,7 +152,7 @@ in
       extraDefaults = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Will be inserted in the Default section of the config file.
         '';
       };
@@ -174,6 +174,7 @@ in
         serviceConfig = {
           DynamicUser = true;
           StateDirectory = "bitlbee";
+          ReadWritePaths = [ cfg.configDir ];
           ExecStart = "${bitlbeePkg}/sbin/bitlbee -F -n -c ${bitlbeeConfig}";
         };
       };
diff --git a/nixos/modules/services/networking/blockbook-frontend.nix b/nixos/modules/services/networking/blockbook-frontend.nix
index eeea521c8d5..ab784563e4a 100644
--- a/nixos/modules/services/networking/blockbook-frontend.nix
+++ b/nixos/modules/services/networking/blockbook-frontend.nix
@@ -10,34 +10,34 @@ let
 
     options = {
 
-      enable = mkEnableOption "blockbook-frontend application.";
+      enable = mkEnableOption (lib.mdDoc "blockbook-frontend application.");
 
       package = mkOption {
         type = types.package;
         default = pkgs.blockbook;
         defaultText = literalExpression "pkgs.blockbook";
-        description = "Which blockbook package to use.";
+        description = lib.mdDoc "Which blockbook package to use.";
       };
 
       user = mkOption {
         type = types.str;
         default = "blockbook-frontend-${name}";
-        description = "The user as which to run blockbook-frontend-${name}.";
+        description = lib.mdDoc "The user as which to run blockbook-frontend-${name}.";
       };
 
       group = mkOption {
         type = types.str;
         default = "${config.user}";
-        description = "The group as which to run blockbook-frontend-${name}.";
+        description = lib.mdDoc "The group as which to run blockbook-frontend-${name}.";
       };
 
       certFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/etc/secrets/blockbook-frontend-${name}/certFile";
-        description = ''
+        description = lib.mdDoc ''
           To enable SSL, specify path to the name of certificate files without extension.
-          Expecting <filename>certFile.crt</filename> and <filename>certFile.key</filename>.
+          Expecting {file}`certFile.crt` and {file}`certFile.key`.
         '';
       };
 
@@ -45,14 +45,14 @@ let
         type = with types; nullOr path;
         default = null;
         example = "${config.dataDir}/config.json";
-        description = "Location of the blockbook configuration file.";
+        description = lib.mdDoc "Location of the blockbook configuration file.";
       };
 
       coinName = mkOption {
         type = types.str;
         default = "Bitcoin";
-        description = ''
-          See <link xlink:href="https://github.com/trezor/blockbook/blob/master/bchain/coins/blockchain.go#L61"/>
+        description = lib.mdDoc ''
+          See <https://github.com/trezor/blockbook/blob/master/bchain/coins/blockchain.go#L61>
           for current of coins supported in master (Note: may differ from release).
         '';
       };
@@ -62,8 +62,8 @@ let
         default = "${config.package}/share/css/";
         defaultText = literalExpression ''"''${package}/share/css/"'';
         example = literalExpression ''"''${dataDir}/static/css/"'';
-        description = ''
-          Location of the dir with <filename>main.css</filename> CSS file.
+        description = lib.mdDoc ''
+          Location of the dir with {file}`main.css` CSS file.
           By default, the one shipped with the package is used.
         '';
       };
@@ -71,68 +71,68 @@ let
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/blockbook-frontend-${name}";
-        description = "Location of blockbook-frontend-${name} data directory.";
+        description = lib.mdDoc "Location of blockbook-frontend-${name} data directory.";
       };
 
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = "Debug mode, return more verbose errors, reload templates on each request.";
+        description = lib.mdDoc "Debug mode, return more verbose errors, reload templates on each request.";
       };
 
       internal = mkOption {
         type = types.nullOr types.str;
         default = ":9030";
-        description = "Internal http server binding <literal>[address]:port</literal>.";
+        description = lib.mdDoc "Internal http server binding `[address]:port`.";
       };
 
       messageQueueBinding = mkOption {
         type = types.str;
         default = "tcp://127.0.0.1:38330";
-        description = "Message Queue Binding <literal>address:port</literal>.";
+        description = lib.mdDoc "Message Queue Binding `address:port`.";
       };
 
       public = mkOption {
         type = types.nullOr types.str;
         default = ":9130";
-        description = "Public http server binding <literal>[address]:port</literal>.";
+        description = lib.mdDoc "Public http server binding `[address]:port`.";
       };
 
       rpc = {
         url = mkOption {
           type = types.str;
           default = "http://127.0.0.1";
-          description = "URL for JSON-RPC connections.";
+          description = lib.mdDoc "URL for JSON-RPC connections.";
         };
 
         port = mkOption {
           type = types.port;
           default = 8030;
-          description = "Port for JSON-RPC connections.";
+          description = lib.mdDoc "Port for JSON-RPC connections.";
         };
 
         user = mkOption {
           type = types.str;
           default = "rpc";
-          description = "Username for JSON-RPC connections.";
+          description = lib.mdDoc "Username for JSON-RPC connections.";
         };
 
         password = mkOption {
           type = types.str;
           default = "rpc";
-          description = ''
+          description = lib.mdDoc ''
             RPC password for JSON-RPC connections.
             Warning: this is stored in cleartext in the Nix store!!!
-            Use <literal>configFile</literal> or <literal>passwordFile</literal> if needed.
+            Use `configFile` or `passwordFile` if needed.
           '';
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             File containing password of the RPC user.
-            Note: This options is ignored when <literal>configFile</literal> is used.
+            Note: This options is ignored when `configFile` is used.
           '';
         };
       };
@@ -140,7 +140,7 @@ let
       sync = mkOption {
         type = types.bool;
         default = true;
-        description = "Synchronizes until tip, if together with zeromq, keeps index synchronized.";
+        description = lib.mdDoc "Synchronizes until tip, if together with zeromq, keeps index synchronized.";
       };
 
       templateDir = mkOption {
@@ -148,7 +148,7 @@ let
         default = "${config.package}/share/templates/";
         defaultText = literalExpression ''"''${package}/share/templates/"'';
         example = literalExpression ''"''${dataDir}/templates/static/"'';
-        description = "Location of the HTML templates. By default, ones shipped with the package are used.";
+        description = lib.mdDoc "Location of the HTML templates. By default, ones shipped with the package are used.";
       };
 
       extraConfig = mkOption {
@@ -171,10 +171,10 @@ let
           "mempool_sub_workers" = 2;
           "block_addresses_to_keep" = 300;
         }'';
-        description = ''
-          Additional configurations to be appended to <filename>coin.conf</filename>.
+        description = lib.mdDoc ''
+          Additional configurations to be appended to {file}`coin.conf`.
           Overrides any already defined configuration options.
-          See <link xlink:href="https://github.com/trezor/blockbook/tree/master/configs/coins"/>
+          See <https://github.com/trezor/blockbook/tree/master/configs/coins>
           for current configuration options supported in master (Note: may differ from release).
         '';
       };
@@ -183,7 +183,7 @@ let
         type = types.listOf types.str;
         default = [];
         example = [ "-workers=1" "-dbcache=0" "-logtosderr" ];
-        description = ''
+        description = lib.mdDoc ''
           Extra command line options to pass to Blockbook.
           Run blockbook --help to list all available options.
         '';
@@ -198,7 +198,7 @@ in
     services.blockbook-frontend = mkOption {
       type = types.attrsOf (types.submodule blockbookOpts);
       default = {};
-      description = "Specification of one or more blockbook-frontend instances.";
+      description = lib.mdDoc "Specification of one or more blockbook-frontend instances.";
     };
   };
 
diff --git a/nixos/modules/services/networking/blocky.nix b/nixos/modules/services/networking/blocky.nix
index 7488e05fc03..97144854561 100644
--- a/nixos/modules/services/networking/blocky.nix
+++ b/nixos/modules/services/networking/blocky.nix
@@ -10,14 +10,14 @@ let
 in
 {
   options.services.blocky = {
-    enable = mkEnableOption "Fast and lightweight DNS proxy as ad-blocker for local network with many features";
+    enable = mkEnableOption (lib.mdDoc "blocky, a fast and lightweight DNS proxy as ad-blocker for local network with many features");
 
     settings = mkOption {
       type = format.type;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Blocky configuration. Refer to
-        <link xlink:href="https://0xerr0r.github.io/blocky/configuration/"/>
+        <https://0xerr0r.github.io/blocky/configuration/>
         for details on supported values.
       '';
     };
diff --git a/nixos/modules/services/networking/charybdis.nix b/nixos/modules/services/networking/charybdis.nix
index ff09c0160cb..168da243dba 100644
--- a/nixos/modules/services/networking/charybdis.nix
+++ b/nixos/modules/services/networking/charybdis.nix
@@ -18,11 +18,11 @@ in
 
     services.charybdis = {
 
-      enable = mkEnableOption "Charybdis IRC daemon";
+      enable = mkEnableOption (lib.mdDoc "Charybdis IRC daemon");
 
       config = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Charybdis IRC daemon configuration file.
         '';
       };
@@ -30,7 +30,7 @@ in
       statedir = mkOption {
         type = types.path;
         default = "/var/lib/charybdis";
-        description = ''
+        description = lib.mdDoc ''
           Location of the state directory of charybdis.
         '';
       };
@@ -38,7 +38,7 @@ in
       user = mkOption {
         type = types.str;
         default = "ircd";
-        description = ''
+        description = lib.mdDoc ''
           Charybdis IRC daemon user.
         '';
       };
@@ -46,7 +46,7 @@ in
       group = mkOption {
         type = types.str;
         default = "ircd";
-        description = ''
+        description = lib.mdDoc ''
           Charybdis IRC daemon group.
         '';
       };
@@ -54,7 +54,7 @@ in
       motd = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Charybdis MOTD text.
 
           Charybdis will read its MOTD from /etc/charybdis/ircd.motd .
diff --git a/nixos/modules/services/networking/chisel-server.nix b/nixos/modules/services/networking/chisel-server.nix
new file mode 100644
index 00000000000..134c71430cd
--- /dev/null
+++ b/nixos/modules/services/networking/chisel-server.nix
@@ -0,0 +1,99 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.chisel-server;
+
+in {
+  options = {
+    services.chisel-server = {
+      enable = mkEnableOption (mdDoc "Chisel Tunnel Server");
+      host = mkOption {
+        description = mdDoc "Address to listen on, falls back to 0.0.0.0";
+        type = with types; nullOr str;
+        default = null;
+        example = "[::1]";
+      };
+      port = mkOption {
+        description = mdDoc "Port to listen on, falls back to 8080";
+        type = with types; nullOr port;
+        default = null;
+      };
+      authfile = mkOption {
+        description = mdDoc "Path to auth.json file";
+        type = with types; nullOr path;
+        default = null;
+      };
+      keepalive  = mkOption {
+        description = mdDoc "Keepalive interval, falls back to 25s";
+        type = with types; nullOr str;
+        default = null;
+        example = "5s";
+      };
+      backend = mkOption {
+        description = mdDoc "HTTP server to proxy normal requests to";
+        type = with types; nullOr str;
+        default = null;
+        example = "http://127.0.0.1:8888";
+      };
+      socks5 = mkOption {
+        description = mdDoc "Allow clients access to internal SOCKS5 proxy";
+        type = types.bool;
+        default = false;
+      };
+      reverse = mkOption {
+        description = mdDoc "Allow clients reverse port forwarding";
+        type = types.bool;
+        default = false;
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.chisel-server = {
+      description = "Chisel Tunnel Server";
+      wantedBy = [ "network-online.target" ];
+
+      serviceConfig = {
+        ExecStart = "${pkgs.chisel}/bin/chisel server " + concatStringsSep " " (
+          optional (cfg.host != null) "--host ${cfg.host}"
+          ++ optional (cfg.port != null) "--port ${builtins.toString cfg.port}"
+          ++ optional (cfg.authfile != null) "--authfile ${cfg.authfile}"
+          ++ optional (cfg.keepalive != null) "--keepalive ${cfg.keepalive}"
+          ++ optional (cfg.backend != null) "--backend ${cfg.backend}"
+          ++ optional cfg.socks5 "--socks5"
+          ++ optional cfg.reverse "--reverse"
+        );
+
+        # Security Hardening
+        # Refer to systemd.exec(5) for option descriptions.
+        CapabilityBoundingSet = "";
+
+        # implies RemoveIPC=, PrivateTmp=, NoNewPrivileges=, RestrictSUIDSGID=,
+        # ProtectSystem=strict, ProtectHome=read-only
+        DynamicUser = true;
+        LockPersonality = true;
+        PrivateDevices = true;
+        PrivateUsers = true;
+        ProcSubset = "pid";
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectProc = "invisible";
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        SystemCallArchitectures = "native";
+        SystemCallFilter = "~@clock @cpu-emulation @debug @mount @obsolete @reboot @swap @privileged @resources";
+        UMask = "0077";
+      };
+    };
+  };
+
+  meta.maintainers = with maintainers; [ clerie ];
+}
diff --git a/nixos/modules/services/networking/cjdns.nix b/nixos/modules/services/networking/cjdns.nix
index 0d97d379e90..5a19475161f 100644
--- a/nixos/modules/services/networking/cjdns.nix
+++ b/nixos/modules/services/networking/cjdns.nix
@@ -13,27 +13,27 @@ let
   { options =
     { password = mkOption {
         type = types.str;
-        description = "Authorized password to the opposite end of the tunnel.";
+        description = lib.mdDoc "Authorized password to the opposite end of the tunnel.";
       };
       login = mkOption {
         default = "";
         type = types.str;
-        description = "(optional) name your peer has for you";
+        description = lib.mdDoc "(optional) name your peer has for you";
       };
       peerName = mkOption {
         default = "";
         type = types.str;
-        description = "(optional) human-readable name for peer";
+        description = lib.mdDoc "(optional) human-readable name for peer";
       };
       publicKey = mkOption {
         type = types.str;
-        description = "Public key at the opposite end of the tunnel.";
+        description = lib.mdDoc "Public key at the opposite end of the tunnel.";
       };
       hostname = mkOption {
         default = "";
         example = "foobar.hype";
         type = types.str;
-        description = "Optional hostname to add to /etc/hosts; prevents reverse lookup failures.";
+        description = lib.mdDoc "Optional hostname to add to /etc/hosts; prevents reverse lookup failures.";
       };
     };
   };
@@ -87,7 +87,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the cjdns network encryption
           and routing engine. A file at /etc/cjdns.keys will
           be created if it does not exist to contain a random
@@ -99,7 +99,7 @@ in
         type = types.attrs;
         default = {};
         example = { router.interface.tunDevice = "tun10"; };
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration, given as attrs, that will be merged recursively
           with the rest of the JSON generated by this module, at the root node.
         '';
@@ -109,7 +109,7 @@ in
         type = types.nullOr types.path;
         default = null;
         example = "/etc/cjdroute.conf";
-        description = ''
+        description = lib.mdDoc ''
           Ignore all other cjdns options and load configuration from this file.
         '';
       };
@@ -122,7 +122,7 @@ in
           "z9md3t4p45mfrjzdjurxn4wuj0d8swv"
           "49275fut6tmzu354pq70sr5b95qq0vj"
         ];
-        description = ''
+        description = lib.mdDoc ''
           Any remote cjdns nodes that offer these passwords on
           connection will be allowed to route through this node.
         '';
@@ -132,7 +132,7 @@ in
         bind = mkOption {
           type = types.str;
           default = "127.0.0.1:11234";
-          description = ''
+          description = lib.mdDoc ''
             Bind the administration port to this address and port.
           '';
         };
@@ -143,7 +143,7 @@ in
           type = types.str;
           default = "";
           example = "192.168.1.32:43211";
-          description = ''
+          description = lib.mdDoc ''
             Address and port to bind UDP tunnels to.
           '';
          };
@@ -159,7 +159,7 @@ in
               };
             }
           '';
-          description = ''
+          description = lib.mdDoc ''
             Credentials for making UDP tunnels.
           '';
         };
@@ -171,16 +171,16 @@ in
           default = "";
           example = "eth0";
           description =
-            ''
+            lib.mdDoc ''
               Bind to this device for native ethernet operation.
-              <literal>all</literal> is a pseudo-name which will try to connect to all devices.
+              `all` is a pseudo-name which will try to connect to all devices.
             '';
         };
 
         beacon = mkOption {
           type = types.int;
           default = 2;
-          description = ''
+          description = lib.mdDoc ''
             Auto-connect to other cjdns nodes on the same network.
             Options:
               0: Disabled.
@@ -206,7 +206,7 @@ in
               };
             }
           '';
-          description = ''
+          description = lib.mdDoc ''
             Credentials for connecting look similar to UDP credientials
             except they begin with the mac address.
           '';
@@ -216,9 +216,9 @@ in
       addExtraHosts = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to add cjdns peers with an associated hostname to
-          <filename>/etc/hosts</filename>.  Beware that enabling this
+          {file}`/etc/hosts`.  Beware that enabling this
           incurs heavy eval-time costs.
         '';
       };
diff --git a/nixos/modules/services/networking/cloudflare-dyndns.nix b/nixos/modules/services/networking/cloudflare-dyndns.nix
new file mode 100644
index 00000000000..627fdb880a6
--- /dev/null
+++ b/nixos/modules/services/networking/cloudflare-dyndns.nix
@@ -0,0 +1,93 @@
+{ config, pkgs, lib, ... }:
+
+with lib;
+
+let
+  cfg = config.services.cloudflare-dyndns;
+in
+{
+  options = {
+    services.cloudflare-dyndns = {
+      enable = mkEnableOption (lib.mdDoc "Cloudflare Dynamic DNS Client");
+
+      apiTokenFile = mkOption {
+        type = types.nullOr types.str;
+        default = null;
+        description = lib.mdDoc ''
+          The path to a file containing the CloudFlare API token.
+
+          The file must have the form `CLOUDFLARE_API_TOKEN=...`
+        '';
+      };
+
+      domains = mkOption {
+        type = types.listOf types.str;
+        default = [ ];
+        description = lib.mdDoc ''
+          List of domain names to update records for.
+        '';
+      };
+
+      proxied = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether this is a DNS-only record, or also being proxied through CloudFlare.
+        '';
+      };
+
+      ipv4 = mkOption {
+        type = types.bool;
+        default = true;
+        description = lib.mdDoc ''
+          Whether to enable setting IPv4 A records.
+        '';
+      };
+
+      ipv6 = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to enable setting IPv6 AAAA records.
+        '';
+      };
+
+      deleteMissing = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to delete the record when no IP address is found.
+        '';
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.cloudflare-dyndns = {
+      description = "CloudFlare Dynamic DNS Client";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+      startAt = "*:0/5";
+
+      environment = {
+        CLOUDFLARE_DOMAINS = toString cfg.domains;
+      };
+
+      serviceConfig = {
+        Type = "simple";
+        DynamicUser = true;
+        StateDirectory = "cloudflare-dyndns";
+        EnvironmentFile = cfg.apiTokenFile;
+        ExecStart =
+          let
+            args = [ "--cache-file /var/lib/cloudflare-dyndns/ip.cache" ]
+              ++ (if cfg.ipv4 then [ "-4" ] else [ "-no-4" ])
+              ++ (if cfg.ipv6 then [ "-6" ] else [ "-no-6" ])
+              ++ optional cfg.deleteMissing "--delete-missing"
+              ++ optional cfg.proxied "--proxied";
+          in
+          "${pkgs.cloudflare-dyndns}/bin/cloudflare-dyndns ${toString args}";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/networking/cntlm.nix b/nixos/modules/services/networking/cntlm.nix
index eea28e12ce0..41510a8f074 100644
--- a/nixos/modules/services/networking/cntlm.nix
+++ b/nixos/modules/services/networking/cntlm.nix
@@ -33,37 +33,37 @@ in
 
   options.services.cntlm = {
 
-    enable = mkEnableOption "cntlm, which starts a local proxy";
+    enable = mkEnableOption (lib.mdDoc "cntlm, which starts a local proxy");
 
     username = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Proxy account name, without the possibility to include domain name ('at' sign is interpreted literally).
       '';
     };
 
     domain = mkOption {
       type = types.str;
-      description = "Proxy account domain/workgroup name.";
+      description = lib.mdDoc "Proxy account domain/workgroup name.";
     };
 
     password = mkOption {
       default = "/etc/cntlm.password";
       type = types.str;
-      description = "Proxy account password. Note: use chmod 0600 on /etc/cntlm.password for security.";
+      description = lib.mdDoc "Proxy account password. Note: use chmod 0600 on /etc/cntlm.password for security.";
     };
 
     netbios_hostname = mkOption {
       type = types.str;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         The hostname of your machine.
       '';
     };
 
     proxy = mkOption {
       type = types.listOf types.str;
-      description = ''
+      description = lib.mdDoc ''
         A list of NTLM/NTLMv2 authenticating HTTP proxies.
 
         Parent proxy, which requires authentication. The same as proxy on the command-line, can be used more than  once  to  specify  unlimited
@@ -74,7 +74,7 @@ in
     };
 
     noproxy = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         A list of domains where the proxy is skipped.
       '';
       default = [];
@@ -85,19 +85,19 @@ in
     port = mkOption {
       default = [3128];
       type = types.listOf types.port;
-      description = "Specifies on which ports the cntlm daemon listens.";
+      description = lib.mdDoc "Specifies on which ports the cntlm daemon listens.";
     };
 
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = "Additional config appended to the end of the generated <filename>cntlm.conf</filename>.";
+      description = lib.mdDoc "Additional config appended to the end of the generated {file}`cntlm.conf`.";
     };
 
     configText = mkOption {
        type = types.lines;
        default = "";
-       description = "Verbatim contents of <filename>cntlm.conf</filename>.";
+       description = lib.mdDoc "Verbatim contents of {file}`cntlm.conf`.";
     };
 
   };
diff --git a/nixos/modules/services/networking/connman.nix b/nixos/modules/services/networking/connman.nix
index 9945dc83a27..49899141957 100644
--- a/nixos/modules/services/networking/connman.nix
+++ b/nixos/modules/services/networking/connman.nix
@@ -27,7 +27,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use ConnMan for managing your network connections.
         '';
       };
@@ -35,7 +35,7 @@ in {
       enableVPN = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable ConnMan VPN service.
         '';
       };
@@ -43,7 +43,7 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Configuration lines appended to the generated connman configuration file.
         '';
       };
@@ -51,7 +51,7 @@ in {
       networkInterfaceBlacklist = mkOption {
         type = with types; listOf str;
         default = [ "vmnet" "vboxnet" "virbr" "ifb" "ve" ];
-        description = ''
+        description = lib.mdDoc ''
           Default blacklisted interfaces, this includes NixOS containers interfaces (ve).
         '';
       };
@@ -60,9 +60,9 @@ in {
         backend = mkOption {
           type = types.enum [ "wpa_supplicant" "iwd" ];
           default = "wpa_supplicant";
-          description = ''
+          description = lib.mdDoc ''
             Specify the Wi-Fi backend used.
-            Currently supported are <option>wpa_supplicant</option> or <option>iwd</option>.
+            Currently supported are {option}`wpa_supplicant` or {option}`iwd`.
           '';
         };
       };
@@ -71,14 +71,14 @@ in {
         type = with types; listOf str;
         default = [ ];
         example = [ "--nodnsproxy" ];
-        description = ''
+        description = lib.mdDoc ''
           Extra flags to pass to connmand
         '';
       };
 
       package = mkOption {
         type = types.package;
-        description = "The connman package / build flavor";
+        description = lib.mdDoc "The connman package / build flavor";
         default = connman;
         defaultText = literalExpression "pkgs.connman";
         example = literalExpression "pkgs.connmanFull";
diff --git a/nixos/modules/services/networking/consul.nix b/nixos/modules/services/networking/consul.nix
index ca9c422e6d7..bee41dcf765 100644
--- a/nixos/modules/services/networking/consul.nix
+++ b/nixos/modules/services/networking/consul.nix
@@ -28,7 +28,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enables the consul daemon.
         '';
       };
@@ -37,7 +37,7 @@ in
         type = types.package;
         default = pkgs.consul;
         defaultText = literalExpression "pkgs.consul";
-        description = ''
+        description = lib.mdDoc ''
           The package used for the Consul agent and CLI.
         '';
       };
@@ -46,7 +46,7 @@ in
       webUi = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enables the web interface on the consul http port.
         '';
       };
@@ -54,7 +54,7 @@ in
       leaveOnStop = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, causes a leave action to be sent when closing consul.
           This allows a clean termination of the node, but permanently removes
           it from the cluster. You probably don't want this option unless you
@@ -68,7 +68,7 @@ in
         advertise = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The name of the interface to pull the advertise_addr from.
           '';
         };
@@ -76,17 +76,25 @@ in
         bind = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The name of the interface to pull the bind_addr from.
           '';
         };
+      };
 
+      forceAddrFamily = mkOption {
+        type = types.enum [ "any" "ipv4" "ipv6" ];
+        default = "any";
+        description = lib.mdDoc ''
+          Whether to bind ipv4/ipv6 or both kind of addresses.
+        '';
       };
 
       forceIpv4 = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
+        type = types.nullOr types.bool;
+        default = null;
+        description = lib.mdDoc ''
+          Deprecated: Use consul.forceAddrFamily instead.
           Whether we should force the interfaces to only pull ipv4 addresses.
         '';
       };
@@ -94,7 +102,7 @@ in
       dropPrivileges = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether the consul agent should be run as a non-root consul user.
         '';
       };
@@ -102,7 +110,7 @@ in
       extraConfig = mkOption {
         default = { };
         type = types.attrsOf types.anything;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration options which are serialized to json and added
           to the config.json file.
         '';
@@ -111,42 +119,42 @@ in
       extraConfigFiles = mkOption {
         default = [ ];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Additional configuration files to pass to consul
           NOTE: These will not trigger the service to be restarted when altered.
         '';
       };
 
       alerts = {
-        enable = mkEnableOption "consul-alerts";
+        enable = mkEnableOption (lib.mdDoc "consul-alerts");
 
         package = mkOption {
-          description = "Package to use for consul-alerts.";
+          description = lib.mdDoc "Package to use for consul-alerts.";
           default = pkgs.consul-alerts;
           defaultText = literalExpression "pkgs.consul-alerts";
           type = types.package;
         };
 
         listenAddr = mkOption {
-          description = "Api listening address.";
+          description = lib.mdDoc "Api listening address.";
           default = "localhost:9000";
           type = types.str;
         };
 
         consulAddr = mkOption {
-          description = "Consul api listening adddress";
+          description = lib.mdDoc "Consul api listening adddress";
           default = "localhost:8500";
           type = types.str;
         };
 
         watchChecks = mkOption {
-          description = "Whether to enable check watcher.";
+          description = lib.mdDoc "Whether to enable check watcher.";
           default = true;
           type = types.bool;
         };
 
         watchEvents = mkOption {
-          description = "Whether to enable event watcher.";
+          description = lib.mdDoc "Whether to enable event watcher.";
           default = true;
           type = types.bool;
         };
@@ -175,6 +183,13 @@ in
         systemPackages = [ cfg.package ];
       };
 
+      warnings = lib.flatten [
+        (lib.optional (cfg.forceIpv4 != null) ''
+          The option consul.forceIpv4 is deprecated, please use
+          consul.forceAddrFamily instead.
+        '')
+      ];
+
       systemd.services.consul = {
         wantedBy = [ "multi-user.target" ];
         after = [ "network.target" ] ++ systemdDevices;
@@ -186,7 +201,7 @@ in
         serviceConfig = {
           ExecStart = "@${cfg.package}/bin/consul consul agent -config-dir /etc/consul.d"
             + concatMapStrings (n: " -config-file ${n}") configFiles;
-          ExecReload = "${cfg.package}/bin/consul reload";
+          ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
           PermissionsStartOnly = true;
           User = if cfg.dropPrivileges then "consul" else null;
           Restart = "on-failure";
@@ -196,15 +211,21 @@ in
         });
 
         path = with pkgs; [ iproute2 gnugrep gawk consul ];
-        preStart = ''
+        preStart = let
+          family = if cfg.forceAddrFamily == "ipv6" then
+            "-6"
+          else if cfg.forceAddrFamily == "ipv4" then
+            "-4"
+          else
+            "";
+        in ''
           mkdir -m 0700 -p ${dataDir}
           chown -R consul ${dataDir}
 
           # Determine interface addresses
           getAddrOnce () {
-            ip addr show dev "$1" \
-              | grep 'inet${optionalString (cfg.forceIpv4) " "}.*scope global' \
-              | awk -F '[ /\t]*' '{print $3}' | head -n 1
+            ip ${family} addr show dev "$1" scope global \
+              | awk -F '[ /\t]*' '/inet/ {print $3}' | head -n 1
           }
           getAddr () {
             ADDR="$(getAddrOnce $1)"
@@ -234,6 +255,11 @@ in
       };
     }
 
+    # deprecated
+    (mkIf (cfg.forceIpv4 != null && cfg.forceIpv4) {
+      services.consul.forceAddrFamily = "ipv4";
+    })
+
     (mkIf (cfg.alerts.enable) {
       systemd.services.consul-alerts = {
         wantedBy = [ "multi-user.target" ];
diff --git a/nixos/modules/services/networking/coredns.nix b/nixos/modules/services/networking/coredns.nix
index 88615d8e610..f928cdf9614 100644
--- a/nixos/modules/services/networking/coredns.nix
+++ b/nixos/modules/services/networking/coredns.nix
@@ -7,7 +7,7 @@ let
   configFile = pkgs.writeText "Corefile" cfg.config;
 in {
   options.services.coredns = {
-    enable = mkEnableOption "Coredns dns server";
+    enable = mkEnableOption (lib.mdDoc "Coredns dns server");
 
     config = mkOption {
       default = "";
@@ -17,14 +17,17 @@ in {
         }
       '';
       type = types.lines;
-      description = "Verbatim Corefile to use. See <link xlink:href=\"https://coredns.io/manual/toc/#configuration\"/> for details.";
+      description = lib.mdDoc ''
+        Verbatim Corefile to use.
+        See <https://coredns.io/manual/toc/#configuration> for details.
+      '';
     };
 
     package = mkOption {
       default = pkgs.coredns;
       defaultText = literalExpression "pkgs.coredns";
       type = types.package;
-      description = "Coredns package to use.";
+      description = lib.mdDoc "Coredns package to use.";
     };
   };
 
diff --git a/nixos/modules/services/networking/corerad.nix b/nixos/modules/services/networking/corerad.nix
index 9d79d5d7686..0c6fb7a17ca 100644
--- a/nixos/modules/services/networking/corerad.nix
+++ b/nixos/modules/services/networking/corerad.nix
@@ -10,7 +10,7 @@ in {
   meta.maintainers = with maintainers; [ mdlayher ];
 
   options.services.corerad = {
-    enable = mkEnableOption "CoreRAD IPv6 NDP RA daemon";
+    enable = mkEnableOption (lib.mdDoc "CoreRAD IPv6 NDP RA daemon");
 
     settings = mkOption {
       type = settingsFormat.type;
@@ -36,8 +36,8 @@ in {
           };
         }
       '';
-      description = ''
-        Configuration for CoreRAD, see <link xlink:href="https://github.com/mdlayher/corerad/blob/main/internal/config/reference.toml"/>
+      description = lib.mdDoc ''
+        Configuration for CoreRAD, see <https://github.com/mdlayher/corerad/blob/main/internal/config/reference.toml>
         for supported values. Ignored if configFile is set.
       '';
     };
@@ -45,14 +45,14 @@ in {
     configFile = mkOption {
       type = types.path;
       example = literalExpression ''"''${pkgs.corerad}/etc/corerad/corerad.toml"'';
-      description = "Path to CoreRAD TOML configuration file.";
+      description = lib.mdDoc "Path to CoreRAD TOML configuration file.";
     };
 
     package = mkOption {
       default = pkgs.corerad;
       defaultText = literalExpression "pkgs.corerad";
       type = types.package;
-      description = "CoreRAD package to use.";
+      description = lib.mdDoc "CoreRAD package to use.";
     };
   };
 
diff --git a/nixos/modules/services/networking/coturn.nix b/nixos/modules/services/networking/coturn.nix
index ce563c31136..2f34a72377c 100644
--- a/nixos/modules/services/networking/coturn.nix
+++ b/nixos/modules/services/networking/coturn.nix
@@ -40,11 +40,11 @@ ${cfg.extraConfig}
 in {
   options = {
     services.coturn = {
-      enable = mkEnableOption "coturn TURN server";
+      enable = mkEnableOption (lib.mdDoc "coturn TURN server");
       listening-port = mkOption {
         type = types.int;
         default = 3478;
-        description = ''
+        description = lib.mdDoc ''
           TURN listener port for UDP and TCP.
           Note: actually, TLS and DTLS sessions can connect to the
           "plain" TCP and UDP port(s), too - if allowed by configuration.
@@ -53,7 +53,7 @@ in {
       tls-listening-port = mkOption {
         type = types.int;
         default = 5349;
-        description = ''
+        description = lib.mdDoc ''
           TURN listener port for TLS.
           Note: actually, "plain" TCP and UDP sessions can connect to the TLS and
           DTLS port(s), too - if allowed by configuration. The TURN server
@@ -69,7 +69,7 @@ in {
         type = types.int;
         default = cfg.listening-port + 1;
         defaultText = literalExpression "listening-port + 1";
-        description = ''
+        description = lib.mdDoc ''
           Alternative listening port for UDP and TCP listeners;
           default (or zero) value means "listening port plus one".
           This is needed for RFC 5780 support
@@ -84,7 +84,7 @@ in {
         type = types.int;
         default = cfg.tls-listening-port + 1;
         defaultText = literalExpression "tls-listening-port + 1";
-        description = ''
+        description = lib.mdDoc ''
           Alternative listening port for TLS and DTLS protocols.
         '';
       };
@@ -92,7 +92,7 @@ in {
         type = types.listOf types.str;
         default = [];
         example = [ "203.0.113.42" "2001:DB8::42" ];
-        description = ''
+        description = lib.mdDoc ''
           Listener IP addresses of relay server.
           If no IP(s) specified in the config file or in the command line options,
           then all IPv4 and IPv6 system IPs will be used for listening.
@@ -102,7 +102,7 @@ in {
         type = types.listOf types.str;
         default = [];
         example = [ "203.0.113.42" "2001:DB8::42" ];
-        description = ''
+        description = lib.mdDoc ''
           Relay address (the local IP address that will be used to relay the
           packets to the peer).
           Multiple relay addresses may be used.
@@ -118,28 +118,28 @@ in {
       min-port = mkOption {
         type = types.int;
         default = 49152;
-        description = ''
+        description = lib.mdDoc ''
           Lower bound of UDP relay endpoints
         '';
       };
       max-port = mkOption {
         type = types.int;
         default = 65535;
-        description = ''
+        description = lib.mdDoc ''
           Upper bound of UDP relay endpoints
         '';
       };
       lt-cred-mech = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Use long-term credential mechanism.
         '';
       };
       no-auth = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           This option is opposite to lt-cred-mech.
           (TURN Server with no-auth option allows anonymous access).
           If neither option is defined, and no users are defined,
@@ -151,7 +151,7 @@ in {
       use-auth-secret = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           TURN REST API flag.
           Flag that sets a special authorization option that is based upon authentication secret.
           This feature can be used with the long-term authentication mechanism, only.
@@ -175,7 +175,7 @@ in {
       static-auth-secret = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           'Static' authentication secret value (a string) for TURN REST API only.
           If not set, then the turn server
           will try to use the 'dynamic' value in turn_secret table
@@ -186,7 +186,7 @@ in {
       static-auth-secret-file = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to the file containing the static authentication secret.
         '';
       };
@@ -195,7 +195,7 @@ in {
         default = config.networking.hostName;
         defaultText = literalExpression "config.networking.hostName";
         example = "example.com";
-        description = ''
+        description = lib.mdDoc ''
           The default realm to be used for the users when no explicit
           origin/realm relationship was found in the database, or if the TURN
           server is not using any database (just the commands-line settings
@@ -207,7 +207,7 @@ in {
         type = types.nullOr types.str;
         default = null;
         example = "/var/lib/acme/example.com/fullchain.pem";
-        description = ''
+        description = lib.mdDoc ''
           Certificate file in PEM format.
         '';
       };
@@ -215,21 +215,21 @@ in {
         type = types.nullOr types.str;
         default = null;
         example = "/var/lib/acme/example.com/key.pem";
-        description = ''
+        description = lib.mdDoc ''
           Private key file in PEM format.
         '';
       };
       dh-file = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Use custom DH TLS key, stored in PEM format in the file.
         '';
       };
       secure-stun = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Require authentication of the STUN Binding request.
           By default, the clients are allowed anonymous access to the STUN Binding functionality.
         '';
@@ -237,28 +237,28 @@ in {
       no-cli = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Turn OFF the CLI support.
         '';
       };
       cli-ip = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = ''
+        description = lib.mdDoc ''
           Local system IP address to be used for CLI server endpoint.
         '';
       };
       cli-port = mkOption {
         type = types.int;
         default = 5766;
-        description = ''
+        description = lib.mdDoc ''
           CLI server port.
         '';
       };
       cli-password = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           CLI access password.
           For the security reasons, it is recommended to use the encrypted
           for of the password (see the -P command in the turnadmin utility).
@@ -267,37 +267,37 @@ in {
       no-udp = mkOption {
         type = types.bool;
         default = false;
-        description = "Disable UDP client listener";
+        description = lib.mdDoc "Disable UDP client listener";
       };
       no-tcp = mkOption {
         type = types.bool;
         default = false;
-        description = "Disable TCP client listener";
+        description = lib.mdDoc "Disable TCP client listener";
       };
       no-tls = mkOption {
         type = types.bool;
         default = false;
-        description = "Disable TLS client listener";
+        description = lib.mdDoc "Disable TLS client listener";
       };
       no-dtls = mkOption {
         type = types.bool;
         default = false;
-        description = "Disable DTLS client listener";
+        description = lib.mdDoc "Disable DTLS client listener";
       };
       no-udp-relay = mkOption {
         type = types.bool;
         default = false;
-        description = "Disable UDP relay endpoints";
+        description = lib.mdDoc "Disable UDP relay endpoints";
       };
       no-tcp-relay = mkOption {
         type = types.bool;
         default = false;
-        description = "Disable TCP relay endpoints";
+        description = lib.mdDoc "Disable TCP relay endpoints";
       };
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Additional configuration options";
+        description = lib.mdDoc "Additional configuration options";
       };
     };
   };
@@ -335,9 +335,10 @@ in {
         preStart = ''
           cat ${configFile} > ${runConfig}
           ${optionalString (cfg.static-auth-secret-file != null) ''
-            STATIC_AUTH_SECRET="$(head -n1 ${cfg.static-auth-secret-file} || :)"
-            sed -e "s,#static-auth-secret#,$STATIC_AUTH_SECRET,g" \
-              -i ${runConfig}
+            ${pkgs.replace-secret}/bin/replace-secret \
+              "#static-auth-secret#" \
+              ${cfg.static-auth-secret-file} \
+              ${runConfig}
           '' }
           chmod 640 ${runConfig}
         '';
diff --git a/nixos/modules/services/networking/create_ap.nix b/nixos/modules/services/networking/create_ap.nix
new file mode 100644
index 00000000000..e772cf21ec5
--- /dev/null
+++ b/nixos/modules/services/networking/create_ap.nix
@@ -0,0 +1,50 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.create_ap;
+  configFile = pkgs.writeText "create_ap.conf" (generators.toKeyValue { } cfg.settings);
+in {
+  options = {
+    services.create_ap = {
+      enable = mkEnableOption (lib.mdDoc "setup wifi hotspots using create_ap");
+      settings = mkOption {
+        type = with types; attrsOf (oneOf [ int bool str ]);
+        default = {};
+        description = lib.mdDoc ''
+          Configuration for `create_ap`.
+          See [upstream example configuration](https://raw.githubusercontent.com/lakinduakash/linux-wifi-hotspot/master/src/scripts/create_ap.conf)
+          for supported values.
+        '';
+        example = {
+          INTERNET_IFACE = "eth0";
+          WIFI_IFACE = "wlan0";
+          SSID = "My Wifi Hotspot";
+          PASSPHRASE = "12345678";
+        };
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    systemd = {
+      services.create_ap = {
+        wantedBy = [ "multi-user.target" ];
+        description = "Create AP Service";
+        after = [ "network.target" ];
+        restartTriggers = [ configFile ];
+        serviceConfig = {
+          ExecStart = "${pkgs.linux-wifi-hotspot}/bin/create_ap --config ${configFile}";
+          KillSignal = "SIGINT";
+          Restart = "on-failure";
+        };
+      };
+    };
+
+  };
+
+  meta.maintainers = with lib.maintainers; [ onny ];
+
+}
diff --git a/nixos/modules/services/networking/croc.nix b/nixos/modules/services/networking/croc.nix
index d044979e10d..45bfd447da4 100644
--- a/nixos/modules/services/networking/croc.nix
+++ b/nixos/modules/services/networking/croc.nix
@@ -6,19 +6,19 @@ let
 in
 {
   options.services.croc = {
-    enable = lib.mkEnableOption "croc relay";
+    enable = lib.mkEnableOption (lib.mdDoc "croc relay");
     ports = lib.mkOption {
       type = with types; listOf port;
       default = [9009 9010 9011 9012 9013];
-      description = "Ports of the relay.";
+      description = lib.mdDoc "Ports of the relay.";
     };
     pass = lib.mkOption {
       type = with types; either path str;
       default = "pass123";
-      description = "Password or passwordfile for the relay.";
+      description = lib.mdDoc "Password or passwordfile for the relay.";
     };
-    openFirewall = lib.mkEnableOption "opening of the peer port(s) in the firewall";
-    debug = lib.mkEnableOption "debug logs";
+    openFirewall = lib.mkEnableOption (lib.mdDoc "opening of the peer port(s) in the firewall");
+    debug = lib.mkEnableOption (lib.mdDoc "debug logs");
   };
 
   config = lib.mkIf cfg.enable {
@@ -72,7 +72,7 @@ in
         RuntimeDirectoryMode = "700";
         SystemCallFilter = [
           "@system-service"
-          "~@aio" "~@keyring" "~@memlock" "~@privileged" "~@resources" "~@setuid" "~@sync" "~@timer"
+          "~@aio" "~@keyring" "~@memlock" "~@privileged" "~@setuid" "~@sync" "~@timer"
         ];
         SystemCallArchitectures = "native";
         SystemCallErrorNumber = "EPERM";
diff --git a/nixos/modules/services/networking/dante.nix b/nixos/modules/services/networking/dante.nix
index 20d4faa1cdb..605f2d74f82 100644
--- a/nixos/modules/services/networking/dante.nix
+++ b/nixos/modules/services/networking/dante.nix
@@ -19,11 +19,11 @@ in
 
   options = {
     services.dante = {
-      enable = mkEnableOption "Dante SOCKS proxy";
+      enable = mkEnableOption (lib.mdDoc "Dante SOCKS proxy");
 
       config = mkOption {
         type        = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Contents of Dante's configuration file.
           NOTE: user.privileged, user.unprivileged and logoutput are set by the service.
         '';
diff --git a/nixos/modules/services/networking/ddclient.nix b/nixos/modules/services/networking/ddclient.nix
index d025c8f8177..5c32817979a 100644
--- a/nixos/modules/services/networking/ddclient.nix
+++ b/nixos/modules/services/networking/ddclient.nix
@@ -13,7 +13,7 @@ let
     foreground=YES
     use=${cfg.use}
     login=${cfg.username}
-    password=${lib.optionalString (cfg.protocol == "nsupdate") "/run/${RuntimeDirectory}/ddclient.key"}
+    password=${if cfg.protocol == "nsupdate" then "/run/${RuntimeDirectory}/ddclient.key" else "@password_placeholder@"}
     protocol=${cfg.protocol}
     ${lib.optionalString (cfg.script != "") "script=${cfg.script}"}
     ${lib.optionalString (cfg.server != "") "server=${cfg.server}"}
@@ -33,10 +33,9 @@ let
     ${lib.optionalString (cfg.configFile == null) (if (cfg.protocol == "nsupdate") then ''
       install ${cfg.passwordFile} /run/${RuntimeDirectory}/ddclient.key
     '' else if (cfg.passwordFile != null) then ''
-      password=$(printf "%q" "$(head -n 1 "${cfg.passwordFile}")")
-      sed -i "s|^password=$|password=$password|" /run/${RuntimeDirectory}/ddclient.conf
+      "${pkgs.replace-secret}/bin/replace-secret" "@password_placeholder@" "${cfg.passwordFile}" "/run/${RuntimeDirectory}/ddclient.conf"
     '' else ''
-      sed -i '/^password=$/d' /run/${RuntimeDirectory}/ddclient.conf
+      sed -i '/^password=@password_placeholder@$/d' /run/${RuntimeDirectory}/ddclient.conf
     '')}
   '';
 
@@ -64,7 +63,7 @@ with lib;
       enable = mkOption {
         default = false;
         type = bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to synchronise your machine's IP address with a dynamic DNS provider (e.g. dyndns.org).
         '';
       };
@@ -73,7 +72,7 @@ with lib;
         type = package;
         default = pkgs.ddclient;
         defaultText = "pkgs.ddclient";
-        description = ''
+        description = lib.mdDoc ''
           The ddclient executable package run by the service.
         '';
       };
@@ -81,7 +80,7 @@ with lib;
       domains = mkOption {
         default = [ "" ];
         type = listOf str;
-        description = ''
+        description = lib.mdDoc ''
           Domain name(s) to synchronize.
         '';
       };
@@ -91,7 +90,7 @@ with lib;
         default = lib.optionalString (config.services.ddclient.protocol == "nsupdate") "${pkgs.bind.dnsutils}/bin/nsupdate";
         defaultText = "";
         type = str;
-        description = ''
+        description = lib.mdDoc ''
           User name.
         '';
       };
@@ -99,7 +98,7 @@ with lib;
       passwordFile = mkOption {
         default = null;
         type = nullOr str;
-        description = ''
+        description = lib.mdDoc ''
           A file containing the password or a TSIG key in named format when using the nsupdate protocol.
         '';
       };
@@ -107,16 +106,16 @@ with lib;
       interval = mkOption {
         default = "10min";
         type = str;
-        description = ''
+        description = lib.mdDoc ''
           The interval at which to run the check and update.
-          See <command>man 7 systemd.time</command> for the format.
+          See {command}`man 7 systemd.time` for the format.
         '';
       };
 
       configFile = mkOption {
         default = null;
         type = nullOr path;
-        description = ''
+        description = lib.mdDoc ''
           Path to configuration file.
           When set this overrides the generated configuration from module options.
         '';
@@ -126,7 +125,7 @@ with lib;
       protocol = mkOption {
         default = "dyndns2";
         type = str;
-        description = ''
+        description = lib.mdDoc ''
           Protocol to use with dynamic DNS provider (see https://sourceforge.net/p/ddclient/wiki/protocols).
         '';
       };
@@ -134,7 +133,7 @@ with lib;
       server = mkOption {
         default = "";
         type = str;
-        description = ''
+        description = lib.mdDoc ''
           Server address.
         '';
       };
@@ -142,7 +141,7 @@ with lib;
       ssl = mkOption {
         default = true;
         type = bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use SSL/TLS to connect to dynamic DNS provider.
         '';
       };
@@ -150,7 +149,7 @@ with lib;
       ipv6 = mkOption {
         default = false;
         type = bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use IPv6.
         '';
       };
@@ -159,7 +158,7 @@ with lib;
       quiet = mkOption {
         default = false;
         type = bool;
-        description = ''
+        description = lib.mdDoc ''
           Print no messages for unnecessary updates.
         '';
       };
@@ -167,7 +166,7 @@ with lib;
       script = mkOption {
         default = "";
         type = str;
-        description = ''
+        description = lib.mdDoc ''
           script as required by some providers.
         '';
       };
@@ -175,15 +174,15 @@ with lib;
       use = mkOption {
         default = "web, web=checkip.dyndns.com/, web-skip='Current IP Address: '";
         type = str;
-        description = ''
+        description = lib.mdDoc ''
           Method to determine the IP address to send to the dynamic DNS provider.
         '';
       };
 
       verbose = mkOption {
-        default = true;
+        default = false;
         type = bool;
-        description = ''
+        description = lib.mdDoc ''
           Print verbose information.
         '';
       };
@@ -191,7 +190,7 @@ with lib;
       zone = mkOption {
         default = "";
         type = str;
-        description = ''
+        description = lib.mdDoc ''
           zone as required by some providers.
         '';
       };
@@ -199,8 +198,12 @@ with lib;
       extraConfig = mkOption {
         default = "";
         type = lines;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration. Contents will be added verbatim to the configuration file.
+
+          ::: {.note}
+          `daemon` should not be added here because it does not work great with the systemd-timer approach the service uses.
+          :::
         '';
       };
     };
diff --git a/nixos/modules/services/networking/dhcpcd.nix b/nixos/modules/services/networking/dhcpcd.nix
index 3eb7ca99eaf..ac5d45a65e3 100644
--- a/nixos/modules/services/networking/dhcpcd.nix
+++ b/nixos/modules/services/networking/dhcpcd.nix
@@ -103,7 +103,7 @@ in
     networking.dhcpcd.enable = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable dhcpcd for device configuration. This is mainly to
         explicitly disable dhcpcd (for example when using networkd).
       '';
@@ -112,7 +112,7 @@ in
     networking.dhcpcd.persistent = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
           Whenever to leave interfaces configured on dhcpcd daemon
           shutdown. Set to true if you have your root or store mounted
           over the network or this machine accepts SSH connections
@@ -124,7 +124,7 @@ in
     networking.dhcpcd.denyInterfaces = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
          Disable the DHCP client for any interface whose name matches
          any of the shell glob patterns in this list. The purpose of
          this option is to blacklist virtual interfaces such as those
@@ -135,7 +135,7 @@ in
     networking.dhcpcd.allowInterfaces = mkOption {
       type = types.nullOr (types.listOf types.str);
       default = null;
-      description = ''
+      description = lib.mdDoc ''
          Enable the DHCP client for any interface whose name matches
          any of the shell glob patterns in this list. Any interface not
          explicitly matched by this pattern will be denied. This pattern only
@@ -146,7 +146,7 @@ in
     networking.dhcpcd.extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
          Literal string to append to the config file generated for dhcpcd.
       '';
     };
@@ -155,7 +155,7 @@ in
       type = types.lines;
       default = "";
       example = "if [[ $reason =~ BOUND ]]; then echo $interface: Routers are $new_routers - were $old_routers; fi";
-      description = ''
+      description = lib.mdDoc ''
          Shell code that will be run after all other hooks. See
          `man dhcpcd-run-hooks` for details on what is possible.
       '';
@@ -164,7 +164,7 @@ in
     networking.dhcpcd.wait = mkOption {
       type = types.enum [ "background" "any" "ipv4" "ipv6" "both" "if-carrier-up" ];
       default = "any";
-      description = ''
+      description = lib.mdDoc ''
         This option specifies when the dhcpcd service will fork to background.
         If set to "background", dhcpcd will fork to background immediately.
         If set to "ipv4" or "ipv6", dhcpcd will wait for the corresponding IP
@@ -215,7 +215,7 @@ in
         # dhcpcd.  So do a "systemctl restart" instead.
         stopIfChanged = false;
 
-        path = [ dhcpcd pkgs.nettools pkgs.openresolv ];
+        path = [ dhcpcd pkgs.nettools config.networking.resolvconf.package ];
 
         unitConfig.ConditionCapability = "CAP_NET_ADMIN";
 
diff --git a/nixos/modules/services/networking/dhcpd.nix b/nixos/modules/services/networking/dhcpd.nix
index 3c4c0069dfd..0bd5e4ef553 100644
--- a/nixos/modules/services/networking/dhcpd.nix
+++ b/nixos/modules/services/networking/dhcpd.nix
@@ -7,7 +7,7 @@ let
   cfg4 = config.services.dhcpd4;
   cfg6 = config.services.dhcpd6;
 
-  writeConfig = cfg: pkgs.writeText "dhcpd.conf"
+  writeConfig = postfix: cfg: pkgs.writeText "dhcpd.conf"
     ''
       default-lease-time 600;
       max-lease-time 7200;
@@ -21,7 +21,9 @@ let
           (machine: ''
             host ${machine.hostName} {
               hardware ethernet ${machine.ethernetAddress};
-              fixed-address ${machine.ipAddress};
+              fixed-address${
+                optionalString (postfix == "6") postfix
+              } ${machine.ipAddress};
             }
           '')
           cfg.machines
@@ -33,7 +35,7 @@ let
       configFile =
         if cfg.configFile != null
           then cfg.configFile
-          else writeConfig cfg;
+          else writeConfig postfix cfg;
       leaseFile = "/var/lib/dhcpd${postfix}/dhcpd.leases";
       args = [
         "@${pkgs.dhcp}/sbin/dhcpd" "dhcpd${postfix}" "-${postfix}"
@@ -75,7 +77,7 @@ let
       hostName = mkOption {
         type = types.str;
         example = "foo";
-        description = ''
+        description = lib.mdDoc ''
           Hostname which is assigned statically to the machine.
         '';
       };
@@ -83,7 +85,7 @@ let
       ethernetAddress = mkOption {
         type = types.str;
         example = "00:16:76:9a:32:1d";
-        description = ''
+        description = lib.mdDoc ''
           MAC address of the machine.
         '';
       };
@@ -91,7 +93,7 @@ let
       ipAddress = mkOption {
         type = types.str;
         example = "192.168.1.10";
-        description = ''
+        description = lib.mdDoc ''
           IP address of the machine.
         '';
       };
@@ -104,7 +106,7 @@ let
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable the DHCPv${postfix} server.
       '';
     };
@@ -122,7 +124,7 @@ let
           range 192.168.1.100 192.168.1.200;
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Extra text to be appended to the DHCP server configuration
         file. Currently, you almost certainly need to specify something
         there, such as the options specifying the subnet mask, DNS servers,
@@ -133,7 +135,7 @@ let
     extraFlags = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Additional command line flags to be passed to the dhcpd daemon.
       '';
     };
@@ -141,7 +143,7 @@ let
     configFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The path of the DHCP server configuration file.  If no file
         is specified, a file is generated using the other options.
       '';
@@ -150,7 +152,7 @@ let
     interfaces = mkOption {
       type = types.listOf types.str;
       default = ["eth0"];
-      description = ''
+      description = lib.mdDoc ''
         The interfaces on which the DHCP server should listen.
       '';
     };
@@ -168,7 +170,7 @@ let
           ipAddress = "192.168.1.11";
         }
       ];
-      description = ''
+      description = lib.mdDoc ''
         A list mapping Ethernet addresses to IPv${postfix} addresses for the
         DHCP server.
       '';
@@ -177,7 +179,7 @@ let
     authoritative = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether the DHCP server shall send DHCPNAK messages to misconfigured
         clients. If this is not done, clients may be unable to get a correct
         IP address after changing subnets until their old lease has expired.
diff --git a/nixos/modules/services/networking/dnscache.nix b/nixos/modules/services/networking/dnscache.nix
index 7452210de47..eff13f69f47 100644
--- a/nixos/modules/services/networking/dnscache.nix
+++ b/nixos/modules/services/networking/dnscache.nix
@@ -38,26 +38,26 @@ in {
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = "Whether to run the dnscache caching dns server.";
+        description = lib.mdDoc "Whether to run the dnscache caching dns server.";
       };
 
       ip = mkOption {
         default = "0.0.0.0";
         type = types.str;
-        description = "IP address on which to listen for connections.";
+        description = lib.mdDoc "IP address on which to listen for connections.";
       };
 
       clientIps = mkOption {
         default = [ "127.0.0.1" ];
         type = types.listOf types.str;
-        description = "Client IP addresses (or prefixes) from which to accept connections.";
+        description = lib.mdDoc "Client IP addresses (or prefixes) from which to accept connections.";
         example = ["192.168" "172.23.75.82"];
       };
 
       domainServers = mkOption {
         default = { };
         type = types.attrsOf (types.listOf types.str);
-        description = ''
+        description = lib.mdDoc ''
           Table of {hostname: server} pairs to use as authoritative servers for hosts (and subhosts).
           If entry for @ is not specified predefined list of root servers is used.
         '';
@@ -72,7 +72,7 @@ in {
       forwardOnly = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to treat root servers (for @) as caching
           servers, requesting addresses the same way a client does. This is
           needed if you want to use e.g. Google DNS as your upstream DNS.
diff --git a/nixos/modules/services/networking/dnscrypt-proxy2.nix b/nixos/modules/services/networking/dnscrypt-proxy2.nix
index 316e6e37f9d..de1ca0d2f20 100644
--- a/nixos/modules/services/networking/dnscrypt-proxy2.nix
+++ b/nixos/modules/services/networking/dnscrypt-proxy2.nix
@@ -6,12 +6,12 @@ in
 
 {
   options.services.dnscrypt-proxy2 = {
-    enable = mkEnableOption "dnscrypt-proxy2";
+    enable = mkEnableOption (lib.mdDoc "dnscrypt-proxy2");
 
     settings = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Attrset that is converted and passed as TOML config file.
-        For available params, see: <link xlink:href="https://github.com/DNSCrypt/dnscrypt-proxy/blob/${pkgs.dnscrypt-proxy2.version}/dnscrypt-proxy/example-dnscrypt-proxy.toml"/>
+        For available params, see: <https://github.com/DNSCrypt/dnscrypt-proxy/blob/${pkgs.dnscrypt-proxy2.version}/dnscrypt-proxy/example-dnscrypt-proxy.toml>
       '';
       example = literalExpression ''
         {
@@ -28,8 +28,8 @@ in
     };
 
     upstreamDefaults = mkOption {
-      description = ''
-        Whether to base the config declared in <option>services.dnscrypt-proxy2.settings</option> on the upstream example config (<link xlink:href="https://github.com/DNSCrypt/dnscrypt-proxy/blob/master/dnscrypt-proxy/example-dnscrypt-proxy.toml"/>)
+      description = lib.mdDoc ''
+        Whether to base the config declared in {option}`services.dnscrypt-proxy2.settings` on the upstream example config (<https://github.com/DNSCrypt/dnscrypt-proxy/blob/master/dnscrypt-proxy/example-dnscrypt-proxy.toml>)
 
         Disable this if you want to declare your dnscrypt config from scratch.
       '';
@@ -38,8 +38,8 @@ in
     };
 
     configFile = mkOption {
-      description = ''
-        Path to TOML config file. See: <link xlink:href="https://github.com/DNSCrypt/dnscrypt-proxy/blob/master/dnscrypt-proxy/example-dnscrypt-proxy.toml"/>
+      description = lib.mdDoc ''
+        Path to TOML config file. See: <https://github.com/DNSCrypt/dnscrypt-proxy/blob/master/dnscrypt-proxy/example-dnscrypt-proxy.toml>
         If this option is set, it will override any configuration done in options.services.dnscrypt-proxy2.settings.
       '';
       example = "/etc/dnscrypt-proxy/dnscrypt-proxy.toml";
@@ -56,7 +56,7 @@ in
         ''}
         ${pkgs.remarshal}/bin/json2toml < config.json > $out
       '';
-      defaultText = literalDocBook "TOML file generated from <option>services.dnscrypt-proxy2.settings</option>";
+      defaultText = literalMD "TOML file generated from {option}`services.dnscrypt-proxy2.settings`";
     };
   };
 
@@ -111,7 +111,6 @@ in
           "~@aio"
           "~@keyring"
           "~@memlock"
-          "~@resources"
           "~@setuid"
           "~@timer"
         ];
diff --git a/nixos/modules/services/networking/dnscrypt-wrapper.nix b/nixos/modules/services/networking/dnscrypt-wrapper.nix
index c2add170e9c..082e0195093 100644
--- a/nixos/modules/services/networking/dnscrypt-wrapper.nix
+++ b/nixos/modules/services/networking/dnscrypt-wrapper.nix
@@ -124,20 +124,20 @@ in {
   ###### interface
 
   options.services.dnscrypt-wrapper = {
-    enable = mkEnableOption "DNSCrypt wrapper";
+    enable = mkEnableOption (lib.mdDoc "DNSCrypt wrapper");
 
     address = mkOption {
       type = types.str;
       default = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         The DNSCrypt wrapper will bind to this IP address.
       '';
     };
 
     port = mkOption {
-      type = types.int;
+      type = types.port;
       default = 5353;
-      description = ''
+      description = lib.mdDoc ''
         The DNSCrypt wrapper will listen for DNS queries on this port.
       '';
     };
@@ -147,9 +147,9 @@ in {
       default = "2.dnscrypt-cert.${config.networking.hostName}";
       defaultText = literalExpression ''"2.dnscrypt-cert.''${config.networking.hostName}"'';
       example = "2.dnscrypt-cert.myresolver";
-      description = ''
+      description = lib.mdDoc ''
         The name that will be given to this DNSCrypt resolver.
-        Note: the resolver name must start with <literal>2.dnscrypt-cert.</literal>.
+        Note: the resolver name must start with `2.dnscrypt-cert.`.
       '';
     };
 
@@ -157,7 +157,7 @@ in {
       type = types.nullOr types.path;
       default = null;
       example = "/etc/secrets/public.key";
-      description = ''
+      description = lib.mdDoc ''
         The filepath to the provider public key. If not given a new
         provider key pair will be generated on the first run.
       '';
@@ -167,7 +167,7 @@ in {
       type = types.nullOr types.path;
       default = null;
       example = "/etc/secrets/secret.key";
-      description = ''
+      description = lib.mdDoc ''
         The filepath to the provider secret key. If not given a new
         provider key pair will be generated on the first run.
       '';
@@ -176,15 +176,15 @@ in {
     upstream.address = mkOption {
       type = types.str;
       default = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         The IP address of the upstream DNS server DNSCrypt will "wrap".
       '';
     };
 
     upstream.port = mkOption {
-      type = types.int;
+      type = types.port;
       default = 53;
-      description = ''
+      description = lib.mdDoc ''
         The port of the upstream DNS server DNSCrypt will "wrap".
       '';
     };
@@ -192,7 +192,7 @@ in {
     keys.expiration = mkOption {
       type = types.int;
       default = 30;
-      description = ''
+      description = lib.mdDoc ''
         The duration (in days) of the time-limited secret key.
         This will be automatically rotated before expiration.
       '';
@@ -201,7 +201,7 @@ in {
     keys.checkInterval = mkOption {
       type = types.int;
       default = 1440;
-      description = ''
+      description = lib.mdDoc ''
         The time interval (in minutes) between key expiration checks.
       '';
     };
diff --git a/nixos/modules/services/networking/dnsdist.nix b/nixos/modules/services/networking/dnsdist.nix
index c7c6a79864c..483300111df 100644
--- a/nixos/modules/services/networking/dnsdist.nix
+++ b/nixos/modules/services/networking/dnsdist.nix
@@ -11,23 +11,23 @@ let
 in {
   options = {
     services.dnsdist = {
-      enable = mkEnableOption "dnsdist domain name server";
+      enable = mkEnableOption (lib.mdDoc "dnsdist domain name server");
 
       listenAddress = mkOption {
         type = types.str;
-        description = "Listen IP Address";
+        description = lib.mdDoc "Listen IP Address";
         default = "0.0.0.0";
       };
       listenPort = mkOption {
         type = types.int;
-        description = "Listen port";
+        description = lib.mdDoc "Listen port";
         default = 53;
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to dnsdist.conf.
         '';
       };
diff --git a/nixos/modules/services/networking/dnsmasq.nix b/nixos/modules/services/networking/dnsmasq.nix
index 59a3ca2f28e..cfc37b74b9a 100644
--- a/nixos/modules/services/networking/dnsmasq.nix
+++ b/nixos/modules/services/networking/dnsmasq.nix
@@ -32,7 +32,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run dnsmasq.
         '';
       };
@@ -40,7 +40,7 @@ in
       resolveLocalQueries = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether dnsmasq should resolve local queries (i.e. add 127.0.0.1 to
           /etc/resolv.conf).
         '';
@@ -50,7 +50,7 @@ in
         type = types.listOf types.str;
         default = [];
         example = [ "8.8.8.8" "8.8.4.4" ];
-        description = ''
+        description = lib.mdDoc ''
           The DNS servers which dnsmasq should query.
         '';
       };
@@ -58,7 +58,7 @@ in
       alwaysKeepRunning = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, systemd will always respawn dnsmasq even if shut down manually. The default, disabled, will only restart it on error.
         '';
       };
@@ -66,9 +66,9 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration directives that should be added to
-          <literal>dnsmasq.conf</literal>.
+          `dnsmasq.conf`.
         '';
       };
 
diff --git a/nixos/modules/services/networking/doh-proxy-rust.nix b/nixos/modules/services/networking/doh-proxy-rust.nix
index efd492e23f8..7f8bbb8a769 100644
--- a/nixos/modules/services/networking/doh-proxy-rust.nix
+++ b/nixos/modules/services/networking/doh-proxy-rust.nix
@@ -10,15 +10,15 @@ in {
 
   options.services.doh-proxy-rust = {
 
-    enable = mkEnableOption "doh-proxy-rust";
+    enable = mkEnableOption (lib.mdDoc "doh-proxy-rust");
 
     flags = mkOption {
       type = types.listOf types.str;
       default = [];
       example = [ "--server-address=9.9.9.9:53" ];
-      description = ''
+      description = lib.mdDoc ''
         A list of command-line flags to pass to doh-proxy. For details on the
-        available options, see <link xlink:href="https://github.com/jedisct1/doh-server#usage"/>.
+        available options, see <https://github.com/jedisct1/doh-server#usage>.
       '';
     };
 
diff --git a/nixos/modules/services/networking/ejabberd.nix b/nixos/modules/services/networking/ejabberd.nix
index daf8d5c4247..3feafc3bb3b 100644
--- a/nixos/modules/services/networking/ejabberd.nix
+++ b/nixos/modules/services/networking/ejabberd.nix
@@ -26,63 +26,63 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable ejabberd server";
+        description = lib.mdDoc "Whether to enable ejabberd server";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.ejabberd;
         defaultText = literalExpression "pkgs.ejabberd";
-        description = "ejabberd server package to use";
+        description = lib.mdDoc "ejabberd server package to use";
       };
 
       user = mkOption {
         type = types.str;
         default = "ejabberd";
-        description = "User under which ejabberd is ran";
+        description = lib.mdDoc "User under which ejabberd is ran";
       };
 
       group = mkOption {
         type = types.str;
         default = "ejabberd";
-        description = "Group under which ejabberd is ran";
+        description = lib.mdDoc "Group under which ejabberd is ran";
       };
 
       spoolDir = mkOption {
         type = types.path;
         default = "/var/lib/ejabberd";
-        description = "Location of the spooldir of ejabberd";
+        description = lib.mdDoc "Location of the spooldir of ejabberd";
       };
 
       logsDir = mkOption {
         type = types.path;
         default = "/var/log/ejabberd";
-        description = "Location of the logfile directory of ejabberd";
+        description = lib.mdDoc "Location of the logfile directory of ejabberd";
       };
 
       configFile = mkOption {
         type = types.nullOr types.path;
-        description = "Configuration file for ejabberd in YAML format";
+        description = lib.mdDoc "Configuration file for ejabberd in YAML format";
         default = null;
       };
 
       ctlConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Configuration of ejabberdctl";
+        description = lib.mdDoc "Configuration of ejabberdctl";
       };
 
       loadDumps = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = "Configuration dumps that should be loaded on the first startup";
+        description = lib.mdDoc "Configuration dumps that should be loaded on the first startup";
         example = literalExpression "[ ./myejabberd.dump ]";
       };
 
       imagemagick = mkOption {
         type = types.bool;
         default = false;
-        description = "Add ImageMagick to server's path; allows for image thumbnailing";
+        description = lib.mdDoc "Add ImageMagick to server's path; allows for image thumbnailing";
       };
     };
 
diff --git a/nixos/modules/services/networking/envoy.nix b/nixos/modules/services/networking/envoy.nix
new file mode 100644
index 00000000000..20cfebb7991
--- /dev/null
+++ b/nixos/modules/services/networking/envoy.nix
@@ -0,0 +1,84 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.envoy;
+  format = pkgs.formats.json { };
+  conf = format.generate "envoy.json" cfg.settings;
+  validateConfig = file:
+    pkgs.runCommand "validate-envoy-conf" { } ''
+      ${pkgs.envoy}/bin/envoy --log-level error --mode validate -c "${file}"
+      cp "${file}" "$out"
+    '';
+
+in
+
+{
+  options.services.envoy = {
+    enable = mkEnableOption (lib.mdDoc "Envoy reverse proxy");
+
+    settings = mkOption {
+      type = format.type;
+      default = { };
+      example = literalExpression ''
+        {
+          admin = {
+            access_log_path = "/dev/null";
+            address = {
+              socket_address = {
+                protocol = "TCP";
+                address = "127.0.0.1";
+                port_value = 9901;
+              };
+            };
+          };
+          static_resources = {
+            listeners = [];
+            clusters = [];
+          };
+        }
+      '';
+      description = lib.mdDoc ''
+        Specify the configuration for Envoy in Nix.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    environment.systemPackages = [ pkgs.envoy ];
+    systemd.services.envoy = {
+      description = "Envoy reverse proxy";
+      after = [ "network-online.target" ];
+      requires = [ "network-online.target" ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        ExecStart = "${pkgs.envoy}/bin/envoy -c ${validateConfig conf}";
+        DynamicUser = true;
+        Restart = "no";
+        CacheDirectory = "envoy";
+        LogsDirectory = "envoy";
+        AmbientCapabilities = "CAP_NET_BIND_SERVICE";
+        CapabilityBoundingSet = "CAP_NET_BIND_SERVICE";
+        RestrictAddressFamilies = "AF_UNIX AF_INET AF_INET6 AF_NETLINK AF_XDP";
+        SystemCallArchitectures = "native";
+        LockPersonality = true;
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        PrivateUsers = false;  # breaks CAP_NET_BIND_SERVICE
+        PrivateDevices = true;
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectProc = "ptraceable";
+        ProtectHostname = true;
+        ProtectSystem = "strict";
+        UMask = "0066";
+        SystemCallFilter = "~@clock @module @mount @reboot @swap @obsolete @cpu-emulation";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/networking/epmd.nix b/nixos/modules/services/networking/epmd.nix
index 75d78476e57..534b8090621 100644
--- a/nixos/modules/services/networking/epmd.nix
+++ b/nixos/modules/services/networking/epmd.nix
@@ -11,7 +11,7 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable socket activation for Erlang Port Mapper Daemon (epmd),
         which acts as a name server on all hosts involved in distributed
         Erlang computations.
@@ -21,7 +21,7 @@ in
       type = types.package;
       default = pkgs.erlang;
       defaultText = literalExpression "pkgs.erlang";
-      description = ''
+      description = lib.mdDoc ''
         The Erlang package to use to get epmd binary. That way you can re-use
         an Erlang runtime that is already installed for other purposes.
       '';
@@ -30,7 +30,7 @@ in
       {
         type = types.str;
         default = "[::]:4369";
-        description = ''
+        description = lib.mdDoc ''
           the listenStream used by the systemd socket.
           see https://www.freedesktop.org/software/systemd/man/systemd.socket.html#ListenStream= for more informations.
           use this to change the port epmd will run on.
diff --git a/nixos/modules/services/networking/ergo.nix b/nixos/modules/services/networking/ergo.nix
index 6e55a7cfff6..033d4d9caf8 100644
--- a/nixos/modules/services/networking/ergo.nix
+++ b/nixos/modules/services/networking/ergo.nix
@@ -33,25 +33,25 @@ in {
   options = {
 
     services.ergo = {
-      enable = mkEnableOption "Ergo service";
+      enable = mkEnableOption (lib.mdDoc "Ergo service");
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/ergo";
-        description = "The data directory for the Ergo node.";
+        description = lib.mdDoc "The data directory for the Ergo node.";
       };
 
       listen = {
         ip = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = "IP address on which the Ergo node should listen.";
+          description = lib.mdDoc "IP address on which the Ergo node should listen.";
         };
 
         port = mkOption {
           type = types.port;
           default = 9006;
-          description = "Listen port for the Ergo node.";
+          description = lib.mdDoc "Listen port for the Ergo node.";
         };
       };
 
@@ -60,20 +60,20 @@ in {
         type = types.nullOr types.str;
         default = null;
         example = "324dcf027dd4a30a932c441f365a25e86b173defa4b8e58948253471b81b72cf";
-        description = "Hex-encoded Blake2b256 hash of an API key as a 64-chars long Base16 string.";
+        description = lib.mdDoc "Hex-encoded Blake2b256 hash of an API key as a 64-chars long Base16 string.";
        };
 
        listen = {
         ip = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = "IP address that the Ergo node API should listen on if <option>api.keyHash</option> is defined.";
+          description = lib.mdDoc "IP address that the Ergo node API should listen on if {option}`api.keyHash` is defined.";
           };
 
         port = mkOption {
           type = types.port;
           default = 9052;
-          description = "Listen port for the API endpoint if <option>api.keyHash</option> is defined.";
+          description = lib.mdDoc "Listen port for the API endpoint if {option}`api.keyHash` is defined.";
         };
        };
       };
@@ -81,26 +81,26 @@ in {
       testnet = mkOption {
          type = types.bool;
          default = false;
-         description = "Connect to testnet network instead of the default mainnet.";
+         description = lib.mdDoc "Connect to testnet network instead of the default mainnet.";
       };
 
       user = mkOption {
         type = types.str;
         default = "ergo";
-        description = "The user as which to run the Ergo node.";
+        description = lib.mdDoc "The user as which to run the Ergo node.";
       };
 
       group = mkOption {
         type = types.str;
         default = cfg.user;
         defaultText = literalExpression "config.${opt.user}";
-        description = "The group as which to run the Ergo node.";
+        description = lib.mdDoc "The group as which to run the Ergo node.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the Ergo node as well as the API.";
+        description = lib.mdDoc "Open ports in the firewall for the Ergo node as well as the API.";
       };
     };
   };
diff --git a/nixos/modules/services/networking/ergochat.nix b/nixos/modules/services/networking/ergochat.nix
index cfaf69fc613..1a70b1f8613 100644
--- a/nixos/modules/services/networking/ergochat.nix
+++ b/nixos/modules/services/networking/ergochat.nix
@@ -4,12 +4,12 @@ in {
   options = {
     services.ergochat = {
 
-      enable = lib.mkEnableOption "Ergo IRC daemon";
+      enable = lib.mkEnableOption (lib.mdDoc "Ergo IRC daemon");
 
       openFilesLimit = lib.mkOption {
         type = lib.types.int;
         default = 1024;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of open files. Limits the clients and server connections.
         '';
       };
@@ -18,15 +18,15 @@ in {
         type = lib.types.path;
         default = (pkgs.formats.yaml {}).generate "ergo.conf" cfg.settings;
         defaultText = "generated config file from <literal>.settings</literal>";
-        description = ''
+        description = lib.mdDoc ''
           Path to configuration file.
-          Setting this will skip any configuration done via <literal>.settings</literal>
+          Setting this will skip any configuration done via `.settings`
         '';
       };
 
       settings = lib.mkOption {
         type = (pkgs.formats.yaml {}).type;
-        description = ''
+        description = lib.mdDoc ''
           Ergo IRC daemon configuration file.
           https://raw.githubusercontent.com/ergochat/ergo/master/default.yaml
         '';
diff --git a/nixos/modules/services/networking/eternal-terminal.nix b/nixos/modules/services/networking/eternal-terminal.nix
index 0dcf3d28f4e..c6b6b04dcf7 100644
--- a/nixos/modules/services/networking/eternal-terminal.nix
+++ b/nixos/modules/services/networking/eternal-terminal.nix
@@ -16,12 +16,12 @@ in
 
     services.eternal-terminal = {
 
-      enable = mkEnableOption "Eternal Terminal server";
+      enable = mkEnableOption (lib.mdDoc "Eternal Terminal server");
 
       port = mkOption {
         default = 2022;
-        type = types.int;
-        description = ''
+        type = types.port;
+        description = lib.mdDoc ''
           The port the server should listen on. Will use the server's default (2022) if not specified.
 
           Make sure to open this port in the firewall if necessary.
@@ -31,7 +31,7 @@ in
       verbosity = mkOption {
         default = 0;
         type = types.enum (lib.range 0 9);
-        description = ''
+        description = lib.mdDoc ''
           The verbosity level (0-9).
         '';
       };
@@ -39,7 +39,7 @@ in
       silent = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, disables all logging.
         '';
       };
@@ -47,7 +47,7 @@ in
       logSize = mkOption {
         default = 20971520;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           The maximum log size.
         '';
       };
diff --git a/nixos/modules/services/networking/expressvpn.nix b/nixos/modules/services/networking/expressvpn.nix
new file mode 100644
index 00000000000..30de6987d31
--- /dev/null
+++ b/nixos/modules/services/networking/expressvpn.nix
@@ -0,0 +1,29 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+{
+  options.services.expressvpn.enable = mkOption {
+    type = types.bool;
+    default = false;
+    description = lib.mdDoc ''
+      Enable the ExpressVPN daemon.
+    '';
+  };
+
+  config = mkIf config.services.expressvpn.enable {
+    boot.kernelModules = [ "tun" ];
+
+    systemd.services.expressvpn = {
+      description = "ExpressVPN Daemon";
+      serviceConfig = {
+        ExecStart = "${pkgs.expressvpn}/bin/expressvpnd";
+        Restart = "on-failure";
+        RestartSec = 5;
+      };
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" "network-online.target" ];
+    };
+  };
+
+  meta.maintainers = with maintainers; [ yureien ];
+}
diff --git a/nixos/modules/services/networking/fakeroute.nix b/nixos/modules/services/networking/fakeroute.nix
index 7916ad4098a..ed6b1a3c4d2 100644
--- a/nixos/modules/services/networking/fakeroute.nix
+++ b/nixos/modules/services/networking/fakeroute.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the fakeroute service.
         '';
       };
@@ -33,7 +33,7 @@ in
           "198.116.142.34"
           "63.199.8.242"
         ];
-        description = ''
+        description = lib.mdDoc ''
          Fake route that will appear after the real
          one to any host running a traceroute.
         '';
diff --git a/nixos/modules/services/networking/ferm.nix b/nixos/modules/services/networking/ferm.nix
index 8e03f30efc0..09151eb0b54 100644
--- a/nixos/modules/services/networking/ferm.nix
+++ b/nixos/modules/services/networking/ferm.nix
@@ -20,7 +20,7 @@ in {
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Ferm Firewall.
           *Warning*: Enabling this service WILL disable the existing NixOS
           firewall! Default firewall rules provided by packages are not
@@ -28,13 +28,13 @@ in {
         '';
       };
       config = mkOption {
-        description = "Verbatim ferm.conf configuration.";
+        description = lib.mdDoc "Verbatim ferm.conf configuration.";
         default = "";
-        defaultText = literalDocBook "empty firewall, allows any traffic";
+        defaultText = literalMD "empty firewall, allows any traffic";
         type = types.lines;
       };
       package = mkOption {
-        description = "The ferm package.";
+        description = lib.mdDoc "The ferm package.";
         type = types.package;
         default = pkgs.ferm;
         defaultText = literalExpression "pkgs.ferm";
diff --git a/nixos/modules/services/networking/firefox-syncserver.md b/nixos/modules/services/networking/firefox-syncserver.md
new file mode 100644
index 00000000000..3ee863343ec
--- /dev/null
+++ b/nixos/modules/services/networking/firefox-syncserver.md
@@ -0,0 +1,55 @@
+# Firefox Sync server {#module-services-firefox-syncserver}
+
+A storage server for Firefox Sync that you can easily host yourself.
+
+## Quickstart {#module-services-firefox-syncserver-quickstart}
+
+The absolute minimal configuration for the sync server looks like this:
+
+```nix
+services.mysql.package = pkgs.mariadb;
+
+services.firefox-syncserver = {
+  enable = true;
+  secrets = builtins.toFile "sync-secrets" ''
+    SYNC_MASTER_SECRET=this-secret-is-actually-leaked-to-/nix/store
+  '';
+  singleNode = {
+    enable = true;
+    hostname = "localhost";
+    url = "http://localhost:5000";
+  };
+};
+```
+
+This will start a sync server that is only accessible locally. Once the services is
+running you can navigate to `about:config` in your Firefox profile and set
+`identity.sync.tokenserver.uri` to `http://localhost:5000/1.0/sync/1.5`. Your browser
+will now use your local sync server for data storage.
+
+::: {.warning}
+This configuration should never be used in production. It is not encrypted and
+stores its secrets in a world-readable location.
+:::
+
+## More detailed setup {#module-services-firefox-syncserver-configuration}
+
+The `firefox-syncserver` service provides a number of options to make setting up
+small deployment easier. These are grouped under the `singleNode` element of the
+option tree and allow simple configuration of the most important parameters.
+
+Single node setup is split into two kinds of options: those that affect the sync
+server itself, and those that affect its surroundings. Options that affect the
+sync server are `capacity`, which configures how many accounts may be active on
+this instance, and `url`, which holds the URL under which the sync server can be
+accessed. The `url` can be configured automatically when using nginx.
+
+Options that affect the surroundings of the sync server are `enableNginx`,
+`enableTLS` and `hostnam`. If `enableNginx` is set the sync server module will
+automatically add an nginx virtual host to the system using `hostname` as the
+domain and set `url` accordingly. If `enableTLS` is set the module will also
+enable ACME certificates on the new virtual host and force all connections to
+be made via TLS.
+
+For actual deployment it is also recommended to store the `secrets` file in a
+secure location.
diff --git a/nixos/modules/services/networking/firefox-syncserver.nix b/nixos/modules/services/networking/firefox-syncserver.nix
new file mode 100644
index 00000000000..c3d9f43f745
--- /dev/null
+++ b/nixos/modules/services/networking/firefox-syncserver.nix
@@ -0,0 +1,317 @@
+{ config, pkgs, lib, options, ... }:
+
+let
+  cfg = config.services.firefox-syncserver;
+  opt = options.services.firefox-syncserver;
+  defaultDatabase = "firefox_syncserver";
+  defaultUser = "firefox-syncserver";
+
+  dbIsLocal = cfg.database.host == "localhost";
+  dbURL = "mysql://${cfg.database.user}@${cfg.database.host}/${cfg.database.name}";
+
+  format = pkgs.formats.toml {};
+  settings = {
+    database_url = dbURL;
+    human_logs = true;
+    tokenserver = {
+      node_type = "mysql";
+      database_url = dbURL;
+      fxa_email_domain = "api.accounts.firefox.com";
+      fxa_oauth_server_url = "https://oauth.accounts.firefox.com/v1";
+      run_migrations = true;
+      # if JWK caching is not enabled the token server must verify tokens
+      # using the fxa api, on a thread pool with a static size.
+      additional_blocking_threads_for_fxa_requests = 10;
+    } // lib.optionalAttrs cfg.singleNode.enable {
+      # Single-node mode is likely to be used on small instances with little
+      # capacity. The default value (0.1) can only ever release capacity when
+      # accounts are removed if the total capacity is 10 or larger to begin
+      # with.
+      # https://github.com/mozilla-services/syncstorage-rs/issues/1313#issuecomment-1145293375
+      node_capacity_release_rate = 1;
+    };
+  };
+  configFile = format.generate "syncstorage.toml" (lib.recursiveUpdate settings cfg.settings);
+  setupScript = pkgs.writeShellScript "firefox-syncserver-setup" ''
+        set -euo pipefail
+        shopt -s inherit_errexit
+
+        schema_configured() {
+          mysql ${cfg.database.name} -Ne 'SHOW TABLES' | grep -q services
+        }
+
+        update_config() {
+          mysql ${cfg.database.name} <<"EOF"
+            BEGIN;
+
+            INSERT INTO `services` (`id`, `service`, `pattern`)
+              VALUES (1, 'sync-1.5', '{node}/1.5/{uid}')
+              ON DUPLICATE KEY UPDATE service='sync-1.5', pattern='{node}/1.5/{uid}';
+            INSERT INTO `nodes` (`id`, `service`, `node`, `available`, `current_load`,
+                                 `capacity`, `downed`, `backoff`)
+              VALUES (1, 1, '${cfg.singleNode.url}', ${toString cfg.singleNode.capacity},
+              0, ${toString cfg.singleNode.capacity}, 0, 0)
+              ON DUPLICATE KEY UPDATE node = '${cfg.singleNode.url}', capacity=${toString cfg.singleNode.capacity};
+
+            COMMIT;
+        EOF
+        }
+
+
+        for (( try = 0; try < 60; try++ )); do
+          if ! schema_configured; then
+            sleep 2
+          else
+            update_config
+            exit 0
+          fi
+        done
+
+        echo "Single-node setup failed"
+        exit 1
+      '';
+in
+
+{
+  options = {
+    services.firefox-syncserver = {
+      enable = lib.mkEnableOption (lib.mdDoc ''
+        the Firefox Sync storage service.
+
+        Out of the box this will not be very useful unless you also configure at least
+        one service and one nodes by inserting them into the mysql database manually, e.g.
+        by running
+
+        ```
+          INSERT INTO `services` (`id`, `service`, `pattern`) VALUES ('1', 'sync-1.5', '{node}/1.5/{uid}');
+          INSERT INTO `nodes` (`id`, `service`, `node`, `available`, `current_load`,
+              `capacity`, `downed`, `backoff`)
+            VALUES ('1', '1', 'https://mydomain.tld', '1', '0', '10', '0', '0');
+        ```
+
+        {option}`${opt.singleNode.enable}` does this automatically when enabled
+      '');
+
+      package = lib.mkOption {
+        type = lib.types.package;
+        default = pkgs.syncstorage-rs;
+        defaultText = lib.literalExpression "pkgs.syncstorage-rs";
+        description = lib.mdDoc ''
+          Package to use.
+        '';
+      };
+
+      database.name = lib.mkOption {
+        # the mysql module does not allow `-quoting without resorting to shell
+        # escaping, so we restrict db names for forward compaitiblity should this
+        # behavior ever change.
+        type = lib.types.strMatching "[a-z_][a-z0-9_]*";
+        default = defaultDatabase;
+        description = lib.mdDoc ''
+          Database to use for storage. Will be created automatically if it does not exist
+          and `config.${opt.database.createLocally}` is set.
+        '';
+      };
+
+      database.user = lib.mkOption {
+        type = lib.types.str;
+        default = defaultUser;
+        description = lib.mdDoc ''
+          Username for database connections.
+        '';
+      };
+
+      database.host = lib.mkOption {
+        type = lib.types.str;
+        default = "localhost";
+        description = lib.mdDoc ''
+          Database host name. `localhost` is treated specially and inserts
+          systemd dependencies, other hostnames or IP addresses of the local machine do not.
+        '';
+      };
+
+      database.createLocally = lib.mkOption {
+        type = lib.types.bool;
+        default = true;
+        description = lib.mdDoc ''
+          Whether to create database and user on the local machine if they do not exist.
+          This includes enabling unix domain socket authentication for the configured user.
+        '';
+      };
+
+      logLevel = lib.mkOption {
+        type = lib.types.str;
+        default = "error";
+        description = lib.mdDoc ''
+          Log level to run with. This can be a simple log level like `error`
+          or `trace`, or a more complicated logging expression.
+        '';
+      };
+
+      secrets = lib.mkOption {
+        type = lib.types.path;
+        description = lib.mdDoc ''
+          A file containing the various secrets. Should be in the format expected by systemd's
+          `EnvironmentFile` directory. Two secrets are currently available:
+          `SYNC_MASTER_SECRET` and
+          `SYNC_TOKENSERVER__FXA_METRICS_HASH_SECRET`.
+        '';
+      };
+
+      singleNode = {
+        enable = lib.mkEnableOption (lib.mdDoc "auto-configuration for a simple single-node setup");
+
+        enableTLS = lib.mkEnableOption (lib.mdDoc "automatic TLS setup");
+
+        enableNginx = lib.mkEnableOption (lib.mdDoc "nginx virtualhost definitions");
+
+        hostname = lib.mkOption {
+          type = lib.types.str;
+          description = lib.mdDoc ''
+            Host name to use for this service.
+          '';
+        };
+
+        capacity = lib.mkOption {
+          type = lib.types.ints.unsigned;
+          default = 10;
+          description = lib.mdDoc ''
+            How many sync accounts are allowed on this server. Setting this value
+            equal to or less than the number of currently active accounts will
+            effectively deny service to accounts not yet registered here.
+          '';
+        };
+
+        url = lib.mkOption {
+          type = lib.types.str;
+          default = "${if cfg.singleNode.enableTLS then "https" else "http"}://${cfg.singleNode.hostname}";
+          defaultText = lib.literalExpression ''
+            ''${if cfg.singleNode.enableTLS then "https" else "http"}://''${config.${opt.singleNode.hostname}}
+          '';
+          description = lib.mdDoc ''
+            URL of the host. If you are not using the automatic webserver proxy setup you will have
+            to change this setting or your sync server may not be functional.
+          '';
+        };
+      };
+
+      settings = lib.mkOption {
+        type = lib.types.submodule {
+          freeformType = format.type;
+
+          options = {
+            port = lib.mkOption {
+              type = lib.types.port;
+              default = 5000;
+              description = lib.mdDoc ''
+                Port to bind to.
+              '';
+            };
+
+            tokenserver.enabled = lib.mkOption {
+              type = lib.types.bool;
+              default = true;
+              description = lib.mdDoc ''
+                Whether to enable the token service as well.
+              '';
+            };
+          };
+        };
+        default = { };
+        description = lib.mdDoc ''
+          Settings for the sync server. These take priority over values computed
+          from NixOS options.
+
+          See the doc comments on the `Settings` structs in
+          <https://github.com/mozilla-services/syncstorage-rs/blob/master/syncstorage/src/settings.rs>
+          and
+          <https://github.com/mozilla-services/syncstorage-rs/blob/master/syncstorage/src/tokenserver/settings.rs>
+          for available options.
+        '';
+      };
+    };
+  };
+
+  config = lib.mkIf cfg.enable {
+    services.mysql = lib.mkIf cfg.database.createLocally {
+      enable = true;
+      ensureDatabases = [ cfg.database.name ];
+      ensureUsers = [{
+        name = cfg.database.user;
+        ensurePermissions = {
+          "${cfg.database.name}.*" = "all privileges";
+        };
+      }];
+    };
+
+    systemd.services.firefox-syncserver = {
+      wantedBy = [ "multi-user.target" ];
+      requires = lib.mkIf dbIsLocal [ "mysql.service" ];
+      after = lib.mkIf dbIsLocal [ "mysql.service" ];
+      restartTriggers = lib.optional cfg.singleNode.enable setupScript;
+      environment.RUST_LOG = cfg.logLevel;
+      serviceConfig = {
+        User = defaultUser;
+        Group = defaultUser;
+        ExecStart = "${cfg.package}/bin/syncstorage --config ${configFile}";
+        Stderr = "journal";
+        EnvironmentFile = lib.mkIf (cfg.secrets != null) "${cfg.secrets}";
+
+        # hardening
+        RemoveIPC = true;
+        CapabilityBoundingSet = [ "" ];
+        DynamicUser = true;
+        NoNewPrivileges = true;
+        PrivateDevices = true;
+        ProtectClock = true;
+        ProtectKernelLogs = true;
+        ProtectControlGroups = true;
+        ProtectKernelModules = true;
+        SystemCallArchitectures = "native";
+        # syncstorage-rs uses python-cffi internally, and python-cffi does not
+        # work with MemoryDenyWriteExecute=true
+        MemoryDenyWriteExecute = false;
+        RestrictNamespaces = true;
+        RestrictSUIDSGID = true;
+        ProtectHostname = true;
+        LockPersonality = true;
+        ProtectKernelTunables = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+        RestrictRealtime = true;
+        ProtectSystem = "strict";
+        ProtectProc = "invisible";
+        ProcSubset = "pid";
+        ProtectHome = true;
+        PrivateUsers = true;
+        PrivateTmp = true;
+        SystemCallFilter = [ "@system-service" "~ @privileged @resources" ];
+        UMask = "0077";
+      };
+    };
+
+    systemd.services.firefox-syncserver-setup = lib.mkIf cfg.singleNode.enable {
+      wantedBy = [ "firefox-syncserver.service" ];
+      requires = [ "firefox-syncserver.service" ] ++ lib.optional dbIsLocal "mysql.service";
+      after = [ "firefox-syncserver.service" ] ++ lib.optional dbIsLocal "mysql.service";
+      path = [ config.services.mysql.package ];
+      serviceConfig.ExecStart = [ "${setupScript}" ];
+    };
+
+    services.nginx.virtualHosts = lib.mkIf cfg.singleNode.enableNginx {
+      ${cfg.singleNode.hostname} = {
+        enableACME = cfg.singleNode.enableTLS;
+        forceSSL = cfg.singleNode.enableTLS;
+        locations."/" = {
+          proxyPass = "http://127.0.0.1:${toString cfg.settings.port}";
+        };
+      };
+    };
+  };
+
+  meta = {
+    maintainers = with lib.maintainers; [ pennae ];
+    # Don't edit the docbook xml directly, edit the md and generate it:
+    # `pandoc firefox-syncserver.md -t docbook --top-level-division=chapter --extract-media=media -f markdown+smart > firefox-syncserver.xml`
+    doc = ./firefox-syncserver.xml;
+  };
+}
diff --git a/nixos/modules/services/networking/firefox-syncserver.xml b/nixos/modules/services/networking/firefox-syncserver.xml
new file mode 100644
index 00000000000..66c81226695
--- /dev/null
+++ b/nixos/modules/services/networking/firefox-syncserver.xml
@@ -0,0 +1,77 @@
+<chapter xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xml:id="module-services-firefox-syncserver">
+  <title>Firefox Sync server</title>
+  <para>
+    A storage server for Firefox Sync that you can easily host yourself.
+  </para>
+  <section xml:id="module-services-firefox-syncserver-quickstart">
+    <title>Quickstart</title>
+    <para>
+      The absolute minimal configuration for the sync server looks like
+      this:
+    </para>
+    <programlisting language="nix">
+services.mysql.package = pkgs.mariadb;
+
+services.firefox-syncserver = {
+  enable = true;
+  secrets = builtins.toFile &quot;sync-secrets&quot; ''
+    SYNC_MASTER_SECRET=this-secret-is-actually-leaked-to-/nix/store
+  '';
+  singleNode = {
+    enable = true;
+    hostname = &quot;localhost&quot;;
+    url = &quot;http://localhost:5000&quot;;
+  };
+};
+</programlisting>
+    <para>
+      This will start a sync server that is only accessible locally.
+      Once the services is running you can navigate to
+      <literal>about:config</literal> in your Firefox profile and set
+      <literal>identity.sync.tokenserver.uri</literal> to
+      <literal>http://localhost:5000/1.0/sync/1.5</literal>. Your
+      browser will now use your local sync server for data storage.
+    </para>
+    <warning>
+      <para>
+        This configuration should never be used in production. It is not
+        encrypted and stores its secrets in a world-readable location.
+      </para>
+    </warning>
+  </section>
+  <section xml:id="module-services-firefox-syncserver-configuration">
+    <title>More detailed setup</title>
+    <para>
+      The <literal>firefox-syncserver</literal> service provides a
+      number of options to make setting up small deployment easier.
+      These are grouped under the <literal>singleNode</literal> element
+      of the option tree and allow simple configuration of the most
+      important parameters.
+    </para>
+    <para>
+      Single node setup is split into two kinds of options: those that
+      affect the sync server itself, and those that affect its
+      surroundings. Options that affect the sync server are
+      <literal>capacity</literal>, which configures how many accounts
+      may be active on this instance, and <literal>url</literal>, which
+      holds the URL under which the sync server can be accessed. The
+      <literal>url</literal> can be configured automatically when using
+      nginx.
+    </para>
+    <para>
+      Options that affect the surroundings of the sync server are
+      <literal>enableNginx</literal>, <literal>enableTLS</literal> and
+      <literal>hostnam</literal>. If <literal>enableNginx</literal> is
+      set the sync server module will automatically add an nginx virtual
+      host to the system using <literal>hostname</literal> as the domain
+      and set <literal>url</literal> accordingly. If
+      <literal>enableTLS</literal> is set the module will also enable
+      ACME certificates on the new virtual host and force all
+      connections to be made via TLS.
+    </para>
+    <para>
+      For actual deployment it is also recommended to store the
+      <literal>secrets</literal> file in a secure location.
+    </para>
+  </section>
+</chapter>
diff --git a/nixos/modules/services/networking/fireqos.nix b/nixos/modules/services/networking/fireqos.nix
index 0b34f0b6b8b..b7f51a89c0e 100644
--- a/nixos/modules/services/networking/fireqos.nix
+++ b/nixos/modules/services/networking/fireqos.nix
@@ -10,7 +10,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         If enabled, FireQOS will be launched with the specified
         configuration given in `config`.
       '';
@@ -28,7 +28,7 @@ in {
           class web commit 50kbit
             match tcp ports 80,443
       '';
-      description = ''
+      description = lib.mdDoc ''
         The FireQOS configuration goes here.
       '';
     };
diff --git a/nixos/modules/services/networking/firewall.nix b/nixos/modules/services/networking/firewall.nix
index c213a5516a4..27119dcc57c 100644
--- a/nixos/modules/services/networking/firewall.nix
+++ b/nixos/modules/services/networking/firewall.nix
@@ -16,7 +16,7 @@
      certain packets anyway, you can insert rules at the start of
      this chain.
 
-   - ‘nixos-fw-rpfilter’ is used as the main chain in the raw table,
+   - ‘nixos-fw-rpfilter’ is used as the main chain in the mangle table,
      called from the built-in ‘PREROUTING’ chain.  If the kernel
      supports it and `cfg.checkReversePath` is set this chain will
      perform a reverse path filter test.
@@ -109,28 +109,28 @@ let
     ip46tables -N nixos-fw
 
     # Clean up rpfilter rules
-    ip46tables -t raw -D PREROUTING -j nixos-fw-rpfilter 2> /dev/null || true
-    ip46tables -t raw -F nixos-fw-rpfilter 2> /dev/null || true
-    ip46tables -t raw -X nixos-fw-rpfilter 2> /dev/null || true
+    ip46tables -t mangle -D PREROUTING -j nixos-fw-rpfilter 2> /dev/null || true
+    ip46tables -t mangle -F nixos-fw-rpfilter 2> /dev/null || true
+    ip46tables -t mangle -X nixos-fw-rpfilter 2> /dev/null || true
 
     ${optionalString (kernelHasRPFilter && (cfg.checkReversePath != false)) ''
       # Perform a reverse-path test to refuse spoofers
-      # For now, we just drop, as the raw table doesn't have a log-refuse yet
-      ip46tables -t raw -N nixos-fw-rpfilter 2> /dev/null || true
-      ip46tables -t raw -A nixos-fw-rpfilter -m rpfilter --validmark ${optionalString (cfg.checkReversePath == "loose") "--loose"} -j RETURN
+      # For now, we just drop, as the mangle table doesn't have a log-refuse yet
+      ip46tables -t mangle -N nixos-fw-rpfilter 2> /dev/null || true
+      ip46tables -t mangle -A nixos-fw-rpfilter -m rpfilter --validmark ${optionalString (cfg.checkReversePath == "loose") "--loose"} -j RETURN
 
       # Allows this host to act as a DHCP4 client without first having to use APIPA
-      iptables -t raw -A nixos-fw-rpfilter -p udp --sport 67 --dport 68 -j RETURN
+      iptables -t mangle -A nixos-fw-rpfilter -p udp --sport 67 --dport 68 -j RETURN
 
       # Allows this host to act as a DHCPv4 server
-      iptables -t raw -A nixos-fw-rpfilter -s 0.0.0.0 -d 255.255.255.255 -p udp --sport 68 --dport 67 -j RETURN
+      iptables -t mangle -A nixos-fw-rpfilter -s 0.0.0.0 -d 255.255.255.255 -p udp --sport 68 --dport 67 -j RETURN
 
       ${optionalString cfg.logReversePathDrops ''
-        ip46tables -t raw -A nixos-fw-rpfilter -j LOG --log-level info --log-prefix "rpfilter drop: "
+        ip46tables -t mangle -A nixos-fw-rpfilter -j LOG --log-level info --log-prefix "rpfilter drop: "
       ''}
-      ip46tables -t raw -A nixos-fw-rpfilter -j DROP
+      ip46tables -t mangle -A nixos-fw-rpfilter -j DROP
 
-      ip46tables -t raw -A PREROUTING -j nixos-fw-rpfilter
+      ip46tables -t mangle -A PREROUTING -j nixos-fw-rpfilter
     ''}
 
     # Accept all traffic on the trusted interfaces.
@@ -218,7 +218,7 @@ let
     ip46tables -D INPUT -j nixos-fw 2>/dev/null || true
 
     ${optionalString (kernelHasRPFilter && (cfg.checkReversePath != false)) ''
-      ip46tables -t raw -D PREROUTING -j nixos-fw-rpfilter 2>/dev/null || true
+      ip46tables -t mangle -D PREROUTING -j nixos-fw-rpfilter 2>/dev/null || true
     ''}
 
     ${cfg.extraStopCommands}
@@ -258,7 +258,7 @@ let
       apply = canonicalizePortList;
       example = [ 22 80 ];
       description =
-        ''
+        lib.mdDoc ''
           List of TCP ports on which incoming connections are
           accepted.
         '';
@@ -269,7 +269,7 @@ let
       default = [ ];
       example = [ { from = 8999; to = 9003; } ];
       description =
-        ''
+        lib.mdDoc ''
           A range of TCP ports on which incoming connections are
           accepted.
         '';
@@ -281,7 +281,7 @@ let
       apply = canonicalizePortList;
       example = [ 53 ];
       description =
-        ''
+        lib.mdDoc ''
           List of open UDP ports.
         '';
     };
@@ -291,7 +291,7 @@ let
       default = [ ];
       example = [ { from = 60000; to = 61000; } ];
       description =
-        ''
+        lib.mdDoc ''
           Range of open UDP ports.
         '';
     };
@@ -310,7 +310,7 @@ in
         type = types.bool;
         default = true;
         description =
-          ''
+          lib.mdDoc ''
             Whether to enable the firewall.  This is a simple stateful
             firewall that blocks connection attempts to unauthorised TCP
             or UDP ports on this machine.  It does not affect packet
@@ -324,8 +324,8 @@ in
         defaultText = literalExpression "pkgs.iptables";
         example = literalExpression "pkgs.iptables-legacy";
         description =
-          ''
-            The iptables package to use for running the firewall service."
+          lib.mdDoc ''
+            The iptables package to use for running the firewall service.
           '';
       };
 
@@ -333,7 +333,7 @@ in
         type = types.bool;
         default = true;
         description =
-          ''
+          lib.mdDoc ''
             Whether to log rejected or dropped incoming connections.
             Note: The logs are found in the kernel logs, i.e. dmesg
             or journalctl -k.
@@ -344,7 +344,7 @@ in
         type = types.bool;
         default = false;
         description =
-          ''
+          lib.mdDoc ''
             Whether to log all rejected or dropped incoming packets.
             This tends to give a lot of log messages, so it's mostly
             useful for debugging.
@@ -357,8 +357,8 @@ in
         type = types.bool;
         default = true;
         description =
-          ''
-            If <option>networking.firewall.logRefusedPackets</option>
+          lib.mdDoc ''
+            If {option}`networking.firewall.logRefusedPackets`
             and this option are enabled, then only log packets
             specifically directed at this machine, i.e., not broadcasts
             or multicasts.
@@ -369,7 +369,7 @@ in
         type = types.bool;
         default = false;
         description =
-          ''
+          lib.mdDoc ''
             If set, refused packets are rejected rather than dropped
             (ignored).  This means that an ICMP "port unreachable" error
             message is sent back to the client (or a TCP RST packet in
@@ -383,7 +383,7 @@ in
         default = [ ];
         example = [ "enp0s2" ];
         description =
-          ''
+          lib.mdDoc ''
             Traffic coming in from these interfaces will be accepted
             unconditionally.  Traffic from the loopback (lo) interface
             will always be accepted.
@@ -394,7 +394,7 @@ in
         type = types.bool;
         default = true;
         description =
-          ''
+          lib.mdDoc ''
             Whether to respond to incoming ICMPv4 echo requests
             ("pings").  ICMPv6 pings are always allowed because the
             larger address space of IPv6 makes network scanning much
@@ -407,7 +407,7 @@ in
         default = null;
         example = "--limit 1/minute --limit-burst 5";
         description =
-          ''
+          lib.mdDoc ''
             If pings are allowed, this allows setting rate limits
             on them.  If non-null, this option should be in the form of
             flags like "--limit 1/minute --limit-burst 5"
@@ -417,10 +417,10 @@ in
       checkReversePath = mkOption {
         type = types.either types.bool (types.enum ["strict" "loose"]);
         default = kernelHasRPFilter;
-        defaultText = literalDocBook "<literal>true</literal> if supported by the chosen kernel";
+        defaultText = literalMD "`true` if supported by the chosen kernel";
         example = "loose";
         description =
-          ''
+          lib.mdDoc ''
             Performs a reverse path filter test on a packet.  If a reply
             to the packet would not be sent via the same interface that
             the packet arrived on, it is refused.
@@ -440,7 +440,7 @@ in
         type = types.bool;
         default = false;
         description =
-          ''
+          lib.mdDoc ''
             Logs dropped packets failing the reverse path filter test if
             the option networking.firewall.checkReversePath is enabled.
           '';
@@ -451,7 +451,7 @@ in
         default = [ ];
         example = [ "ftp" "irc" "sane" "sip" "tftp" "amanda" "h323" "netbios_sn" "pptp" "snmp" ];
         description =
-          ''
+          lib.mdDoc ''
             List of connection-tracking helpers that are auto-loaded.
             The complete list of possible values is given in the example.
 
@@ -471,7 +471,7 @@ in
         type = types.bool;
         default = false;
         description =
-          ''
+          lib.mdDoc ''
             Whether to auto-load connection-tracking helpers.
             See the description at networking.firewall.connectionTrackingModules
 
@@ -484,7 +484,7 @@ in
         default = "";
         example = "iptables -A INPUT -p icmp -j ACCEPT";
         description =
-          ''
+          lib.mdDoc ''
             Additional shell commands executed as part of the firewall
             initialisation script.  These are executed just before the
             final "reject" firewall rule is added, so they can be used
@@ -497,7 +497,7 @@ in
         default = [ ];
         example = literalExpression "[ pkgs.ipset ]";
         description =
-          ''
+          lib.mdDoc ''
             Additional packages to be included in the environment of the system
             as well as the path of networking.firewall.extraCommands.
           '';
@@ -508,7 +508,7 @@ in
         default = "";
         example = "iptables -P INPUT ACCEPT";
         description =
-          ''
+          lib.mdDoc ''
             Additional shell commands executed as part of the firewall
             shutdown script.  These are executed just after the removal
             of the NixOS input rule, or if the service enters a failed
@@ -520,7 +520,7 @@ in
         default = { };
         type = with types; attrsOf (submodule [ { options = commonOptions; } ]);
         description =
-          ''
+          lib.mdDoc ''
             Interface-specific open ports.
           '';
       };
diff --git a/nixos/modules/services/networking/flannel.nix b/nixos/modules/services/networking/flannel.nix
index ac84b3d35a3..6ed4f78ddc9 100644
--- a/nixos/modules/services/networking/flannel.nix
+++ b/nixos/modules/services/networking/flannel.nix
@@ -14,17 +14,17 @@ let
   };
 in {
   options.services.flannel = {
-    enable = mkEnableOption "flannel";
+    enable = mkEnableOption (lib.mdDoc "flannel");
 
     package = mkOption {
-      description = "Package to use for flannel";
+      description = lib.mdDoc "Package to use for flannel";
       type = types.package;
       default = pkgs.flannel;
       defaultText = literalExpression "pkgs.flannel";
     };
 
     publicIp = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         IP accessible by other nodes for inter-host communication.
         Defaults to the IP of the interface being used for communication.
       '';
@@ -33,7 +33,7 @@ in {
     };
 
     iface = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Interface to use (IP or name) for inter-host communication.
         Defaults to the interface for the default route on the machine.
       '';
@@ -43,38 +43,38 @@ in {
 
     etcd = {
       endpoints = mkOption {
-        description = "Etcd endpoints";
+        description = lib.mdDoc "Etcd endpoints";
         type = types.listOf types.str;
         default = ["http://127.0.0.1:2379"];
       };
 
       prefix = mkOption {
-        description = "Etcd key prefix";
+        description = lib.mdDoc "Etcd key prefix";
         type = types.str;
         default = "/coreos.com/network";
       };
 
       caFile = mkOption {
-        description = "Etcd certificate authority file";
+        description = lib.mdDoc "Etcd certificate authority file";
         type = types.nullOr types.path;
         default = null;
       };
 
       certFile = mkOption {
-        description = "Etcd cert file";
+        description = lib.mdDoc "Etcd cert file";
         type = types.nullOr types.path;
         default = null;
       };
 
       keyFile = mkOption {
-        description = "Etcd key file";
+        description = lib.mdDoc "Etcd key file";
         type = types.nullOr types.path;
         default = null;
       };
     };
 
     kubeconfig = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Path to kubeconfig to use for storing flannel config using the
         Kubernetes API
       '';
@@ -83,30 +83,28 @@ in {
     };
 
     network = mkOption {
-      description = " IPv4 network in CIDR format to use for the entire flannel network.";
+      description = lib.mdDoc " IPv4 network in CIDR format to use for the entire flannel network.";
       type = types.str;
     };
 
     nodeName = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Needed when running with Kubernetes as backend as this cannot be auto-detected";
       '';
       type = types.nullOr types.str;
-      default = with config.networking; (hostName + optionalString (domain != null) ".${domain}");
-      defaultText = literalExpression ''
-        with config.networking; (hostName + optionalString (domain != null) ".''${domain}")
-      '';
+      default = config.networking.fqdnOrHostName;
+      defaultText = literalExpression "config.networking.fqdnOrHostName";
       example = "node1.example.com";
     };
 
     storageBackend = mkOption {
-      description = "Determines where flannel stores its configuration at runtime";
+      description = lib.mdDoc "Determines where flannel stores its configuration at runtime";
       type = types.enum ["etcd" "kubernetes"];
       default = "etcd";
     };
 
     subnetLen = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The size of the subnet allocated to each host. Defaults to 24 (i.e. /24)
         unless the Network was configured to be smaller than a /24 in which case
         it is one less than the network.
@@ -116,7 +114,7 @@ in {
     };
 
     subnetMin = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The beginning of IP range which the subnet allocation should start with.
         Defaults to the first subnet of Network.
       '';
@@ -125,7 +123,7 @@ in {
     };
 
     subnetMax = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The end of IP range which the subnet allocation should start with.
         Defaults to the last subnet of Network.
       '';
@@ -134,7 +132,7 @@ in {
     };
 
     backend = mkOption {
-      description = "Type of backend to use and specific configurations for that backend.";
+      description = lib.mdDoc "Type of backend to use and specific configurations for that backend.";
       type = types.attrs;
       default = {
         Type = "vxlan";
@@ -155,10 +153,11 @@ in {
         FLANNELD_ETCD_KEYFILE = cfg.etcd.keyFile;
         FLANNELD_ETCD_CERTFILE = cfg.etcd.certFile;
         FLANNELD_ETCD_CAFILE = cfg.etcd.caFile;
-        ETCDCTL_CERT_FILE = cfg.etcd.certFile;
-        ETCDCTL_KEY_FILE = cfg.etcd.keyFile;
-        ETCDCTL_CA_FILE = cfg.etcd.caFile;
-        ETCDCTL_PEERS = concatStringsSep "," cfg.etcd.endpoints;
+        ETCDCTL_CERT = cfg.etcd.certFile;
+        ETCDCTL_KEY = cfg.etcd.keyFile;
+        ETCDCTL_CACERT = cfg.etcd.caFile;
+        ETCDCTL_ENDPOINTS = concatStringsSep "," cfg.etcd.endpoints;
+        ETCDCTL_API = "3";
       } // optionalAttrs (cfg.storageBackend == "kubernetes") {
         FLANNELD_KUBE_SUBNET_MGR = "true";
         FLANNELD_KUBECONFIG_FILE = cfg.kubeconfig;
@@ -167,7 +166,7 @@ in {
       path = [ pkgs.iptables ];
       preStart = optionalString (cfg.storageBackend == "etcd") ''
         echo "setting network configuration"
-        until ${pkgs.etcd}/bin/etcdctl set /coreos.com/network/config '${builtins.toJSON networkConfig}'
+        until ${pkgs.etcd}/bin/etcdctl put /coreos.com/network/config '${builtins.toJSON networkConfig}'
         do
           echo "setting network configuration, retry"
           sleep 1
diff --git a/nixos/modules/services/networking/freenet.nix b/nixos/modules/services/networking/freenet.nix
index 3da3ab0c7df..e1737e820a5 100644
--- a/nixos/modules/services/networking/freenet.nix
+++ b/nixos/modules/services/networking/freenet.nix
@@ -22,13 +22,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable the Freenet daemon";
+        description = lib.mdDoc "Enable the Freenet daemon";
       };
 
       nice = mkOption {
         type = types.int;
         default = 10;
-        description = "Set the nice level for the Freenet daemon";
+        description = lib.mdDoc "Set the nice level for the Freenet daemon";
       };
 
     };
diff --git a/nixos/modules/services/networking/freeradius.nix b/nixos/modules/services/networking/freeradius.nix
index 7fa3a8fa17f..419a683cb77 100644
--- a/nixos/modules/services/networking/freeradius.nix
+++ b/nixos/modules/services/networking/freeradius.nix
@@ -33,12 +33,12 @@ let
   };
 
   freeradiusConfig = {
-    enable = mkEnableOption "the freeradius server";
+    enable = mkEnableOption (lib.mdDoc "the freeradius server");
 
     configDir = mkOption {
       type = types.path;
       default = "/etc/raddb";
-      description = ''
+      description = lib.mdDoc ''
         The path of the freeradius server configuration directory.
       '';
     };
@@ -46,7 +46,7 @@ let
     debug = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable debug logging for freeradius (-xx
         option). This should not be left on, since it includes
         sensitive data such as passwords in the logs.
diff --git a/nixos/modules/services/networking/frr.nix b/nixos/modules/services/networking/frr.nix
index 45a82b9450a..d350fe3548a 100644
--- a/nixos/modules/services/networking/frr.nix
+++ b/nixos/modules/services/networking/frr.nix
@@ -51,13 +51,13 @@ let
 
   serviceOptions = service:
     {
-      enable = mkEnableOption "the FRR ${toUpper service} routing protocol";
+      enable = mkEnableOption (lib.mdDoc "the FRR ${toUpper service} routing protocol");
 
       configFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/etc/frr/${daemonName service}.conf";
-        description = ''
+        description = lib.mdDoc ''
           Configuration file to use for FRR ${daemonName service}.
           By default the NixOS generated files are used.
         '';
@@ -86,7 +86,7 @@ let
             };
           in
             examples.${service} or "";
-        description = ''
+        description = lib.mdDoc ''
           ${daemonName service} configuration statements.
         '';
       };
@@ -94,7 +94,7 @@ let
       vtyListenAddress = mkOption {
         type = types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           Address to bind to for the VTY interface.
         '';
       };
@@ -102,10 +102,18 @@ let
       vtyListenPort = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           TCP Port to bind to for the VTY interface.
         '';
       };
+
+      extraOptions = mkOption {
+        type = types.listOf types.str;
+        default = [];
+        description = lib.mdDoc ''
+          Extra options for the daemon.
+        '';
+      };
     };
 
 in
@@ -120,7 +128,7 @@ in
           enable = mkOption {
             type = types.bool;
             default = any isEnabled services;
-            description = ''
+            description = lib.mdDoc ''
               Whether to enable the Zebra routing manager.
 
               The Zebra routing manager is automatically enabled
@@ -196,7 +204,8 @@ in
                 PIDFile = "frr/${daemon}.pid";
                 ExecStart = "${pkgs.frr}/libexec/frr/${daemon} -f /etc/frr/${service}.conf"
                   + optionalString (scfg.vtyListenAddress != "") " -A ${scfg.vtyListenAddress}"
-                  + optionalString (scfg.vtyListenPort != null) " -P ${toString scfg.vtyListenPort}";
+                  + optionalString (scfg.vtyListenPort != null) " -P ${toString scfg.vtyListenPort}"
+                  + " " + (concatStringsSep " " scfg.extraOptions);
                 ExecReload = "${pkgs.python3.interpreter} ${pkgs.frr}/libexec/frr/frr-reload.py --reload --daemon ${daemonName service} --bindir ${pkgs.frr}/bin --rundir /run/frr /etc/frr/${service}.conf";
                 Restart = "on-abnormal";
               };
diff --git a/nixos/modules/services/networking/gateone.nix b/nixos/modules/services/networking/gateone.nix
index 3e3a3c1aa94..ac3f3c9bbf2 100644
--- a/nixos/modules/services/networking/gateone.nix
+++ b/nixos/modules/services/networking/gateone.nix
@@ -6,16 +6,16 @@ in
 {
 options = {
     services.gateone = {
-      enable = mkEnableOption "GateOne server";
+      enable = mkEnableOption (lib.mdDoc "GateOne server");
       pidDir = mkOption {
         default = "/run/gateone";
         type = types.path;
-        description = "Path of pid files for GateOne.";
+        description = lib.mdDoc "Path of pid files for GateOne.";
       };
       settingsDir = mkOption {
         default = "/var/lib/gateone";
         type = types.path;
-        description = "Path of configuration files for GateOne.";
+        description = lib.mdDoc "Path of configuration files for GateOne.";
       };
     };
 };
@@ -36,11 +36,11 @@ config = mkIf cfg.enable {
     preStart = ''
       if [ ! -d ${cfg.settingsDir} ] ; then
         mkdir -m 0750 -p ${cfg.settingsDir}
-        chown -R gateone.gateone ${cfg.settingsDir}
+        chown -R gateone:gateone ${cfg.settingsDir}
       fi
       if [ ! -d ${cfg.pidDir} ] ; then
         mkdir -m 0750 -p ${cfg.pidDir}
-        chown -R gateone.gateone ${cfg.pidDir}
+        chown -R gateone:gateone ${cfg.pidDir}
       fi
       '';
     #unitConfig.RequiresMountsFor = "${cfg.settingsDir}";
diff --git a/nixos/modules/services/networking/gdomap.nix b/nixos/modules/services/networking/gdomap.nix
index 3d829cb6913..53ea8b6875d 100644
--- a/nixos/modules/services/networking/gdomap.nix
+++ b/nixos/modules/services/networking/gdomap.nix
@@ -8,7 +8,7 @@ with lib;
   #
   options = {
     services.gdomap = {
-      enable = mkEnableOption "GNUstep Distributed Objects name server";
+      enable = mkEnableOption (lib.mdDoc "GNUstep Distributed Objects name server");
    };
   };
 
diff --git a/nixos/modules/services/networking/ghostunnel.nix b/nixos/modules/services/networking/ghostunnel.nix
index 7a62d378e2c..4902367e2a6 100644
--- a/nixos/modules/services/networking/ghostunnel.nix
+++ b/nixos/modules/services/networking/ghostunnel.nix
@@ -23,60 +23,60 @@ let
       options = {
 
         listen = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Address and port to listen on (can be HOST:PORT, unix:PATH).
           '';
           type = types.str;
         };
 
         target = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Address to forward connections to (can be HOST:PORT or unix:PATH).
           '';
           type = types.str;
         };
 
         keystore = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Path to keystore (combined PEM with cert/key, or PKCS12 keystore).
 
-            NB: storepass is not supported because it would expose credentials via <code>/proc/*/cmdline</code>.
+            NB: storepass is not supported because it would expose credentials via `/proc/*/cmdline`.
 
-            Specify this or <code>cert</code> and <code>key</code>.
+            Specify this or `cert` and `key`.
           '';
           type = types.nullOr types.str;
           default = null;
         };
 
         cert = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Path to certificate (PEM with certificate chain).
 
-            Not required if <code>keystore</code> is set.
+            Not required if `keystore` is set.
           '';
           type = types.nullOr types.str;
           default = null;
         };
 
         key = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Path to certificate private key (PEM with private key).
 
-            Not required if <code>keystore</code> is set.
+            Not required if `keystore` is set.
           '';
           type = types.nullOr types.str;
           default = null;
         };
 
         cacert = mkOption {
-          description = ''
-            Path to CA bundle file (PEM/X509). Uses system trust store if <code>null</code>.
+          description = lib.mdDoc ''
+            Path to CA bundle file (PEM/X509). Uses system trust store if `null`.
           '';
           type = types.nullOr types.str;
         };
 
         disableAuthentication = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Disable client authentication, no client certificate will be required.
           '';
           type = types.bool;
@@ -84,7 +84,7 @@ let
         };
 
         allowAll = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             If true, allow all clients, do not check client cert subject.
           '';
           type = types.bool;
@@ -92,7 +92,7 @@ let
         };
 
         allowCN = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Allow client if common name appears in the list.
           '';
           type = types.listOf types.str;
@@ -100,7 +100,7 @@ let
         };
 
         allowOU = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Allow client if organizational unit name appears in the list.
           '';
           type = types.listOf types.str;
@@ -108,7 +108,7 @@ let
         };
 
         allowDNS = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Allow client if DNS subject alternative name appears in the list.
           '';
           type = types.listOf types.str;
@@ -116,7 +116,7 @@ let
         };
 
         allowURI = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Allow client if URI subject alternative name appears in the list.
           '';
           type = types.listOf types.str;
@@ -124,13 +124,13 @@ let
         };
 
         extraArguments = mkOption {
-          description = "Extra arguments to pass to <code>ghostunnel server</code>";
+          description = lib.mdDoc "Extra arguments to pass to `ghostunnel server`";
           type = types.separatedString " ";
           default = "";
         };
 
         unsafeTarget = mkOption {
-          description = ''
+          description = lib.mdDoc ''
             If set, does not limit target to localhost, 127.0.0.1, [::1], or UNIX sockets.
 
             This is meant to protect against accidental unencrypted traffic on
@@ -213,17 +213,17 @@ in
 {
 
   options = {
-    services.ghostunnel.enable = mkEnableOption "ghostunnel";
+    services.ghostunnel.enable = mkEnableOption (lib.mdDoc "ghostunnel");
 
     services.ghostunnel.package = mkOption {
-      description = "The ghostunnel package to use.";
+      description = lib.mdDoc "The ghostunnel package to use.";
       type = types.package;
       default = pkgs.ghostunnel;
       defaultText = literalExpression "pkgs.ghostunnel";
     };
 
     services.ghostunnel.servers = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Server mode ghostunnels (TLS listener -> plain TCP/UNIX target)
       '';
       type = types.attrsOf (types.submodule module);
diff --git a/nixos/modules/services/networking/git-daemon.nix b/nixos/modules/services/networking/git-daemon.nix
index 6be72505c21..80b15eedbbd 100644
--- a/nixos/modules/services/networking/git-daemon.nix
+++ b/nixos/modules/services/networking/git-daemon.nix
@@ -15,7 +15,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable Git daemon, which allows public hosting of git repositories
           without any access controls. This is mostly intended for read-only access.
 
@@ -31,7 +31,7 @@ in
         type = types.str;
         default = "";
         example = "/srv/git/";
-        description = ''
+        description = lib.mdDoc ''
           Remap all the path requests as relative to the given path. For example,
           if you set base-path to /srv/git, then if you later try to pull
           git://example.com/hello.git, Git daemon will interpret the path as /srv/git/hello.git.
@@ -41,7 +41,7 @@ in
       exportAll = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Publish all directories that look like Git repositories (have the objects
           and refs subdirectories), even if they do not have the git-daemon-export-ok file.
 
@@ -57,7 +57,7 @@ in
         type = types.listOf types.str;
         default = [];
         example = [ "/srv/git" "/home/user/git/repo2" ];
-        description = ''
+        description = lib.mdDoc ''
           A whitelist of paths of git repositories, or directories containing repositories
           all of which would be published. Paths must not end in "/".
 
@@ -70,31 +70,31 @@ in
         type = types.str;
         default = "";
         example = "example.com";
-        description = "Listen on a specific IP address or hostname.";
+        description = lib.mdDoc "Listen on a specific IP address or hostname.";
       };
 
       port = mkOption {
         type = types.port;
         default = 9418;
-        description = "Port to listen on.";
+        description = lib.mdDoc "Port to listen on.";
       };
 
       options = mkOption {
         type = types.str;
         default = "";
-        description = "Extra configuration options to be passed to Git daemon.";
+        description = lib.mdDoc "Extra configuration options to be passed to Git daemon.";
       };
 
       user = mkOption {
         type = types.str;
         default = "git";
-        description = "User under which Git daemon would be running.";
+        description = lib.mdDoc "User under which Git daemon would be running.";
       };
 
       group = mkOption {
         type = types.str;
         default = "git";
-        description = "Group under which Git daemon would be running.";
+        description = lib.mdDoc "Group under which Git daemon would be running.";
       };
 
     };
diff --git a/nixos/modules/services/networking/globalprotect-vpn.nix b/nixos/modules/services/networking/globalprotect-vpn.nix
index 976fdf2b962..36aa9378040 100644
--- a/nixos/modules/services/networking/globalprotect-vpn.nix
+++ b/nixos/modules/services/networking/globalprotect-vpn.nix
@@ -5,7 +5,8 @@ with lib;
 let
   cfg = config.services.globalprotect;
 
-  execStart = if cfg.csdWrapper == null then
+  execStart =
+    if cfg.csdWrapper == null then
       "${pkgs.globalprotect-openconnect}/bin/gpservice"
     else
       "${pkgs.globalprotect-openconnect}/bin/gpservice --csd-wrapper=${cfg.csdWrapper}";
@@ -13,12 +14,26 @@ in
 
 {
   options.services.globalprotect = {
-    enable = mkEnableOption "globalprotect";
+    enable = mkEnableOption (lib.mdDoc "globalprotect");
+
+    settings = mkOption {
+      description = lib.mdDoc ''
+        GlobalProtect-openconnect configuration. For more information, visit
+        <https://github.com/yuezk/GlobalProtect-openconnect/wiki/Configuration>.
+      '';
+      default = { };
+      example = {
+        "vpn1.company.com" = {
+          openconnect-args = "--script=/path/to/vpnc-script";
+        };
+      };
+      type = types.attrs;
+    };
 
     csdWrapper = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         A script that will produce a Host Integrity Protection (HIP) report,
-        as described at <link xlink:href="https://www.infradead.org/openconnect/hip.html" />
+        as described at <https://www.infradead.org/openconnect/hip.html>
       '';
       default = null;
       example = literalExpression ''"''${pkgs.openconnect}/libexec/openconnect/hipreport.sh"'';
@@ -29,12 +44,14 @@ in
   config = mkIf cfg.enable {
     services.dbus.packages = [ pkgs.globalprotect-openconnect ];
 
+    environment.etc."gpservice/gp.conf".text = lib.generators.toINI { } cfg.settings;
+
     systemd.services.gpservice = {
       description = "GlobalProtect openconnect DBus service";
       serviceConfig = {
-        Type="dbus";
-        BusName="com.yuezk.qt.GPService";
-        ExecStart=execStart;
+        Type = "dbus";
+        BusName = "com.yuezk.qt.GPService";
+        ExecStart = execStart;
       };
       wantedBy = [ "multi-user.target" ];
       after = [ "network.target" ];
diff --git a/nixos/modules/services/networking/gnunet.nix b/nixos/modules/services/networking/gnunet.nix
index 5c41967d279..9d1c9746f72 100644
--- a/nixos/modules/services/networking/gnunet.nix
+++ b/nixos/modules/services/networking/gnunet.nix
@@ -47,7 +47,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run the GNUnet daemon.  GNUnet is GNU's anonymous
           peer-to-peer communication and file sharing framework.
         '';
@@ -57,7 +57,7 @@ in
         quota = mkOption {
           type = types.int;
           default = 1024;
-          description = ''
+          description = lib.mdDoc ''
             Maximum file system usage (in MiB) for file sharing.
           '';
         };
@@ -67,7 +67,7 @@ in
         port = mkOption {
           type = types.port;
           default = 2086;  # assigned by IANA
-          description = ''
+          description = lib.mdDoc ''
             The UDP port for use by GNUnet.
           '';
         };
@@ -77,7 +77,7 @@ in
         port = mkOption {
           type = types.port;
           default = 2086;  # assigned by IANA
-          description = ''
+          description = lib.mdDoc ''
             The TCP port for use by GNUnet.
           '';
         };
@@ -87,7 +87,7 @@ in
         maxNetDownBandwidth = mkOption {
           type = types.int;
           default = 50000;
-          description = ''
+          description = lib.mdDoc ''
             Maximum bandwidth usage (in bits per second) for GNUnet
             when downloading data.
           '';
@@ -96,7 +96,7 @@ in
         maxNetUpBandwidth = mkOption {
           type = types.int;
           default = 50000;
-          description = ''
+          description = lib.mdDoc ''
             Maximum bandwidth usage (in bits per second) for GNUnet
             when downloading data.
           '';
@@ -105,7 +105,7 @@ in
         hardNetUpBandwidth = mkOption {
           type = types.int;
           default = 0;
-          description = ''
+          description = lib.mdDoc ''
             Hard bandwidth limit (in bits per second) when uploading
             data.
           '';
@@ -116,14 +116,14 @@ in
         type = types.package;
         default = pkgs.gnunet;
         defaultText = literalExpression "pkgs.gnunet";
-        description = "Overridable attribute of the gnunet package to use.";
+        description = lib.mdDoc "Overridable attribute of the gnunet package to use.";
         example = literalExpression "pkgs.gnunet_git";
       };
 
       extraOptions = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Additional options that will be copied verbatim in `gnunet.conf'.
           See `gnunet.conf(5)' for details.
         '';
diff --git a/nixos/modules/services/networking/go-autoconfig.nix b/nixos/modules/services/networking/go-autoconfig.nix
new file mode 100644
index 00000000000..07c628ae2ca
--- /dev/null
+++ b/nixos/modules/services/networking/go-autoconfig.nix
@@ -0,0 +1,66 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+
+  cfg = config.services.go-autoconfig;
+  format = pkgs.formats.yaml { };
+  configFile = format.generate "config.yml" cfg.settings;
+
+in {
+  options = {
+    services.go-autoconfig = {
+
+      enable = mkEnableOption (mdDoc "IMAP/SMTP autodiscover feature for mail clients");
+
+      settings = mkOption {
+        default = { };
+        description = mdDoc ''
+          Configuration for go-autoconfig. See
+          <https://github.com/L11R/go-autoconfig/blob/master/config.yml>
+          for more information.
+        '';
+        type = types.submodule {
+          freeformType = format.type;
+        };
+        example = literalExpression ''
+          {
+            service_addr = ":1323";
+            domain = "autoconfig.example.org";
+            imap = {
+              server = "example.org";
+              port = 993;
+            };
+            smtp = {
+              server = "example.org";
+              port = 465;
+            };
+          }
+        '';
+      };
+
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    systemd = {
+      services.go-autoconfig = {
+        wantedBy = [ "multi-user.target" ];
+        description = "IMAP/SMTP autodiscover server";
+        after = [ "network.target" ];
+        serviceConfig = {
+          ExecStart = "${pkgs.go-autoconfig}/bin/go-autoconfig -config ${configFile}";
+          Restart = "on-failure";
+          WorkingDirectory = ''${pkgs.go-autoconfig}/'';
+          DynamicUser = true;
+        };
+      };
+    };
+
+  };
+
+  meta.maintainers = with lib.maintainers; [ onny ];
+
+}
diff --git a/nixos/modules/services/networking/go-neb.nix b/nixos/modules/services/networking/go-neb.nix
index 765834fad83..8c04542c47c 100644
--- a/nixos/modules/services/networking/go-neb.nix
+++ b/nixos/modules/services/networking/go-neb.nix
@@ -9,11 +9,11 @@ let
   configFile = settingsFormat.generate "config.yaml" cfg.config;
 in {
   options.services.go-neb = {
-    enable = mkEnableOption "Extensible matrix bot written in Go";
+    enable = mkEnableOption (lib.mdDoc "Extensible matrix bot written in Go");
 
     bindAddress = mkOption {
       type = types.str;
-      description = "Port (and optionally address) to listen on.";
+      description = lib.mdDoc "Port (and optionally address) to listen on.";
       default = ":4050";
     };
 
@@ -21,25 +21,25 @@ in {
       type = types.nullOr types.path;
       default = null;
       example = "/run/keys/go-neb.env";
-      description = ''
+      description = lib.mdDoc ''
         Environment variables from this file will be interpolated into the
-        final config file using envsubst with this syntax: <literal>$ENVIRONMENT</literal>
-        or <literal>''${VARIABLE}</literal>.
-        The file should contain lines formatted as <literal>SECRET_VAR=SECRET_VALUE</literal>.
+        final config file using envsubst with this syntax: `$ENVIRONMENT`
+        or `''${VARIABLE}`.
+        The file should contain lines formatted as `SECRET_VAR=SECRET_VALUE`.
         This is useful to avoid putting secrets into the nix store.
       '';
     };
 
     baseUrl = mkOption {
       type = types.str;
-      description = "Public-facing endpoint that can receive webhooks.";
+      description = lib.mdDoc "Public-facing endpoint that can receive webhooks.";
     };
 
     config = mkOption {
       inherit (settingsFormat) type;
-      description = ''
-        Your <filename>config.yaml</filename> as a Nix attribute set.
-        See <link xlink:href="https://github.com/matrix-org/go-neb/blob/master/config.sample.yaml">config.sample.yaml</link>
+      description = lib.mdDoc ''
+        Your {file}`config.yaml` as a Nix attribute set.
+        See [config.sample.yaml](https://github.com/matrix-org/go-neb/blob/master/config.sample.yaml)
         for possible options.
       '';
     };
diff --git a/nixos/modules/services/networking/go-shadowsocks2.nix b/nixos/modules/services/networking/go-shadowsocks2.nix
index afbd7ea27c6..d9c4a2421d7 100644
--- a/nixos/modules/services/networking/go-shadowsocks2.nix
+++ b/nixos/modules/services/networking/go-shadowsocks2.nix
@@ -5,11 +5,11 @@ let
   cfg = config.services.go-shadowsocks2.server;
 in {
   options.services.go-shadowsocks2.server = {
-    enable = mkEnableOption "go-shadowsocks2 server";
+    enable = mkEnableOption (lib.mdDoc "go-shadowsocks2 server");
 
     listenAddress = mkOption {
       type = types.str;
-      description = "Server listen address or URL";
+      description = lib.mdDoc "Server listen address or URL";
       example = "ss://AEAD_CHACHA20_POLY1305:your-password@:8488";
     };
   };
diff --git a/nixos/modules/services/networking/gobgpd.nix b/nixos/modules/services/networking/gobgpd.nix
index 29ef9a5cf1e..b22242edaad 100644
--- a/nixos/modules/services/networking/gobgpd.nix
+++ b/nixos/modules/services/networking/gobgpd.nix
@@ -8,14 +8,14 @@ let
   confFile = format.generate "gobgpd.conf" cfg.settings;
 in {
   options.services.gobgpd = {
-    enable = mkEnableOption "GoBGP Routing Daemon";
+    enable = mkEnableOption (lib.mdDoc "GoBGP Routing Daemon");
 
     settings = mkOption {
       type = format.type;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         GoBGP configuration. Refer to
-        <link xlink:href="https://github.com/osrg/gobgp#documentation"/>
+        <https://github.com/osrg/gobgp#documentation>
         for details on supported values.
       '';
       example = literalExpression ''
diff --git a/nixos/modules/services/networking/gvpe.nix b/nixos/modules/services/networking/gvpe.nix
index 4fad37ba15e..2279ceee2f5 100644
--- a/nixos/modules/services/networking/gvpe.nix
+++ b/nixos/modules/services/networking/gvpe.nix
@@ -42,12 +42,12 @@ in
 {
   options = {
     services.gvpe = {
-      enable = lib.mkEnableOption "gvpe";
+      enable = lib.mkEnableOption (lib.mdDoc "gvpe");
 
       nodename = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description =''
+        description =lib.mdDoc ''
           GVPE node name
         '';
       };
@@ -68,7 +68,7 @@ in
           on alpha if-up = if-up-0
           on alpha pid-file = /var/gvpe/gvpe.pid
         '';
-        description = ''
+        description = lib.mdDoc ''
           GVPE config contents
         '';
       };
@@ -76,14 +76,14 @@ in
         default = null;
         type = types.nullOr types.path;
         example = "/root/my-gvpe-conf";
-        description = ''
+        description = lib.mdDoc ''
           GVPE config file, if already present
         '';
       };
       ipAddress = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           IP address to assign to GVPE interface
         '';
       };
@@ -91,14 +91,14 @@ in
         default = null;
         type = types.nullOr types.str;
         example = "10.0.0.0/8";
-        description = ''
+        description = lib.mdDoc ''
           IP subnet assigned to GVPE network
         '';
       };
       customIFSetup = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Additional commands to apply in ifup script
         '';
       };
diff --git a/nixos/modules/services/networking/hans.nix b/nixos/modules/services/networking/hans.nix
index 2639b4b6800..ffb2ee841c6 100644
--- a/nixos/modules/services/networking/hans.nix
+++ b/nixos/modules/services/networking/hans.nix
@@ -19,12 +19,12 @@ in
     services.hans = {
       clients = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Each attribute of this option defines a systemd service that
           runs hans. Many or none may be defined.
           The name of each service is
-          <literal>hans-<replaceable>name</replaceable></literal>
-          where <replaceable>name</replaceable> is the name of the
+          `hans-«name»`
+          where «name» is the name of the
           corresponding attribute name.
         '';
         example = literalExpression ''
@@ -41,21 +41,21 @@ in
             server = mkOption {
               type = types.str;
               default = "";
-              description = "IP address of server running hans";
+              description = lib.mdDoc "IP address of server running hans";
               example = "192.0.2.1";
             };
 
             extraConfig = mkOption {
               type = types.str;
               default = "";
-              description = "Additional command line parameters";
+              description = lib.mdDoc "Additional command line parameters";
               example = "-v";
             };
 
             passwordFile = mkOption {
               type = types.str;
               default = "";
-              description = "File that containts password";
+              description = lib.mdDoc "File that containts password";
             };
 
           };
@@ -66,33 +66,33 @@ in
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = "enable hans server";
+          description = lib.mdDoc "enable hans server";
         };
 
         ip = mkOption {
           type = types.str;
           default = "";
-          description = "The assigned ip range";
+          description = lib.mdDoc "The assigned ip range";
           example = "198.51.100.0";
         };
 
         respondToSystemPings = mkOption {
           type = types.bool;
           default = false;
-          description = "Force hans respond to ordinary pings";
+          description = lib.mdDoc "Force hans respond to ordinary pings";
         };
 
         extraConfig = mkOption {
           type = types.str;
           default = "";
-          description = "Additional command line parameters";
+          description = lib.mdDoc "Additional command line parameters";
           example = "-v";
         };
 
         passwordFile = mkOption {
           type = types.str;
           default = "";
-          description = "File that containts password";
+          description = lib.mdDoc "File that containts password";
         };
       };
 
diff --git a/nixos/modules/services/networking/haproxy.nix b/nixos/modules/services/networking/haproxy.nix
index e9d72b35499..e0b686434b6 100644
--- a/nixos/modules/services/networking/haproxy.nix
+++ b/nixos/modules/services/networking/haproxy.nix
@@ -20,7 +20,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable HAProxy, the reliable, high performance TCP/HTTP
           load balancer.
         '';
@@ -29,21 +29,21 @@ with lib;
       user = mkOption {
         type = types.str;
         default = "haproxy";
-        description = "User account under which haproxy runs.";
+        description = lib.mdDoc "User account under which haproxy runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "haproxy";
-        description = "Group account under which haproxy runs.";
+        description = lib.mdDoc "Group account under which haproxy runs.";
       };
 
       config = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Contents of the HAProxy configuration file,
-          <filename>haproxy.conf</filename>.
+          {file}`haproxy.conf`.
         '';
       };
     };
diff --git a/nixos/modules/services/networking/headscale.nix b/nixos/modules/services/networking/headscale.nix
index 091d2a938cd..0334c5a00ba 100644
--- a/nixos/modules/services/networking/headscale.nix
+++ b/nixos/modules/services/networking/headscale.nix
@@ -12,13 +12,13 @@ in
 {
   options = {
     services.headscale = {
-      enable = mkEnableOption "headscale, Open Source coordination server for Tailscale";
+      enable = mkEnableOption (lib.mdDoc "headscale, Open Source coordination server for Tailscale");
 
       package = mkOption {
         type = types.package;
         default = pkgs.headscale;
         defaultText = literalExpression "pkgs.headscale";
-        description = ''
+        description = lib.mdDoc ''
           Which headscale package to use for the running server.
         '';
       };
@@ -26,33 +26,35 @@ in
       user = mkOption {
         default = "headscale";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User account under which headscale runs.
-          <note><para>
+
+          ::: {.note}
           If left as the default value this user will automatically be created
           on system activation, otherwise you are responsible for
           ensuring the user exists before the headscale service starts.
-          </para></note>
+          :::
         '';
       };
 
       group = mkOption {
         default = "headscale";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Group under which headscale runs.
-          <note><para>
+
+          ::: {.note}
           If left as the default value this group will automatically be created
           on system activation, otherwise you are responsible for
           ensuring the user exists before the headscale service starts.
-          </para></note>
+          :::
         '';
       };
 
       serverUrl = mkOption {
         type = types.str;
         default = "http://127.0.0.1:8080";
-        description = ''
+        description = lib.mdDoc ''
           The url clients will connect to.
         '';
         example = "https://myheadscale.example.com:443";
@@ -61,7 +63,7 @@ in
       address = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = ''
+        description = lib.mdDoc ''
           Listening address of headscale.
         '';
         example = "0.0.0.0";
@@ -70,7 +72,7 @@ in
       port = mkOption {
         type = types.port;
         default = 8080;
-        description = ''
+        description = lib.mdDoc ''
           Listening port of headscale.
         '';
         example = 443;
@@ -79,7 +81,7 @@ in
       privateKeyFile = mkOption {
         type = types.path;
         default = "${dataDir}/private.key";
-        description = ''
+        description = lib.mdDoc ''
           Path to private key file, generated automatically if it does not exist.
         '';
       };
@@ -88,18 +90,18 @@ in
         urls = mkOption {
           type = types.listOf types.str;
           default = [ "https://controlplane.tailscale.com/derpmap/default" ];
-          description = ''
+          description = lib.mdDoc ''
             List of urls containing DERP maps.
-            See <link xlink:href="https://tailscale.com/blog/how-tailscale-works/">How Tailscale works</link> for more information on DERP maps.
+            See [How Tailscale works](https://tailscale.com/blog/how-tailscale-works/) for more information on DERP maps.
           '';
         };
 
         paths = mkOption {
           type = types.listOf types.path;
           default = [ ];
-          description = ''
+          description = lib.mdDoc ''
             List of file paths containing DERP maps.
-            See <link xlink:href="https://tailscale.com/blog/how-tailscale-works/">How Tailscale works</link> for more information on DERP maps.
+            See [How Tailscale works](https://tailscale.com/blog/how-tailscale-works/) for more information on DERP maps.
           '';
         };
 
@@ -107,7 +109,7 @@ in
         autoUpdate = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to automatically update DERP maps on a set frequency.
           '';
           example = false;
@@ -116,7 +118,7 @@ in
         updateFrequency = mkOption {
           type = types.str;
           default = "24h";
-          description = ''
+          description = lib.mdDoc ''
             Frequency to update DERP maps.
           '';
           example = "5m";
@@ -127,7 +129,7 @@ in
       ephemeralNodeInactivityTimeout = mkOption {
         type = types.str;
         default = "30m";
-        description = ''
+        description = lib.mdDoc ''
           Time before an inactive ephemeral node is deleted.
         '';
         example = "5m";
@@ -138,58 +140,58 @@ in
           type = types.enum [ "sqlite3" "postgres" ];
           example = "postgres";
           default = "sqlite3";
-          description = "Database engine to use.";
+          description = lib.mdDoc "Database engine to use.";
         };
 
         host = mkOption {
           type = types.nullOr types.str;
           default = null;
           example = "127.0.0.1";
-          description = "Database host address.";
+          description = lib.mdDoc "Database host address.";
         };
 
         port = mkOption {
           type = types.nullOr types.port;
           default = null;
           example = 3306;
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = mkOption {
           type = types.nullOr types.str;
           default = null;
           example = "headscale";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = mkOption {
           type = types.nullOr types.str;
           default = null;
           example = "headscale";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/headscale-dbpassword";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
 
         path = mkOption {
           type = types.nullOr types.str;
           default = "${dataDir}/db.sqlite";
-          description = "Path to the sqlite3 database file.";
+          description = lib.mdDoc "Path to the sqlite3 database file.";
         };
       };
 
       logLevel = mkOption {
         type = types.str;
         default = "info";
-        description = ''
+        description = lib.mdDoc ''
           headscale log level.
         '';
         example = "debug";
@@ -199,7 +201,7 @@ in
         nameservers = mkOption {
           type = types.listOf types.str;
           default = [ "1.1.1.1" ];
-          description = ''
+          description = lib.mdDoc ''
             List of nameservers to pass to Tailscale clients.
           '';
         };
@@ -207,7 +209,7 @@ in
         domains = mkOption {
           type = types.listOf types.str;
           default = [ ];
-          description = ''
+          description = lib.mdDoc ''
             Search domains to inject to Tailscale clients.
           '';
           example = [ "mydomain.internal" ];
@@ -216,7 +218,7 @@ in
         magicDns = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to use [MagicDNS](https://tailscale.com/kb/1081/magicdns/).
             Only works if there is at least a nameserver defined.
           '';
@@ -226,12 +228,12 @@ in
         baseDomain = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Defines the base domain to create the hostnames for MagicDNS.
-            <option>baseDomain</option> must be a FQDNs, without the trailing dot.
+            {option}`baseDomain` must be a FQDNs, without the trailing dot.
             The FQDN of the hosts will be
-            <literal>hostname.namespace.base_domain</literal> (e.g.
-            <literal>myhost.mynamespace.example.com</literal>).
+            `hostname.namespace.base_domain` (e.g.
+            `myhost.mynamespace.example.com`).
           '';
         };
       };
@@ -240,7 +242,7 @@ in
         issuer = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             URL to OpenID issuer.
           '';
           example = "https://openid.example.com";
@@ -249,7 +251,7 @@ in
         clientId = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             OpenID Connect client ID.
           '';
         };
@@ -257,7 +259,7 @@ in
         clientSecretFile = mkOption {
           type = types.nullOr types.path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Path to OpenID Connect client secret file.
           '';
         };
@@ -265,7 +267,7 @@ in
         domainMap = mkOption {
           type = types.attrsOf types.str;
           default = { };
-          description = ''
+          description = lib.mdDoc ''
             Domain map is used to map incomming users (by their email) to
             a namespace. The key can be a string, or regex.
           '';
@@ -281,25 +283,25 @@ in
           hostname = mkOption {
             type = types.nullOr types.str;
             default = "";
-            description = ''
+            description = lib.mdDoc ''
               Domain name to request a TLS certificate for.
             '';
           };
           challengeType = mkOption {
-            type = types.enum [ "TLS_ALPN-01" "HTTP-01" ];
+            type = types.enum [ "TLS-ALPN-01" "HTTP-01" ];
             default = "HTTP-01";
-            description = ''
+            description = lib.mdDoc ''
               Type of ACME challenge to use, currently supported types:
-              <literal>HTTP-01</literal> or <literal>TLS_ALPN-01</literal>.
+              `HTTP-01` or `TLS-ALPN-01`.
             '';
           };
           httpListen = mkOption {
             type = types.nullOr types.str;
             default = ":http";
-            description = ''
+            description = lib.mdDoc ''
               When HTTP-01 challenge is chosen, letsencrypt must set up a
               verification endpoint, and it will be listening on:
-              <literal>:http = port 80</literal>.
+              `:http = port 80`.
             '';
           };
         };
@@ -307,14 +309,14 @@ in
         certFile = mkOption {
           type = types.nullOr types.path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Path to already created certificate.
           '';
         };
         keyFile = mkOption {
           type = types.nullOr types.path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Path to key for already created certificate.
           '';
         };
@@ -323,7 +325,7 @@ in
       aclPolicyFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to a file containg ACL policies.
         '';
       };
@@ -331,10 +333,10 @@ in
       settings = mkOption {
         type = settingsFormat.type;
         default = { };
-        description = ''
-          Overrides to <filename>config.yaml</filename> as a Nix attribute set.
+        description = lib.mdDoc ''
+          Overrides to {file}`config.yaml` as a Nix attribute set.
           This option is ideal for overriding settings not exposed as Nix options.
-          Check the <link xlink:href="https://github.com/juanfont/headscale/blob/main/config-example.yaml">example config</link>
+          Check the [example config](https://github.com/juanfont/headscale/blob/main/config-example.yaml)
           for possible options.
         '';
       };
@@ -429,12 +431,16 @@ in
       wantedBy = [ "multi-user.target" ];
       restartTriggers = [ configFile ];
 
+      environment.GIN_MODE = "release";
+
       script = ''
         ${optionalString (cfg.database.passwordFile != null) ''
           export HEADSCALE_DB_PASS="$(head -n1 ${escapeShellArg cfg.database.passwordFile})"
         ''}
 
-        export HEADSCALE_OIDC_CLIENT_SECRET="$(head -n1 ${escapeShellArg cfg.openIdConnect.clientSecretFile})"
+        ${optionalString (cfg.openIdConnect.clientSecretFile != null) ''
+          export HEADSCALE_OIDC_CLIENT_SECRET="$(head -n1 ${escapeShellArg cfg.openIdConnect.clientSecretFile})"
+        ''}
         exec ${cfg.package}/bin/headscale serve
       '';
 
@@ -479,7 +485,7 @@ in
           NoNewPrivileges = true;
           LockPersonality = true;
           RestrictRealtime = true;
-          SystemCallFilter = [ "@system-service" "~@priviledged" "@chown" ];
+          SystemCallFilter = [ "@system-service" "~@privileged" "@chown" ];
           SystemCallArchitectures = "native";
           RestrictAddressFamilies = "AF_INET AF_INET6 AF_UNIX";
         };
diff --git a/nixos/modules/services/networking/hostapd.nix b/nixos/modules/services/networking/hostapd.nix
index f719ff59cc7..63bb44256dd 100644
--- a/nixos/modules/services/networking/hostapd.nix
+++ b/nixos/modules/services/networking/hostapd.nix
@@ -53,13 +53,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable putting a wireless interface into infrastructure mode,
           allowing other wireless devices to associate with the wireless
           interface and do wireless networking. A simple access point will
-          <option>enable hostapd.wpa</option>,
-          <option>hostapd.wpaPassphrase</option>, and
-          <option>hostapd.ssid</option>, as well as DHCP on the wireless
+          {option}`enable hostapd.wpa`,
+          {option}`hostapd.wpaPassphrase`, and
+          {option}`hostapd.ssid`, as well as DHCP on the wireless
           interface to provide IP addresses to the associated stations, and
           NAT (from the wireless interface to an upstream interface).
         '';
@@ -69,15 +69,15 @@ in
         default = "";
         example = "wlp2s0";
         type = types.str;
-        description = ''
-          The interfaces <command>hostapd</command> will use.
+        description = lib.mdDoc ''
+          The interfaces {command}`hostapd` will use.
         '';
       };
 
       noScan = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Do not scan for overlapping BSSs in HT40+/- mode.
           Caution: turning this on will violate regulatory requirements!
         '';
@@ -87,8 +87,8 @@ in
         default = "nl80211";
         example = "hostapd";
         type = types.str;
-        description = ''
-          Which driver <command>hostapd</command> will use.
+        description = lib.mdDoc ''
+          Which driver {command}`hostapd` will use.
           Most applications will probably use the default.
         '';
       };
@@ -97,13 +97,13 @@ in
         default = "nixos";
         example = "mySpecialSSID";
         type = types.str;
-        description = "SSID to be used in IEEE 802.11 management frames.";
+        description = lib.mdDoc "SSID to be used in IEEE 802.11 management frames.";
       };
 
       hwMode = mkOption {
         default = "g";
         type = types.enum [ "a" "b" "g" ];
-        description = ''
+        description = lib.mdDoc ''
           Operation mode.
           (a = IEEE 802.11a, b = IEEE 802.11b, g = IEEE 802.11g).
         '';
@@ -113,11 +113,11 @@ in
         default = 7;
         example = 11;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Channel number (IEEE 802.11)
           Please note that some drivers do not use this value from
-          <command>hostapd</command> and the channel will need to be configured
-          separately with <command>iwconfig</command>.
+          {command}`hostapd` and the channel will need to be configured
+          separately with {command}`iwconfig`.
         '';
       };
 
@@ -125,15 +125,15 @@ in
         default = "wheel";
         example = "network";
         type = types.str;
-        description = ''
-          Members of this group can control <command>hostapd</command>.
+        description = lib.mdDoc ''
+          Members of this group can control {command}`hostapd`.
         '';
       };
 
       wpa = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Enable WPA (IEEE 802.11i/D3.0) to authenticate with the access point.
         '';
       };
@@ -142,7 +142,7 @@ in
         default = "my_sekret";
         example = "any_64_char_string";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           WPA-PSK (pre-shared-key) passphrase. Clients will need this
           passphrase to associate with this access point.
           Warning: This passphrase will get put into a world-readable file in
@@ -153,7 +153,7 @@ in
       logLevel = mkOption {
         default = 2;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Levels (minimum value for logged events):
           0 = verbose debugging
           1 = debugging
@@ -167,7 +167,7 @@ in
         default = null;
         example = "US";
         type = with types; nullOr str;
-        description = ''
+        description = lib.mdDoc ''
           Country code (ISO/IEC 3166-1). Used to set regulatory domain.
           Set as needed to indicate country in which device is operating.
           This can limit available channels and transmit power.
@@ -187,7 +187,7 @@ in
           ht_capab=[HT40-][SHORT-GI-40][DSSS_CCK-40]
           '';
         type = types.lines;
-        description = "Extra configuration options to put in hostapd.conf.";
+        description = lib.mdDoc "Extra configuration options to put in hostapd.conf.";
       };
     };
   };
@@ -199,7 +199,7 @@ in
 
     environment.systemPackages =  [ pkgs.hostapd ];
 
-    services.udev.packages = optional (cfg.countryCode != null) [ pkgs.crda ];
+    services.udev.packages = optionals (cfg.countryCode != null) [ pkgs.crda ];
 
     systemd.services.hostapd =
       { description = "hostapd wireless AP";
diff --git a/nixos/modules/services/networking/htpdate.nix b/nixos/modules/services/networking/htpdate.nix
index 6954e5b060c..8b9bb2888da 100644
--- a/nixos/modules/services/networking/htpdate.nix
+++ b/nixos/modules/services/networking/htpdate.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable htpdate daemon.
         '';
       };
@@ -27,7 +27,7 @@ in
       extraOptions = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Additional command line arguments to pass to htpdate.
         '';
       };
@@ -35,7 +35,7 @@ in
       servers = mkOption {
         type = types.listOf types.str;
         default = [ "www.google.com" ];
-        description = ''
+        description = lib.mdDoc ''
           HTTP servers to use for time synchronization.
         '';
       };
@@ -44,7 +44,7 @@ in
         type = types.str;
         default = "";
         example = "127.0.0.1:8118";
-        description = ''
+        description = lib.mdDoc ''
           HTTP proxy used for requests.
         '';
       };
diff --git a/nixos/modules/services/networking/https-dns-proxy.nix b/nixos/modules/services/networking/https-dns-proxy.nix
index 85d6c362b46..87eb23ea458 100644
--- a/nixos/modules/services/networking/https-dns-proxy.nix
+++ b/nixos/modules/services/networking/https-dns-proxy.nix
@@ -20,19 +20,23 @@ let
       ips = [ "9.9.9.9" "149.112.112.112" ];
       url = "https://dns.quad9.net/dns-query";
     };
+    opendns = {
+      ips = [ "208.67.222.222" "208.67.220.220" ];
+      url = "https://doh.opendns.com/dns-query";
+    };
+    custom = {
+      inherit (cfg.provider) ips url;
+    };
   };
 
   defaultProvider = "quad9";
 
   providerCfg =
-    let
-      isCustom = cfg.provider.kind == "custom";
-    in
-    lib.concatStringsSep " " [
+    concatStringsSep " " [
       "-b"
-      (concatStringsSep "," (if isCustom then cfg.provider.ips else providers."${cfg.provider.kind}".ips))
+      (concatStringsSep "," providers."${cfg.provider.kind}".ips)
       "-r"
-      (if isCustom then cfg.provider.url else providers."${cfg.provider.kind}".url)
+      providers."${cfg.provider.kind}".url
     ];
 
 in
@@ -42,50 +46,52 @@ in
   ###### interface
 
   options.services.https-dns-proxy = {
-    enable = mkEnableOption "https-dns-proxy daemon";
+    enable = mkEnableOption (lib.mdDoc "https-dns-proxy daemon");
 
     address = mkOption {
-      description = "The address on which to listen";
+      description = lib.mdDoc "The address on which to listen";
       type = types.str;
       default = "127.0.0.1";
     };
 
     port = mkOption {
-      description = "The port on which to listen";
+      description = lib.mdDoc "The port on which to listen";
       type = types.port;
       default = 5053;
     };
 
     provider = {
       kind = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The upstream provider to use or custom in case you do not trust any of
           the predefined providers or just want to use your own.
 
-          The default is ${defaultProvider} and there are privacy and security trade-offs
-          when using any upstream provider. Please consider that before using any
-          of them.
+          The default is ${defaultProvider} and there are privacy and security
+          trade-offs when using any upstream provider. Please consider that
+          before using any of them.
+
+          Supported providers: ${concatStringsSep ", " (builtins.attrNames providers)}
 
-          If you pick a custom provider, you will need to provide the bootstrap
-          IP addresses as well as the resolver https URL.
+          If you pick the custom provider, you will need to provide the
+          bootstrap IP addresses as well as the resolver https URL.
         '';
-        type = types.enum ((builtins.attrNames providers) ++ [ "custom" ]);
+        type = types.enum (builtins.attrNames providers);
         default = defaultProvider;
       };
 
       ips = mkOption {
-        description = "The custom provider IPs";
+        description = lib.mdDoc "The custom provider IPs";
         type = types.listOf types.str;
       };
 
       url = mkOption {
-        description = "The custom provider URL";
+        description = lib.mdDoc "The custom provider URL";
         type = types.str;
       };
     };
 
     preferIPv4 = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         https_dns_proxy will by default use IPv6 and fail if it is not available.
         To play it safe, we choose IPv4.
       '';
@@ -94,7 +100,7 @@ in
     };
 
     extraArgs = mkOption {
-      description = "Additional arguments to pass to the process.";
+      description = lib.mdDoc "Additional arguments to pass to the process.";
       type = types.listOf types.str;
       default = [ "-v" ];
     };
@@ -105,14 +111,18 @@ in
   config = lib.mkIf cfg.enable {
     systemd.services.https-dns-proxy = {
       description = "DNS to DNS over HTTPS (DoH) proxy";
+      requires = [ "network.target" ];
       after = [ "network.target" ];
+      wants = [ "nss-lookup.target" ];
+      before = [ "nss-lookup.target" ];
       wantedBy = [ "multi-user.target" ];
       serviceConfig = rec {
         Type = "exec";
         DynamicUser = true;
+        ProtectHome = "tmpfs";
         ExecStart = lib.concatStringsSep " " (
           [
-            "${pkgs.https-dns-proxy}/bin/https_dns_proxy"
+            (lib.getExe pkgs.https-dns-proxy)
             "-a ${toString cfg.address}"
             "-p ${toString cfg.port}"
             "-l -"
diff --git a/nixos/modules/services/networking/hylafax/options.nix b/nixos/modules/services/networking/hylafax/options.nix
index 8f621b61002..82c144236f3 100644
--- a/nixos/modules/services/networking/hylafax/options.nix
+++ b/nixos/modules/services/networking/hylafax/options.nix
@@ -37,17 +37,17 @@ let
       name = mkOption {
         type = nonEmptyStr;
         example = "ttyS1";
-        description = ''
+        description = lib.mdDoc ''
           Name of modem device,
-          will be searched for in <filename>/dev</filename>.
+          will be searched for in {file}`/dev`.
         '';
       };
       type = mkOption {
         type = nonEmptyStr;
         example = "cirrus";
-        description = ''
+        description = lib.mdDoc ''
           Name of modem configuration file,
-          will be searched for in <filename>config</filename>
+          will be searched for in {file}`config`
           in the spooling area directory.
         '';
       };
@@ -59,11 +59,11 @@ let
           FAXNumber = "123456";
           LocalIdentifier = "LostInBerlin";
         };
-        description = ''
+        description = lib.mdDoc ''
           Attribute set of values for the given modem.
           ${commonDescr}
           Options defined here override options in
-          <option>commonModemConfig</option> for this modem.
+          {option}`commonModemConfig` for this modem.
         '';
       };
     };
@@ -118,15 +118,15 @@ in
 
   options.services.hylafax = {
 
-    enable = mkEnableOption "HylaFAX server";
+    enable = mkEnableOption (lib.mdDoc "HylaFAX server");
 
     autostart = mkOption {
       type = bool;
       default = true;
       example = false;
-      description = ''
+      description = lib.mdDoc ''
         Autostart the HylaFAX queue manager at system start.
-        If this is <literal>false</literal>, the queue manager
+        If this is `false`, the queue manager
         will still be started if there are pending
         jobs or if a user tries to connect to it.
       '';
@@ -136,34 +136,34 @@ in
       type = nullOr nonEmptyStr;
       default = null;
       example = "49";
-      description = "Country code for server and all modems.";
+      description = lib.mdDoc "Country code for server and all modems.";
     };
 
     areaCode = mkOption {
       type = nullOr nonEmptyStr;
       default = null;
       example = "30";
-      description = "Area code for server and all modems.";
+      description = lib.mdDoc "Area code for server and all modems.";
     };
 
     longDistancePrefix = mkOption {
       type = nullOr str;
       default = null;
       example = "0";
-      description = "Long distance prefix for server and all modems.";
+      description = lib.mdDoc "Long distance prefix for server and all modems.";
     };
 
     internationalPrefix = mkOption {
       type = nullOr str;
       default = null;
       example = "00";
-      description = "International prefix for server and all modems.";
+      description = lib.mdDoc "International prefix for server and all modems.";
     };
 
     spoolAreaPath = mkOption {
       type = path;
       default = "/var/spool/fax";
-      description = ''
+      description = lib.mdDoc ''
         The spooling area will be created/maintained
         at the location given here.
       '';
@@ -172,23 +172,23 @@ in
     userAccessFile = mkOption {
       type = path;
       default = "/etc/hosts.hfaxd";
-      description = ''
-        The <filename>hosts.hfaxd</filename>
+      description = lib.mdDoc ''
+        The {file}`hosts.hfaxd`
         file entry in the spooling area
         will be symlinked to the location given here.
         This file must exist and be
-        readable only by the <literal>uucp</literal> user.
+        readable only by the `uucp` user.
         See hosts.hfaxd(5) for details.
         This configuration permits access for all users:
-        <literal>
+        ```
           environment.etc."hosts.hfaxd" = {
             mode = "0600";
             user = "uucp";
             text = ".*";
           };
-        </literal>
+        ```
         Note that host-based access can be controlled with
-        <option>config.systemd.sockets.hylafax-hfaxd.listenStreams</option>;
+        {option}`config.systemd.sockets.hylafax-hfaxd.listenStreams`;
         by default, only 127.0.0.1 is permitted to connect.
       '';
     };
@@ -197,11 +197,11 @@ in
       type = path;
       example = literalExpression ''"''${pkgs.postfix}/bin/sendmail"'';
       # '' ;  # fix vim
-      description = ''
-        Path to <filename>sendmail</filename> program.
+      description = lib.mdDoc ''
+        Path to {file}`sendmail` program.
         The default uses the local sendmail wrapper
-        (see <option>config.services.mail.sendmailSetuidWrapper</option>),
-        otherwise the <filename>false</filename>
+        (see {option}`config.services.mail.sendmailSetuidWrapper`),
+        otherwise the {file}`false`
         binary to cause an error if used.
       '';
     };
@@ -209,9 +209,9 @@ in
     hfaxdConfig = mkOption {
       type = configAttrType;
       example.RecvqProtection = "0400";
-      description = ''
+      description = lib.mdDoc ''
         Attribute set of lines for the global
-        hfaxd config file <filename>etc/hfaxd.conf</filename>.
+        hfaxd config file {file}`etc/hfaxd.conf`.
         ${commonDescr}
       '';
     };
@@ -222,9 +222,9 @@ in
         InternationalPrefix = "00";
         LongDistancePrefix = "0";
       };
-      description = ''
+      description = lib.mdDoc ''
         Attribute set of lines for the global
-        faxq config file <filename>etc/config</filename>.
+        faxq config file {file}`etc/config`.
         ${commonDescr}
       '';
     };
@@ -235,9 +235,9 @@ in
         InternationalPrefix = "00";
         LongDistancePrefix = "0";
       };
-      description = ''
+      description = lib.mdDoc ''
         Attribute set of default values for
-        modem config files <filename>etc/config.*</filename>.
+        modem config files {file}`etc/config.*`.
         ${commonDescr}
         Think twice before changing
         paths of fax-processing scripts.
@@ -254,7 +254,7 @@ in
           LocalIdentifier = "Smith";
         };
       };
-      description = ''
+      description = lib.mdDoc ''
         Description of installed modems.
         At least on modem must be defined
         to enable the HylaFAX server.
@@ -265,31 +265,31 @@ in
       type = lines;
       default = "";
       example = "chmod 0755 .  # everyone may read my faxes";
-      description = ''
+      description = lib.mdDoc ''
         Additional shell code that is executed within the
         spooling area directory right after its setup.
       '';
     };
 
-    faxcron.enable.spoolInit = mkEnableOption ''
+    faxcron.enable.spoolInit = mkEnableOption (lib.mdDoc ''
       Purge old files from the spooling area with
-      <filename>faxcron</filename>
+      {file}`faxcron`
       each time the spooling area is initialized.
-    '';
+    '');
     faxcron.enable.frequency = mkOption {
       type = nullOr nonEmptyStr;
       default = null;
       example = "daily";
-      description = ''
+      description = lib.mdDoc ''
         Purge old files from the spooling area with
-        <filename>faxcron</filename> with the given frequency
+        {file}`faxcron` with the given frequency
         (see systemd.time(7)).
       '';
     };
     faxcron.infoDays = mkOption {
       type = ints.positive;
       default = 30;
-      description = ''
+      description = lib.mdDoc ''
         Set the expiration time for data in the
         remote machine information directory in days.
       '';
@@ -297,7 +297,7 @@ in
     faxcron.logDays = mkOption {
       type = ints.positive;
       default = 30;
-      description = ''
+      description = lib.mdDoc ''
         Set the expiration time for
         session trace log files in days.
       '';
@@ -305,24 +305,24 @@ in
     faxcron.rcvDays = mkOption {
       type = ints.positive;
       default = 7;
-      description = ''
+      description = lib.mdDoc ''
         Set the expiration time for files in
         the received facsimile queue in days.
       '';
     };
 
-    faxqclean.enable.spoolInit = mkEnableOption ''
+    faxqclean.enable.spoolInit = mkEnableOption (lib.mdDoc ''
       Purge old files from the spooling area with
-      <filename>faxqclean</filename>
+      {file}`faxqclean`
       each time the spooling area is initialized.
-    '';
+    '');
     faxqclean.enable.frequency = mkOption {
       type = nullOr nonEmptyStr;
       default = null;
       example = "daily";
-      description = ''
+      description = lib.mdDoc ''
         Purge old files from the spooling area with
-        <filename>faxcron</filename> with the given frequency
+        {file}`faxcron` with the given frequency
         (see systemd.time(7)).
       '';
     };
@@ -330,12 +330,12 @@ in
       type = enum [ "never" "as-flagged" "always" ];
       default = "as-flagged";
       example = "always";
-      description = ''
+      description = lib.mdDoc ''
         Enable or suppress job archiving:
-        <literal>never</literal> disables job archiving,
-        <literal>as-flagged</literal> archives jobs that
+        `never` disables job archiving,
+        `as-flagged` archives jobs that
         have been flagged for archiving by sendfax,
-        <literal>always</literal> forces archiving of all jobs.
+        `always` forces archiving of all jobs.
         See also sendfax(1) and faxqclean(8).
       '';
     };
@@ -343,7 +343,7 @@ in
       type = ints.positive;
       default = 15;
       example = literalExpression "24*60";
-      description = ''
+      description = lib.mdDoc ''
         Set the job
         age threshold (in minutes) that controls how long
         jobs may reside in the doneq directory.
@@ -353,7 +353,7 @@ in
       type = ints.positive;
       default = 60;
       example = literalExpression "24*60";
-      description = ''
+      description = lib.mdDoc ''
         Set the document
         age threshold (in minutes) that controls how long
         unreferenced files may reside in the docq directory.
diff --git a/nixos/modules/services/networking/i2p.nix b/nixos/modules/services/networking/i2p.nix
index 3b6010531f1..c5c7a955cbd 100644
--- a/nixos/modules/services/networking/i2p.nix
+++ b/nixos/modules/services/networking/i2p.nix
@@ -7,7 +7,7 @@ let
   homeDir = "/var/lib/i2p";
 in {
   ###### interface
-  options.services.i2p.enable = mkEnableOption "I2P router";
+  options.services.i2p.enable = mkEnableOption (lib.mdDoc "I2P router");
 
   ###### implementation
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/networking/i2pd.nix b/nixos/modules/services/networking/i2pd.nix
index 34fda57b23d..a02f8df1116 100644
--- a/nixos/modules/services/networking/i2pd.nix
+++ b/nixos/modules/services/networking/i2pd.nix
@@ -17,36 +17,36 @@ let
   optionalNullInt = o: i: optional (i != null) (intOpt o i);
   optionalEmptyList = o: l: optional ([] != l) (lstOpt o l);
 
-  mkEnableTrueOption = name: mkEnableOption name // { default = true; };
+  mkEnableTrueOption = name: mkEnableOption (lib.mdDoc name) // { default = true; };
 
   mkEndpointOpt = name: addr: port: {
-    enable = mkEnableOption name;
+    enable = mkEnableOption (lib.mdDoc name);
     name = mkOption {
       type = types.str;
       default = name;
-      description = "The endpoint name.";
+      description = lib.mdDoc "The endpoint name.";
     };
     address = mkOption {
       type = types.str;
       default = addr;
-      description = "Bind address for ${name} endpoint.";
+      description = lib.mdDoc "Bind address for ${name} endpoint.";
     };
     port = mkOption {
       type = types.port;
       default = port;
-      description = "Bind port for ${name} endpoint.";
+      description = lib.mdDoc "Bind port for ${name} endpoint.";
     };
   };
 
   i2cpOpts = name: {
     length = mkOption {
       type = types.int;
-      description = "Guaranteed minimum hops for ${name} tunnels.";
+      description = lib.mdDoc "Guaranteed minimum hops for ${name} tunnels.";
       default = 3;
     };
     quantity = mkOption {
       type = types.int;
-      description = "Number of simultaneous ${name} tunnels.";
+      description = lib.mdDoc "Number of simultaneous ${name} tunnels.";
       default = 5;
     };
   };
@@ -56,7 +56,7 @@ let
       keys = mkOption {
         type = with types; nullOr str;
         default = keyloc;
-        description = ''
+        description = lib.mdDoc ''
           File to persist ${lib.toUpper name} keys.
         '';
       };
@@ -64,12 +64,12 @@ let
       outbound = i2cpOpts name;
       latency.min = mkOption {
         type = with types; nullOr int;
-        description = "Min latency for tunnels.";
+        description = lib.mdDoc "Min latency for tunnels.";
         default = null;
       };
       latency.max = mkOption {
         type = with types; nullOr int;
-        description = "Max latency for tunnels.";
+        description = lib.mdDoc "Max latency for tunnels.";
         default = null;
       };
     };
@@ -79,17 +79,17 @@ let
     inbound = i2cpOpts name;
     crypto.tagsToSend = mkOption {
       type = types.int;
-      description = "Number of ElGamal/AES tags to send.";
+      description = lib.mdDoc "Number of ElGamal/AES tags to send.";
       default = 40;
     };
     destination = mkOption {
       type = types.str;
-      description = "Remote endpoint, I2P hostname or b32.i2p address.";
+      description = lib.mdDoc "Remote endpoint, I2P hostname or b32.i2p address.";
     };
     keys = mkOption {
       type = types.str;
       default = name + "-keys.dat";
-      description = "Keyset used for tunnel identity.";
+      description = lib.mdDoc "Keyset used for tunnel identity.";
     };
   } // mkEndpointOpt name "127.0.0.1" 0;
 
@@ -158,6 +158,10 @@ let
       (sec "addressbook")
       (strOpt "defaulturl" cfg.addressbook.defaulturl)
     ] ++ (optionalEmptyList "subscriptions" cfg.addressbook.subscriptions)
+      ++ [
+      (sec "meshnets")
+      (boolOpt "yggdrasil" cfg.yggdrasil.enable)
+    ] ++ (optionalNullString "yggaddress" cfg.yggdrasil.address)
       ++ (flip map
       (collect (proto: proto ? port && proto ? address) cfg.proto)
       (proto: let protoOpts = [
@@ -243,8 +247,8 @@ in
 
     services.i2pd = {
 
-      enable = mkEnableOption "I2Pd daemon" // {
-        description = ''
+      enable = mkEnableOption (lib.mdDoc "I2Pd daemon") // {
+        description = lib.mdDoc ''
           Enables I2Pd as a running service upon activation.
           Please read http://i2pd.readthedocs.io/en/latest/ for further
           configuration help.
@@ -255,7 +259,7 @@ in
         type = types.package;
         default = pkgs.i2pd;
         defaultText = literalExpression "pkgs.i2pd";
-        description = ''
+        description = lib.mdDoc ''
           i2pd package to use.
         '';
       };
@@ -263,21 +267,21 @@ in
       logLevel = mkOption {
         type = types.enum ["debug" "info" "warn" "error"];
         default = "error";
-        description = ''
-          The log level. <command>i2pd</command> defaults to "info"
+        description = lib.mdDoc ''
+          The log level. {command}`i2pd` defaults to "info"
           but that generates copious amounts of log messages.
 
           We default to "error" which is similar to the default log
-          level of <command>tor</command>.
+          level of {command}`tor`.
         '';
       };
 
-      logCLFTime = mkEnableOption "Full CLF-formatted date and time to log";
+      logCLFTime = mkEnableOption (lib.mdDoc "Full CLF-formatted date and time to log");
 
       address = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Your external IP or hostname.
         '';
       };
@@ -285,7 +289,7 @@ in
       family = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Specify a family the router belongs to.
         '';
       };
@@ -293,7 +297,7 @@ in
       dataDir = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Alternative path to storage of i2pd data (RI, keys, peer profiles, ...)
         '';
       };
@@ -301,7 +305,7 @@ in
       share = mkOption {
         type = types.int;
         default = 100;
-        description = ''
+        description = lib.mdDoc ''
           Limit of transit traffic from max bandwidth in percents.
         '';
       };
@@ -309,7 +313,7 @@ in
       ifname = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Network interface to bind to.
         '';
       };
@@ -317,7 +321,7 @@ in
       ifname4 = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           IPv4 interface to bind to.
         '';
       };
@@ -325,7 +329,7 @@ in
       ifname6 = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           IPv6 interface to bind to.
         '';
       };
@@ -333,7 +337,7 @@ in
       ntcpProxy = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Proxy URL for NTCP transport.
         '';
       };
@@ -341,14 +345,14 @@ in
       ntcp = mkEnableTrueOption "ntcp";
       ssu = mkEnableTrueOption "ssu";
 
-      notransit = mkEnableOption "notransit" // {
-        description = ''
+      notransit = mkEnableOption (lib.mdDoc "notransit") // {
+        description = lib.mdDoc ''
           Tells the router to not accept transit tunnels during startup.
         '';
       };
 
-      floodfill = mkEnableOption "floodfill" // {
-        description = ''
+      floodfill = mkEnableOption (lib.mdDoc "floodfill") // {
+        description = lib.mdDoc ''
           If the router is declared to be unreachable and needs introduction nodes.
         '';
       };
@@ -356,7 +360,7 @@ in
       netid = mkOption {
         type = types.int;
         default = 2;
-        description = ''
+        description = lib.mdDoc ''
           I2P overlay netid.
         '';
       };
@@ -364,50 +368,50 @@ in
       bandwidth = mkOption {
         type = with types; nullOr int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
            Set a router bandwidth limit integer in KBps.
-           If not set, <command>i2pd</command> defaults to 32KBps.
+           If not set, {command}`i2pd` defaults to 32KBps.
         '';
       };
 
       port = mkOption {
         type = with types; nullOr int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           I2P listen port. If no one is given the router will pick between 9111 and 30777.
         '';
       };
 
       enableIPv4 = mkEnableTrueOption "IPv4 connectivity";
-      enableIPv6 = mkEnableOption "IPv6 connectivity";
+      enableIPv6 = mkEnableOption (lib.mdDoc "IPv6 connectivity");
       nat = mkEnableTrueOption "NAT bypass";
 
-      upnp.enable = mkEnableOption "UPnP service discovery";
+      upnp.enable = mkEnableOption (lib.mdDoc "UPnP service discovery");
       upnp.name = mkOption {
         type = types.str;
         default = "I2Pd";
-        description = ''
+        description = lib.mdDoc ''
           Name i2pd appears in UPnP forwardings list.
         '';
       };
 
       precomputation.elgamal = mkEnableTrueOption "Precomputed ElGamal tables" // {
-        description = ''
+        description = lib.mdDoc ''
           Whenever to use precomputated tables for ElGamal.
-          <command>i2pd</command> defaults to <literal>false</literal>
+          {command}`i2pd` defaults to `false`
           to save 64M of memory (and looses some performance).
 
-          We default to <literal>true</literal> as that is what most
+          We default to `true` as that is what most
           users want anyway.
         '';
       };
 
-      reseed.verify = mkEnableOption "SU3 signature verification";
+      reseed.verify = mkEnableOption (lib.mdDoc "SU3 signature verification");
 
       reseed.file = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Full path to SU3 file to reseed from.
         '';
       };
@@ -415,7 +419,7 @@ in
       reseed.urls = mkOption {
         type = with types; listOf str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Reseed URLs.
         '';
       };
@@ -423,7 +427,7 @@ in
       reseed.floodfill = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to router info of floodfill to reseed from.
         '';
       };
@@ -431,7 +435,7 @@ in
       reseed.zipfile = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to local .zip file to reseed from.
         '';
       };
@@ -439,7 +443,7 @@ in
       reseed.proxy = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           URL for reseed proxy, supports http/socks.
         '';
       };
@@ -447,7 +451,7 @@ in
      addressbook.defaulturl = mkOption {
         type = types.str;
         default = "http://joajgazyztfssty4w2on5oaqksz6tqoxbduy553y34mf4byv6gpq.b32.i2p/export/alive-hosts.txt";
-        description = ''
+        description = lib.mdDoc ''
           AddressBook subscription URL for initial setup
         '';
       };
@@ -458,17 +462,17 @@ in
           "http://i2p-projekt.i2p/hosts.txt"
           "http://stats.i2p/cgi-bin/newhosts.txt"
         ];
-        description = ''
+        description = lib.mdDoc ''
           AddressBook subscription URLs
         '';
       };
 
-      trust.enable = mkEnableOption "Explicit trust options";
+      trust.enable = mkEnableOption (lib.mdDoc "Explicit trust options");
 
       trust.family = mkOption {
         type = with types; nullOr str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Router Familiy to trust for first hops.
         '';
       };
@@ -476,12 +480,12 @@ in
       trust.routers = mkOption {
         type = with types; listOf str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Only connect to the listed routers.
         '';
       };
 
-      trust.hidden = mkEnableOption "Router concealment";
+      trust.hidden = mkEnableOption (lib.mdDoc "Router concealment");
 
       websocket = mkEndpointOpt "websockets" "127.0.0.1" 7666;
 
@@ -489,11 +493,11 @@ in
       exploratory.outbound = i2cpOpts "exploratory";
 
       ntcp2.enable = mkEnableTrueOption "NTCP2";
-      ntcp2.published = mkEnableOption "NTCP2 publication";
+      ntcp2.published = mkEnableOption (lib.mdDoc "NTCP2 publication");
       ntcp2.port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Port to listen for incoming NTCP2 connections (0=auto).
         '';
       };
@@ -501,7 +505,7 @@ in
       limits.transittunnels = mkOption {
         type = types.int;
         default = 2500;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of active transit sessions.
         '';
       };
@@ -509,7 +513,7 @@ in
       limits.coreSize = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Maximum size of corefile in Kb (0 - use system limit).
         '';
       };
@@ -517,7 +521,7 @@ in
       limits.openFiles = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of open files (0 - use system default).
         '';
       };
@@ -525,7 +529,7 @@ in
       limits.ntcpHard = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of active transit sessions.
         '';
       };
@@ -533,7 +537,7 @@ in
       limits.ntcpSoft = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Threshold to start probabalistic backoff with ntcp sessions (default: use system limit).
         '';
       };
@@ -541,19 +545,30 @@ in
       limits.ntcpThreads = mkOption {
         type = types.int;
         default = 1;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of threads used by NTCP DH worker.
         '';
       };
 
+      yggdrasil.enable = mkEnableOption (lib.mdDoc "Yggdrasil");
+
+      yggdrasil.address = mkOption {
+        type = with types; nullOr str;
+        default = null;
+        description = lib.mdDoc ''
+          Your local yggdrasil address. Specify it if you want to bind your router to a
+          particular address.
+        '';
+      };
+
       proto.http = (mkEndpointOpt "http" "127.0.0.1" 7070) // {
 
-        auth = mkEnableOption "Webconsole authentication";
+        auth = mkEnableOption (lib.mdDoc "Webconsole authentication");
 
         user = mkOption {
           type = types.str;
           default = "i2pd";
-          description = ''
+          description = lib.mdDoc ''
             Username for webconsole access
           '';
         };
@@ -561,7 +576,7 @@ in
         pass = mkOption {
           type = types.str;
           default = "i2pd";
-          description = ''
+          description = lib.mdDoc ''
             Password for webconsole access.
           '';
         };
@@ -569,7 +584,7 @@ in
         strictHeaders = mkOption {
           type = with types; nullOr bool;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Enable strict host checking on WebUI.
           '';
         };
@@ -577,7 +592,7 @@ in
         hostname = mkOption {
           type = with types; nullOr str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Expected hostname for WebUI.
           '';
         };
@@ -588,21 +603,21 @@ in
         outproxy = mkOption {
           type = with types; nullOr str;
           default = null;
-          description = "Upstream outproxy bind address.";
+          description = lib.mdDoc "Upstream outproxy bind address.";
         };
       };
       proto.socksProxy = (mkKeyedEndpointOpt "socksproxy" "127.0.0.1" 4447 "socksproxy-keys.dat")
       // {
-        outproxyEnable = mkEnableOption "SOCKS outproxy";
+        outproxyEnable = mkEnableOption (lib.mdDoc "SOCKS outproxy");
         outproxy = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "Upstream outproxy bind address.";
+          description = lib.mdDoc "Upstream outproxy bind address.";
         };
         outproxyPort = mkOption {
           type = types.int;
           default = 4444;
-          description = "Upstream outproxy bind port.";
+          description = lib.mdDoc "Upstream outproxy bind port.";
         };
       };
 
@@ -619,7 +634,7 @@ in
               destinationPort = mkOption {
                 type = with types; nullOr int;
                 default = null;
-                description = "Connect to particular port at destination.";
+                description = lib.mdDoc "Connect to particular port at destination.";
               };
             } // commonTunOpts name;
             config = {
@@ -627,7 +642,7 @@ in
             };
           }
         ));
-        description = ''
+        description = lib.mdDoc ''
           Connect to someone as a client and establish a local accept endpoint
         '';
       };
@@ -640,12 +655,12 @@ in
               inPort = mkOption {
                 type = types.int;
                 default = 0;
-                description = "Service port. Default to the tunnel's listen port.";
+                description = lib.mdDoc "Service port. Default to the tunnel's listen port.";
               };
               accessList = mkOption {
                 type = with types; listOf str;
                 default = [];
-                description = "I2P nodes that are allowed to connect to this service.";
+                description = lib.mdDoc "I2P nodes that are allowed to connect to this service.";
               };
             } // commonTunOpts name;
             config = {
@@ -653,7 +668,7 @@ in
             };
           }
         ));
-        description = ''
+        description = lib.mdDoc ''
           Serve something on I2P network at port and delegate requests to address inPort.
         '';
       };
diff --git a/nixos/modules/services/networking/icecream/daemon.nix b/nixos/modules/services/networking/icecream/daemon.nix
index 8593c94e34d..fdd7a139c2f 100644
--- a/nixos/modules/services/networking/icecream/daemon.nix
+++ b/nixos/modules/services/networking/icecream/daemon.nix
@@ -12,18 +12,18 @@ in {
 
     services.icecream.daemon = {
 
-     enable = mkEnableOption "Icecream Daemon";
+     enable = mkEnableOption (lib.mdDoc "Icecream Daemon");
 
       openFirewall = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to automatically open receive port in the firewall.
         '';
       };
 
       openBroadcast = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to automatically open the firewall for scheduler discovery.
         '';
       };
@@ -31,7 +31,7 @@ in {
       cacheLimit = mkOption {
         type = types.ints.u16;
         default = 256;
-        description = ''
+        description = lib.mdDoc ''
           Maximum size in Megabytes of cache used to store compile environments of compile clients.
         '';
       };
@@ -39,7 +39,7 @@ in {
       netName = mkOption {
         type = types.str;
         default = "ICECREAM";
-        description = ''
+        description = lib.mdDoc ''
           Network name to connect to. A scheduler with the same name needs to be running.
         '';
       };
@@ -47,7 +47,7 @@ in {
       noRemote = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Prevent jobs from other nodes being scheduled on this daemon.
         '';
       };
@@ -55,7 +55,7 @@ in {
       schedulerHost = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Explicit scheduler hostname, useful in firewalled environments.
 
           Uses scheduler autodiscovery via broadcast if set to null.
@@ -65,7 +65,7 @@ in {
       maxProcesses = mkOption {
         type = types.nullOr types.ints.u16;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of compile jobs started in parallel for this daemon.
 
           Uses the number of CPUs if set to null.
@@ -75,7 +75,7 @@ in {
       nice = mkOption {
         type = types.int;
         default = 5;
-        description = ''
+        description = lib.mdDoc ''
           The level of niceness to use.
         '';
       };
@@ -83,7 +83,7 @@ in {
       hostname = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Hostname of the daemon in the icecream infrastructure.
 
           Uses the hostname retrieved via uname if set to null.
@@ -93,7 +93,7 @@ in {
       user = mkOption {
         type = types.str;
         default = "icecc";
-        description = ''
+        description = lib.mdDoc ''
           User to run the icecream daemon as. Set to root to enable receive of
           remote compile environments.
         '';
@@ -103,13 +103,13 @@ in {
         default = pkgs.icecream;
         defaultText = literalExpression "pkgs.icecream";
         type = types.package;
-        description = "Icecream package to use.";
+        description = lib.mdDoc "Icecream package to use.";
       };
 
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Additional command line parameters.";
+        description = lib.mdDoc "Additional command line parameters.";
         example = [ "-v" ];
       };
     };
diff --git a/nixos/modules/services/networking/icecream/scheduler.nix b/nixos/modules/services/networking/icecream/scheduler.nix
index 14fbc966b98..33aee1bb19c 100644
--- a/nixos/modules/services/networking/icecream/scheduler.nix
+++ b/nixos/modules/services/networking/icecream/scheduler.nix
@@ -11,12 +11,12 @@ in {
   options = {
 
     services.icecream.scheduler = {
-      enable = mkEnableOption "Icecream Scheduler";
+      enable = mkEnableOption (lib.mdDoc "Icecream Scheduler");
 
       netName = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Network name for the icecream scheduler.
 
           Uses the default ICECREAM if null.
@@ -26,14 +26,14 @@ in {
       port = mkOption {
         type = types.port;
         default = 8765;
-        description = ''
+        description = lib.mdDoc ''
           Server port to listen for icecream daemon requests.
         '';
       };
 
       openFirewall = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to automatically open the daemon port in the firewall.
         '';
       };
@@ -41,7 +41,7 @@ in {
       openTelnet = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to open the telnet TCP port on 8766.
         '';
       };
@@ -49,7 +49,7 @@ in {
       persistentClientConnection = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to prevent clients from connecting to a better scheduler.
         '';
       };
@@ -58,13 +58,13 @@ in {
         default = pkgs.icecream;
         defaultText = literalExpression "pkgs.icecream";
         type = types.package;
-        description = "Icecream package to use.";
+        description = lib.mdDoc "Icecream package to use.";
       };
 
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Additional command line parameters";
+        description = lib.mdDoc "Additional command line parameters";
         example = [ "-v" ];
       };
     };
diff --git a/nixos/modules/services/networking/inspircd.nix b/nixos/modules/services/networking/inspircd.nix
index 81c367ec8f7..da193df105b 100644
--- a/nixos/modules/services/networking/inspircd.nix
+++ b/nixos/modules/services/networking/inspircd.nix
@@ -12,17 +12,17 @@ in {
 
   options = {
     services.inspircd = {
-      enable = lib.mkEnableOption "InspIRCd";
+      enable = lib.mkEnableOption (lib.mdDoc "InspIRCd");
 
       package = lib.mkOption {
         type = lib.types.package;
         default = pkgs.inspircd;
         defaultText = lib.literalExpression "pkgs.inspircd";
         example = lib.literalExpression "pkgs.inspircdMinimal";
-        description = ''
+        description = lib.mdDoc ''
           The InspIRCd package to use. This is mainly useful
           to specify an overridden version of the
-          <literal>pkgs.inspircd</literal> dervivation, for
+          `pkgs.inspircd` dervivation, for
           example if you want to use a more minimal InspIRCd
           distribution with less modules enabled or with
           modules enabled which can't be distributed in binary
@@ -32,13 +32,13 @@ in {
 
       config = lib.mkOption {
         type = lib.types.lines;
-        description = ''
-          Verbatim <literal>inspircd.conf</literal> file.
+        description = lib.mdDoc ''
+          Verbatim `inspircd.conf` file.
           For a list of options, consult the
-          <link xlink:href="https://docs.inspircd.org/3/configuration/">InspIRCd documentation</link>, the
-          <link xlink:href="https://docs.inspircd.org/3/modules/">Module documentation</link>
+          [InspIRCd documentation](https://docs.inspircd.org/3/configuration/), the
+          [Module documentation](https://docs.inspircd.org/3/modules/)
           and the example configuration files distributed
-          with <literal>pkgs.inspircd.doc</literal>
+          with `pkgs.inspircd.doc`
         '';
       };
     };
diff --git a/nixos/modules/services/networking/iodine.nix b/nixos/modules/services/networking/iodine.nix
index e241afe3269..ea2fa3ac4be 100644
--- a/nixos/modules/services/networking/iodine.nix
+++ b/nixos/modules/services/networking/iodine.nix
@@ -28,12 +28,12 @@ in
     services.iodine = {
       clients = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Each attribute of this option defines a systemd service that
           runs iodine. Many or none may be defined.
           The name of each service is
-          <literal>iodine-<replaceable>name</replaceable></literal>
-          where <replaceable>name</replaceable> is the name of the
+          `iodine-«name»`
+          where «name» is the name of the
           corresponding attribute name.
         '';
         example = literalExpression ''
@@ -52,28 +52,28 @@ in
                 server = mkOption {
                   type = types.str;
                   default = "";
-                  description = "Hostname of server running iodined";
+                  description = lib.mdDoc "Hostname of server running iodined";
                   example = "tunnel.mydomain.com";
                 };
 
                 relay = mkOption {
                   type = types.str;
                   default = "";
-                  description = "DNS server to use as an intermediate relay to the iodined server";
+                  description = lib.mdDoc "DNS server to use as an intermediate relay to the iodined server";
                   example = "8.8.8.8";
                 };
 
                 extraConfig = mkOption {
                   type = types.str;
                   default = "";
-                  description = "Additional command line parameters";
+                  description = lib.mdDoc "Additional command line parameters";
                   example = "-l 192.168.1.10 -p 23";
                 };
 
                 passwordFile = mkOption {
                   type = types.str;
                   default = "";
-                  description = "Path to a file containing the password.";
+                  description = lib.mdDoc "Path to a file containing the password.";
                 };
               };
             }
@@ -85,34 +85,34 @@ in
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = "enable iodined server";
+          description = lib.mdDoc "enable iodined server";
         };
 
         ip = mkOption {
           type = types.str;
           default = "";
-          description = "The assigned ip address or ip range";
+          description = lib.mdDoc "The assigned ip address or ip range";
           example = "172.16.10.1/24";
         };
 
         domain = mkOption {
           type = types.str;
           default = "";
-          description = "Domain or subdomain of which nameservers point to us";
+          description = lib.mdDoc "Domain or subdomain of which nameservers point to us";
           example = "tunnel.mydomain.com";
         };
 
         extraConfig = mkOption {
           type = types.str;
           default = "";
-          description = "Additional command line parameters";
+          description = lib.mdDoc "Additional command line parameters";
           example = "-l 192.168.1.10 -p 23";
         };
 
         passwordFile = mkOption {
           type = types.str;
           default = "";
-          description = "File that contains password";
+          description = lib.mdDoc "File that contains password";
         };
       };
 
diff --git a/nixos/modules/services/networking/iperf3.nix b/nixos/modules/services/networking/iperf3.nix
index 0fe378b225d..a70085bb1f5 100644
--- a/nixos/modules/services/networking/iperf3.nix
+++ b/nixos/modules/services/networking/iperf3.nix
@@ -3,56 +3,56 @@ let
   cfg = config.services.iperf3;
 
   api = {
-    enable = mkEnableOption "iperf3 network throughput testing server";
+    enable = mkEnableOption (lib.mdDoc "iperf3 network throughput testing server");
     port = mkOption {
       type        = types.ints.u16;
       default     = 5201;
-      description = "Server port to listen on for iperf3 client requsts.";
+      description = lib.mdDoc "Server port to listen on for iperf3 client requsts.";
     };
     affinity = mkOption {
       type        = types.nullOr types.ints.unsigned;
       default     = null;
-      description = "CPU affinity for the process.";
+      description = lib.mdDoc "CPU affinity for the process.";
     };
     bind = mkOption {
       type        = types.nullOr types.str;
       default     = null;
-      description = "Bind to the specific interface associated with the given address.";
+      description = lib.mdDoc "Bind to the specific interface associated with the given address.";
     };
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = "Open ports in the firewall for iperf3.";
+      description = lib.mdDoc "Open ports in the firewall for iperf3.";
     };
     verbose = mkOption {
       type        = types.bool;
       default     = false;
-      description = "Give more detailed output.";
+      description = lib.mdDoc "Give more detailed output.";
     };
     forceFlush = mkOption {
       type        = types.bool;
       default     = false;
-      description = "Force flushing output at every interval.";
+      description = lib.mdDoc "Force flushing output at every interval.";
     };
     debug = mkOption {
       type        = types.bool;
       default     = false;
-      description = "Emit debugging output.";
+      description = lib.mdDoc "Emit debugging output.";
     };
     rsaPrivateKey = mkOption {
       type        = types.nullOr types.path;
       default     = null;
-      description = "Path to the RSA private key (not password-protected) used to decrypt authentication credentials from the client.";
+      description = lib.mdDoc "Path to the RSA private key (not password-protected) used to decrypt authentication credentials from the client.";
     };
     authorizedUsersFile = mkOption {
       type        = types.nullOr types.path;
       default     = null;
-      description = "Path to the configuration file containing authorized users credentials to run iperf tests.";
+      description = lib.mdDoc "Path to the configuration file containing authorized users credentials to run iperf tests.";
     };
     extraFlags = mkOption {
       type        = types.listOf types.str;
       default     = [ ];
-      description = "Extra flags to pass to iperf3(1).";
+      description = lib.mdDoc "Extra flags to pass to iperf3(1).";
     };
   };
 
diff --git a/nixos/modules/services/networking/ircd-hybrid/default.nix b/nixos/modules/services/networking/ircd-hybrid/default.nix
index f659f3f3e8c..554b0f7bb8b 100644
--- a/nixos/modules/services/networking/ircd-hybrid/default.nix
+++ b/nixos/modules/services/networking/ircd-hybrid/default.nix
@@ -36,74 +36,74 @@ in
 
     services.ircdHybrid = {
 
-      enable = mkEnableOption "IRCD";
+      enable = mkEnableOption (lib.mdDoc "IRCD");
 
       serverName = mkOption {
         default = "hades.arpa";
         type = types.str;
-        description = "
+        description = lib.mdDoc ''
           IRCD server name.
-        ";
+        '';
       };
 
       sid = mkOption {
         default = "0NL";
         type = types.str;
-        description = "
+        description = lib.mdDoc ''
           IRCD server unique ID in a net of servers.
-        ";
+        '';
       };
 
       description = mkOption {
         default = "Hybrid-7 IRC server.";
         type = types.str;
-        description = "
+        description = lib.mdDoc ''
           IRCD server description.
-        ";
+        '';
       };
 
       rsaKey = mkOption {
         default = null;
         example = literalExpression "/root/certificates/irc.key";
         type = types.nullOr types.path;
-        description = "
+        description = lib.mdDoc ''
           IRCD server RSA key.
-        ";
+        '';
       };
 
       certificate = mkOption {
         default = null;
         example = literalExpression "/root/certificates/irc.pem";
         type = types.nullOr types.path;
-        description = "
+        description = lib.mdDoc ''
           IRCD server SSL certificate. There are some limitations - read manual.
-        ";
+        '';
       };
 
       adminEmail = mkOption {
         default = "<bit-bucket@example.com>";
         type = types.str;
         example = "<name@domain.tld>";
-        description = "
+        description = lib.mdDoc ''
           IRCD server administrator e-mail.
-        ";
+        '';
       };
 
       extraIPs = mkOption {
         default = [];
         example = ["127.0.0.1"];
         type = types.listOf types.str;
-        description = "
+        description = lib.mdDoc ''
           Extra IP's to bind.
-        ";
+        '';
       };
 
       extraPort = mkOption {
         default = "7117";
         type = types.str;
-        description = "
+        description = lib.mdDoc ''
           Extra port to avoid filtering.
-        ";
+        '';
       };
 
     };
diff --git a/nixos/modules/services/networking/ircd-hybrid/ircd.conf b/nixos/modules/services/networking/ircd-hybrid/ircd.conf
index 17ef203840a..b82094cf5f0 100644
--- a/nixos/modules/services/networking/ircd-hybrid/ircd.conf
+++ b/nixos/modules/services/networking/ircd-hybrid/ircd.conf
@@ -98,7 +98,7 @@ serverinfo {
 	 * 
 	 * 	openssl genrsa -out rsa.key 2048
 	 *	openssl rsa -in rsa.key -pubout -out rsa.pub
-	 *	chown <ircd-user>.<ircd.group> rsa.key rsa.pub
+	 *	chown <ircd-user>:<ircd.group> rsa.key rsa.pub
 	 *	chmod 0600 rsa.key
 	 *	chmod 0644 rsa.pub
 	 */
diff --git a/nixos/modules/services/networking/iscsi/initiator.nix b/nixos/modules/services/networking/iscsi/initiator.nix
index 051c9c7bff3..d2865a660ea 100644
--- a/nixos/modules/services/networking/iscsi/initiator.nix
+++ b/nixos/modules/services/networking/iscsi/initiator.nix
@@ -4,24 +4,24 @@ let
 in
 {
   options.services.openiscsi = with types; {
-    enable = mkEnableOption "the openiscsi iscsi daemon";
-    enableAutoLoginOut = mkEnableOption ''
+    enable = mkEnableOption (lib.mdDoc "the openiscsi iscsi daemon");
+    enableAutoLoginOut = mkEnableOption (lib.mdDoc ''
       automatic login and logout of all automatic targets.
       You probably do not want this.
-    '';
+    '');
     discoverPortal = mkOption {
       type = nullOr str;
       default = null;
-      description = "Portal to discover targets on";
+      description = lib.mdDoc "Portal to discover targets on";
     };
     name = mkOption {
       type = str;
-      description = "Name of this iscsi initiator";
+      description = lib.mdDoc "Name of this iscsi initiator";
       example = "iqn.2020-08.org.linux-iscsi.initiatorhost:example";
     };
     package = mkOption {
       type = package;
-      description = "openiscsi package to use";
+      description = lib.mdDoc "openiscsi package to use";
       default = pkgs.openiscsi;
       defaultText = literalExpression "pkgs.openiscsi";
     };
@@ -29,11 +29,11 @@ in
     extraConfig = mkOption {
       type = str;
       default = "";
-      description = "Lines to append to default iscsid.conf";
+      description = lib.mdDoc "Lines to append to default iscsid.conf";
     };
 
     extraConfigFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Append an additional file's contents to /etc/iscsid.conf. Use a non-store path
         and store passwords in this file.
       '';
diff --git a/nixos/modules/services/networking/iscsi/root-initiator.nix b/nixos/modules/services/networking/iscsi/root-initiator.nix
index c12aca1bc24..4434fedce1e 100644
--- a/nixos/modules/services/networking/iscsi/root-initiator.nix
+++ b/nixos/modules/services/networking/iscsi/root-initiator.nix
@@ -19,7 +19,7 @@ in
   # machines to be up.
   options.boot.iscsi-initiator = with types; {
     name = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Name of the iSCSI initiator to boot from. Note, booting from iscsi
         requires networkd based networking.
       '';
@@ -29,7 +29,7 @@ in
     };
 
     discoverPortal = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         iSCSI portal to boot from.
       '';
       default = null;
@@ -38,7 +38,7 @@ in
     };
 
     target = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Name of the iSCSI target to boot from.
       '';
       default = null;
@@ -47,7 +47,7 @@ in
     };
 
     logLevel = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Higher numbers elicits more logs.
       '';
       default = 1;
@@ -56,7 +56,7 @@ in
     };
 
     loginAll = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Do not log into a specific target on the portal, but to all that we discover.
         This overrides setting target.
       '';
@@ -65,19 +65,19 @@ in
     };
 
     extraIscsiCommands = mkOption {
-      description = "Extra iscsi commands to run in the initrd.";
+      description = lib.mdDoc "Extra iscsi commands to run in the initrd.";
       default = "";
       type = lines;
     };
 
     extraConfig = mkOption {
-      description = "Extra lines to append to /etc/iscsid.conf";
+      description = lib.mdDoc "Extra lines to append to /etc/iscsid.conf";
       default = null;
       type = nullOr lines;
     };
 
     extraConfigFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Append an additional file's contents to `/etc/iscsid.conf`. Use a non-store path
         and store passwords in this file. Note: the file specified here must be available
         in the initrd, see: `boot.initrd.secrets`.
diff --git a/nixos/modules/services/networking/iscsi/target.nix b/nixos/modules/services/networking/iscsi/target.nix
index 8a10e7d346a..88eaf459003 100644
--- a/nixos/modules/services/networking/iscsi/target.nix
+++ b/nixos/modules/services/networking/iscsi/target.nix
@@ -9,12 +9,12 @@ in
   ###### interface
   options = {
     services.target = with types; {
-      enable = mkEnableOption "the kernel's LIO iscsi target";
+      enable = mkEnableOption (lib.mdDoc "the kernel's LIO iscsi target");
 
       config = mkOption {
         type = attrs;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Content of /etc/target/saveconfig.json
           This file is normally read and written by targetcli
         '';
diff --git a/nixos/modules/services/networking/iwd.nix b/nixos/modules/services/networking/iwd.nix
index 5c1480e7e2f..993a603c1ed 100644
--- a/nixos/modules/services/networking/iwd.nix
+++ b/nixos/modules/services/networking/iwd.nix
@@ -17,7 +17,16 @@ let
 in
 {
   options.networking.wireless.iwd = {
-    enable = mkEnableOption "iwd";
+    enable = mkEnableOption (lib.mdDoc "iwd");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.iwd;
+      defaultText = lib.literalExpression "pkgs.iwd";
+      description = lib.mdDoc ''
+        The iwd package to use.
+      '';
+    };
 
     settings = mkOption {
       type = ini.type;
@@ -32,9 +41,9 @@ in
         };
       };
 
-      description = ''
+      description = lib.mdDoc ''
         Options passed to iwd.
-        See <link xlink:href="https://iwd.wiki.kernel.org/networkconfigurationsettings">here</link> for supported options.
+        See [here](https://iwd.wiki.kernel.org/networkconfigurationsettings) for supported options.
       '';
     };
   };
@@ -50,11 +59,11 @@ in
     environment.etc."iwd/${configFile.name}".source = configFile;
 
     # for iwctl
-    environment.systemPackages = [ pkgs.iwd ];
+    environment.systemPackages = [ cfg.package ];
 
-    services.dbus.packages = [ pkgs.iwd ];
+    services.dbus.packages = [ cfg.package ];
 
-    systemd.packages = [ pkgs.iwd ];
+    systemd.packages = [ cfg.package ];
 
     systemd.network.links."80-iwd" = {
       matchConfig.Type = "wlan";
@@ -67,5 +76,5 @@ in
     };
   };
 
-  meta.maintainers = with lib.maintainers; [ mic92 dtzWill ];
+  meta.maintainers = with lib.maintainers; [ dtzWill ];
 }
diff --git a/nixos/modules/services/networking/jibri/default.nix b/nixos/modules/services/networking/jibri/default.nix
index 113a7aa4384..a931831fc28 100644
--- a/nixos/modules/services/networking/jibri/default.nix
+++ b/nixos/modules/services/networking/jibri/default.nix
@@ -89,13 +89,13 @@ let
 in
 {
   options.services.jibri = with types; {
-    enable = mkEnableOption "Jitsi BRoadcasting Infrastructure. Currently Jibri must be run on a host that is also running <option>services.jitsi-meet.enable</option>, so for most use cases it will be simpler to run <option>services.jitsi-meet.jibri.enable</option>";
+    enable = mkEnableOption (lib.mdDoc "Jitsi BRoadcasting Infrastructure. Currently Jibri must be run on a host that is also running {option}`services.jitsi-meet.enable`, so for most use cases it will be simpler to run {option}`services.jitsi-meet.jibri.enable`");
     config = mkOption {
       type = attrs;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Jibri configuration.
-        See <link xlink:href="https://github.com/jitsi/jibri/blob/master/src/main/resources/reference.conf" />
+        See <https://github.com/jitsi/jibri/blob/master/src/main/resources/reference.conf>
         for default configuration with comments.
       '';
     };
@@ -136,7 +136,7 @@ in
         exit 0
         '''''';
       '';
-      description = ''
+      description = lib.mdDoc ''
         This script runs when jibri finishes recording a video of a conference.
       '';
     };
@@ -145,14 +145,14 @@ in
       type = bool;
       default = false;
       example = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable the flag "--ignore-certificate-errors" for the Chromium browser opened by Jibri.
         Intended for use in automated tests or anywhere else where using a verified cert for Jitsi-Meet is not possible.
       '';
     };
 
     xmppEnvironments = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         XMPP servers to connect to.
       '';
       example = literalExpression ''
@@ -189,54 +189,54 @@ in
           xmppServerHosts = mkOption {
             type = listOf str;
             example = [ "xmpp.example.org" ];
-            description = ''
+            description = lib.mdDoc ''
               Hostnames of the XMPP servers to connect to.
             '';
           };
           xmppDomain = mkOption {
             type = str;
             example = "xmpp.example.org";
-            description = ''
+            description = lib.mdDoc ''
               The base XMPP domain.
             '';
           };
           control.muc.domain = mkOption {
             type = str;
-            description = ''
+            description = lib.mdDoc ''
               The domain part of the MUC to connect to for control.
             '';
           };
           control.muc.roomName = mkOption {
             type = str;
             default = "JibriBrewery";
-            description = ''
+            description = lib.mdDoc ''
               The room name of the MUC to connect to for control.
             '';
           };
           control.muc.nickname = mkOption {
             type = str;
             default = "jibri";
-            description = ''
+            description = lib.mdDoc ''
               The nickname for this Jibri instance in the MUC.
             '';
           };
           control.login.domain = mkOption {
             type = str;
-            description = ''
+            description = lib.mdDoc ''
               The domain part of the JID for this Jibri instance.
             '';
           };
           control.login.username = mkOption {
             type = str;
             default = "jvb";
-            description = ''
+            description = lib.mdDoc ''
               User part of the JID.
             '';
           };
           control.login.passwordFile = mkOption {
             type = str;
             example = "/run/keys/jibri-xmpp1";
-            description = ''
+            description = lib.mdDoc ''
               File containing the password for the user.
             '';
           };
@@ -244,28 +244,28 @@ in
           call.login.domain = mkOption {
             type = str;
             example = "recorder.xmpp.example.org";
-            description = ''
+            description = lib.mdDoc ''
               The domain part of the JID for the recorder.
             '';
           };
           call.login.username = mkOption {
             type = str;
             default = "recorder";
-            description = ''
+            description = lib.mdDoc ''
               User part of the JID for the recorder.
             '';
           };
           call.login.passwordFile = mkOption {
             type = str;
             example = "/run/keys/jibri-recorder-xmpp1";
-            description = ''
+            description = lib.mdDoc ''
               File containing the password for the user.
             '';
           };
           disableCertificateVerification = mkOption {
             type = bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Whether to skip validation of the server's certificate.
             '';
           };
@@ -274,7 +274,7 @@ in
             type = str;
             default = "0";
             example = "conference.";
-            description = ''
+            description = lib.mdDoc ''
               The prefix to strip from the room's JID domain to derive the call URL.
             '';
           };
@@ -282,7 +282,7 @@ in
             type = str;
             default = "0";
             example = "1 hour";
-            description = ''
+            description = lib.mdDoc ''
               The duration that the Jibri session can be.
               A value of zero means indefinitely.
             '';
@@ -378,7 +378,7 @@ in
         '')
         cfg.xmppEnvironments))
       + ''
-        ${pkgs.jre8_headless}/bin/java -Djava.util.logging.config.file=${./logging.properties-journal} -Dconfig.file=${configFile} -jar ${pkgs.jibri}/opt/jitsi/jibri/jibri.jar --config /var/lib/jibri/jibri.json
+        ${pkgs.jdk11_headless}/bin/java -Djava.util.logging.config.file=${./logging.properties-journal} -Dconfig.file=${configFile} -jar ${pkgs.jibri}/opt/jitsi/jibri/jibri.jar --config /var/lib/jibri/jibri.json
       '';
 
       environment.HOME = "/var/lib/jibri";
diff --git a/nixos/modules/services/networking/jicofo.nix b/nixos/modules/services/networking/jicofo.nix
index 647119b9039..5e978896073 100644
--- a/nixos/modules/services/networking/jicofo.nix
+++ b/nixos/modules/services/networking/jicofo.nix
@@ -7,12 +7,12 @@ let
 in
 {
   options.services.jicofo = with types; {
-    enable = mkEnableOption "Jitsi Conference Focus - component of Jitsi Meet";
+    enable = mkEnableOption (lib.mdDoc "Jitsi Conference Focus - component of Jitsi Meet");
 
     xmppHost = mkOption {
       type = str;
       example = "localhost";
-      description = ''
+      description = lib.mdDoc ''
         Hostname of the XMPP server to connect to.
       '';
     };
@@ -20,17 +20,17 @@ in
     xmppDomain = mkOption {
       type = nullOr str;
       example = "meet.example.org";
-      description = ''
+      description = lib.mdDoc ''
         Domain name of the XMMP server to which to connect as a component.
 
-        If null, <option>xmppHost</option> is used.
+        If null, {option}`xmppHost` is used.
       '';
     };
 
     componentPasswordFile = mkOption {
       type = str;
       example = "/run/keys/jicofo-component";
-      description = ''
+      description = lib.mdDoc ''
         Path to file containing component secret.
       '';
     };
@@ -38,7 +38,7 @@ in
     userName = mkOption {
       type = str;
       default = "focus";
-      description = ''
+      description = lib.mdDoc ''
         User part of the JID for XMPP user connection.
       '';
     };
@@ -46,7 +46,7 @@ in
     userDomain = mkOption {
       type = str;
       example = "auth.meet.example.org";
-      description = ''
+      description = lib.mdDoc ''
         Domain part of the JID for XMPP user connection.
       '';
     };
@@ -54,7 +54,7 @@ in
     userPasswordFile = mkOption {
       type = str;
       example = "/run/keys/jicofo-user";
-      description = ''
+      description = lib.mdDoc ''
         Path to file containing password for XMPP user connection.
       '';
     };
@@ -62,7 +62,7 @@ in
     bridgeMuc = mkOption {
       type = str;
       example = "jvbbrewery@internal.meet.example.org";
-      description = ''
+      description = lib.mdDoc ''
         JID of the internal MUC used to communicate with Videobridges.
       '';
     };
@@ -75,8 +75,8 @@ in
           "org.jitsi.jicofo.auth.URL" = "XMPP:jitsi-meet.example.com";
         }
       '';
-      description = ''
-        Contents of the <filename>sip-communicator.properties</filename> configuration file for jicofo.
+      description = lib.mdDoc ''
+        Contents of the {file}`sip-communicator.properties` configuration file for jicofo.
       '';
     };
   };
diff --git a/nixos/modules/services/networking/jitsi-videobridge.nix b/nixos/modules/services/networking/jitsi-videobridge.nix
index abb0bd0a25e..09f2ddf92c5 100644
--- a/nixos/modules/services/networking/jitsi-videobridge.nix
+++ b/nixos/modules/services/networking/jitsi-videobridge.nix
@@ -51,7 +51,7 @@ let
 in
 {
   options.services.jitsi-videobridge = with types; {
-    enable = mkEnableOption "Jitsi Videobridge, a WebRTC compatible video router";
+    enable = mkEnableOption (lib.mdDoc "Jitsi Videobridge, a WebRTC compatible video router");
 
     config = mkOption {
       type = attrs;
@@ -67,19 +67,19 @@ in
           };
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Videobridge configuration.
 
-        See <link xlink:href="https://github.com/jitsi/jitsi-videobridge/blob/master/src/main/resources/reference.conf" />
+        See <https://github.com/jitsi/jitsi-videobridge/blob/master/jvb/src/main/resources/reference.conf>
         for default configuration with comments.
       '';
     };
 
     xmppConfigs = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         XMPP servers to connect to.
 
-        See <link xlink:href="https://github.com/jitsi/jitsi-videobridge/blob/master/doc/muc.md" /> for more information.
+        See <https://github.com/jitsi/jitsi-videobridge/blob/master/doc/muc.md> for more information.
       '';
       default = { };
       example = literalExpression ''
@@ -98,7 +98,7 @@ in
           hostName = mkOption {
             type = str;
             example = "xmpp.example.org";
-            description = ''
+            description = lib.mdDoc ''
               Hostname of the XMPP server to connect to. Name of the attribute set is used by default.
             '';
           };
@@ -106,35 +106,35 @@ in
             type = nullOr str;
             default = null;
             example = "auth.xmpp.example.org";
-            description = ''
+            description = lib.mdDoc ''
               Domain part of JID of the XMPP user, if it is different from hostName.
             '';
           };
           userName = mkOption {
             type = str;
             default = "jvb";
-            description = ''
+            description = lib.mdDoc ''
               User part of the JID.
             '';
           };
           passwordFile = mkOption {
             type = str;
             example = "/run/keys/jitsi-videobridge-xmpp1";
-            description = ''
+            description = lib.mdDoc ''
               File containing the password for the user.
             '';
           };
           mucJids = mkOption {
             type = str;
             example = "jvbbrewery@internal.xmpp.example.org";
-            description = ''
+            description = lib.mdDoc ''
               JID of the MUC to join. JiCoFo needs to be configured to join the same MUC.
             '';
           };
           mucNickname = mkOption {
             # Upstream DEBs use UUID, let's use hostname instead.
             type = str;
-            description = ''
+            description = lib.mdDoc ''
               Videobridges use the same XMPP account and need to be distinguished by the
               nickname (aka resource part of the JID). By default, system hostname is used.
             '';
@@ -142,7 +142,7 @@ in
           disableCertificateVerification = mkOption {
             type = bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Whether to skip validation of the server's certificate.
             '';
           };
@@ -150,7 +150,7 @@ in
         config = {
           hostName = mkDefault name;
           mucNickname = mkDefault (builtins.replaceStrings [ "." ] [ "-" ] (
-            config.networking.hostName + optionalString (config.networking.domain != null) ".${config.networking.domain}"
+            config.networking.fqdnOrHostName
           ));
         };
       }));
@@ -161,7 +161,7 @@ in
         type = nullOr str;
         default = null;
         example = "192.168.1.42";
-        description = ''
+        description = lib.mdDoc ''
           Local address when running behind NAT.
         '';
       };
@@ -170,7 +170,7 @@ in
         type = nullOr str;
         default = null;
         example = "1.2.3.4";
-        description = ''
+        description = lib.mdDoc ''
           Public address when running behind NAT.
         '';
       };
@@ -179,7 +179,7 @@ in
     extraProperties = mkOption {
       type = attrsOf str;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Additional Java properties passed to jitsi-videobridge.
       '';
     };
@@ -187,14 +187,14 @@ in
     openFirewall = mkOption {
       type = bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to open ports in the firewall for the videobridge.
       '';
     };
 
     apis = mkOption {
       type = with types; listOf str;
-      description = ''
+      description = lib.mdDoc ''
         What is passed as --apis= parameter. If this is empty, "none" is passed.
         Needed for monitoring jitsi.
       '';
diff --git a/nixos/modules/services/networking/kea.nix b/nixos/modules/services/networking/kea.nix
index 17b4eb2e283..f39b149dd60 100644
--- a/nixos/modules/services/networking/kea.nix
+++ b/nixos/modules/services/networking/kea.nix
@@ -9,47 +9,64 @@ with lib;
 let
   cfg = config.services.kea;
 
+  xor = x: y: (!x && y) || (x && !y);
   format = pkgs.formats.json {};
 
-  ctrlAgentConfig = format.generate "kea-ctrl-agent.conf" {
+  chooseNotNull = x: y: if x != null then x else y;
+
+  ctrlAgentConfig = chooseNotNull cfg.ctrl-agent.configFile (format.generate "kea-ctrl-agent.conf" {
     Control-agent = cfg.ctrl-agent.settings;
-  };
-  dhcp4Config = format.generate "kea-dhcp4.conf" {
+  });
+
+  dhcp4Config = chooseNotNull cfg.dhcp4.configFile (format.generate "kea-dhcp4.conf" {
     Dhcp4 = cfg.dhcp4.settings;
-  };
-  dhcp6Config = format.generate "kea-dhcp6.conf" {
+  });
+
+  dhcp6Config = chooseNotNull cfg.dhcp6.configFile (format.generate "kea-dhcp6.conf" {
     Dhcp6 = cfg.dhcp6.settings;
-  };
-  dhcpDdnsConfig = format.generate "kea-dhcp-ddns.conf" {
+  });
+
+  dhcpDdnsConfig = chooseNotNull cfg.dhcp-ddns.configFile (format.generate "kea-dhcp-ddns.conf" {
     DhcpDdns = cfg.dhcp-ddns.settings;
-  };
+  });
 
   package = pkgs.kea;
 in
 {
   options.services.kea = with types; {
     ctrl-agent = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kea Control Agent configuration
       '';
       default = {};
       type = submodule {
         options = {
-          enable = mkEnableOption "Kea Control Agent";
+          enable = mkEnableOption (lib.mdDoc "Kea Control Agent");
 
           extraArgs = mkOption {
             type = listOf str;
             default = [];
-            description = ''
+            description = lib.mdDoc ''
               List of additonal arguments to pass to the daemon.
             '';
           };
 
+          configFile = mkOption {
+            type = nullOr path;
+            default = null;
+            description = lib.mdDoc ''
+              Kea Control Agent configuration as a path, see <https://kea.readthedocs.io/en/kea-${package.version}/arm/agent.html>.
+
+              Takes preference over [settings](#opt-services.kea.ctrl-agent.settings).
+              Most users should prefer using [settings](#opt-services.kea.ctrl-agent.settings) instead.
+            '';
+          };
+
           settings = mkOption {
             type = format.type;
             default = null;
-            description = ''
-              Kea Control Agent configuration as an attribute set, see <link xlink:href="https://kea.readthedocs.io/en/kea-${package.version}/arm/agent.html"/>.
+            description = lib.mdDoc ''
+              Kea Control Agent configuration as an attribute set, see <https://kea.readthedocs.io/en/kea-${package.version}/arm/agent.html>.
             '';
           };
         };
@@ -57,22 +74,33 @@ in
     };
 
     dhcp4 = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         DHCP4 Server configuration
       '';
       default = {};
       type = submodule {
         options = {
-          enable = mkEnableOption "Kea DHCP4 server";
+          enable = mkEnableOption (lib.mdDoc "Kea DHCP4 server");
 
           extraArgs = mkOption {
             type = listOf str;
             default = [];
-            description = ''
+            description = lib.mdDoc ''
               List of additonal arguments to pass to the daemon.
             '';
           };
 
+          configFile = mkOption {
+            type = nullOr path;
+            default = null;
+            description = lib.mdDoc ''
+              Kea DHCP4 configuration as a path, see <https://kea.readthedocs.io/en/kea-${package.version}/arm/dhcp4-srv.html>.
+
+              Takes preference over [settings](#opt-services.kea.dhcp4.settings).
+              Most users should prefer using [settings](#opt-services.kea.dhcp4.settings) instead.
+            '';
+          };
+
           settings = mkOption {
             type = format.type;
             default = null;
@@ -97,8 +125,8 @@ in
                 } ];
               } ];
             };
-            description = ''
-              Kea DHCP4 configuration as an attribute set, see <link xlink:href="https://kea.readthedocs.io/en/kea-${package.version}/arm/dhcp4-srv.html"/>.
+            description = lib.mdDoc ''
+              Kea DHCP4 configuration as an attribute set, see <https://kea.readthedocs.io/en/kea-${package.version}/arm/dhcp4-srv.html>.
             '';
           };
         };
@@ -106,22 +134,33 @@ in
     };
 
     dhcp6 = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         DHCP6 Server configuration
       '';
       default = {};
       type = submodule {
         options = {
-          enable = mkEnableOption "Kea DHCP6 server";
+          enable = mkEnableOption (lib.mdDoc "Kea DHCP6 server");
 
           extraArgs = mkOption {
             type = listOf str;
             default = [];
-            description = ''
+            description = lib.mdDoc ''
               List of additonal arguments to pass to the daemon.
             '';
           };
 
+          configFile = mkOption {
+            type = nullOr path;
+            default = null;
+            description = lib.mdDoc ''
+              Kea DHCP6 configuration as a path, see <https://kea.readthedocs.io/en/kea-${package.version}/arm/dhcp6-srv.html>.
+
+              Takes preference over [settings](#opt-services.kea.dhcp6.settings).
+              Most users should prefer using [settings](#opt-services.kea.dhcp6.settings) instead.
+            '';
+          };
+
           settings = mkOption {
             type = format.type;
             default = null;
@@ -147,8 +186,8 @@ in
                 } ];
               } ];
             };
-            description = ''
-              Kea DHCP6 configuration as an attribute set, see <link xlink:href="https://kea.readthedocs.io/en/kea-${package.version}/arm/dhcp6-srv.html"/>.
+            description = lib.mdDoc ''
+              Kea DHCP6 configuration as an attribute set, see <https://kea.readthedocs.io/en/kea-${package.version}/arm/dhcp6-srv.html>.
             '';
           };
         };
@@ -156,22 +195,33 @@ in
     };
 
     dhcp-ddns = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Kea DHCP-DDNS configuration
       '';
       default = {};
       type = submodule {
         options = {
-          enable = mkEnableOption "Kea DDNS server";
+          enable = mkEnableOption (lib.mdDoc "Kea DDNS server");
 
           extraArgs = mkOption {
             type = listOf str;
             default = [];
-            description = ''
+            description = lib.mdDoc ''
               List of additonal arguments to pass to the daemon.
             '';
           };
 
+          configFile = mkOption {
+            type = nullOr path;
+            default = null;
+            description = lib.mdDoc ''
+              Kea DHCP-DDNS configuration as a path, see <https://kea.readthedocs.io/en/kea-${package.version}/arm/ddns.html>.
+
+              Takes preference over [settings](#opt-services.kea.dhcp-ddns.settings).
+              Most users should prefer using [settings](#opt-services.kea.dhcp-ddns.settings) instead.
+            '';
+          };
+
           settings = mkOption {
             type = format.type;
             default = null;
@@ -189,8 +239,8 @@ in
                 ddns-domains = [ ];
               };
             };
-            description = ''
-              Kea DHCP-DDNS configuration as an attribute set, see <link xlink:href="https://kea.readthedocs.io/en/kea-${package.version}/arm/ddns.html"/>.
+            description = lib.mdDoc ''
+              Kea DHCP-DDNS configuration as an attribute set, see <https://kea.readthedocs.io/en/kea-${package.version}/arm/ddns.html>.
             '';
           };
         };
@@ -214,6 +264,10 @@ in
   }
 
   (mkIf cfg.ctrl-agent.enable {
+    assertions = [{
+        assertion = xor (cfg.ctrl-agent.settings == null) (cfg.ctrl-agent.configFile == null);
+        message = "Either services.kea.ctrl-agent.settings or services.kea.ctrl-agent.configFile must be set to a non-null value.";
+    }];
 
     environment.etc."kea/ctrl-agent.conf".source = ctrlAgentConfig;
 
@@ -244,7 +298,7 @@ in
       ];
 
       serviceConfig = {
-        ExecStart = "${package}/bin/kea-ctrl-agent -c /etc/kea/ctrl-agent.conf ${lib.escapeShellArgs cfg.dhcp4.extraArgs}";
+        ExecStart = "${package}/bin/kea-ctrl-agent -c /etc/kea/ctrl-agent.conf ${lib.escapeShellArgs cfg.ctrl-agent.extraArgs}";
         KillMode = "process";
         Restart = "on-failure";
       } // commonServiceConfig;
@@ -252,6 +306,10 @@ in
   })
 
   (mkIf cfg.dhcp4.enable {
+    assertions = [{
+        assertion = xor (cfg.dhcp4.settings == null) (cfg.dhcp4.configFile == null);
+        message = "Either services.kea.dhcp4.settings or services.kea.dhcp4.configFile must be set to a non-null value.";
+    }];
 
     environment.etc."kea/dhcp4-server.conf".source = dhcp4Config;
 
@@ -295,6 +353,10 @@ in
   })
 
   (mkIf cfg.dhcp6.enable {
+    assertions = [{
+        assertion = xor (cfg.dhcp6.settings == null) (cfg.dhcp6.configFile == null);
+        message = "Either services.kea.dhcp6.settings or services.kea.dhcp6.configFile must be set to a non-null value.";
+    }];
 
     environment.etc."kea/dhcp6-server.conf".source = dhcp6Config;
 
@@ -336,6 +398,10 @@ in
   })
 
   (mkIf cfg.dhcp-ddns.enable {
+    assertions = [{
+        assertion = xor (cfg.dhcp-ddns.settings == null) (cfg.dhcp-ddns.configFile == null);
+        message = "Either services.kea.dhcp-ddns.settings or services.kea.dhcp-ddns.configFile must be set to a non-null value.";
+    }];
 
     environment.etc."kea/dhcp-ddns.conf".source = dhcpDdnsConfig;
 
diff --git a/nixos/modules/services/networking/keepalived/default.nix b/nixos/modules/services/networking/keepalived/default.nix
index c9ac2ee2599..29fbea5545c 100644
--- a/nixos/modules/services/networking/keepalived/default.nix
+++ b/nixos/modules/services/networking/keepalived/default.nix
@@ -84,13 +84,11 @@ let
     ''
   ) vrrpInstances);
 
-  virtualIpLine = (ip:
-    ip.addr
+  virtualIpLine = ip: ip.addr
     + optionalString (notNullOrEmpty ip.brd) " brd ${ip.brd}"
     + optionalString (notNullOrEmpty ip.dev) " dev ${ip.dev}"
     + optionalString (notNullOrEmpty ip.scope) " scope ${ip.scope}"
-    + optionalString (notNullOrEmpty ip.label) " label ${ip.label}"
-  );
+    + optionalString (notNullOrEmpty ip.label) " label ${ip.label}";
 
   notNullOrEmpty = s: !(s == null || s == "");
 
@@ -147,7 +145,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Keepalived.
         '';
       };
@@ -155,7 +153,7 @@ in
       enableScriptSecurity = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Don't run scripts configured to be run as root if any part of the path is writable by a non-root user.
         '';
       };
@@ -165,7 +163,7 @@ in
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable the builtin AgentX subagent.
           '';
         };
@@ -173,7 +171,7 @@ in
         socket = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Socket to use for connecting to SNMP master agent. If this value is
             set to null, keepalived's default will be used, which is
             unix:/var/agentx/master, unless using a network namespace, when the
@@ -184,7 +182,7 @@ in
         enableKeepalived = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Enable SNMP handling of vrrp element of KEEPALIVED MIB.
           '';
         };
@@ -192,7 +190,7 @@ in
         enableChecker = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Enable SNMP handling of checker element of KEEPALIVED MIB.
           '';
         };
@@ -200,7 +198,7 @@ in
         enableRfc = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Enable SNMP handling of RFC2787 and RFC6527 VRRP MIBs.
           '';
         };
@@ -208,7 +206,7 @@ in
         enableRfcV2 = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Enable SNMP handling of RFC2787 VRRP MIB.
           '';
         };
@@ -216,7 +214,7 @@ in
         enableRfcV3 = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Enable SNMP handling of RFC6527 VRRP MIB.
           '';
         };
@@ -224,7 +222,7 @@ in
         enableTraps = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Enable SNMP traps.
           '';
         };
@@ -236,7 +234,7 @@ in
           inherit lib;
         }));
         default = {};
-        description = "Declarative vrrp script config";
+        description = lib.mdDoc "Declarative vrrp script config";
       };
 
       vrrpInstances = mkOption {
@@ -244,13 +242,13 @@ in
           inherit lib;
         }));
         default = {};
-        description = "Declarative vhost config";
+        description = lib.mdDoc "Declarative vhost config";
       };
 
       extraGlobalDefs = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to the 'global_defs' block of the
           configuration file
         '';
@@ -259,11 +257,24 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to the configuration file.
         '';
       };
 
+      secretFile = mkOption {
+        type = types.nullOr types.path;
+        default = null;
+        example = "/run/keys/keepalived.env";
+        description = lib.mdDoc ''
+          Environment variables from this file will be interpolated into the
+          final config file using envsubst with this syntax: `$ENVIRONMENT`
+          or `''${VARIABLE}`.
+          The file should contain lines formatted as `SECRET_VAR=SECRET_VALUE`.
+          This is useful to avoid putting secrets into the nix store.
+        '';
+      };
+
     };
   };
 
@@ -282,7 +293,9 @@ in
       };
     };
 
-    systemd.services.keepalived = {
+    systemd.services.keepalived = let
+      finalConfigFile = if cfg.secretFile == null then keepalivedConf else "/run/keepalived/keepalived.conf";
+    in {
       description = "Keepalive Daemon (LVS and VRRP)";
       after = [ "network.target" "network-online.target" "syslog.target" ];
       wants = [ "network-online.target" ];
@@ -290,8 +303,15 @@ in
         Type = "forking";
         PIDFile = pidFile;
         KillMode = "process";
+        RuntimeDirectory = "keepalived";
+        EnvironmentFile = lib.optional (cfg.secretFile != null) cfg.secretFile;
+        ExecStartPre = lib.optional (cfg.secretFile != null)
+        (pkgs.writeShellScript "keepalived-pre-start" ''
+          umask 077
+          ${pkgs.envsubst}/bin/envsubst -i "${keepalivedConf}" > ${finalConfigFile}
+        '');
         ExecStart = "${pkgs.keepalived}/sbin/keepalived"
-          + " -f ${keepalivedConf}"
+          + " -f ${finalConfigFile}"
           + " -p ${pidFile}"
           + optionalString cfg.snmp.enable " --snmp";
         ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
diff --git a/nixos/modules/services/networking/keepalived/virtual-ip-options.nix b/nixos/modules/services/networking/keepalived/virtual-ip-options.nix
index 1b8889b1b47..1fa6a0ee3bf 100644
--- a/nixos/modules/services/networking/keepalived/virtual-ip-options.nix
+++ b/nixos/modules/services/networking/keepalived/virtual-ip-options.nix
@@ -6,7 +6,7 @@ with lib;
 
     addr = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         IP address, optionally with a netmask: IPADDR[/MASK]
       '';
     };
@@ -14,7 +14,7 @@ with lib;
     brd = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The broadcast address on the interface.
       '';
     };
@@ -22,7 +22,7 @@ with lib;
     dev = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The name of the device to add the address to.
       '';
     };
@@ -30,7 +30,7 @@ with lib;
     scope = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The scope of the area where this address is valid.
       '';
     };
@@ -38,7 +38,7 @@ with lib;
     label = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Each address may be tagged with a label string. In order to preserve
         compatibility with Linux-2.0 net aliases, this string must coincide with
         the name of the device or must be prefixed with the device name followed
diff --git a/nixos/modules/services/networking/keepalived/vrrp-instance-options.nix b/nixos/modules/services/networking/keepalived/vrrp-instance-options.nix
index e96dde5fa89..20e5558d782 100644
--- a/nixos/modules/services/networking/keepalived/vrrp-instance-options.nix
+++ b/nixos/modules/services/networking/keepalived/vrrp-instance-options.nix
@@ -6,7 +6,7 @@ with lib;
 
     interface = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Interface for inside_network, bound by vrrp.
       '';
     };
@@ -14,7 +14,7 @@ with lib;
     state = mkOption {
       type = types.enum [ "MASTER" "BACKUP" ];
       default = "BACKUP";
-      description = ''
+      description = lib.mdDoc ''
         Initial state. As soon as the other machine(s) come up, an election will
         be held and the machine with the highest "priority" will become MASTER.
         So the entry here doesn't matter a whole lot.
@@ -23,7 +23,7 @@ with lib;
 
     virtualRouterId = mkOption {
       type = types.int;
-      description = ''
+      description = lib.mdDoc ''
         Arbitrary unique number 0..255. Used to differentiate multiple instances
         of vrrpd running on the same NIC (and hence same socket).
       '';
@@ -32,7 +32,7 @@ with lib;
     priority = mkOption {
       type = types.int;
       default = 100;
-      description = ''
+      description = lib.mdDoc ''
         For electing MASTER, highest priority wins. To be MASTER, make 50 more
         than other machines.
       '';
@@ -41,7 +41,7 @@ with lib;
     noPreempt = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         VRRP will normally preempt a lower priority machine when a higher
         priority machine comes online. "nopreempt" allows the lower priority
         machine to maintain the master role, even when a higher priority machine
@@ -53,7 +53,7 @@ with lib;
     useVmac = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Use VRRP Virtual MAC.
       '';
     };
@@ -61,7 +61,7 @@ with lib;
     vmacInterface = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
          Name of the vmac interface to use. keepalived will come up with a name
          if you don't specify one.
       '';
@@ -70,7 +70,7 @@ with lib;
     vmacXmitBase = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Send/Recv VRRP messages from base interface instead of VMAC interface.
       '';
     };
@@ -78,7 +78,7 @@ with lib;
     unicastSrcIp = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
          Default IP for binding vrrpd is the primary IP on interface. If you
          want to hide location of vrrpd, use this IP as src_addr for unicast
          vrrp packets.
@@ -88,7 +88,7 @@ with lib;
     unicastPeers = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Do not send VRRP adverts over VRRP multicast group. Instead it sends
         adverts to the following list of ip addresses using unicast design
         fashion. It can be cool to use VRRP FSM and features in a networking
@@ -103,27 +103,27 @@ with lib;
       }));
       default = [];
       # TODO: example
-      description = "Declarative vhost config";
+      description = lib.mdDoc "Declarative vhost config";
     };
 
     trackScripts = mkOption {
       type = types.listOf types.str;
       default = [];
       example = [ "chk_cmd1" "chk_cmd2" ];
-      description = "List of script names to invoke for health tracking.";
+      description = lib.mdDoc "List of script names to invoke for health tracking.";
     };
 
     trackInterfaces = mkOption {
       type = types.listOf types.str;
       default = [];
       example = [ "eth0" "eth1" ];
-      description = "List of network interfaces to monitor for health tracking.";
+      description = lib.mdDoc "List of network interfaces to monitor for health tracking.";
     };
 
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra lines to be added verbatim to the vrrp_instance section.
       '';
     };
diff --git a/nixos/modules/services/networking/keepalived/vrrp-script-options.nix b/nixos/modules/services/networking/keepalived/vrrp-script-options.nix
index df7a89cff8c..852d6b0ec26 100644
--- a/nixos/modules/services/networking/keepalived/vrrp-script-options.nix
+++ b/nixos/modules/services/networking/keepalived/vrrp-script-options.nix
@@ -8,55 +8,55 @@ with lib.types;
     script = mkOption {
       type = str;
       example = literalExpression ''"''${pkgs.curl} -f http://localhost:80"'';
-      description = "(Path of) Script command to execute followed by args, i.e. cmd [args]...";
+      description = lib.mdDoc "(Path of) Script command to execute followed by args, i.e. cmd [args]...";
     };
 
     interval = mkOption {
       type = int;
       default = 1;
-      description = "Seconds between script invocations.";
+      description = lib.mdDoc "Seconds between script invocations.";
     };
 
     timeout = mkOption {
       type = int;
       default = 5;
-      description = "Seconds after which script is considered to have failed.";
+      description = lib.mdDoc "Seconds after which script is considered to have failed.";
     };
 
     weight = mkOption {
       type = int;
       default = 0;
-      description = "Following a failure, adjust the priority by this weight.";
+      description = lib.mdDoc "Following a failure, adjust the priority by this weight.";
     };
 
     rise = mkOption {
       type = int;
       default = 5;
-      description = "Required number of successes for OK transition.";
+      description = lib.mdDoc "Required number of successes for OK transition.";
     };
 
     fall = mkOption {
       type = int;
       default = 3;
-      description = "Required number of failures for KO transition.";
+      description = lib.mdDoc "Required number of failures for KO transition.";
     };
 
     user = mkOption {
       type = str;
       default = "keepalived_script";
-      description = "Name of user to run the script under.";
+      description = lib.mdDoc "Name of user to run the script under.";
     };
 
     group = mkOption {
       type = nullOr str;
       default = null;
-      description = "Name of group to run the script under. Defaults to user group.";
+      description = lib.mdDoc "Name of group to run the script under. Defaults to user group.";
     };
 
     extraConfig = mkOption {
       type = lines;
       default = "";
-      description = "Extra lines to be added verbatim to the vrrp_script section.";
+      description = lib.mdDoc "Extra lines to be added verbatim to the vrrp_script section.";
     };
 
   };
diff --git a/nixos/modules/services/networking/keybase.nix b/nixos/modules/services/networking/keybase.nix
index 495102cb7ee..ae10aebb86e 100644
--- a/nixos/modules/services/networking/keybase.nix
+++ b/nixos/modules/services/networking/keybase.nix
@@ -14,7 +14,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to start the Keybase service.";
+        description = lib.mdDoc "Whether to start the Keybase service.";
       };
 
     };
diff --git a/nixos/modules/services/networking/knot.nix b/nixos/modules/services/networking/knot.nix
index a58a03997b3..ee7ea83456d 100644
--- a/nixos/modules/services/networking/knot.nix
+++ b/nixos/modules/services/networking/knot.nix
@@ -18,7 +18,7 @@ let
 
   knot-cli-wrappers = pkgs.stdenv.mkDerivation {
     name = "knot-cli-wrappers";
-    buildInputs = [ pkgs.makeWrapper ];
+    nativeBuildInputs = [ pkgs.makeWrapper ];
     buildCommand = ''
       mkdir -p $out/bin
       makeWrapper ${cfg.package}/bin/knotc "$out/bin/knotc" \
@@ -37,12 +37,12 @@ let
 in {
   options = {
     services.knot = {
-      enable = mkEnableOption "Knot authoritative-only DNS server";
+      enable = mkEnableOption (lib.mdDoc "Knot authoritative-only DNS server");
 
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of additional command line paramters for knotd
         '';
       };
@@ -50,7 +50,7 @@ in {
       keyFiles = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of files containing additional configuration
           to be included using the include directive. This option
           allows to include configuration like TSIG keys without
@@ -63,7 +63,7 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to knot.conf
         '';
       };
@@ -72,7 +72,7 @@ in {
         type = types.package;
         default = pkgs.knot-dns;
         defaultText = literalExpression "pkgs.knot-dns";
-        description = ''
+        description = lib.mdDoc ''
           Which Knot DNS package to use
         '';
       };
diff --git a/nixos/modules/services/networking/kresd.nix b/nixos/modules/services/networking/kresd.nix
index 28b8be7a9a0..55af6abd5e0 100644
--- a/nixos/modules/services/networking/kresd.nix
+++ b/nixos/modules/services/networking/kresd.nix
@@ -50,18 +50,18 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable knot-resolver domain name server.
         DNSSEC validation is turned on by default.
-        You can run <literal>sudo nc -U /run/knot-resolver/control/1</literal>
+        You can run `sudo nc -U /run/knot-resolver/control/1`
         and give commands interactively to kresd@1.service.
       '';
     };
     package = mkOption {
       type = types.package;
-      description = "
+      description = lib.mdDoc ''
         knot-resolver package to use.
-      ";
+      '';
       default = pkgs.knot-resolver;
       defaultText = literalExpression "pkgs.knot-resolver";
       example = literalExpression "pkgs.knot-resolver.override { extraFeatures = true; }";
@@ -69,7 +69,7 @@ in {
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra lines to be added verbatim to the generated configuration file.
       '';
     };
@@ -77,7 +77,7 @@ in {
       type = with types; listOf str;
       default = [ "[::1]:53" "127.0.0.1:53" ];
       example = [ "53" ];
-      description = ''
+      description = lib.mdDoc ''
         What addresses and ports the server should listen on.
         For detailed syntax see ListenStream in man systemd.socket.
       '';
@@ -86,7 +86,7 @@ in {
       type = with types; listOf str;
       default = [];
       example = [ "198.51.100.1:853" "[2001:db8::1]:853" "853" ];
-      description = ''
+      description = lib.mdDoc ''
         Addresses and ports on which kresd should provide DNS over TLS (see RFC 7858).
         For detailed syntax see ListenStream in man systemd.socket.
       '';
@@ -95,7 +95,7 @@ in {
       type = with types; listOf str;
       default = [];
       example = [ "198.51.100.1:443" "[2001:db8::1]:443" "443" ];
-      description = ''
+      description = lib.mdDoc ''
         Addresses and ports on which kresd should provide DNS over HTTPS/2 (see RFC 8484).
         For detailed syntax see ListenStream in man systemd.socket.
       '';
@@ -103,7 +103,7 @@ in {
     instances = mkOption {
       type = types.ints.unsigned;
       default = 1;
-      description = ''
+      description = lib.mdDoc ''
         The number of instances to start.  They will be called kresd@{1,2,...}.service.
         Knot Resolver uses no threads, so this is the way to scale.
         You can dynamically start/stop them at will, so this is just system default.
diff --git a/nixos/modules/services/networking/lambdabot.nix b/nixos/modules/services/networking/lambdabot.nix
index 3005e582455..8609bc97196 100644
--- a/nixos/modules/services/networking/lambdabot.nix
+++ b/nixos/modules/services/networking/lambdabot.nix
@@ -21,20 +21,20 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable the Lambdabot IRC bot";
+        description = lib.mdDoc "Enable the Lambdabot IRC bot";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.lambdabot;
         defaultText = literalExpression "pkgs.lambdabot";
-        description = "Used lambdabot package";
+        description = lib.mdDoc "Used lambdabot package";
       };
 
       script = mkOption {
         type = types.str;
         default = "";
-        description = "Lambdabot script";
+        description = lib.mdDoc "Lambdabot script";
       };
 
     };
diff --git a/nixos/modules/services/networking/libreswan.nix b/nixos/modules/services/networking/libreswan.nix
index 429167aed9d..b5df31c28d7 100644
--- a/nixos/modules/services/networking/libreswan.nix
+++ b/nixos/modules/services/networking/libreswan.nix
@@ -47,7 +47,7 @@ in
 
     services.libreswan = {
 
-      enable = mkEnableOption "Libreswan IPsec service";
+      enable = mkEnableOption (lib.mdDoc "Libreswan IPsec service");
 
       configSetup = mkOption {
         type = types.lines;
@@ -60,7 +60,7 @@ in
             protostack=netkey
             virtual_private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12,%v4:25.0.0.0/8,%v4:100.64.0.0/10,%v6:fd00::/8,%v6:fe80::/10
         '';
-        description = "Options to go in the 'config setup' section of the Libreswan IPsec configuration";
+        description = lib.mdDoc "Options to go in the 'config setup' section of the Libreswan IPsec configuration";
       };
 
       connections = mkOption {
@@ -79,7 +79,7 @@ in
             ''';
           }
         '';
-        description = "A set of connections to define for the Libreswan IPsec service";
+        description = lib.mdDoc "A set of connections to define for the Libreswan IPsec service";
       };
 
       policies = mkOption {
@@ -93,22 +93,22 @@ in
             ''';
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           A set of policies to apply to the IPsec connections.
 
-          <note><para>
-            The policy name must match the one of connection it needs to apply to.
-          </para></note>
+          ::: {.note}
+          The policy name must match the one of connection it needs to apply to.
+          :::
         '';
       };
 
       disableRedirects = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to disable send and accept redirects for all nework interfaces.
-          See the Libreswan <link xlink:href="https://libreswan.org/wiki/FAQ#Why_is_it_recommended_to_disable_send_redirects_in_.2Fproc.2Fsys.2Fnet_.3F">
-          FAQ</link> page for why this is recommended.
+          See the Libreswan [
+          FAQ](https://libreswan.org/wiki/FAQ#Why_is_it_recommended_to_disable_send_redirects_in_.2Fproc.2Fsys.2Fnet_.3F) page for why this is recommended.
         '';
       };
 
diff --git a/nixos/modules/services/networking/lldpd.nix b/nixos/modules/services/networking/lldpd.nix
index d5de9c45d84..b7ac99d75d7 100644
--- a/nixos/modules/services/networking/lldpd.nix
+++ b/nixos/modules/services/networking/lldpd.nix
@@ -9,13 +9,13 @@ in
 
 {
   options.services.lldpd = {
-    enable = mkEnableOption "Link Layer Discovery Protocol Daemon";
+    enable = mkEnableOption (lib.mdDoc "Link Layer Discovery Protocol Daemon");
 
     extraArgs = mkOption {
       type = types.listOf types.str;
       default = [];
       example = [ "-c" "-k" "-I eth0" ];
-      description = "List of command line parameters for lldpd";
+      description = lib.mdDoc "List of command line parameters for lldpd";
     };
   };
 
diff --git a/nixos/modules/services/networking/logmein-hamachi.nix b/nixos/modules/services/networking/logmein-hamachi.nix
index 11cbdda2f84..7c00b82e3b3 100644
--- a/nixos/modules/services/networking/logmein-hamachi.nix
+++ b/nixos/modules/services/networking/logmein-hamachi.nix
@@ -18,7 +18,7 @@ in
       type = types.bool;
       default = false;
       description =
-        ''
+        lib.mdDoc ''
           Whether to enable LogMeIn Hamachi, a proprietary
           (closed source) commercial VPN software.
         '';
diff --git a/nixos/modules/services/networking/lokinet.nix b/nixos/modules/services/networking/lokinet.nix
new file mode 100644
index 00000000000..f6bc314ed26
--- /dev/null
+++ b/nixos/modules/services/networking/lokinet.nix
@@ -0,0 +1,157 @@
+{ config, lib, pkgs, ... }:
+
+let
+  cfg = config.services.lokinet;
+  dataDir = "/var/lib/lokinet";
+  settingsFormat = pkgs.formats.ini { listsAsDuplicateKeys = true; };
+  configFile = settingsFormat.generate "lokinet.ini" (lib.filterAttrsRecursive (n: v: v != null) cfg.settings);
+in with lib; {
+  options.services.lokinet = {
+    enable = mkEnableOption (lib.mdDoc "Lokinet daemon");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.lokinet;
+      defaultText = literalExpression "pkgs.lokinet";
+      description = lib.mdDoc "Lokinet package to use.";
+    };
+
+    useLocally = mkOption {
+      type = types.bool;
+      default = false;
+      example = true;
+      description = lib.mdDoc "Whether to use Lokinet locally.";
+    };
+
+    settings = mkOption {
+      type = with types;
+        submodule {
+          freeformType = settingsFormat.type;
+
+          options = {
+            dns = {
+              bind = mkOption {
+                type = str;
+                default = "127.3.2.1";
+                description = lib.mdDoc "Address to bind to for handling DNS requests.";
+              };
+
+              upstream = mkOption {
+                type = listOf str;
+                default = [ "9.9.9.10" ];
+                example = [ "1.1.1.1" "8.8.8.8" ];
+                description = lib.mdDoc ''
+                  Upstream resolver(s) to use as fallback for non-loki addresses.
+                  Multiple values accepted.
+                '';
+              };
+            };
+
+            network = {
+              exit = mkOption {
+                type = bool;
+                default = false;
+                description = lib.mdDoc ''
+                  Whether to act as an exit node. Beware that this
+                  increases demand on the server and may pose liability concerns.
+                  Enable at your own risk.
+                '';
+              };
+
+              exit-node = mkOption {
+                type = nullOr (listOf str);
+                default = null;
+                example = ''
+                  exit-node = [ "example.loki" ];              # maps all exit traffic to example.loki
+                  exit-node = [ "example.loki:100.0.0.0/24" ]; # maps 100.0.0.0/24 to example.loki
+                '';
+                description = lib.mdDoc ''
+                  Specify a `.loki` address and an optional ip range to use as an exit broker.
+                  See <http://probably.loki/wiki/index.php?title=Exit_Nodes> for
+                  a list of exit nodes.
+                '';
+              };
+
+              keyfile = mkOption {
+                type = nullOr str;
+                default = null;
+                example = "snappkey.private";
+                description = lib.mdDoc ''
+                  The private key to persist address with. If not specified the address will be ephemeral.
+                  This keyfile is generated automatically if the specified file doesn't exist.
+                '';
+              };
+            };
+          };
+        };
+      default = { };
+      example = literalExpression ''
+        {
+          dns = {
+            bind = "127.3.2.1";
+            upstream = [ "1.1.1.1" "8.8.8.8" ];
+          };
+
+          network.exit-node = [ "example.loki" "example2.loki" ];
+        }
+      '';
+      description = lib.mdDoc ''
+        Configuration for Lokinet.
+        Currently, the best way to view the available settings is by
+        generating a config file using `lokinet -g`.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    networking.resolvconf.extraConfig = mkIf cfg.useLocally ''
+      name_servers="${cfg.settings.dns.bind}"
+    '';
+
+    systemd.services.lokinet = {
+      description = "Lokinet";
+      after = [ "network-online.target" "network.target" ];
+      wants = [ "network-online.target" "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+
+      preStart = ''
+        ln -sf ${cfg.package}/share/bootstrap.signed ${dataDir}
+        ${pkgs.coreutils}/bin/install -m 600 ${configFile} ${dataDir}/lokinet.ini
+
+        ${optionalString (cfg.settings.network.keyfile != null) ''
+          ${pkgs.crudini}/bin/crudini --set ${dataDir}/lokinet.ini network keyfile "${dataDir}/${cfg.settings.network.keyfile}"
+        ''}
+      '';
+
+      serviceConfig = {
+        DynamicUser = true;
+        StateDirectory = "lokinet";
+        AmbientCapabilities = [ "CAP_NET_ADMIN" "CAP_NET_BIND_SERVICE" ];
+        ExecStart = "${cfg.package}/bin/lokinet ${dataDir}/lokinet.ini";
+        Restart = "always";
+        RestartSec = "5s";
+
+        # hardening
+        LockPersonality = true;
+        MemoryDenyWriteExecute = true;
+        NoNewPrivileges = true;
+        PrivateTmp = true;
+        PrivateMounts = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectSystem = "strict";
+        ReadWritePaths = "/dev/net/tun";
+        RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" "AF_NETLINK" ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        RestrictSUIDSGID = true;
+      };
+    };
+
+    environment.systemPackages = [ cfg.package ];
+  };
+}
diff --git a/nixos/modules/services/networking/lxd-image-server.nix b/nixos/modules/services/networking/lxd-image-server.nix
index b119ba8acf6..1099169440a 100644
--- a/nixos/modules/services/networking/lxd-image-server.nix
+++ b/nixos/modules/services/networking/lxd-image-server.nix
@@ -11,30 +11,30 @@ in
 {
   options = {
     services.lxd-image-server = {
-      enable = mkEnableOption "lxd-image-server";
+      enable = mkEnableOption (lib.mdDoc "lxd-image-server");
 
       group = mkOption {
         type = types.str;
-        description = "Group assigned to the user and the webroot directory.";
+        description = lib.mdDoc "Group assigned to the user and the webroot directory.";
         default = "nginx";
         example = "www-data";
       };
 
       settings = mkOption {
         type = format.type;
-        description = ''
+        description = lib.mdDoc ''
           Configuration for lxd-image-server.
 
-          Example see <link xlink:href="https://github.com/Avature/lxd-image-server/blob/master/config.toml"/>.
+          Example see <https://github.com/Avature/lxd-image-server/blob/master/config.toml>.
         '';
         default = {};
       };
 
       nginx = {
-        enable = mkEnableOption "nginx";
+        enable = mkEnableOption (lib.mdDoc "nginx");
         domain = mkOption {
           type = types.str;
-          description = "Domain to use for nginx virtual host.";
+          description = lib.mdDoc "Domain to use for nginx virtual host.";
           example = "images.example.org";
         };
       };
@@ -51,18 +51,14 @@ in
 
       environment.etc."lxd-image-server/config.toml".source = format.generate "config.toml" cfg.settings;
 
-      services.logrotate.paths.lxd-image-server = {
-        path = "/var/log/lxd-image-server/lxd-image-server.log";
+      services.logrotate.settings.lxd-image-server = {
+        files = "/var/log/lxd-image-server/lxd-image-server.log";
         frequency = "daily";
-        keep = 21;
-        extraConfig = ''
-          create 755 lxd-image-server ${cfg.group}
-          missingok
-          compress
-          delaycompress
-          copytruncate
-          notifempty
-        '';
+        rotate = 21;
+        create = "755 lxd-image-server ${cfg.group}";
+        compress = true;
+        delaycompress = true;
+        copytruncate = true;
       };
 
       systemd.tmpfiles.rules = [
diff --git a/nixos/modules/services/networking/magic-wormhole-mailbox-server.nix b/nixos/modules/services/networking/magic-wormhole-mailbox-server.nix
index 09d357cd2b6..9dd1f62350a 100644
--- a/nixos/modules/services/networking/magic-wormhole-mailbox-server.nix
+++ b/nixos/modules/services/networking/magic-wormhole-mailbox-server.nix
@@ -9,7 +9,7 @@ let
 in
 {
   options.services.magic-wormhole-mailbox-server = {
-    enable = mkEnableOption "Enable Magic Wormhole Mailbox Server";
+    enable = mkEnableOption (lib.mdDoc "Magic Wormhole Mailbox Server");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/networking/matterbridge.nix b/nixos/modules/services/networking/matterbridge.nix
index 9186eee26ab..2921074fcd2 100644
--- a/nixos/modules/services/networking/matterbridge.nix
+++ b/nixos/modules/services/networking/matterbridge.nix
@@ -17,13 +17,13 @@ in
 {
   options = {
     services.matterbridge = {
-      enable = mkEnableOption "Matterbridge chat platform bridge";
+      enable = mkEnableOption (lib.mdDoc "Matterbridge chat platform bridge");
 
       configPath = mkOption {
         type = with types; nullOr str;
         default = null;
         example = "/etc/nixos/matterbridge.toml";
-        description = ''
+        description = lib.mdDoc ''
           The path to the matterbridge configuration file.
         '';
       };
@@ -62,10 +62,10 @@ in
               account="mattermost.work"
               channel="off-topic"
         '';
-        description = ''
+        description = lib.mdDoc ''
           WARNING: THIS IS INSECURE, as your password will end up in
-          <filename>/nix/store</filename>, thus publicly readable. Use
-          <literal>services.matterbridge.configPath</literal> instead.
+          {file}`/nix/store`, thus publicly readable. Use
+          `services.matterbridge.configPath` instead.
 
           The matterbridge configuration file in the TOML file format.
         '';
@@ -73,7 +73,7 @@ in
       user = mkOption {
         type = types.str;
         default = "matterbridge";
-        description = ''
+        description = lib.mdDoc ''
           User which runs the matterbridge service.
         '';
       };
@@ -81,7 +81,7 @@ in
       group = mkOption {
         type = types.str;
         default = "matterbridge";
-        description = ''
+        description = lib.mdDoc ''
           Group which runs the matterbridge service.
         '';
       };
diff --git a/nixos/modules/services/networking/minidlna.nix b/nixos/modules/services/networking/minidlna.nix
index c860f63efa6..549f1fe5de3 100644
--- a/nixos/modules/services/networking/minidlna.nix
+++ b/nixos/modules/services/networking/minidlna.nix
@@ -1,168 +1,129 @@
 # Module for MiniDLNA, a simple DLNA server.
 { config, lib, pkgs, ... }:
-
 with lib;
 
 let
   cfg = config.services.minidlna;
-  port = 8200;
+  settingsFormat = pkgs.formats.keyValue { listsAsDuplicateKeys = true; };
+  settingsFile = settingsFormat.generate "minidlna.conf" cfg.settings;
 in
 
 {
   ###### interface
-  options = {
-    services.minidlna.enable = mkOption {
-      type = types.bool;
-      default = false;
-      description =
-        ''
-          Whether to enable MiniDLNA, a simple DLNA server.  It serves
-          media files such as video and music to DLNA client devices
-          such as televisions and media players.
-        '';
-    };
-
-    services.minidlna.mediaDirs = mkOption {
-      type = types.listOf types.str;
-      default = [];
-      example = [ "/data/media" "V,/home/alice/video" ];
-      description =
-        ''
-          Directories to be scanned for media files.  The prefixes
-          <literal>A,</literal>, <literal>V,</literal> and
-          <literal>P,</literal> restrict a directory to audio, video
-          or image files.  The directories must be accessible to the
-          <literal>minidlna</literal> user account.
-        '';
-    };
-
-    services.minidlna.friendlyName = mkOption {
-      type = types.str;
-      default = "${config.networking.hostName} MiniDLNA";
-      defaultText = literalExpression ''"''${config.networking.hostName} MiniDLNA"'';
-      example = "rpi3";
-      description =
-        ''
-          Name that the DLNA server presents to clients.
-        '';
-    };
-
-    services.minidlna.rootContainer = mkOption {
-      type = types.str;
-      default = ".";
-      example = "B";
-      description =
-        ''
-          Use a different container as the root of the directory tree presented
-          to clients. The possible values are:
-          - "." - standard container
-          - "B" - "Browse Directory"
-          - "M" - "Music"
-          - "P" - "Pictures"
-          - "V" - "Video"
-          - Or, you can specify the ObjectID of your desired root container
-            (eg. 1$F for Music/Playlists)
-          If you specify "B" and the client device is audio-only then
-          "Music/Folders" will be used as root.
-         '';
-    };
-
-    services.minidlna.loglevel = mkOption {
-      type = types.str;
-      default = "warn";
-      example = "general,artwork,database,inotify,scanner,metadata,http,ssdp,tivo=warn";
-      description =
-        ''
-          Defines the type of messages that should be logged, and down to
-          which level of importance they should be considered.
-
-          The possible types are “artwork”, “database”, “general”, “http”,
-          “inotify”, “metadata”, “scanner”, “ssdp” and “tivo”.
-
-          The levels are “off”, “fatal”, “error”, “warn”, “info” and
-          “debug”, listed here in order of decreasing importance.  “off”
-          turns off logging messages entirely, “fatal” logs the most
-          critical messages only, and so on down to “debug” that logs every
-          single messages.
+  options.services.minidlna.enable = mkOption {
+    type = types.bool;
+    default = false;
+    description = lib.mdDoc ''
+      Whether to enable MiniDLNA, a simple DLNA server.
+      It serves media files such as video and music to DLNA client devices
+      such as televisions and media players. If you use the firewall consider
+      adding the following: `services.minidlna.openFirewall = true;`
+    '';
+  };
 
-          The types are comma-separated, followed by an equal sign (‘=’),
-          followed by a level that applies to the preceding types. This can
-          be repeated, separating each of these constructs with a comma.
+  options.services.minidlna.openFirewall = mkOption {
+    type = types.bool;
+    default = false;
+    description = lib.mdDoc ''
+      Whether to open both HTTP (TCP) and SSDP (UDP) ports in the firewall.
+    '';
+  };
 
-          Defaults to “general,artwork,database,inotify,scanner,metadata,
-          http,ssdp,tivo=warn” which logs every type of message at the
-          “warn” level.
+  options.services.minidlna.settings = mkOption {
+    default = {};
+    description = lib.mdDoc ''
+      The contents of MiniDLNA's configuration file.
+      When the service is activated, a basic template is generated from the current options opened here.
+    '';
+    type = types.submodule {
+      freeformType = settingsFormat.type;
+
+      options.media_dir = mkOption {
+        type = types.listOf types.str;
+        default = [];
+        example = [ "/data/media" "V,/home/alice/video" ];
+        description = lib.mdDoc ''
+          Directories to be scanned for media files.
+          The `A,` `V,` `P,` prefixes restrict a directory to audio, video or image files.
+          The directories must be accessible to the `minidlna` user account.
         '';
-    };
-
-    services.minidlna.announceInterval = mkOption {
-      type = types.int;
-      default = 895;
-      description =
-        ''
+      };
+      options.notify_interval = mkOption {
+        type = types.int;
+        default = 90000;
+        description = lib.mdDoc ''
           The interval between announces (in seconds).
+          Instead of waiting for announces, you should set `openFirewall` option to use SSDP discovery.
+          Furthermore, this option has been set to 90000 in order to prevent disconnects with certain
+          clients and relies solely on the discovery.
 
-          By default miniDLNA will announce its presence on the network
-          approximately every 15 minutes.
-
-          Many people prefer shorter announce intervals (e.g. 60 seconds)
-          on their home networks, especially when DLNA clients are
-          started on demand.
+          Lower values (e.g. 30 seconds) should be used if you can't use the discovery.
+          Some relevant information can be found here:
+          https://sourceforge.net/p/minidlna/discussion/879957/thread/1389d197/
         '';
-    };
-
-    services.minidlna.config = mkOption {
-      type = types.lines;
-      description =
-      ''
-        The contents of MiniDLNA's configuration file.
-        When the service is activated, a basic template is generated
-        from the current options opened here.
-      '';
-    };
-
-    services.minidlna.extraConfig = mkOption {
-      type = types.lines;
-      default = "";
-      example = ''
-        # Not exhaustive example
-        # Support for streaming .jpg and .mp3 files to a TiVo supporting HMO.
-        enable_tivo=no
-        # SSDP notify interval, in seconds.
-        notify_interval=10
-        # maximum number of simultaneous connections
-        # note: many clients open several simultaneous connections while
-        # streaming
-        max_connections=50
-        # set this to yes to allow symlinks that point outside user-defined
-        # media_dirs.
-        wide_links=yes
-      '';
-      description =
-      ''
-        Extra minidlna options not yet opened for configuration here
-        (strict_dlna, model_number, model_name, etc...).  This is appended
-        to the current service already provided.
-      '';
+      };
+      options.port = mkOption {
+        type = types.port;
+        default = 8200;
+        description = lib.mdDoc "Port number for HTTP traffic (descriptions, SOAP, media transfer).";
+      };
+      options.db_dir = mkOption {
+        type = types.path;
+        default = "/var/cache/minidlna";
+        example = "/tmp/minidlna";
+        description = lib.mdDoc "Specify the directory where you want MiniDLNA to store its database and album art cache.";
+      };
+      options.friendly_name = mkOption {
+        type = types.str;
+        default = config.networking.hostName;
+        defaultText = literalExpression "config.networking.hostName";
+        example = "rpi3";
+        description = lib.mdDoc "Name that the DLNA server presents to clients.";
+      };
+      options.root_container = mkOption {
+        type = types.str;
+        default = ".";
+        example = "B";
+        description = lib.mdDoc "Use a different container as the root of the directory tree presented to clients.";
+      };
+      options.log_level = mkOption {
+        type = types.str;
+        default = "warn";
+        example = "general,artwork,database,inotify,scanner,metadata,http,ssdp,tivo=warn";
+        description = lib.mdDoc "Defines the type of messages that should be logged and down to which level of importance.";
+      };
+      options.inotify = mkOption {
+        type = types.enum [ "yes" "no" ];
+        default = "no";
+        description = lib.mdDoc "Whether to enable inotify monitoring to automatically discover new files.";
+      };
+      options.enable_tivo = mkOption {
+        type = types.enum [ "yes" "no" ];
+        default = "no";
+        description = lib.mdDoc "Support for streaming .jpg and .mp3 files to a TiVo supporting HMO.";
+      };
+      options.wide_links = mkOption {
+        type = types.enum [ "yes" "no" ];
+        default = "no";
+        description = lib.mdDoc "Set this to yes to allow symlinks that point outside user-defined `media_dir`.";
+      };
     };
   };
 
+  imports = [
+    (mkRemovedOptionModule [ "services" "minidlna" "config" ] "")
+    (mkRemovedOptionModule [ "services" "minidlna" "extraConfig" ] "")
+    (mkRenamedOptionModule [ "services" "minidlna" "loglevel"] [ "services" "minidlna" "settings" "log_level" ])
+    (mkRenamedOptionModule [ "services" "minidlna" "rootContainer"] [ "services" "minidlna" "settings" "root_container" ])
+    (mkRenamedOptionModule [ "services" "minidlna" "mediaDirs"] [ "services" "minidlna" "settings" "media_dir" ])
+    (mkRenamedOptionModule [ "services" "minidlna" "friendlyName"] [ "services" "minidlna" "settings" "friendly_name" ])
+    (mkRenamedOptionModule [ "services" "minidlna" "announceInterval"] [ "services" "minidlna" "settings" "notify_interval" ])
+  ];
+
   ###### implementation
   config = mkIf cfg.enable {
-    services.minidlna.config =
-      ''
-        port=${toString port}
-        friendly_name=${cfg.friendlyName}
-        db_dir=/var/cache/minidlna
-        log_level=${cfg.loglevel}
-        inotify=yes
-        root_container=${cfg.rootContainer}
-        ${concatMapStrings (dir: ''
-          media_dir=${dir}
-        '') cfg.mediaDirs}
-        notify_interval=${toString cfg.announceInterval}
-        ${cfg.extraConfig}
-      '';
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.settings.port ];
+    networking.firewall.allowedUDPPorts = mkIf cfg.openFirewall [ 1900 ];
 
     users.users.minidlna = {
       description = "MiniDLNA daemon user";
@@ -186,7 +147,7 @@ in
             PIDFile = "/run/minidlna/pid";
             ExecStart =
               "${pkgs.minidlna}/sbin/minidlnad -S -P /run/minidlna/pid" +
-              " -f ${pkgs.writeText "minidlna.conf" cfg.config}";
+              " -f ${settingsFile}";
           };
       };
   };
diff --git a/nixos/modules/services/networking/miniupnpd.nix b/nixos/modules/services/networking/miniupnpd.nix
index c095d994854..64aacaf3504 100644
--- a/nixos/modules/services/networking/miniupnpd.nix
+++ b/nixos/modules/services/networking/miniupnpd.nix
@@ -19,11 +19,11 @@ in
 {
   options = {
     services.miniupnpd = {
-      enable = mkEnableOption "MiniUPnP daemon";
+      enable = mkEnableOption (lib.mdDoc "MiniUPnP daemon");
 
       externalInterface = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Name of the external interface.
         '';
       };
@@ -31,17 +31,17 @@ in
       internalIPs = mkOption {
         type = types.listOf types.str;
         example = [ "192.168.1.1/24" "enp1s0" ];
-        description = ''
+        description = lib.mdDoc ''
           The IP address ranges to listen on.
         '';
       };
 
-      natpmp = mkEnableOption "NAT-PMP support";
+      natpmp = mkEnableOption (lib.mdDoc "NAT-PMP support");
 
       upnp = mkOption {
         default = true;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable UPNP support.
         '';
       };
@@ -49,7 +49,7 @@ in
       appendConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Configuration lines appended to the MiniUPnP config.
         '';
       };
diff --git a/nixos/modules/services/networking/miredo.nix b/nixos/modules/services/networking/miredo.nix
index b7f657efb71..d15a55b4d7d 100644
--- a/nixos/modules/services/networking/miredo.nix
+++ b/nixos/modules/services/networking/miredo.nix
@@ -20,13 +20,13 @@ in
 
     services.miredo = {
 
-      enable = mkEnableOption "the Miredo IPv6 tunneling service";
+      enable = mkEnableOption (lib.mdDoc "the Miredo IPv6 tunneling service");
 
       package = mkOption {
         type = types.package;
         default = pkgs.miredo;
         defaultText = literalExpression "pkgs.miredo";
-        description = ''
+        description = lib.mdDoc ''
           The package to use for the miredo daemon's binary.
         '';
       };
@@ -34,7 +34,7 @@ in
       serverAddress = mkOption {
         default = "teredo.remlab.net";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The hostname or primary IPv4 address of the Teredo server.
           This setting is required if Miredo runs as a Teredo client.
           "teredo.remlab.net" is an experimental service for testing only.
@@ -45,7 +45,7 @@ in
       interfaceName = mkOption {
         default = "teredo";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Name of the network tunneling interface.
         '';
       };
@@ -53,7 +53,7 @@ in
       bindAddress = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           Depending on the local firewall/NAT rules, you might need to force
           Miredo to use a fixed UDP port and or IPv4 address.
         '';
@@ -62,7 +62,7 @@ in
       bindPort = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           Depending on the local firewall/NAT rules, you might need to force
           Miredo to use a fixed UDP port and or IPv4 address.
         '';
diff --git a/nixos/modules/services/networking/mjpg-streamer.nix b/nixos/modules/services/networking/mjpg-streamer.nix
index dbc35e2e71c..8f8d5f5c4d3 100644
--- a/nixos/modules/services/networking/mjpg-streamer.nix
+++ b/nixos/modules/services/networking/mjpg-streamer.nix
@@ -12,12 +12,12 @@ in {
 
     services.mjpg-streamer = {
 
-      enable = mkEnableOption "mjpg-streamer webcam streamer";
+      enable = mkEnableOption (lib.mdDoc "mjpg-streamer webcam streamer");
 
       inputPlugin = mkOption {
         type = types.str;
         default = "input_uvc.so";
-        description = ''
+        description = lib.mdDoc ''
           Input plugin. See plugins documentation for more information.
         '';
       };
@@ -25,8 +25,8 @@ in {
       outputPlugin = mkOption {
         type = types.str;
         default = "output_http.so -w @www@ -n -p 5050";
-        description = ''
-          Output plugin. <literal>@www@</literal> is substituted for default mjpg-streamer www directory.
+        description = lib.mdDoc ''
+          Output plugin. `@www@` is substituted for default mjpg-streamer www directory.
           See plugins documentation for more information.
         '';
       };
@@ -34,13 +34,13 @@ in {
       user = mkOption {
         type = types.str;
         default = "mjpg-streamer";
-        description = "mjpg-streamer user name.";
+        description = lib.mdDoc "mjpg-streamer user name.";
       };
 
       group = mkOption {
         type = types.str;
         default = "video";
-        description = "mjpg-streamer group name.";
+        description = lib.mdDoc "mjpg-streamer group name.";
       };
 
     };
diff --git a/nixos/modules/services/networking/monero.nix b/nixos/modules/services/networking/monero.nix
index 8bed89917c8..0de02882aca 100644
--- a/nixos/modules/services/networking/monero.nix
+++ b/nixos/modules/services/networking/monero.nix
@@ -50,12 +50,12 @@ in
 
     services.monero = {
 
-      enable = mkEnableOption "Monero node daemon";
+      enable = mkEnableOption (lib.mdDoc "Monero node daemon");
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/monero";
-        description = ''
+        description = lib.mdDoc ''
           The directory where Monero stores its data files.
         '';
       };
@@ -63,7 +63,7 @@ in
       mining.enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to mine monero.
         '';
       };
@@ -71,7 +71,7 @@ in
       mining.address = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Monero address where to send mining rewards.
         '';
       };
@@ -79,16 +79,16 @@ in
       mining.threads = mkOption {
         type = types.addCheck types.int (x: x>=0);
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Number of threads used for mining.
-          Set to <literal>0</literal> to use all available.
+          Set to `0` to use all available.
         '';
       };
 
       rpc.user = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           User name for RPC connections.
         '';
       };
@@ -96,7 +96,7 @@ in
       rpc.password = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Password for RPC connections.
         '';
       };
@@ -104,7 +104,7 @@ in
       rpc.address = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = ''
+        description = lib.mdDoc ''
           IP address the RPC server will bind to.
         '';
       };
@@ -112,7 +112,7 @@ in
       rpc.port = mkOption {
         type = types.port;
         default = 18081;
-        description = ''
+        description = lib.mdDoc ''
           Port the RPC server will bind to.
         '';
       };
@@ -120,7 +120,7 @@ in
       rpc.restricted = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to restrict RPC to view only commands.
         '';
       };
@@ -128,43 +128,43 @@ in
       limits.upload = mkOption {
         type = types.addCheck types.int (x: x>=-1);
         default = -1;
-        description = ''
+        description = lib.mdDoc ''
           Limit of the upload rate in kB/s.
-          Set to <literal>-1</literal> to leave unlimited.
+          Set to `-1` to leave unlimited.
         '';
       };
 
       limits.download = mkOption {
         type = types.addCheck types.int (x: x>=-1);
         default = -1;
-        description = ''
+        description = lib.mdDoc ''
           Limit of the download rate in kB/s.
-          Set to <literal>-1</literal> to leave unlimited.
+          Set to `-1` to leave unlimited.
         '';
       };
 
       limits.threads = mkOption {
         type = types.addCheck types.int (x: x>=0);
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of threads used for a parallel job.
-          Set to <literal>0</literal> to leave unlimited.
+          Set to `0` to leave unlimited.
         '';
       };
 
       limits.syncSize = mkOption {
         type = types.addCheck types.int (x: x>=0);
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of blocks to sync at once.
-          Set to <literal>0</literal> for adaptive.
+          Set to `0` for adaptive.
         '';
       };
 
       extraNodes = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           List of additional peer IP addresses to add to the local list.
         '';
       };
@@ -172,7 +172,7 @@ in
       priorityNodes = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           List of peer IP addresses to connect to and
           attempt to keep the connection open.
         '';
@@ -181,7 +181,7 @@ in
       exclusiveNodes = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           List of peer IP addresses to connect to *only*.
           If given the other peer options will be ignored.
         '';
@@ -190,7 +190,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra lines to be added verbatim to monerod configuration.
         '';
       };
diff --git a/nixos/modules/services/networking/morty.nix b/nixos/modules/services/networking/morty.nix
index dff2f482ca6..4b20c34cfc9 100644
--- a/nixos/modules/services/networking/morty.nix
+++ b/nixos/modules/services/networking/morty.nix
@@ -17,48 +17,48 @@ in
     services.morty = {
 
       enable = mkEnableOption
-        "Morty proxy server. See https://github.com/asciimoo/morty";
+        (lib.mdDoc "Morty proxy server. See https://github.com/asciimoo/morty");
 
       ipv6 = mkOption {
         type = types.bool;
         default = true;
-        description = "Allow IPv6 HTTP requests?";
+        description = lib.mdDoc "Allow IPv6 HTTP requests?";
       };
 
       key = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           HMAC url validation key (hexadecimal encoded).
           Leave blank to disable. Without validation key, anyone can
           submit proxy requests. Leave blank to disable.
-          Generate with <literal>printf %s somevalue | openssl dgst -sha1 -hmac somekey</literal>
+          Generate with `printf %s somevalue | openssl dgst -sha1 -hmac somekey`
         '';
       };
 
       timeout = mkOption {
         type = types.int;
         default = 2;
-        description = "Request timeout in seconds.";
+        description = lib.mdDoc "Request timeout in seconds.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.morty;
         defaultText = literalExpression "pkgs.morty";
-        description = "morty package to use.";
+        description = lib.mdDoc "morty package to use.";
       };
 
       port = mkOption {
         type = types.int;
         default = 3000;
-        description = "Listing port";
+        description = lib.mdDoc "Listing port";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "The address on which the service listens";
+        description = lib.mdDoc "The address on which the service listens";
       };
 
     };
diff --git a/nixos/modules/services/networking/mosquitto.nix b/nixos/modules/services/networking/mosquitto.nix
index b41a2fd27be..6543eb34b4b 100644
--- a/nixos/modules/services/networking/mosquitto.nix
+++ b/nixos/modules/services/networking/mosquitto.nix
@@ -36,7 +36,7 @@ let
       password = mkOption {
         type = uniq (nullOr str);
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the (clear text) password for the MQTT User.
         '';
       };
@@ -45,7 +45,7 @@ let
         type = uniq (nullOr types.path);
         example = "/path/to/file";
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the path to a file containing the
           clear text password for the MQTT user.
         '';
@@ -54,10 +54,12 @@ let
       hashedPassword = mkOption {
         type = uniq (nullOr str);
         default = null;
-        description = ''
+        description = mdDoc ''
           Specifies the hashed password for the MQTT User.
-          To generate hashed password install <literal>mosquitto</literal>
-          package and use <literal>mosquitto_passwd</literal>.
+          To generate hashed password install the `mosquitto`
+          package and use `mosquitto_passwd`, then extract
+          the second field (after the `:`) from the generated
+          file.
         '';
       };
 
@@ -65,11 +67,12 @@ let
         type = uniq (nullOr types.path);
         example = "/path/to/file";
         default = null;
-        description = ''
+        description = mdDoc ''
           Specifies the path to a file containing the
           hashed password for the MQTT user.
-          To generate hashed password install <literal>mosquitto</literal>
-          package and use <literal>mosquitto_passwd</literal>.
+          To generate hashed password install the `mosquitto`
+          package and use `mosquitto_passwd`, then remove the
+          `username:` prefix from the generated file.
         '';
       };
 
@@ -77,7 +80,7 @@ let
         type = listOf str;
         example = [ "read A/B" "readwrite A/#" ];
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Control client access to topics on the broker.
         '';
       };
@@ -155,24 +158,24 @@ let
     options = {
       plugin = mkOption {
         type = path;
-        description = ''
-          Plugin path to load, should be a <literal>.so</literal> file.
+        description = mdDoc ''
+          Plugin path to load, should be a `.so` file.
         '';
       };
 
       denySpecialChars = mkOption {
         type = bool;
-        description = ''
-          Automatically disallow all clients using <literal>#</literal>
-          or <literal>+</literal> in their name/id.
+        description = mdDoc ''
+          Automatically disallow all clients using `#`
+          or `+` in their name/id.
         '';
         default = true;
       };
 
       options = mkOption {
         type = attrsOf optionType;
-        description = ''
-          Options for the auth plugin. Each key turns into a <literal>auth_opt_*</literal>
+        description = mdDoc ''
+          Options for the auth plugin. Each key turns into a `auth_opt_*`
            line in the config.
         '';
         default = {};
@@ -199,6 +202,7 @@ let
     allow_anonymous = 1;
     allow_zero_length_clientid = 1;
     auto_id_prefix = 1;
+    bind_interface = 1;
     cafile = 1;
     capath = 1;
     certfile = 1;
@@ -230,7 +234,7 @@ let
     options = {
       port = mkOption {
         type = port;
-        description = ''
+        description = lib.mdDoc ''
           Port to listen on. Must be set to 0 to listen on a unix domain socket.
         '';
         default = 1883;
@@ -238,8 +242,8 @@ let
 
       address = mkOption {
         type = nullOr str;
-        description = ''
-          Address to listen on. Listen on <literal>0.0.0.0</literal>/<literal>::</literal>
+        description = mdDoc ''
+          Address to listen on. Listen on `0.0.0.0`/`::`
           when unset.
         '';
         default = null;
@@ -247,10 +251,10 @@ let
 
       authPlugins = mkOption {
         type = listOf authPluginOptions;
-        description = ''
+        description = mdDoc ''
           Authentication plugin to attach to this listener.
-          Refer to the <link xlink:href="https://mosquitto.org/man/mosquitto-conf-5.html">
-          mosquitto.conf documentation</link> for details on authentication plugins.
+          Refer to the [mosquitto.conf documentation](https://mosquitto.org/man/mosquitto-conf-5.html)
+          for details on authentication plugins.
         '';
         default = [];
       };
@@ -258,7 +262,7 @@ let
       users = mkOption {
         type = attrsOf userOptions;
         example = { john = { password = "123456"; acl = [ "readwrite john/#" ]; }; };
-        description = ''
+        description = lib.mdDoc ''
           A set of users and their passwords and ACLs.
         '';
         default = {};
@@ -266,7 +270,7 @@ let
 
       omitPasswordAuth = mkOption {
         type = bool;
-        description = ''
+        description = lib.mdDoc ''
           Omits password checking, allowing anyone to log in with any user name unless
           other mandatory authentication methods (eg TLS client certificates) are configured.
         '';
@@ -275,7 +279,7 @@ let
 
       acl = mkOption {
         type = listOf str;
-        description = ''
+        description = lib.mdDoc ''
           Additional ACL items to prepend to the generated ACL file.
         '';
         example = [ "pattern read #" "topic readwrite anon/report/#" ];
@@ -286,7 +290,7 @@ let
         type = submodule {
           freeformType = attrsOf optionType;
         };
-        description = ''
+        description = lib.mdDoc ''
           Additional settings for this listener.
         '';
         default = {};
@@ -295,7 +299,7 @@ let
   };
 
   listenerAsserts = prefix: listener:
-    assertKeysValid prefix freeformListenerKeys listener.settings
+    assertKeysValid "${prefix}.settings" freeformListenerKeys listener.settings
     ++ userAsserts prefix listener.users
     ++ imap0
       (i: v: authAsserts "${prefix}.authPlugins.${toString i}" v)
@@ -353,14 +357,14 @@ let
           options = {
             address = mkOption {
               type = str;
-              description = ''
+              description = lib.mdDoc ''
                 Address of the remote MQTT broker.
               '';
             };
 
             port = mkOption {
               type = port;
-              description = ''
+              description = lib.mdDoc ''
                 Port of the remote MQTT broker.
               '';
               default = 1883;
@@ -368,17 +372,17 @@ let
           };
         });
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Remote endpoints for the bridge.
         '';
       };
 
       topics = mkOption {
         type = listOf str;
-        description = ''
+        description = lib.mdDoc ''
           Topic patterns to be shared between the two brokers.
-          Refer to the <link xlink:href="https://mosquitto.org/man/mosquitto-conf-5.html">
-          mosquitto.conf documentation</link> for details on the format.
+          Refer to the [
+          mosquitto.conf documentation](https://mosquitto.org/man/mosquitto-conf-5.html) for details on the format.
         '';
         default = [];
         example = [ "# both 2 local/topic/ remote/topic/" ];
@@ -388,7 +392,7 @@ let
         type = submodule {
           freeformType = attrsOf optionType;
         };
-        description = ''
+        description = lib.mdDoc ''
           Additional settings for this bridge.
         '';
         default = {};
@@ -397,7 +401,7 @@ let
   };
 
   bridgeAsserts = prefix: bridge:
-    assertKeysValid prefix freeformBridgeKeys bridge.settings
+    assertKeysValid "${prefix}.settings" freeformBridgeKeys bridge.settings
     ++ [ {
       assertion = length bridge.addresses > 0;
       message = "Bridge ${prefix} needs remote broker addresses";
@@ -442,13 +446,13 @@ let
   };
 
   globalOptions = with types; {
-    enable = mkEnableOption "the MQTT Mosquitto broker";
+    enable = mkEnableOption (lib.mdDoc "the MQTT Mosquitto broker");
 
     package = mkOption {
       type = package;
       default = pkgs.mosquitto;
       defaultText = literalExpression "pkgs.mosquitto";
-      description = ''
+      description = lib.mdDoc ''
         Mosquitto package to use.
       '';
     };
@@ -456,7 +460,7 @@ let
     bridges = mkOption {
       type = attrsOf bridgeOptions;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         Bridges to build to other MQTT brokers.
       '';
     };
@@ -464,17 +468,17 @@ let
     listeners = mkOption {
       type = listOf listenerOptions;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         Listeners to configure on this broker.
       '';
     };
 
     includeDirs = mkOption {
       type = listOf path;
-      description = ''
+      description = mdDoc ''
         Directories to be scanned for further config files to include.
         Directories will processed in the order given,
-        <literal>*.conf</literal> files in the directory will be
+        `*.conf` files in the directory will be
         read in case-sensistive alphabetical order.
       '';
       default = [];
@@ -482,7 +486,7 @@ let
 
     logDest = mkOption {
       type = listOf (either path (enum [ "stdout" "stderr" "syslog" "topic" "dlt" ]));
-      description = ''
+      description = lib.mdDoc ''
         Destinations to send log messages to.
       '';
       default = [ "stderr" ];
@@ -491,7 +495,7 @@ let
     logType = mkOption {
       type = listOf (enum [ "debug" "error" "warning" "notice" "information"
                             "subscribe" "unsubscribe" "websockets" "none" "all" ]);
-      description = ''
+      description = lib.mdDoc ''
         Types of messages to log.
       '';
       default = [];
@@ -499,7 +503,7 @@ let
 
     persistence = mkOption {
       type = bool;
-      description = ''
+      description = lib.mdDoc ''
         Enable persistent storage of subscriptions and messages.
       '';
       default = true;
@@ -508,7 +512,7 @@ let
     dataDir = mkOption {
       default = "/var/lib/mosquitto";
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         The data directory.
       '';
     };
@@ -517,7 +521,7 @@ let
       type = submodule {
         freeformType = attrsOf optionType;
       };
-      description = ''
+      description = lib.mdDoc ''
         Global configuration options for the mosquitto broker.
       '';
       default = {};
@@ -526,7 +530,7 @@ let
 
   globalAsserts = prefix: cfg:
     flatten [
-      (assertKeysValid prefix freeformGlobalKeys cfg.settings)
+      (assertKeysValid "${prefix}.settings" freeformGlobalKeys cfg.settings)
       (imap0 (n: l: listenerAsserts "${prefix}.listener.${toString n}" l) cfg.listeners)
       (mapAttrsToList (n: b: bridgeAsserts "${prefix}.bridge.${n}" b) cfg.bridges)
     ];
@@ -629,9 +633,10 @@ in
                ]));
         RemoveIPC = true;
         RestrictAddressFamilies = [
-          "AF_UNIX"  # for sd_notify() call
+          "AF_UNIX"
           "AF_INET"
           "AF_INET6"
+          "AF_NETLINK"
         ];
         RestrictNamespaces = true;
         RestrictRealtime = true;
diff --git a/nixos/modules/services/networking/mozillavpn.nix b/nixos/modules/services/networking/mozillavpn.nix
new file mode 100644
index 00000000000..cf962879b42
--- /dev/null
+++ b/nixos/modules/services/networking/mozillavpn.nix
@@ -0,0 +1,14 @@
+{ config, lib, pkgs, ... }:
+
+{
+  options.services.mozillavpn.enable =
+    lib.mkEnableOption (lib.mdDoc "Mozilla VPN daemon");
+
+  config = lib.mkIf config.services.mozillavpn.enable {
+    environment.systemPackages = [ pkgs.mozillavpn ];
+    services.dbus.packages = [ pkgs.mozillavpn ];
+    systemd.packages = [ pkgs.mozillavpn ];
+  };
+
+  meta.maintainers = with lib.maintainers; [ andersk ];
+}
diff --git a/nixos/modules/services/networking/mstpd.nix b/nixos/modules/services/networking/mstpd.nix
index bd71010ce54..ba82c5ac823 100644
--- a/nixos/modules/services/networking/mstpd.nix
+++ b/nixos/modules/services/networking/mstpd.nix
@@ -9,7 +9,7 @@ with lib;
     enable = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable the multiple spanning tree protocol daemon.
       '';
     };
diff --git a/nixos/modules/services/networking/mtprotoproxy.nix b/nixos/modules/services/networking/mtprotoproxy.nix
index d896f227b82..3dd197697b2 100644
--- a/nixos/modules/services/networking/mtprotoproxy.nix
+++ b/nixos/modules/services/networking/mtprotoproxy.nix
@@ -37,12 +37,12 @@ in
 
     services.mtprotoproxy = {
 
-      enable = mkEnableOption "mtprotoproxy";
+      enable = mkEnableOption (lib.mdDoc "mtprotoproxy");
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 3256;
-        description = ''
+        description = lib.mdDoc ''
           TCP port to accept mtproto connections on.
         '';
       };
@@ -53,7 +53,7 @@ in
           tg = "00000000000000000000000000000000";
           tg2 = "0123456789abcdef0123456789abcdef";
         };
-        description = ''
+        description = lib.mdDoc ''
           Allowed users and their secrets. A secret is a 32 characters long hex string.
         '';
       };
@@ -61,7 +61,7 @@ in
       secureOnly = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Don't allow users to connect in non-secure mode (without random padding).
         '';
       };
@@ -71,7 +71,7 @@ in
         default = null;
         # Taken from mtproxyproto's repo.
         example = "3c09c680b76ee91a4c25ad51f742267d";
-        description = ''
+        description = lib.mdDoc ''
           Tag for advertising that can be obtained from @MTProxybot.
         '';
       };
@@ -82,7 +82,7 @@ in
         example = {
           STATS_PRINT_PERIOD = 600;
         };
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration options for mtprotoproxy.
         '';
       };
diff --git a/nixos/modules/services/networking/mtr-exporter.nix b/nixos/modules/services/networking/mtr-exporter.nix
index ca261074ebd..43ebbbe96d0 100644
--- a/nixos/modules/services/networking/mtr-exporter.nix
+++ b/nixos/modules/services/networking/mtr-exporter.nix
@@ -9,37 +9,37 @@ in {
   options = {
     services = {
       mtr-exporter = {
-        enable = mkEnableOption "a Prometheus exporter for MTR";
+        enable = mkEnableOption (lib.mdDoc "a Prometheus exporter for MTR");
 
         target = mkOption {
           type = types.str;
           example = "example.org";
-          description = "Target to check using MTR.";
+          description = lib.mdDoc "Target to check using MTR.";
         };
 
         interval = mkOption {
           type = types.int;
           default = 60;
-          description = "Interval between MTR checks in seconds.";
+          description = lib.mdDoc "Interval between MTR checks in seconds.";
         };
 
         port = mkOption {
           type = types.port;
           default = 8080;
-          description = "Listen port for MTR exporter.";
+          description = lib.mdDoc "Listen port for MTR exporter.";
         };
 
         address = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "Listen address for MTR exporter.";
+          description = lib.mdDoc "Listen address for MTR exporter.";
         };
 
         mtrFlags = mkOption {
           type = with types; listOf str;
           default = [];
           example = ["-G1"];
-          description = "Additional flags to pass to MTR.";
+          description = lib.mdDoc "Additional flags to pass to MTR.";
         };
       };
     };
diff --git a/nixos/modules/services/networking/mullvad-vpn.nix b/nixos/modules/services/networking/mullvad-vpn.nix
index 9ec1ddc929e..82e68bf92af 100644
--- a/nixos/modules/services/networking/mullvad-vpn.nix
+++ b/nixos/modules/services/networking/mullvad-vpn.nix
@@ -4,24 +4,54 @@ let
 in
 with lib;
 {
-  options.services.mullvad-vpn.enable = mkOption {
-    type = types.bool;
-    default = false;
-    description = ''
-      This option enables Mullvad VPN daemon.
-      This sets <option>networking.firewall.checkReversePath</option> to "loose", which might be undesirable for security.
-    '';
+  options.services.mullvad-vpn = {
+    enable = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        This option enables Mullvad VPN daemon.
+        This sets {option}`networking.firewall.checkReversePath` to "loose", which might be undesirable for security.
+      '';
+    };
+
+    enableExcludeWrapper = mkOption {
+      type = types.bool;
+      default = true;
+      description = lib.mdDoc ''
+        This option activates the wrapper that allows the use of mullvad-exclude.
+        Might have minor security impact, so consider disabling if you do not use the feature.
+      '';
+    };
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.mullvad;
+      defaultText = literalExpression "pkgs.mullvad";
+      description = lib.mdDoc ''
+        The Mullvad package to use. `pkgs.mullvad` only provides the CLI tool, `pkgs.mullvad-vpn` provides both the CLI and the GUI.
+      '';
+    };
   };
 
   config = mkIf cfg.enable {
     boot.kernelModules = [ "tun" ];
 
+    environment.systemPackages = [ cfg.package ];
+
     # mullvad-daemon writes to /etc/iproute2/rt_tables
     networking.iproute2.enable = true;
 
     # See https://github.com/NixOS/nixpkgs/issues/113589
     networking.firewall.checkReversePath = "loose";
 
+    # See https://github.com/NixOS/nixpkgs/issues/176603
+    security.wrappers.mullvad-exclude = mkIf cfg.enableExcludeWrapper {
+      setuid = true;
+      owner = "root";
+      group = "root";
+      source = "${cfg.package}/bin/mullvad-exclude";
+    };
+
     systemd.services.mullvad-daemon = {
       description = "Mullvad VPN daemon";
       wantedBy = [ "multi-user.target" ];
@@ -39,12 +69,12 @@ with lib;
       startLimitBurst = 5;
       startLimitIntervalSec = 20;
       serviceConfig = {
-        ExecStart = "${pkgs.mullvad-vpn}/bin/mullvad-daemon -v --disable-stdout-timestamps";
+        ExecStart = "${cfg.package}/bin/mullvad-daemon -v --disable-stdout-timestamps";
         Restart = "always";
         RestartSec = 1;
       };
     };
   };
 
-  meta.maintainers = with maintainers; [ ymarkus ];
+  meta.maintainers = with maintainers; [ patricksjackson ymarkus ];
 }
diff --git a/nixos/modules/services/networking/multipath.nix b/nixos/modules/services/networking/multipath.nix
index 1a44184ff6d..cb6b6db272c 100644
--- a/nixos/modules/services/networking/multipath.nix
+++ b/nixos/modules/services/networking/multipath.nix
@@ -22,11 +22,11 @@ in {
 
   options.services.multipath = with types; {
 
-    enable = mkEnableOption "the device mapper multipath (DM-MP) daemon";
+    enable = mkEnableOption (lib.mdDoc "the device mapper multipath (DM-MP) daemon");
 
     package = mkOption {
       type = package;
-      description = "multipath-tools package to use";
+      description = lib.mdDoc "multipath-tools package to use";
       default = pkgs.multipath-tools;
       defaultText = "pkgs.multipath-tools";
     };
@@ -44,7 +44,7 @@ in {
           }, ...
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         This option allows you to define arrays for use in multipath
         groups.
       '';
@@ -54,62 +54,62 @@ in {
           vendor = mkOption {
             type = str;
             example = "COMPELNT";
-            description = "Regular expression to match the vendor name";
+            description = lib.mdDoc "Regular expression to match the vendor name";
           };
 
           product = mkOption {
             type = str;
             example = "Compellent Vol";
-            description = "Regular expression to match the product name";
+            description = lib.mdDoc "Regular expression to match the product name";
           };
 
           revision = mkOption {
             type = nullOr str;
             default = null;
-            description = "Regular expression to match the product revision";
+            description = lib.mdDoc "Regular expression to match the product revision";
           };
 
           product_blacklist = mkOption {
             type = nullOr str;
             default = null;
-            description = "Products with the given vendor matching this string are blacklisted";
+            description = lib.mdDoc "Products with the given vendor matching this string are blacklisted";
           };
 
           alias_prefix = mkOption {
             type = nullOr str;
             default = null;
-            description = "The user_friendly_names prefix to use for this device type, instead of the default mpath";
+            description = lib.mdDoc "The user_friendly_names prefix to use for this device type, instead of the default mpath";
           };
 
           vpd_vendor = mkOption {
             type = nullOr str;
             default = null;
-            description = "The vendor specific vpd page information, using the vpd page abbreviation";
+            description = lib.mdDoc "The vendor specific vpd page information, using the vpd page abbreviation";
           };
 
           hardware_handler = mkOption {
             type = nullOr (enum [ "emc" "rdac" "hp_sw" "alua" "ana" ]);
             default = null;
-            description = "The hardware handler to use for this device type";
+            description = lib.mdDoc "The hardware handler to use for this device type";
           };
 
           # Optional arguments
           path_grouping_policy = mkOption {
             type = nullOr (enum [ "failover" "multibus" "group_by_serial" "group_by_prio" "group_by_node_name" ]);
             default = null; # real default: "failover"
-            description = "The default path grouping policy to apply to unspecified multipaths";
+            description = lib.mdDoc "The default path grouping policy to apply to unspecified multipaths";
           };
 
           uid_attribute = mkOption {
             type = nullOr str;
             default = null;
-            description = "The udev attribute providing a unique path identifier (WWID)";
+            description = lib.mdDoc "The udev attribute providing a unique path identifier (WWID)";
           };
 
           getuid_callout = mkOption {
             type = nullOr str;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               (Superseded by uid_attribute) The default program and args to callout
               to obtain a unique path identifier. Should be specified with an absolute path.
             '';
@@ -123,13 +123,13 @@ in {
               ''"historical-service-time 0"''
             ]);
             default = null; # real default: "service-time 0"
-            description = "The default path selector algorithm to use; they are offered by the kernel multipath target";
+            description = lib.mdDoc "The default path selector algorithm to use; they are offered by the kernel multipath target";
           };
 
           path_checker = mkOption {
             type = enum [ "readsector0" "tur" "emc_clariion" "hp_sw" "rdac" "directio" "cciss_tur" "none" ];
             default = "tur";
-            description = "The default method used to determine the paths state";
+            description = lib.mdDoc "The default method used to determine the paths state";
           };
 
           prio = mkOption {
@@ -138,31 +138,31 @@ in {
               "random" "weightedpath" "path_latency" "ana" "datacore" "iet"
             ]);
             default = null; # real default: "const"
-            description = "The name of the path priority routine";
+            description = lib.mdDoc "The name of the path priority routine";
           };
 
           prio_args = mkOption {
             type = nullOr str;
             default = null;
-            description = "Arguments to pass to to the prio function";
+            description = lib.mdDoc "Arguments to pass to to the prio function";
           };
 
           features = mkOption {
             type = nullOr str;
             default = null;
-            description = "Specify any device-mapper features to be used";
+            description = lib.mdDoc "Specify any device-mapper features to be used";
           };
 
           failback = mkOption {
             type = nullOr str;
             default = null; # real default: "manual"
-            description = "Tell multipathd how to manage path group failback. Quote integers as strings";
+            description = lib.mdDoc "Tell multipathd how to manage path group failback. Quote integers as strings";
           };
 
           rr_weight = mkOption {
             type = nullOr (enum [ "priorities" "uniform" ]);
             default = null; # real default: "uniform"
-            description = ''
+            description = lib.mdDoc ''
               If set to priorities the multipath configurator will assign path weights
               as "path prio * rr_min_io".
             '';
@@ -171,13 +171,13 @@ in {
           no_path_retry = mkOption {
             type = nullOr str;
             default = null; # real default: "fail"
-            description = "Specify what to do when all paths are down. Quote integers as strings";
+            description = lib.mdDoc "Specify what to do when all paths are down. Quote integers as strings";
           };
 
           rr_min_io = mkOption {
             type = nullOr int;
             default = null; # real default: 1000
-            description = ''
+            description = lib.mdDoc ''
               Number of I/O requests to route to a path before switching to the next in the
               same path group. This is only for Block I/O (BIO) based multipath and
               only apply to round-robin path_selector.
@@ -187,7 +187,7 @@ in {
           rr_min_io_rq = mkOption {
             type = nullOr int;
             default = null; # real default: 1
-            description = ''
+            description = lib.mdDoc ''
               Number of I/O requests to route to a path before switching to the next in the
               same path group. This is only for Request based multipath and
               only apply to round-robin path_selector.
@@ -197,7 +197,7 @@ in {
           fast_io_fail_tmo = mkOption {
             type = nullOr str;
             default = null; # real default: 5
-            description = ''
+            description = lib.mdDoc ''
               Specify the number of seconds the SCSI layer will wait after a problem has been
               detected on a FC remote port before failing I/O to devices on that remote port.
               This should be smaller than dev_loss_tmo. Setting this to "off" will disable
@@ -208,7 +208,7 @@ in {
           dev_loss_tmo = mkOption {
             type = nullOr str;
             default = null; # real default: 600
-            description = ''
+            description = lib.mdDoc ''
               Specify the number of seconds the SCSI layer will wait after a problem has
               been detected on a FC remote port before removing it from the system. This
               can be set to "infinity" which sets it to the max value of 2147483647
@@ -224,7 +224,7 @@ in {
           flush_on_last_del = mkOption {
             type = nullOr (enum [ "yes" "no" ]);
             default = null; # real default: "no"
-            description = ''
+            description = lib.mdDoc ''
               If set to "yes" multipathd will disable queueing when the last path to a
               device has been deleted.
             '';
@@ -233,7 +233,7 @@ in {
           user_friendly_names = mkOption {
             type = nullOr (enum [ "yes" "no" ]);
             default = null; # real default: "no"
-            description = ''
+            description = lib.mdDoc ''
               If set to "yes", using the bindings file /etc/multipath/bindings
               to assign a persistent and unique alias to the multipath, in the
               form of mpath. If set to "no" use the WWID as the alias. In either
@@ -245,7 +245,7 @@ in {
           detect_prio = mkOption {
             type = nullOr (enum [ "yes" "no" ]);
             default = null; # real default: "yes"
-            description = ''
+            description = lib.mdDoc ''
               If set to "yes", multipath will try to detect if the device supports
               SCSI-3 ALUA. If so, the device will automatically use the sysfs
               prioritizer if the required sysf attributes access_state and
@@ -257,7 +257,7 @@ in {
           detect_checker = mkOption {
             type = nullOr (enum [ "yes" "no" ]);
             default = null; # real default: "yes"
-            description = ''
+            description = lib.mdDoc ''
               If set to "yes", multipath will try to detect if the device supports
               SCSI-3 ALUA. If so, the device will automatically use the tur checker.
               If set to "no", the checker will be selected as usual.
@@ -267,7 +267,7 @@ in {
           deferred_remove = mkOption {
             type = nullOr (enum [ "yes" "no" ]);
             default = null; # real default: "no"
-            description = ''
+            description = lib.mdDoc ''
               If set to "yes", multipathd will do a deferred remove instead of a
               regular remove when the last path device has been deleted. This means
               that if the multipath device is still in use, it will be freed when
@@ -279,7 +279,7 @@ in {
           san_path_err_threshold = mkOption {
             type = nullOr str;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               If set to a value greater than 0, multipathd will watch paths and check
               how many times a path has been failed due to errors.If the number of
               failures on a particular path is greater then the san_path_err_threshold,
@@ -292,7 +292,7 @@ in {
           san_path_err_forget_rate = mkOption {
             type = nullOr str;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               If set to a value greater than 0, multipathd will check whether the path
               failures has exceeded the san_path_err_threshold within this many checks
               i.e san_path_err_forget_rate. If so we will not reinstante the path till
@@ -303,7 +303,7 @@ in {
           san_path_err_recovery_time = mkOption {
             type = nullOr str;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               If set to a value greater than 0, multipathd will make sure that when
               path failures has exceeded the san_path_err_threshold within
               san_path_err_forget_rate then the path will be placed in failed state
@@ -316,61 +316,61 @@ in {
           marginal_path_err_sample_time = mkOption {
             type = nullOr int;
             default = null;
-            description = "One of the four parameters of supporting path check based on accounting IO error such as intermittent error";
+            description = lib.mdDoc "One of the four parameters of supporting path check based on accounting IO error such as intermittent error";
           };
 
           marginal_path_err_rate_threshold = mkOption {
             type = nullOr int;
             default = null;
-            description = "The error rate threshold as a permillage (1/1000)";
+            description = lib.mdDoc "The error rate threshold as a permillage (1/1000)";
           };
 
           marginal_path_err_recheck_gap_time = mkOption {
             type = nullOr str;
             default = null;
-            description = "One of the four parameters of supporting path check based on accounting IO error such as intermittent error";
+            description = lib.mdDoc "One of the four parameters of supporting path check based on accounting IO error such as intermittent error";
           };
 
           marginal_path_double_failed_time = mkOption {
             type = nullOr str;
             default = null;
-            description = "One of the four parameters of supporting path check based on accounting IO error such as intermittent error";
+            description = lib.mdDoc "One of the four parameters of supporting path check based on accounting IO error such as intermittent error";
           };
 
           delay_watch_checks = mkOption {
             type = nullOr str;
             default = null;
-            description = "This option is deprecated, and mapped to san_path_err_forget_rate";
+            description = lib.mdDoc "This option is deprecated, and mapped to san_path_err_forget_rate";
           };
 
           delay_wait_checks = mkOption {
             type = nullOr str;
             default = null;
-            description = "This option is deprecated, and mapped to san_path_err_recovery_time";
+            description = lib.mdDoc "This option is deprecated, and mapped to san_path_err_recovery_time";
           };
 
           skip_kpartx = mkOption {
             type = nullOr (enum [ "yes" "no" ]);
             default = null; # real default: "no"
-            description = "If set to yes, kpartx will not automatically create partitions on the device";
+            description = lib.mdDoc "If set to yes, kpartx will not automatically create partitions on the device";
           };
 
           max_sectors_kb = mkOption {
             type = nullOr int;
             default = null;
-            description = "Sets the max_sectors_kb device parameter on all path devices and the multipath device to the specified value";
+            description = lib.mdDoc "Sets the max_sectors_kb device parameter on all path devices and the multipath device to the specified value";
           };
 
           ghost_delay = mkOption {
             type = nullOr int;
             default = null;
-            description = "Sets the number of seconds that multipath will wait after creating a device with only ghost paths before marking it ready for use in systemd";
+            description = lib.mdDoc "Sets the number of seconds that multipath will wait after creating a device with only ghost paths before marking it ready for use in systemd";
           };
 
           all_tg_pt = mkOption {
             type = nullOr str;
             default = null;
-            description = "Set the 'all targets ports' flag when registering keys with mpathpersist";
+            description = lib.mdDoc "Set the 'all targets ports' flag when registering keys with mpathpersist";
           };
 
         };
@@ -380,7 +380,7 @@ in {
     defaults = mkOption {
       type = nullOr str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         This section defines default values for attributes which are used
         whenever no values are given in the appropriate device or multipath
         sections.
@@ -390,7 +390,7 @@ in {
     blacklist = mkOption {
       type = nullOr str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         This section defines which devices should be excluded from the
         multipath topology discovery.
       '';
@@ -399,7 +399,7 @@ in {
     blacklist_exceptions = mkOption {
       type = nullOr str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         This section defines which devices should be included in the
         multipath topology discovery, despite being listed in the
         blacklist section.
@@ -409,7 +409,7 @@ in {
     overrides = mkOption {
       type = nullOr str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         This section defines values for attributes that should override the
         device-specific settings for all devices.
       '';
@@ -418,13 +418,13 @@ in {
     extraConfig = mkOption {
       type = nullOr str;
       default = null;
-      description = "Lines to append to default multipath.conf";
+      description = lib.mdDoc "Lines to append to default multipath.conf";
     };
 
     extraConfigFile = mkOption {
       type = nullOr str;
       default = null;
-      description = "Append an additional file's contents to /etc/multipath.conf";
+      description = lib.mdDoc "Append an additional file's contents to /etc/multipath.conf";
     };
 
     pathGroups = mkOption {
@@ -439,7 +439,7 @@ in {
           }, ...
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         This option allows you to define multipath groups as described
         in http://christophe.varoqui.free.fr/usage.html.
       '';
@@ -449,34 +449,34 @@ in {
           alias = mkOption {
             type = int;
             example = 1001234;
-            description = "The name of the multipath device";
+            description = lib.mdDoc "The name of the multipath device";
           };
 
           wwid = mkOption {
             type = hexStr;
             example = "360080e500043b35c0123456789abcdef";
-            description = "The identifier for the multipath device";
+            description = lib.mdDoc "The identifier for the multipath device";
           };
 
           array = mkOption {
             type = str;
             default = null;
             example = "bigarray.example.com";
-            description = "The DNS name of the storage array";
+            description = lib.mdDoc "The DNS name of the storage array";
           };
 
           fsType = mkOption {
             type = nullOr str;
             default = null;
             example = "zfs";
-            description = "Type of the filesystem";
+            description = lib.mdDoc "Type of the filesystem";
           };
 
           options = mkOption {
             type = nullOr str;
             default = null;
             example = "ro";
-            description = "Options used to mount the file system";
+            description = lib.mdDoc "Options used to mount the file system";
           };
 
         };
diff --git a/nixos/modules/services/networking/murmur.nix b/nixos/modules/services/networking/murmur.nix
index 06ec04dbbf1..32498ca25ea 100644
--- a/nixos/modules/services/networking/murmur.nix
+++ b/nixos/modules/services/networking/murmur.nix
@@ -56,23 +56,31 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "If enabled, start the Murmur Mumble server.";
+        description = lib.mdDoc "If enabled, start the Murmur Mumble server.";
+      };
+
+      openFirewall = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Open ports in the firewall for the Murmur Mumble server.
+        '';
       };
 
       autobanAttempts = mkOption {
         type = types.int;
         default = 10;
-        description = ''
+        description = lib.mdDoc ''
           Number of attempts a client is allowed to make in
-          <literal>autobanTimeframe</literal> seconds, before being
-          banned for <literal>autobanTime</literal>.
+          `autobanTimeframe` seconds, before being
+          banned for `autobanTime`.
         '';
       };
 
       autobanTimeframe = mkOption {
         type = types.int;
         default = 120;
-        description = ''
+        description = lib.mdDoc ''
           Timeframe in which a client can connect without being banned
           for repeated attempts (in seconds).
         '';
@@ -81,51 +89,51 @@ in
       autobanTime = mkOption {
         type = types.int;
         default = 300;
-        description = "The amount of time an IP ban lasts (in seconds).";
+        description = lib.mdDoc "The amount of time an IP ban lasts (in seconds).";
       };
 
       logFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/var/log/murmur/murmurd.log";
-        description = "Path to the log file for Murmur daemon. Empty means log to journald.";
+        description = lib.mdDoc "Path to the log file for Murmur daemon. Empty means log to journald.";
       };
 
       welcometext = mkOption {
         type = types.str;
         default = "";
-        description = "Welcome message for connected clients.";
+        description = lib.mdDoc "Welcome message for connected clients.";
       };
 
       port = mkOption {
         type = types.port;
         default = 64738;
-        description = "Ports to bind to (UDP and TCP).";
+        description = lib.mdDoc "Ports to bind to (UDP and TCP).";
       };
 
       hostName = mkOption {
         type = types.str;
         default = "";
-        description = "Host to bind to. Defaults binding on all addresses.";
+        description = lib.mdDoc "Host to bind to. Defaults binding on all addresses.";
       };
 
       package = mkOption {
         type = types.package;
         default = pkgs.murmur;
         defaultText = literalExpression "pkgs.murmur";
-        description = "Overridable attribute of the murmur package to use.";
+        description = lib.mdDoc "Overridable attribute of the murmur package to use.";
       };
 
       password = mkOption {
         type = types.str;
         default = "";
-        description = "Required password to join server, if specified.";
+        description = lib.mdDoc "Required password to join server, if specified.";
       };
 
       bandwidth = mkOption {
         type = types.int;
         default = 72000;
-        description = ''
+        description = lib.mdDoc ''
           Maximum bandwidth (in bits per second) that clients may send
           speech at.
         '';
@@ -134,25 +142,25 @@ in
       users = mkOption {
         type = types.int;
         default = 100;
-        description = "Maximum number of concurrent clients allowed.";
+        description = lib.mdDoc "Maximum number of concurrent clients allowed.";
       };
 
       textMsgLength = mkOption {
         type = types.int;
         default = 5000;
-        description = "Max length of text messages. Set 0 for no limit.";
+        description = lib.mdDoc "Max length of text messages. Set 0 for no limit.";
       };
 
       imgMsgLength = mkOption {
         type = types.int;
         default = 131072;
-        description = "Max length of image messages. Set 0 for no limit.";
+        description = lib.mdDoc "Max length of image messages. Set 0 for no limit.";
       };
 
       allowHtml = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Allow HTML in client messages, comments, and channel
           descriptions.
         '';
@@ -161,7 +169,7 @@ in
       logDays = mkOption {
         type = types.int;
         default = 31;
-        description = ''
+        description = lib.mdDoc ''
           How long to store RPC logs for in the database. Set 0 to
           keep logs forever, or -1 to disable DB logging.
         '';
@@ -170,7 +178,7 @@ in
       bonjour = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable Bonjour auto-discovery, which allows clients over
           your LAN to automatically discover Murmur servers.
         '';
@@ -179,13 +187,13 @@ in
       sendVersion = mkOption {
         type = types.bool;
         default = true;
-        description = "Send Murmur version in UDP response.";
+        description = lib.mdDoc "Send Murmur version in UDP response.";
       };
 
       registerName = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Public server registration name, and also the name of the
           Root channel. Even if you don't publicly register your
           server, you probably still want to set this.
@@ -195,7 +203,7 @@ in
       registerPassword = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Public server registry password, used authenticate your
           server to the registry to prevent impersonation; required for
           subsequent registry updates.
@@ -205,13 +213,13 @@ in
       registerUrl = mkOption {
         type = types.str;
         default = "";
-        description = "URL website for your server.";
+        description = lib.mdDoc "URL website for your server.";
       };
 
       registerHostname = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           DNS hostname where your server can be reached. This is only
           needed if you want your server to be accessed by its
           hostname and not IP - but the name *must* resolve on the
@@ -222,58 +230,56 @@ in
       clientCertRequired = mkOption {
         type = types.bool;
         default = false;
-        description = "Require clients to authenticate via certificates.";
+        description = lib.mdDoc "Require clients to authenticate via certificates.";
       };
 
       sslCert = mkOption {
         type = types.str;
         default = "";
-        description = "Path to your SSL certificate.";
+        description = lib.mdDoc "Path to your SSL certificate.";
       };
 
       sslKey = mkOption {
         type = types.str;
         default = "";
-        description = "Path to your SSL key.";
+        description = lib.mdDoc "Path to your SSL key.";
       };
 
       sslCa = mkOption {
         type = types.str;
         default = "";
-        description = "Path to your SSL CA certificate.";
+        description = lib.mdDoc "Path to your SSL CA certificate.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Extra configuration to put into murmur.ini.";
+        description = lib.mdDoc "Extra configuration to put into murmur.ini.";
       };
 
       environmentFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/var/lib/murmur/murmurd.env";
-        description = ''
-          Environment file as defined in <citerefentry>
-          <refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum>
-          </citerefentry>.
+        description = lib.mdDoc ''
+          Environment file as defined in {manpage}`systemd.exec(5)`.
 
           Secrets may be passed to the service without adding them to the world-readable
           Nix store, by specifying placeholder variables as the option value in Nix and
           setting these variables accordingly in the environment file.
 
-          <programlisting>
+          ```
             # snippet of murmur-related config
             services.murmur.password = "$MURMURD_PASSWORD";
-          </programlisting>
+          ```
 
-          <programlisting>
+          ```
             # content of the environment file
             MURMURD_PASSWORD=verysecretpassword
-          </programlisting>
+          ```
 
           Note that this file needs to be available on the host on which
-          <literal>murmur</literal> is running.
+          `murmur` is running.
         '';
       };
     };
@@ -291,6 +297,11 @@ in
       gid             = config.ids.gids.murmur;
     };
 
+    networking.firewall = mkIf cfg.openFirewall {
+      allowedTCPPorts = [ cfg.port ];
+      allowedUDPPorts = [ cfg.port ];
+    };
+
     systemd.services.murmur = {
       description = "Murmur Chat Service";
       wantedBy    = [ "multi-user.target" ];
diff --git a/nixos/modules/services/networking/mxisd.nix b/nixos/modules/services/networking/mxisd.nix
index 803f0689d1f..528a51c1f3a 100644
--- a/nixos/modules/services/networking/mxisd.nix
+++ b/nixos/modules/services/networking/mxisd.nix
@@ -37,32 +37,41 @@ let
 in {
   options = {
     services.mxisd = {
-      enable = mkEnableOption "matrix federated identity server";
+      enable = mkEnableOption (lib.mdDoc "matrix federated identity server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.ma1sd;
         defaultText = literalExpression "pkgs.ma1sd";
-        description = "The mxisd/ma1sd package to use";
+        description = lib.mdDoc "The mxisd/ma1sd package to use";
+      };
+
+      environmentFile = mkOption {
+        type = types.nullOr types.str;
+        default = null;
+        description = lib.mdDoc ''
+          Path to an environment-file which may contain secrets to be
+          substituted via `envsubst`.
+        '';
       };
 
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/mxisd";
-        description = "Where data mxisd/ma1sd uses resides";
+        description = lib.mdDoc "Where data mxisd/ma1sd uses resides";
       };
 
       extraConfig = mkOption {
         type = types.attrs;
         default = {};
-        description = "Extra options merged into the mxisd/ma1sd configuration";
+        description = lib.mdDoc "Extra options merged into the mxisd/ma1sd configuration";
       };
 
       matrix = {
 
         domain = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             the domain of the matrix homeserver
           '';
         };
@@ -74,7 +83,7 @@ in {
         name = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Public hostname of mxisd/ma1sd, if different from the Matrix domain.
           '';
         };
@@ -82,7 +91,7 @@ in {
         port = mkOption {
           type = types.nullOr types.int;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             HTTP port to listen on (unencrypted)
           '';
         };
@@ -118,7 +127,13 @@ in {
         Type = "simple";
         User = "mxisd";
         Group = "mxisd";
-        ExecStart = "${cfg.package}/bin/${executable} -c ${configFile}";
+        EnvironmentFile = mkIf (cfg.environmentFile != null) [ cfg.environmentFile ];
+        ExecStart = "${cfg.package}/bin/${executable} -c ${cfg.dataDir}/mxisd-config.yaml";
+        ExecStartPre = "${pkgs.writeShellScript "mxisd-substitute-secrets" ''
+          umask 0077
+          ${pkgs.envsubst}/bin/envsubst -o ${cfg.dataDir}/mxisd-config.yaml \
+            -i ${configFile}
+        ''}";
         WorkingDirectory = cfg.dataDir;
         Restart = "on-failure";
       };
diff --git a/nixos/modules/services/networking/namecoind.nix b/nixos/modules/services/networking/namecoind.nix
index 8f7a5123f7e..085d6c5fe28 100644
--- a/nixos/modules/services/networking/namecoind.nix
+++ b/nixos/modules/services/networking/namecoind.nix
@@ -44,12 +44,12 @@ in
 
     services.namecoind = {
 
-      enable = mkEnableOption "namecoind, Namecoin client";
+      enable = mkEnableOption (lib.mdDoc "namecoind, Namecoin client");
 
       wallet = mkOption {
         type = types.path;
         default = "${dataDir}/wallet.dat";
-        description = ''
+        description = lib.mdDoc ''
           Wallet file. The ownership of the file has to be
           namecoin:namecoin, and the permissions must be 0640.
         '';
@@ -58,7 +58,7 @@ in
       generate = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to generate (mine) Namecoins.
         '';
       };
@@ -66,7 +66,7 @@ in
       extraNodes = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           List of additional peer IP addresses to connect to.
         '';
       };
@@ -74,7 +74,7 @@ in
       trustedNodes = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           List of the only peer IP addresses to connect to. If specified
           no other connection will be made.
         '';
@@ -83,7 +83,7 @@ in
       rpc.user = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           User name for RPC connections.
         '';
       };
@@ -91,7 +91,7 @@ in
       rpc.password = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Password for RPC connections.
         '';
       };
@@ -99,7 +99,7 @@ in
       rpc.address = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           IP address the RPC server will bind to.
         '';
       };
@@ -107,7 +107,7 @@ in
       rpc.port = mkOption {
         type = types.port;
         default = 8332;
-        description = ''
+        description = lib.mdDoc ''
           Port the RPC server will bind to.
         '';
       };
@@ -116,7 +116,7 @@ in
         type = types.nullOr types.path;
         default = null;
         example = "/var/lib/namecoind/server.cert";
-        description = ''
+        description = lib.mdDoc ''
           Certificate file for securing RPC connections.
         '';
       };
@@ -125,7 +125,7 @@ in
         type = types.nullOr types.path;
         default = null;
         example = "/var/lib/namecoind/server.pem";
-        description = ''
+        description = lib.mdDoc ''
           Key file for securing RPC connections.
         '';
       };
@@ -134,7 +134,7 @@ in
       rpc.allowFrom = mkOption {
         type = types.listOf types.str;
         default = [ "127.0.0.1" ];
-        description = ''
+        description = lib.mdDoc ''
           List of IP address ranges allowed to use the RPC API.
           Wiledcards (*) can be user to specify a range.
         '';
diff --git a/nixos/modules/services/networking/nar-serve.nix b/nixos/modules/services/networking/nar-serve.nix
index 745138186a2..beee53c8a24 100644
--- a/nixos/modules/services/networking/nar-serve.nix
+++ b/nixos/modules/services/networking/nar-serve.nix
@@ -10,12 +10,12 @@ in
   };
   options = {
     services.nar-serve = {
-      enable = mkEnableOption "Serve NAR file contents via HTTP";
+      enable = mkEnableOption (lib.mdDoc "Serve NAR file contents via HTTP");
 
       port = mkOption {
         type = types.port;
         default = 8383;
-        description = ''
+        description = lib.mdDoc ''
           Port number where nar-serve will listen on.
         '';
       };
@@ -23,7 +23,7 @@ in
       cacheURL = mkOption {
         type = types.str;
         default = "https://cache.nixos.org/";
-        description = ''
+        description = lib.mdDoc ''
           Binary cache URL to connect to.
 
           The URL format is compatible with the nix remote url style, such as:
diff --git a/nixos/modules/services/networking/nat.nix b/nixos/modules/services/networking/nat.nix
index 2e58cd699b2..0b70ae47ccf 100644
--- a/nixos/modules/services/networking/nat.nix
+++ b/nixos/modules/services/networking/nat.nix
@@ -136,7 +136,7 @@ in
       type = types.bool;
       default = false;
       description =
-        ''
+        lib.mdDoc ''
           Whether to enable Network Address Translation (NAT).
         '';
     };
@@ -145,7 +145,7 @@ in
       type = types.bool;
       default = false;
       description =
-        ''
+        lib.mdDoc ''
           Whether to enable IPv6 NAT.
         '';
     };
@@ -155,7 +155,7 @@ in
       default = [];
       example = [ "eth0" ];
       description =
-        ''
+        lib.mdDoc ''
           The interfaces for which to perform NAT. Packets coming from
           these interface and destined for the external interface will
           be rewritten.
@@ -167,7 +167,7 @@ in
       default = [];
       example = [ "192.168.1.0/24" ];
       description =
-        ''
+        lib.mdDoc ''
           The IP address ranges for which to perform NAT.  Packets
           coming from these addresses (on any interface) and destined
           for the external interface will be rewritten.
@@ -179,7 +179,7 @@ in
       default = [];
       example = [ "fc00::/64" ];
       description =
-        ''
+        lib.mdDoc ''
           The IPv6 address ranges for which to perform NAT.  Packets
           coming from these addresses (on any interface) and destined
           for the external interface will be rewritten.
@@ -191,7 +191,7 @@ in
       default = null;
       example = "eth1";
       description =
-        ''
+        lib.mdDoc ''
           The name of the external network interface.
         '';
     };
@@ -201,7 +201,7 @@ in
       default = null;
       example = "203.0.113.123";
       description =
-        ''
+        lib.mdDoc ''
           The public IP address to which packets from the local
           network are to be rewritten.  If this is left empty, the
           IP address associated with the external interface will be
@@ -214,7 +214,7 @@ in
       default = null;
       example = "2001:dc0:2001:11::175";
       description =
-        ''
+        lib.mdDoc ''
           The public IPv6 address to which packets from the local
           network are to be rewritten.  If this is left empty, the
           IP address associated with the external interface will be
@@ -228,27 +228,27 @@ in
           sourcePort = mkOption {
             type = types.either types.int (types.strMatching "[[:digit:]]+:[[:digit:]]+");
             example = 8080;
-            description = "Source port of the external interface; to specify a port range, use a string with a colon (e.g. \"60000:61000\")";
+            description = lib.mdDoc "Source port of the external interface; to specify a port range, use a string with a colon (e.g. \"60000:61000\")";
           };
 
           destination = mkOption {
             type = types.str;
             example = "10.0.0.1:80";
-            description = "Forward connection to destination ip:port (or [ipv6]:port); to specify a port range, use ip:start-end";
+            description = lib.mdDoc "Forward connection to destination ip:port (or [ipv6]:port); to specify a port range, use ip:start-end";
           };
 
           proto = mkOption {
             type = types.str;
             default = "tcp";
             example = "udp";
-            description = "Protocol of forwarded connection";
+            description = lib.mdDoc "Protocol of forwarded connection";
           };
 
           loopbackIPs = mkOption {
             type = types.listOf types.str;
             default = [];
             example = literalExpression ''[ "55.1.2.3" ]'';
-            description = "Public IPs for NAT reflection; for connections to `loopbackip:sourcePort' from the host itself and from other hosts behind NAT";
+            description = lib.mdDoc "Public IPs for NAT reflection; for connections to `loopbackip:sourcePort' from the host itself and from other hosts behind NAT";
           };
         };
       });
@@ -258,7 +258,7 @@ in
         { sourcePort = 8080; destination = "[fc00::2]:80"; proto = "tcp"; }
       ];
       description =
-        ''
+        lib.mdDoc ''
           List of forwarded ports from the external interface to
           internal destinations by using DNAT. Destination can be
           IPv6 if IPv6 NAT is enabled.
@@ -270,7 +270,7 @@ in
       default = null;
       example = "10.0.0.1";
       description =
-        ''
+        lib.mdDoc ''
           The local IP address to which all traffic that does not match any
           forwarding rule is forwarded.
         '';
@@ -281,7 +281,7 @@ in
       default = "";
       example = "iptables -A INPUT -p icmp -j ACCEPT";
       description =
-        ''
+        lib.mdDoc ''
           Additional shell commands executed as part of the nat
           initialisation script.
         '';
@@ -292,7 +292,7 @@ in
       default = "";
       example = "iptables -D INPUT -p icmp -j ACCEPT || true";
       description =
-        ''
+        lib.mdDoc ''
           Additional shell commands executed as part of the nat
           teardown script.
         '';
@@ -319,7 +319,10 @@ in
         }
       ];
 
-      environment.systemPackages = [ pkgs.iptables ];
+      # Use the same iptables package as in config.networking.firewall.
+      # When the firewall is enabled, this should be deduplicated without any
+      # error.
+      environment.systemPackages = [ config.networking.firewall.package ];
 
       boot = {
         kernelModules = [ "nf_nat_ftp" ];
@@ -347,7 +350,7 @@ in
         description = "Network Address Translation";
         wantedBy = [ "network.target" ];
         after = [ "network-pre.target" "systemd-modules-load.service" ];
-        path = [ pkgs.iptables ];
+        path = [ config.networking.firewall.package ];
         unitConfig.ConditionCapability = "CAP_NET_ADMIN";
 
         serviceConfig = {
diff --git a/nixos/modules/services/networking/nats.nix b/nixos/modules/services/networking/nats.nix
index 3e86a4f07bc..6c21e21b5cb 100644
--- a/nixos/modules/services/networking/nats.nix
+++ b/nixos/modules/services/networking/nats.nix
@@ -16,35 +16,35 @@ in {
 
   options = {
     services.nats = {
-      enable = mkEnableOption "NATS messaging system";
+      enable = mkEnableOption (lib.mdDoc "NATS messaging system");
 
       user = mkOption {
         type = types.str;
         default = "nats";
-        description = "User account under which NATS runs.";
+        description = lib.mdDoc "User account under which NATS runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "nats";
-        description = "Group under which NATS runs.";
+        description = lib.mdDoc "Group under which NATS runs.";
       };
 
       serverName = mkOption {
         default = "nats";
         example = "n1-c3";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Name of the NATS server, must be unique if clustered.
         '';
       };
 
-      jetstream = mkEnableOption "JetStream";
+      jetstream = mkEnableOption (lib.mdDoc "JetStream");
 
       port = mkOption {
         default = 4222;
         type = types.port;
-        description = ''
+        description = lib.mdDoc ''
           Port on which to listen.
         '';
       };
@@ -52,7 +52,7 @@ in {
       dataDir = mkOption {
         default = "/var/lib/nats";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The NATS data directory. Only used if JetStream is enabled, for
           storing stream metadata and messages.
 
@@ -74,10 +74,10 @@ in {
             };
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Declarative NATS configuration. See the
-          <link xlink:href="https://docs.nats.io/nats-server/configuration">
-          NATS documentation</link> for a list of options.
+          [
+          NATS documentation](https://docs.nats.io/nats-server/configuration) for a list of options.
         '';
       };
     };
@@ -137,7 +137,7 @@ in {
           RestrictNamespaces = true;
           RestrictRealtime = true;
           RestrictSUIDSGID = true;
-          SystemCallFilter = [ "@system-service" "~@privileged" "~@resources" ];
+          SystemCallFilter = [ "@system-service" "~@privileged" ];
           UMask = "0077";
         }
       ];
diff --git a/nixos/modules/services/networking/nbd.nix b/nixos/modules/services/networking/nbd.nix
index 87f8c41a8e5..454380aa315 100644
--- a/nixos/modules/services/networking/nbd.nix
+++ b/nixos/modules/services/networking/nbd.nix
@@ -4,28 +4,34 @@ with lib;
 
 let
   cfg = config.services.nbd;
-  configFormat = pkgs.formats.ini { };
   iniFields = with types; attrsOf (oneOf [ bool int float str ]);
-  serverConfig = configFormat.generate "nbd-server-config"
-    ({
-      generic =
-        (cfg.server.extraOptions // {
-          user = "root";
-          group = "root";
-          port = cfg.server.listenPort;
-        } // (optionalAttrs (cfg.server.listenAddress != null) {
-          listenaddr = cfg.server.listenAddress;
-        }));
-    }
-    // (mapAttrs
+  # The `[generic]` section must come before all the others in the
+  # config file.  This means we can't just dump an attrset to INI
+  # because that sorts the sections by name.  Instead, we serialize it
+  # on its own first.
+  genericSection = {
+    generic = (cfg.server.extraOptions // {
+      user = "root";
+      group = "root";
+      port = cfg.server.listenPort;
+    } // (optionalAttrs (cfg.server.listenAddress != null) {
+      listenaddr = cfg.server.listenAddress;
+    }));
+  };
+  exportSections =
+    mapAttrs
       (_: { path, allowAddresses, extraOptions }:
         extraOptions // {
           exportname = path;
         } // (optionalAttrs (allowAddresses != null) {
           authfile = pkgs.writeText "authfile" (concatStringsSep "\n" allowAddresses);
         }))
-      cfg.server.exports)
-    );
+      cfg.server.exports;
+  serverConfig =
+    pkgs.writeText "nbd-server-config" ''
+      ${lib.generators.toINI {} genericSection}
+      ${lib.generators.toINI {} exportSections}
+    '';
   splitLists =
     partition
       (path: hasPrefix "/dev/" path)
@@ -37,12 +43,12 @@ in
   options = {
     services.nbd = {
       server = {
-        enable = mkEnableOption "the Network Block Device (nbd) server";
+        enable = mkEnableOption (lib.mdDoc "the Network Block Device (nbd) server");
 
         listenPort = mkOption {
           type = types.port;
           default = 10809;
-          description = "Port to listen on. The port is NOT automatically opened in the firewall.";
+          description = lib.mdDoc "Port to listen on. The port is NOT automatically opened in the firewall.";
         };
 
         extraOptions = mkOption {
@@ -50,22 +56,21 @@ in
           default = {
             allowlist = false;
           };
-          description = ''
+          description = lib.mdDoc ''
             Extra options for the server. See
-            <citerefentry><refentrytitle>nbd-server</refentrytitle>
-            <manvolnum>5</manvolnum></citerefentry>.
+            {manpage}`nbd-server(5)`.
           '';
         };
 
         exports = mkOption {
-          description = "Files or block devices to make available over the network.";
+          description = lib.mdDoc "Files or block devices to make available over the network.";
           default = { };
           type = with types; attrsOf
             (submodule {
               options = {
                 path = mkOption {
                   type = str;
-                  description = "File or block device to export.";
+                  description = lib.mdDoc "File or block device to export.";
                   example = "/dev/sdb1";
                 };
 
@@ -73,7 +78,7 @@ in
                   type = nullOr (listOf str);
                   default = null;
                   example = [ "10.10.0.0/24" "127.0.0.1" ];
-                  description = "IPs and subnets that are authorized to connect for this device. If not specified, the server will allow all connections.";
+                  description = lib.mdDoc "IPs and subnets that are authorized to connect for this device. If not specified, the server will allow all connections.";
                 };
 
                 extraOptions = mkOption {
@@ -82,10 +87,9 @@ in
                     flush = true;
                     fua = true;
                   };
-                  description = ''
+                  description = lib.mdDoc ''
                     Extra options for this export. See
-                    <citerefentry><refentrytitle>nbd-server</refentrytitle>
-                    <manvolnum>5</manvolnum></citerefentry>.
+                    {manpage}`nbd-server(5)`.
                   '';
                 };
               };
@@ -94,7 +98,7 @@ in
 
         listenAddress = mkOption {
           type = with types; nullOr str;
-          description = "Address to listen on. If not specified, the server will listen on all interfaces.";
+          description = lib.mdDoc "Address to listen on. If not specified, the server will listen on all interfaces.";
           default = null;
           example = "10.10.0.1";
         };
@@ -103,6 +107,13 @@ in
   };
 
   config = mkIf cfg.server.enable {
+    assertions = [
+      {
+        assertion = !(cfg.server.exports ? "generic");
+        message = "services.nbd.server exports must not be named 'generic'";
+      }
+    ];
+
     boot.kernelModules = [ "nbd" ];
 
     systemd.services.nbd-server = {
diff --git a/nixos/modules/services/networking/ncdns.nix b/nixos/modules/services/networking/ncdns.nix
index 82c285d0516..1d494332095 100644
--- a/nixos/modules/services/networking/ncdns.nix
+++ b/nixos/modules/services/networking/ncdns.nix
@@ -50,16 +50,16 @@ in
 
     services.ncdns = {
 
-      enable = mkEnableOption ''
+      enable = mkEnableOption (lib.mdDoc ''
         ncdns, a Go daemon to bridge Namecoin to DNS.
-        To resolve .bit domains set <literal>services.namecoind.enable = true;</literal>
+        To resolve .bit domains set `services.namecoind.enable = true;`
         and an RPC username/password
-      '';
+      '');
 
       address = mkOption {
         type = types.str;
-        default = "127.0.0.1";
-        description = ''
+        default = "[::1]";
+        description = lib.mdDoc ''
           The IP address the ncdns resolver will bind to.  Leave this unchanged
           if you do not wish to directly expose the resolver.
         '';
@@ -68,7 +68,7 @@ in
       port = mkOption {
         type = types.port;
         default = 5333;
-        description = ''
+        description = lib.mdDoc ''
           The port the ncdns resolver will bind to.
         '';
       };
@@ -78,16 +78,16 @@ in
         default = config.networking.hostName;
         defaultText = literalExpression "config.networking.hostName";
         example = "example.com";
-        description = ''
+        description = lib.mdDoc ''
           The hostname of this ncdns instance, which defaults to the machine
           hostname. If specified, ncdns lists the hostname as an NS record at
           the zone apex:
-          <programlisting>
+          ```
           bit. IN NS ns1.example.com.
-          </programlisting>
+          ```
           If unset ncdns will generate an internal psuedo-hostname under the
           zone, which will resolve to the value of
-          <option>services.ncdns.identity.address</option>.
+          {option}`services.ncdns.identity.address`.
           If you are only using ncdns locally you can ignore this.
         '';
       };
@@ -96,7 +96,7 @@ in
         type = types.str;
         default = "";
         example = "root@example.com";
-        description = ''
+        description = lib.mdDoc ''
           An email address for the SOA record at the bit zone.
           If you are only using ncdns locally you can ignore this.
         '';
@@ -105,38 +105,38 @@ in
       identity.address = mkOption {
         type = types.str;
         default = "127.127.127.127";
-        description = ''
+        description = lib.mdDoc ''
           The IP address the hostname specified in
-          <option>services.ncdns.identity.hostname</option> should resolve to.
+          {option}`services.ncdns.identity.hostname` should resolve to.
           If you are only using ncdns locally you can ignore this.
         '';
       };
 
-      dnssec.enable = mkEnableOption ''
+      dnssec.enable = mkEnableOption (lib.mdDoc ''
         DNSSEC support in ncdns. This will generate KSK and ZSK keypairs
         (unless provided via the options
-        <option>services.ncdns.dnssec.publicKey</option>,
-        <option>services.ncdns.dnssec.privateKey</option> etc.) and add a trust
+        {option}`services.ncdns.dnssec.publicKey`,
+        {option}`services.ncdns.dnssec.privateKey` etc.) and add a trust
         anchor to recursive resolvers
-      '';
+      '');
 
       dnssec.keys.public = mkOption {
         type = types.path;
         default = defaultFiles.public;
-        description = ''
+        description = lib.mdDoc ''
           Path to the file containing the KSK public key.
-          The key can be generated using the <literal>dnssec-keygen</literal>
-          command, provided by the package <package>bind</package> as follows:
-          <programlisting>
+          The key can be generated using the `dnssec-keygen`
+          command, provided by the package `bind` as follows:
+          ```
           $ dnssec-keygen -a RSASHA256 -3 -b 2048 -f KSK bit
-          </programlisting>
+          ```
         '';
       };
 
       dnssec.keys.private = mkOption {
         type = types.path;
         default = defaultFiles.private;
-        description = ''
+        description = lib.mdDoc ''
           Path to the file containing the KSK private key.
         '';
       };
@@ -144,20 +144,20 @@ in
       dnssec.keys.zonePublic = mkOption {
         type = types.path;
         default = defaultFiles.zonePublic;
-        description = ''
+        description = lib.mdDoc ''
           Path to the file containing the ZSK public key.
-          The key can be generated using the <literal>dnssec-keygen</literal>
-          command, provided by the package <package>bind</package> as follows:
-          <programlisting>
+          The key can be generated using the `dnssec-keygen`
+          command, provided by the package `bind` as follows:
+          ```
           $ dnssec-keygen -a RSASHA256 -3 -b 2048 bit
-          </programlisting>
+          ```
         '';
       };
 
       dnssec.keys.zonePrivate = mkOption {
         type = types.path;
         default = defaultFiles.zonePrivate;
-        description = ''
+        description = lib.mdDoc ''
           Path to the file containing the ZSK private key.
         '';
       };
@@ -176,11 +176,11 @@ in
             certstore.nssdbdir = "../../home/alice/.pki/nssdb";
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           ncdns settings. Use this option to configure ncds
           settings not exposed in a NixOS option or to bypass one.
-          See the example ncdns.conf file at <link xlink:href="
-          https://git.io/JfX7g"/> for the available options.
+          See the example ncdns.conf file at <https://github.com/namecoin/ncdns/blob/master/_doc/ncdns.conf.example>
+          for the available options.
         '';
       };
 
@@ -189,8 +189,8 @@ in
     services.pdns-recursor.resolveNamecoin = mkOption {
       type = types.bool;
       default = false;
-      description = ''
-        Resolve <literal>.bit</literal> top-level domains using ncdns and namecoin.
+      description = lib.mdDoc ''
+        Resolve `.bit` top-level domains using ncdns and namecoin.
       '';
     };
 
@@ -202,7 +202,7 @@ in
   config = mkIf cfg.enable {
 
     services.pdns-recursor = mkIf cfgs.pdns-recursor.resolveNamecoin {
-      forwardZonesRecurse.bit = "127.0.0.1:${toString cfg.port}";
+      forwardZonesRecurse.bit = "${cfg.address}:${toString cfg.port}";
       luaConfig =
         if cfg.dnssec.enable
           then ''readTrustAnchorsFromFile("${cfg.dnssec.keys.public}")''
diff --git a/nixos/modules/services/networking/ndppd.nix b/nixos/modules/services/networking/ndppd.nix
index 6046ac860cf..6cbc9712be3 100644
--- a/nixos/modules/services/networking/ndppd.nix
+++ b/nixos/modules/services/networking/ndppd.nix
@@ -26,7 +26,7 @@ let
     options = {
       interface = mkOption {
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           Listen for any Neighbor Solicitation messages on this interface,
           and respond to them according to a set of rules.
           Defaults to the name of the attrset.
@@ -35,14 +35,14 @@ let
       };
       router = mkOption {
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Turns on or off the router flag for Neighbor Advertisement Messages.
         '';
         default = true;
       };
       timeout = mkOption {
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Controls how long to wait for a Neighbor Advertisment Message before
           invalidating the entry, in milliseconds.
         '';
@@ -50,7 +50,7 @@ let
       };
       ttl = mkOption {
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Controls how long a valid or invalid entry remains in the cache, in
           milliseconds.
         '';
@@ -58,7 +58,7 @@ let
       };
       rules = mkOption {
         type = types.attrsOf rule;
-        description = ''
+        description = lib.mdDoc ''
           This is a rule that the target address is to match against. If no netmask
           is provided, /128 is assumed. You may have several rule sections, and the
           addresses may or may not overlap.
@@ -72,7 +72,7 @@ let
     options = {
       network = mkOption {
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           This is the target address is to match against. If no netmask
           is provided, /128 is assumed. The addresses of serveral rules
           may or may not overlap.
@@ -82,7 +82,7 @@ let
       };
       method = mkOption {
         type = types.enum [ "static" "iface" "auto" ];
-        description = ''
+        description = lib.mdDoc ''
           static: Immediately answer any Neighbor Solicitation Messages
             (if they match the IP rule).
           iface: Forward the Neighbor Solicitation Message through the specified
@@ -95,7 +95,7 @@ let
       };
       interface = mkOption {
         type = types.nullOr types.str;
-        description = "Interface to use when method is iface.";
+        description = lib.mdDoc "Interface to use when method is iface.";
         default = null;
       };
     };
@@ -103,33 +103,33 @@ let
 
 in {
   options.services.ndppd = {
-    enable = mkEnableOption "daemon that proxies NDP (Neighbor Discovery Protocol) messages between interfaces";
+    enable = mkEnableOption (lib.mdDoc "daemon that proxies NDP (Neighbor Discovery Protocol) messages between interfaces");
     interface = mkOption {
       type = types.nullOr types.str;
-      description = ''
+      description = lib.mdDoc ''
         Interface which is on link-level with router.
-        (Legacy option, use services.ndppd.proxies.&lt;interface&gt;.rules.&lt;network&gt; instead)
+        (Legacy option, use services.ndppd.proxies.\<interface\>.rules.\<network\> instead)
       '';
       default = null;
       example = "eth0";
     };
     network = mkOption {
       type = types.nullOr types.str;
-      description = ''
+      description = lib.mdDoc ''
         Network that we proxy.
-        (Legacy option, use services.ndppd.proxies.&lt;interface&gt;.rules.&lt;network&gt; instead)
+        (Legacy option, use services.ndppd.proxies.\<interface\>.rules.\<network\> instead)
       '';
       default = null;
       example = "1111::/64";
     };
     configFile = mkOption {
       type = types.nullOr types.path;
-      description = "Path to configuration file.";
+      description = lib.mdDoc "Path to configuration file.";
       default = null;
     };
     routeTTL = mkOption {
       type = types.int;
-      description = ''
+      description = lib.mdDoc ''
         This tells 'ndppd' how often to reload the route file /proc/net/ipv6_route,
         in milliseconds.
       '';
@@ -137,7 +137,7 @@ in {
     };
     proxies = mkOption {
       type = types.attrsOf proxy;
-      description = ''
+      description = lib.mdDoc ''
         This sets up a listener, that will listen for any Neighbor Solicitation
         messages, and respond to them according to a set of rules.
       '';
diff --git a/nixos/modules/services/networking/nebula.nix b/nixos/modules/services/networking/nebula.nix
index de4439415cf..2bedafc5d9f 100644
--- a/nixos/modules/services/networking/nebula.nix
+++ b/nixos/modules/services/networking/nebula.nix
@@ -17,45 +17,45 @@ in
   options = {
     services.nebula = {
       networks = mkOption {
-        description = "Nebula network definitions.";
+        description = lib.mdDoc "Nebula network definitions.";
         default = {};
         type = types.attrsOf (types.submodule {
           options = {
             enable = mkOption {
               type = types.bool;
               default = true;
-              description = "Enable or disable this network.";
+              description = lib.mdDoc "Enable or disable this network.";
             };
 
             package = mkOption {
               type = types.package;
               default = pkgs.nebula;
               defaultText = literalExpression "pkgs.nebula";
-              description = "Nebula derivation to use.";
+              description = lib.mdDoc "Nebula derivation to use.";
             };
 
             ca = mkOption {
               type = types.path;
-              description = "Path to the certificate authority certificate.";
+              description = lib.mdDoc "Path to the certificate authority certificate.";
               example = "/etc/nebula/ca.crt";
             };
 
             cert = mkOption {
               type = types.path;
-              description = "Path to the host certificate.";
+              description = lib.mdDoc "Path to the host certificate.";
               example = "/etc/nebula/host.crt";
             };
 
             key = mkOption {
               type = types.path;
-              description = "Path to the host key.";
+              description = lib.mdDoc "Path to the host key.";
               example = "/etc/nebula/host.key";
             };
 
             staticHostMap = mkOption {
               type = types.attrsOf (types.listOf (types.str));
               default = {};
-              description = ''
+              description = lib.mdDoc ''
                 The static host map defines a set of hosts with fixed IP addresses on the internet (or any network).
                 A host can have multiple fixed IP addresses defined here, and nebula will try each when establishing a tunnel.
               '';
@@ -65,13 +65,13 @@ in
             isLighthouse = mkOption {
               type = types.bool;
               default = false;
-              description = "Whether this node is a lighthouse.";
+              description = lib.mdDoc "Whether this node is a lighthouse.";
             };
 
             lighthouses = mkOption {
               type = types.listOf types.str;
               default = [];
-              description = ''
+              description = lib.mdDoc ''
                 List of IPs of lighthouse hosts this node should report to and query from. This should be empty on lighthouse
                 nodes. The IPs should be the lighthouse's Nebula IPs, not their external IPs.
               '';
@@ -81,19 +81,19 @@ in
             listen.host = mkOption {
               type = types.str;
               default = "0.0.0.0";
-              description = "IP address to listen on.";
+              description = lib.mdDoc "IP address to listen on.";
             };
 
             listen.port = mkOption {
               type = types.port;
               default = 4242;
-              description = "Port number to listen on.";
+              description = lib.mdDoc "Port number to listen on.";
             };
 
             tun.disable = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 When tun is disabled, a lighthouse can be started without a local tun interface (and therefore without root).
               '';
             };
@@ -101,29 +101,29 @@ in
             tun.device = mkOption {
               type = types.nullOr types.str;
               default = null;
-              description = "Name of the tun device. Defaults to nebula.\${networkName}.";
+              description = lib.mdDoc "Name of the tun device. Defaults to nebula.\${networkName}.";
             };
 
             firewall.outbound = mkOption {
               type = types.listOf types.attrs;
               default = [];
-              description = "Firewall rules for outbound traffic.";
+              description = lib.mdDoc "Firewall rules for outbound traffic.";
               example = [ { port = "any"; proto = "any"; host = "any"; } ];
             };
 
             firewall.inbound = mkOption {
               type = types.listOf types.attrs;
               default = [];
-              description = "Firewall rules for inbound traffic.";
+              description = lib.mdDoc "Firewall rules for inbound traffic.";
               example = [ { port = "any"; proto = "any"; host = "any"; } ];
             };
 
             settings = mkOption {
               type = format.type;
               default = {};
-              description = ''
+              description = lib.mdDoc ''
                 Nebula configuration. Refer to
-                <link xlink:href="https://github.com/slackhq/nebula/blob/master/examples/config.yml"/>
+                <https://github.com/slackhq/nebula/blob/master/examples/config.yml>
                 for details on supported values.
               '';
               example = literalExpression ''
@@ -192,6 +192,7 @@ in
                 Group = networkId;
               })
             ];
+            unitConfig.StartLimitIntervalSec = 0; # ensure Restart=always is always honoured (networks can go down for arbitrarily long)
           };
         }) enabledNetworks);
 
diff --git a/nixos/modules/services/networking/netbird.nix b/nixos/modules/services/networking/netbird.nix
new file mode 100644
index 00000000000..5bd9e9ca616
--- /dev/null
+++ b/nixos/modules/services/networking/netbird.nix
@@ -0,0 +1,64 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.netbird;
+  kernel = config.boot.kernelPackages;
+  interfaceName = "wt0";
+in {
+  meta.maintainers = with maintainers; [ misuzu ];
+
+  options.services.netbird = {
+    enable = mkEnableOption (lib.mdDoc "Netbird daemon");
+    package = mkOption {
+      type = types.package;
+      default = pkgs.netbird;
+      defaultText = literalExpression "pkgs.netbird";
+      description = lib.mdDoc "The package to use for netbird";
+    };
+  };
+
+  config = mkIf cfg.enable {
+    boot.extraModulePackages = optional (versionOlder kernel.kernel.version "5.6") kernel.wireguard;
+
+    environment.systemPackages = [ cfg.package ];
+
+    networking.dhcpcd.denyInterfaces = [ interfaceName ];
+
+    systemd.network.networks."50-netbird" = mkIf config.networking.useNetworkd {
+      matchConfig = {
+        Name = interfaceName;
+      };
+      linkConfig = {
+        Unmanaged = true;
+        ActivationPolicy = "manual";
+      };
+    };
+
+    systemd.services.netbird = {
+      description = "A WireGuard-based mesh network that connects your devices into a single private network";
+      documentation = [ "https://netbird.io/docs/" ];
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        AmbientCapabilities = [ "CAP_NET_ADMIN" ];
+        DynamicUser = true;
+        Environment = [
+          "NB_CONFIG=/var/lib/netbird/config.json"
+          "NB_LOG_FILE=console"
+        ];
+        ExecStart = "${cfg.package}/bin/netbird service run";
+        Restart = "always";
+        RuntimeDirectory = "netbird";
+        StateDirectory = "netbird";
+        WorkingDirectory = "/var/lib/netbird";
+      };
+      unitConfig = {
+        StartLimitInterval = 5;
+        StartLimitBurst = 10;
+      };
+      stopIfChanged = false;
+    };
+  };
+}
diff --git a/nixos/modules/services/networking/networkmanager.nix b/nixos/modules/services/networking/networkmanager.nix
index 7a9d9e5428a..3b28cec83cb 100644
--- a/nixos/modules/services/networking/networkmanager.nix
+++ b/nixos/modules/services/networking/networkmanager.nix
@@ -5,18 +5,6 @@ with lib;
 let
   cfg = config.networking.networkmanager;
 
-  basePackages = with pkgs; [
-    modemmanager
-    networkmanager
-    networkmanager-fortisslvpn
-    networkmanager-iodine
-    networkmanager-l2tp
-    networkmanager-openconnect
-    networkmanager-openvpn
-    networkmanager-vpnc
-    networkmanager-sstp
-   ] ++ optional (!delegateWireless && !enableIwd) wpa_supplicant;
-
   delegateWireless = config.networking.wireless.enable == true && cfg.unmanaged != [];
 
   enableIwd = cfg.wifi.backend == "iwd";
@@ -118,33 +106,26 @@ let
     type = types.either types.str (types.enum ["permanent" "preserve" "random" "stable"]);
     default = "preserve";
     example = "00:11:22:33:44:55";
-    description = ''
+    description = lib.mdDoc ''
       Set the MAC address of the interface.
-      <variablelist>
-        <varlistentry>
-          <term>"XX:XX:XX:XX:XX:XX"</term>
-          <listitem><para>MAC address of the interface</para></listitem>
-        </varlistentry>
-        <varlistentry>
-          <term><literal>"permanent"</literal></term>
-          <listitem><para>Use the permanent MAC address of the device</para></listitem>
-        </varlistentry>
-        <varlistentry>
-          <term><literal>"preserve"</literal></term>
-          <listitem><para>Don’t change the MAC address of the device upon activation</para></listitem>
-        </varlistentry>
-        <varlistentry>
-          <term><literal>"random"</literal></term>
-          <listitem><para>Generate a randomized value upon each connect</para></listitem>
-        </varlistentry>
-        <varlistentry>
-          <term><literal>"stable"</literal></term>
-          <listitem><para>Generate a stable, hashed MAC address</para></listitem>
-        </varlistentry>
-      </variablelist>
+
+      - `"XX:XX:XX:XX:XX:XX"`: MAC address of the interface
+      - `"permanent"`: Use the permanent MAC address of the device
+      - `"preserve"`: Don’t change the MAC address of the device upon activation
+      - `"random"`: Generate a randomized value upon each connect
+      - `"stable"`: Generate a stable, hashed MAC address
     '';
   };
 
+  packages = [
+    pkgs.modemmanager
+    pkgs.networkmanager
+  ]
+  ++ cfg.plugins
+  ++ lib.optionals (!delegateWireless && !enableIwd) [
+    pkgs.wpa_supplicant
+  ];
+
 in {
 
   meta = {
@@ -160,10 +141,10 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use NetworkManager to obtain an IP address and other
           configuration for all network interfaces that are not manually
-          configured. If enabled, a group <literal>networkmanager</literal>
+          configured. If enabled, a group `networkmanager`
           will be created. Add all users that should have permission
           to change network settings to this group.
         '';
@@ -176,17 +157,14 @@ in {
           str
         ]));
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Configuration for the [connection] section of NetworkManager.conf.
           Refer to
-          <link xlink:href="https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html">
+          [
             https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html#id-1.2.3.11
-          </link>
+          ](https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html)
           or
-          <citerefentry>
-            <refentrytitle>NetworkManager.conf</refentrytitle>
-            <manvolnum>5</manvolnum>
-          </citerefentry>
+          {manpage}`NetworkManager.conf(5)`
           for more information.
         '';
       };
@@ -194,17 +172,14 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Configuration appended to the generated NetworkManager.conf.
           Refer to
-          <link xlink:href="https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html">
+          [
             https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html
-          </link>
+          ](https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html)
           or
-          <citerefentry>
-            <refentrytitle>NetworkManager.conf</refentrytitle>
-            <manvolnum>5</manvolnum>
-          </citerefentry>
+          {manpage}`NetworkManager.conf(5)`
           for more information.
         '';
       };
@@ -212,34 +187,47 @@ in {
       unmanaged = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of interfaces that will not be managed by NetworkManager.
           Interface name can be specified here, but if you need more fidelity,
           refer to
-          <link xlink:href="https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html#device-spec">
+          [
             https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html#device-spec
-          </link>
+          ](https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html#device-spec)
           or the "Device List Format" Appendix of
-          <citerefentry>
-            <refentrytitle>NetworkManager.conf</refentrytitle>
-            <manvolnum>5</manvolnum>
-          </citerefentry>.
+          {manpage}`NetworkManager.conf(5)`.
         '';
       };
 
-      packages = mkOption {
-        type = types.listOf types.package;
+      plugins = mkOption {
+        type =
+          let
+            networkManagerPluginPackage = types.package // {
+              description = "NetworkManager plug-in";
+              check =
+                p:
+                lib.assertMsg
+                  (types.package.check p
+                    && p ? networkManagerPlugin
+                    && lib.isString p.networkManagerPlugin)
+                  ''
+                    Package ‘${p.name}’, is not a NetworkManager plug-in.
+                    Those need to have a ‘networkManagerPlugin’ attribute.
+                  '';
+            };
+          in
+          types.listOf networkManagerPluginPackage;
         default = [ ];
-        description = ''
-          Extra packages that provide NetworkManager plugins.
+        description = lib.mdDoc ''
+          List of NetworkManager plug-ins to enable.
+          Some plug-ins are enabled by the NetworkManager module by default.
         '';
-        apply = list: basePackages ++ list;
       };
 
       dhcp = mkOption {
-        type = types.enum [ "dhclient" "dhcpcd" "internal" ];
+        type = types.enum [ "dhcpcd" "internal" ];
         default = "internal";
-        description = ''
+        description = lib.mdDoc ''
           Which program (or internal library) should be used for DHCP.
         '';
       };
@@ -247,7 +235,7 @@ in {
       firewallBackend = mkOption {
         type = types.enum [ "iptables" "nftables" "none" ];
         default = "iptables";
-        description = ''
+        description = lib.mdDoc ''
           Which firewall backend should be used for configuring masquerading with shared mode.
           If set to none, NetworkManager doesn't manage the configuration at all.
         '';
@@ -256,7 +244,7 @@ in {
       logLevel = mkOption {
         type = types.enum [ "OFF" "ERR" "WARN" "INFO" "DEBUG" "TRACE" ];
         default = "WARN";
-        description = ''
+        description = lib.mdDoc ''
           Set the default logging verbosity level.
         '';
       };
@@ -264,7 +252,7 @@ in {
       appendNameservers = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of name servers that should be appended
           to the ones configured in NetworkManager or received by DHCP.
         '';
@@ -273,7 +261,7 @@ in {
       insertNameservers = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of name servers that should be inserted before
           the ones configured in NetworkManager or received by DHCP.
         '';
@@ -287,16 +275,16 @@ in {
         backend = mkOption {
           type = types.enum [ "wpa_supplicant" "iwd" ];
           default = "wpa_supplicant";
-          description = ''
+          description = lib.mdDoc ''
             Specify the Wi-Fi backend used for the device.
-            Currently supported are <option>wpa_supplicant</option> or <option>iwd</option> (experimental).
+            Currently supported are {option}`wpa_supplicant` or {option}`iwd` (experimental).
           '';
         };
 
         powersave = mkOption {
           type = types.nullOr types.bool;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable Wi-Fi power saving.
           '';
         };
@@ -304,7 +292,7 @@ in {
         scanRandMacAddress = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable MAC address randomization of a Wi-Fi device
             during scanning.
           '';
@@ -314,19 +302,15 @@ in {
       dns = mkOption {
         type = types.enum [ "default" "dnsmasq" "unbound" "systemd-resolved" "none" ];
         default = "default";
-        description = ''
-          Set the DNS (<literal>resolv.conf</literal>) processing mode.
-          </para>
-          <para>
+        description = lib.mdDoc ''
+          Set the DNS (`resolv.conf`) processing mode.
+
           A description of these modes can be found in the main section of
-          <link xlink:href="https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html">
+          [
             https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html
-          </link>
+          ](https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html)
           or in
-          <citerefentry>
-            <refentrytitle>NetworkManager.conf</refentrytitle>
-            <manvolnum>5</manvolnum>
-          </citerefentry>.
+          {manpage}`NetworkManager.conf(5)`.
         '';
       };
 
@@ -335,7 +319,7 @@ in {
           options = {
             source = mkOption {
               type = types.path;
-              description = ''
+              description = lib.mdDoc ''
                 Path to the hook script.
               '';
             };
@@ -343,9 +327,9 @@ in {
             type = mkOption {
               type = types.enum (attrNames dispatcherTypesSubdirMap);
               default = "basic";
-              description = ''
+              description = lib.mdDoc ''
                 Dispatcher hook type. Look up the hooks described at
-                <link xlink:href="https://developer.gnome.org/NetworkManager/stable/NetworkManager.html">https://developer.gnome.org/NetworkManager/stable/NetworkManager.html</link>
+                [https://developer.gnome.org/NetworkManager/stable/NetworkManager.html](https://developer.gnome.org/NetworkManager/stable/NetworkManager.html)
                 and choose the type depending on the output folder.
                 You should then filter the event type (e.g., "up"/"down") from within your script.
               '';
@@ -367,7 +351,7 @@ in {
             ''';
             type = "basic";
         } ]'';
-        description = ''
+        description = lib.mdDoc ''
           A list of scripts which will be executed in response to  network  events.
         '';
       };
@@ -375,23 +359,23 @@ in {
       enableStrongSwan = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the StrongSwan plugin.
-          </para><para>
+
           If you enable this option the
-          <literal>networkmanager_strongswan</literal> plugin will be added to
-          the <option>networking.networkmanager.packages</option> option
-          so you don't need to to that yourself.
+          `networkmanager_strongswan` plugin will be added to
+          the {option}`networking.networkmanager.plugins` option
+          so you don't need to do that yourself.
         '';
       };
 
       enableFccUnlock = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable FCC unlock procedures. Since release 1.18.4, the ModemManager daemon no longer
           automatically performs the FCC unlock procedure by default. See
-          <link xlink:href="https://modemmanager.org/docs/modemmanager/fcc-unlock/">the docs</link>
+          [the docs](https://modemmanager.org/docs/modemmanager/fcc-unlock/)
           for more details.
         '';
       };
@@ -399,6 +383,9 @@ in {
   };
 
   imports = [
+    (mkRenamedOptionModule
+      [ "networking" "networkmanager" "packages" ]
+      [ "networking" "networkmanager" "plugins" ])
     (mkRenamedOptionModule [ "networking" "networkmanager" "useDnsmasq" ] [ "networking" "networkmanager" "dns" ])
     (mkRemovedOptionModule ["networking" "networkmanager" "dynamicHosts"] ''
       This option was removed because allowing (multiple) regular users to
@@ -426,31 +413,12 @@ in {
 
     hardware.wirelessRegulatoryDatabase = true;
 
-    environment.etc = with pkgs; {
-      "NetworkManager/NetworkManager.conf".source = configFile;
-
-      "NetworkManager/VPN/nm-openvpn-service.name".source =
-        "${networkmanager-openvpn}/lib/NetworkManager/VPN/nm-openvpn-service.name";
-
-      "NetworkManager/VPN/nm-vpnc-service.name".source =
-        "${networkmanager-vpnc}/lib/NetworkManager/VPN/nm-vpnc-service.name";
-
-      "NetworkManager/VPN/nm-openconnect-service.name".source =
-        "${networkmanager-openconnect}/lib/NetworkManager/VPN/nm-openconnect-service.name";
-
-      "NetworkManager/VPN/nm-fortisslvpn-service.name".source =
-        "${networkmanager-fortisslvpn}/lib/NetworkManager/VPN/nm-fortisslvpn-service.name";
-
-      "NetworkManager/VPN/nm-l2tp-service.name".source =
-        "${networkmanager-l2tp}/lib/NetworkManager/VPN/nm-l2tp-service.name";
-
-      "NetworkManager/VPN/nm-iodine-service.name".source =
-        "${networkmanager-iodine}/lib/NetworkManager/VPN/nm-iodine-service.name";
-
-      "NetworkManager/VPN/nm-sstp-service.name".source =
-        "${networkmanager-sstp}/lib/NetworkManager/VPN/nm-sstp-service.name";
-
+    environment.etc = {
+        "NetworkManager/NetworkManager.conf".source = configFile;
       }
+      // builtins.listToAttrs (map (pkg: nameValuePair "NetworkManager/${pkg.networkManagerPlugin}" {
+        source = "${pkg}/lib/NetworkManager/${pkg.networkManagerPlugin}";
+      }) cfg.plugins)
       // optionalAttrs cfg.enableFccUnlock
          {
            "ModemManager/fcc-unlock.d".source =
@@ -460,18 +428,13 @@ in {
          {
            "NetworkManager/dispatcher.d/02overridedns".source = overrideNameserversScript;
          }
-      // optionalAttrs cfg.enableStrongSwan
-         {
-           "NetworkManager/VPN/nm-strongswan-service.name".source =
-             "${pkgs.networkmanager_strongswan}/lib/NetworkManager/VPN/nm-strongswan-service.name";
-         }
       // listToAttrs (lib.imap1 (i: s:
          {
             name = "NetworkManager/dispatcher.d/${dispatcherTypesSubdirMap.${s.type}}03userscript${lib.fixedWidthNumber 4 i}";
             value = { mode = "0544"; inherit (s) source; };
          }) cfg.dispatcherScripts);
 
-    environment.systemPackages = cfg.packages;
+    environment.systemPackages = packages;
 
     users.groups = {
       networkmanager.gid = config.ids.gids.networkmanager;
@@ -490,14 +453,13 @@ in {
       };
     };
 
-    systemd.packages = cfg.packages;
+    systemd.packages = packages;
 
     systemd.tmpfiles.rules = [
       "d /etc/NetworkManager/system-connections 0700 root root -"
       "d /etc/ipsec.d 0700 root root -"
       "d /var/lib/NetworkManager-fortisslvpn 0700 root root -"
 
-      "d /var/lib/dhclient 0755 root root -"
       "d /var/lib/misc 0755 root root -" # for dnsmasq.leases
     ];
 
@@ -534,8 +496,20 @@ in {
         useDHCP = false;
       })
 
+      {
+        networkmanager.plugins = with pkgs; [
+          networkmanager-fortisslvpn
+          networkmanager-iodine
+          networkmanager-l2tp
+          networkmanager-openconnect
+          networkmanager-openvpn
+          networkmanager-vpnc
+          networkmanager-sstp
+        ];
+      }
+
       (mkIf cfg.enableStrongSwan {
-        networkmanager.packages = [ pkgs.networkmanager_strongswan ];
+        networkmanager.plugins = [ pkgs.networkmanager_strongswan ];
       })
 
       (mkIf enableIwd {
@@ -559,10 +533,10 @@ in {
     security.polkit.enable = true;
     security.polkit.extraConfig = polkitConf;
 
-    services.dbus.packages = cfg.packages
+    services.dbus.packages = packages
       ++ optional cfg.enableStrongSwan pkgs.strongswanNM
       ++ optional (cfg.dns == "dnsmasq") pkgs.dnsmasq;
 
-    services.udev.packages = cfg.packages;
+    services.udev.packages = packages;
   };
 }
diff --git a/nixos/modules/services/networking/nextdns.nix b/nixos/modules/services/networking/nextdns.nix
index b070eeec894..697fa605049 100644
--- a/nixos/modules/services/networking/nextdns.nix
+++ b/nixos/modules/services/networking/nextdns.nix
@@ -10,13 +10,13 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the NextDNS DNS/53 to DoH Proxy service.";
+        description = lib.mdDoc "Whether to enable the NextDNS DNS/53 to DoH Proxy service.";
       };
       arguments = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "-config" "10.0.3.0/24=abcdef" ];
-        description = "Additional arguments to be passed to nextdns run.";
+        description = lib.mdDoc "Additional arguments to be passed to nextdns run.";
       };
     };
   };
diff --git a/nixos/modules/services/networking/nftables.nix b/nixos/modules/services/networking/nftables.nix
index b911f97491e..d2d7543e8cf 100644
--- a/nixos/modules/services/networking/nftables.nix
+++ b/nixos/modules/services/networking/nftables.nix
@@ -11,7 +11,7 @@ in
       type = types.bool;
       default = false;
       description =
-        ''
+        lib.mdDoc ''
           Whether to enable nftables.  nftables is a Linux-based packet
           filtering framework intended to replace frameworks like iptables.
 
@@ -21,14 +21,13 @@ in
           Note that if you have Docker enabled you will not be able to use
           nftables without intervention. Docker uses iptables internally to
           setup NAT for containers. This module disables the ip_tables kernel
-          module, however Docker automatically loads the module. Please see [1]
+          module, however Docker automatically loads the module. Please see
+          <https://github.com/NixOS/nixpkgs/issues/24318#issuecomment-289216273>
           for more information.
 
           There are other programs that use iptables internally too, such as
-          libvirt. For information on how the two firewalls interact, see [2].
-
-          [1]: https://github.com/NixOS/nixpkgs/issues/24318#issuecomment-289216273
-          [2]: https://wiki.nftables.org/wiki-nftables/index.php/Troubleshooting#Question_4._How_do_nftables_and_iptables_interact_when_used_on_the_same_system.3F
+          libvirt. For information on how the two firewalls interact, see
+          <https://wiki.nftables.org/wiki-nftables/index.php/Troubleshooting#Question_4._How_do_nftables_and_iptables_interact_when_used_on_the_same_system.3F>.
         '';
     };
     networking.nftables.ruleset = mkOption {
@@ -77,7 +76,7 @@ in
         }
       '';
       description =
-        ''
+        lib.mdDoc ''
           The ruleset to be used with nftables.  Should be in a format that
           can be loaded using "/bin/nft -f".  The ruleset is updated atomically.
         '';
@@ -88,9 +87,9 @@ in
         name = "nftables-rules";
         text = cfg.ruleset;
       };
-      defaultText = literalDocBook ''a file with the contents of <option>networking.nftables.ruleset</option>'';
+      defaultText = literalMD ''a file with the contents of {option}`networking.nftables.ruleset`'';
       description =
-        ''
+        lib.mdDoc ''
           The ruleset file to be used with nftables.  Should be in a format that
           can be loaded using "nft -f".  The ruleset is updated atomically.
         '';
diff --git a/nixos/modules/services/networking/nghttpx/backend-params-submodule.nix b/nixos/modules/services/networking/nghttpx/backend-params-submodule.nix
index 6523f4b8b9e..510dc02b5c9 100644
--- a/nixos/modules/services/networking/nghttpx/backend-params-submodule.nix
+++ b/nixos/modules/services/networking/nghttpx/backend-params-submodule.nix
@@ -3,7 +3,7 @@
     proto = lib.mkOption {
       type        = lib.types.enum [ "h2" "http/1.1" ];
       default     = "http/1.1";
-      description = ''
+      description = lib.mdDoc ''
         This option configures the protocol the backend server expects
         to use.
 
@@ -15,7 +15,7 @@
     tls = lib.mkOption {
       type        = lib.types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         This option determines whether nghttpx will negotiate its
         connection with a backend server using TLS or not. The burden
         is on the backend server to provide the TLS certificate!
@@ -28,7 +28,7 @@
     sni = lib.mkOption {
       type        = lib.types.nullOr lib.types.str;
       default     = null;
-      description = ''
+      description = lib.mdDoc ''
         Override the TLS SNI field value. This value (in nghttpx)
         defaults to the host value of the backend configuration.
 
@@ -40,7 +40,7 @@
     fall = lib.mkOption {
       type        = lib.types.int;
       default     = 0;
-      description = ''
+      description = lib.mdDoc ''
         If nghttpx cannot connect to the backend N times in a row, the
         backend is assumed to be offline and is excluded from load
         balancing. If N is 0 the backend is never excluded from load
@@ -54,7 +54,7 @@
     rise = lib.mkOption {
       type        = lib.types.int;
       default     = 0;
-      description = ''
+      description = lib.mdDoc ''
         If the backend is excluded from load balancing, nghttpx will
         periodically attempt to make a connection to the backend. If
         the connection is successful N times in a row the backend is
@@ -69,7 +69,7 @@
     affinity = lib.mkOption {
       type        = lib.types.enum [ "ip" "none" ];
       default     = "none";
-      description = ''
+      description = lib.mdDoc ''
         If "ip" is given, client IP based session affinity is
         enabled. If "none" is given, session affinity is disabled.
 
@@ -91,7 +91,7 @@
     dns = lib.mkOption {
       type        = lib.types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         Name resolution of a backends host name is done at start up,
         or configuration reload. If "dns" is true, name resolution
         takes place dynamically.
@@ -108,7 +108,7 @@
     redirect-if-not-tls = lib.mkOption {
       type        = lib.types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         If true, a backend match requires the frontend connection be
         TLS encrypted. If it is not, nghttpx responds to the request
         with a 308 status code and https URI the client should use
diff --git a/nixos/modules/services/networking/nghttpx/backend-submodule.nix b/nixos/modules/services/networking/nghttpx/backend-submodule.nix
index eb559e926e7..af99b21c9ab 100644
--- a/nixos/modules/services/networking/nghttpx/backend-submodule.nix
+++ b/nixos/modules/services/networking/nghttpx/backend-submodule.nix
@@ -13,7 +13,7 @@
         host = "127.0.0.1";
         port = 80;
       };
-      description = ''
+      description = lib.mdDoc ''
         Backend server location specified as either a host:port pair
         or a unix domain docket.
       '';
@@ -27,7 +27,7 @@
         "/somepath"
       ];
       default     = [];
-      description = ''
+      description = lib.mdDoc ''
         List of nghttpx backend patterns.
 
         Please see https://nghttp2.org/documentation/nghttpx.1.html#cmdoption-nghttpx-b
@@ -42,7 +42,7 @@
         tls   = true;
       };
       default     = null;
-      description = ''
+      description = lib.mdDoc ''
         Parameters to configure a backend.
       '';
     };
diff --git a/nixos/modules/services/networking/nghttpx/frontend-params-submodule.nix b/nixos/modules/services/networking/nghttpx/frontend-params-submodule.nix
index 33c8572bd14..66c6d7efa6a 100644
--- a/nixos/modules/services/networking/nghttpx/frontend-params-submodule.nix
+++ b/nixos/modules/services/networking/nghttpx/frontend-params-submodule.nix
@@ -3,7 +3,7 @@
     tls = lib.mkOption {
       type        = lib.types.enum [ "tls" "no-tls" ];
       default     = "tls";
-      description = ''
+      description = lib.mdDoc ''
         Enable or disable TLS. If true (enabled) the key and
         certificate must be configured for nghttpx.
 
@@ -15,7 +15,7 @@
     sni-fwd = lib.mkOption {
       type    = lib.types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         When performing a match to select a backend server, SNI host
         name received from the client is used instead of the request
         host. See --backend option about the pattern match.
@@ -28,7 +28,7 @@
     api = lib.mkOption {
       type        = lib.types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable API access for this frontend. This enables you to
         dynamically modify nghttpx at run-time therefore this feature
         is disabled by default and should be turned on with care.
@@ -41,7 +41,7 @@
     healthmon = lib.mkOption {
       type        = lib.types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         Make this frontend a health monitor endpoint. Any request
         received on this frontend is responded to with a 200 OK.
 
@@ -53,7 +53,7 @@
     proxyproto = lib.mkOption {
       type        = lib.types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         Accept PROXY protocol version 1 on frontend connection.
 
         Please see https://nghttp2.org/documentation/nghttpx.1.html#cmdoption-nghttpx-f
diff --git a/nixos/modules/services/networking/nghttpx/frontend-submodule.nix b/nixos/modules/services/networking/nghttpx/frontend-submodule.nix
index 887ef450213..3175df20eec 100644
--- a/nixos/modules/services/networking/nghttpx/frontend-submodule.nix
+++ b/nixos/modules/services/networking/nghttpx/frontend-submodule.nix
@@ -13,7 +13,7 @@
         host = "127.0.0.1";
         port = 80;
       };
-      description = ''
+      description = lib.mdDoc ''
         Frontend server interface binding specification as either a
         host:port pair or a unix domain docket.
 
@@ -28,7 +28,7 @@
         tls   = "tls";
       };
       default     = null;
-      description = ''
+      description = lib.mdDoc ''
         Parameters to configure a backend.
       '';
     };
diff --git a/nixos/modules/services/networking/nghttpx/nghttpx-options.nix b/nixos/modules/services/networking/nghttpx/nghttpx-options.nix
index 51f1d081b97..82ab8c4223e 100644
--- a/nixos/modules/services/networking/nghttpx/nghttpx-options.nix
+++ b/nixos/modules/services/networking/nghttpx/nghttpx-options.nix
@@ -1,10 +1,10 @@
 { lib, ... }:
 { options.services.nghttpx = {
-    enable = lib.mkEnableOption "nghttpx";
+    enable = lib.mkEnableOption (lib.mdDoc "nghttpx");
 
     frontends = lib.mkOption {
       type        = lib.types.listOf (lib.types.submodule (import ./frontend-submodule.nix));
-      description = ''
+      description = lib.mdDoc ''
         A list of frontend listener specifications.
       '';
       example = [
@@ -22,7 +22,7 @@
 
     backends  = lib.mkOption {
       type = lib.types.listOf (lib.types.submodule (import ./backend-submodule.nix));
-      description = ''
+      description = lib.mdDoc ''
         A list of backend specifications.
       '';
       example = [
@@ -42,10 +42,10 @@
     tls = lib.mkOption {
       type        = lib.types.nullOr (lib.types.submodule (import ./tls-submodule.nix));
       default     = null;
-      description = ''
+      description = lib.mdDoc ''
         TLS certificate and key paths. Note that this does not enable
         TLS for a frontend listener, to do so, a frontend
-        specification must set <literal>params.tls</literal> to true.
+        specification must set `params.tls` to true.
       '';
       example = {
         key = "/etc/ssl/keys/server.key";
@@ -56,7 +56,7 @@
     extraConfig = lib.mkOption {
       type        = lib.types.lines;
       default     = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra configuration options to be appended to the generated
         configuration file.
       '';
@@ -65,7 +65,7 @@
     single-process = lib.mkOption {
       type        = lib.types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         Run this program in a single process mode for debugging
         purpose. Without this option, nghttpx creates at least 2
         processes: master and worker processes. If this option is
@@ -81,7 +81,7 @@
     backlog = lib.mkOption {
       type        = lib.types.int;
       default     = 65536;
-      description = ''
+      description = lib.mdDoc ''
         Listen backlog size.
 
         Please see https://nghttp2.org/documentation/nghttpx.1.html#cmdoption-nghttpx--backlog
@@ -95,7 +95,7 @@
         "IPv6"
       ];
       default = "auto";
-      description = ''
+      description = lib.mdDoc ''
         Specify address family of backend connections. If "auto" is
         given, both IPv4 and IPv6 are considered. If "IPv4" is given,
         only IPv4 address is considered. If "IPv6" is given, only IPv6
@@ -108,7 +108,7 @@
     workers = lib.mkOption {
       type        = lib.types.int;
       default     = 1;
-      description = ''
+      description = lib.mdDoc ''
         Set the number of worker threads.
 
         Please see https://nghttp2.org/documentation/nghttpx.1.html#cmdoption-nghttpx-n
@@ -118,7 +118,7 @@
     single-thread = lib.mkOption {
       type        = lib.types.bool;
       default     = false;
-      description = ''
+      description = lib.mdDoc ''
         Run everything in one thread inside the worker process. This
         feature is provided for better debugging experience, or for
         the platforms which lack thread support. If threading is
@@ -131,8 +131,8 @@
     rlimit-nofile = lib.mkOption {
       type        = lib.types.int;
       default     = 0;
-      description = ''
-        Set maximum number of open files (RLIMIT_NOFILE) to &lt;N&gt;. If 0
+      description = lib.mdDoc ''
+        Set maximum number of open files (RLIMIT_NOFILE) to \<N\>. If 0
         is given, nghttpx does not set the limit.
 
         Please see https://nghttp2.org/documentation/nghttpx.1.html#cmdoption-nghttpx--rlimit-nofile
diff --git a/nixos/modules/services/networking/nghttpx/server-options.nix b/nixos/modules/services/networking/nghttpx/server-options.nix
index ef23bfd793c..48e2a304559 100644
--- a/nixos/modules/services/networking/nghttpx/server-options.nix
+++ b/nixos/modules/services/networking/nghttpx/server-options.nix
@@ -3,14 +3,14 @@
     host = lib.mkOption {
       type        = lib.types.str;
       example     = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         Server host address.
       '';
     };
     port = lib.mkOption {
       type        = lib.types.int;
       example     = 5088;
-      description = ''
+      description = lib.mdDoc ''
         Server host port.
       '';
     };
diff --git a/nixos/modules/services/networking/nghttpx/tls-submodule.nix b/nixos/modules/services/networking/nghttpx/tls-submodule.nix
index 8f3cdaae2c8..bb6cdae07e5 100644
--- a/nixos/modules/services/networking/nghttpx/tls-submodule.nix
+++ b/nixos/modules/services/networking/nghttpx/tls-submodule.nix
@@ -4,7 +4,7 @@
       type        = lib.types.str;
       example     = "/etc/ssl/keys/mykeyfile.key";
       default     = "/etc/ssl/keys/server.key";
-      description = ''
+      description = lib.mdDoc ''
         Path to the TLS key file.
       '';
     };
@@ -13,7 +13,7 @@
       type        = lib.types.str;
       example     = "/etc/ssl/certs/mycert.crt";
       default     = "/etc/ssl/certs/server.crt";
-      description = ''
+      description = lib.mdDoc ''
         Path to the TLS certificate file.
       '';
     };
diff --git a/nixos/modules/services/networking/ngircd.nix b/nixos/modules/services/networking/ngircd.nix
index c0b9c98fb4b..5e721f5aa62 100644
--- a/nixos/modules/services/networking/ngircd.nix
+++ b/nixos/modules/services/networking/ngircd.nix
@@ -20,16 +20,16 @@ let
 in {
   options = {
     services.ngircd = {
-      enable = mkEnableOption "the ngircd IRC server";
+      enable = mkEnableOption (lib.mdDoc "the ngircd IRC server");
 
       config = mkOption {
-        description = "The ngircd configuration (see ngircd.conf(5)).";
+        description = lib.mdDoc "The ngircd configuration (see ngircd.conf(5)).";
 
         type = types.lines;
       };
 
       package = mkOption {
-        description = "The ngircd package.";
+        description = lib.mdDoc "The ngircd package.";
 
         type = types.package;
 
diff --git a/nixos/modules/services/networking/nix-serve.nix b/nixos/modules/services/networking/nix-serve.nix
index 432938d59d9..f37be31270b 100644
--- a/nixos/modules/services/networking/nix-serve.nix
+++ b/nixos/modules/services/networking/nix-serve.nix
@@ -8,12 +8,12 @@ in
 {
   options = {
     services.nix-serve = {
-      enable = mkEnableOption "nix-serve, the standalone Nix binary cache server";
+      enable = mkEnableOption (lib.mdDoc "nix-serve, the standalone Nix binary cache server");
 
       port = mkOption {
         type = types.port;
         default = 5000;
-        description = ''
+        description = lib.mdDoc ''
           Port number where nix-serve will listen on.
         '';
       };
@@ -21,21 +21,30 @@ in
       bindAddress = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           IP address where nix-serve will bind its listening socket.
         '';
       };
 
+      package = mkOption {
+        type = types.package;
+        default = pkgs.nix-serve;
+        defaultText = literalExpression "pkgs.nix-serve";
+        description = lib.mdDoc ''
+          nix-serve package to use.
+        '';
+      };
+
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for nix-serve.";
+        description = lib.mdDoc "Open ports in the firewall for nix-serve.";
       };
 
       secretKeyFile = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The path to the file used for signing derivation data.
           Generate with:
 
@@ -43,14 +52,14 @@ in
           nix-store --generate-binary-cache-key key-name secret-key-file public-key-file
           ```
 
-          For more details see <citerefentry><refentrytitle>nix-store</refentrytitle><manvolnum>1</manvolnum></citerefentry>.
+          For more details see {manpage}`nix-store(1)`.
         '';
       };
 
       extraParams = mkOption {
         type = types.separatedString " ";
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra command line parameters for nix-serve.
         '';
       };
@@ -70,7 +79,7 @@ in
         ${lib.optionalString (cfg.secretKeyFile != null) ''
           export NIX_SECRET_KEY_FILE="$CREDENTIALS_DIRECTORY/NIX_SECRET_KEY_FILE"
         ''}
-        exec ${pkgs.nix-serve}/bin/nix-serve --listen ${cfg.bindAddress}:${toString cfg.port} ${cfg.extraParams}
+        exec ${cfg.package}/bin/nix-serve --listen ${cfg.bindAddress}:${toString cfg.port} ${cfg.extraParams}
       '';
 
       serviceConfig = {
diff --git a/nixos/modules/services/networking/nix-store-gcs-proxy.nix b/nixos/modules/services/networking/nix-store-gcs-proxy.nix
index 0012302db2e..531b2bde763 100644
--- a/nixos/modules/services/networking/nix-store-gcs-proxy.nix
+++ b/nixos/modules/services/networking/nix-store-gcs-proxy.nix
@@ -9,18 +9,18 @@ let
         default = true;
         type = types.bool;
         example = true;
-        description = "Whether to enable proxy for this bucket";
+        description = lib.mdDoc "Whether to enable proxy for this bucket";
       };
       bucketName = mkOption {
         type = types.str;
         default = name;
         example = "my-bucket-name";
-        description = "Name of Google storage bucket";
+        description = lib.mdDoc "Name of Google storage bucket";
       };
       address = mkOption {
         type = types.str;
         example = "localhost:3000";
-        description = "The address of the proxy.";
+        description = lib.mdDoc "The address of the proxy.";
       };
     };
   };
@@ -31,7 +31,7 @@ in
   options.services.nix-store-gcs-proxy = mkOption {
     type = types.attrsOf (types.submodule opts);
     default = {};
-    description = ''
+    description = lib.mdDoc ''
       An attribute set describing an HTTP to GCS proxy that allows us to use GCS
       bucket via HTTP protocol.
     '';
diff --git a/nixos/modules/services/networking/nixops-dns.nix b/nixos/modules/services/networking/nixops-dns.nix
index 5e33d872ea4..378c2ee6d05 100644
--- a/nixos/modules/services/networking/nixops-dns.nix
+++ b/nixos/modules/services/networking/nixops-dns.nix
@@ -12,7 +12,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the nixops-dns resolution
           of NixOps virtual machines via dnsmasq and fake domain name.
         '';
@@ -20,7 +20,7 @@ in
 
       user = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The user the nixops-dns daemon should run as.
           This should be the user, which is also used for nixops and
           have the .nixops directory in its home.
@@ -29,7 +29,7 @@ in
 
       domain = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Fake domain name to resolve to NixOps virtual machines.
 
           For example "ops" will resolve "vm.ops".
@@ -40,7 +40,7 @@ in
       dnsmasq = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Enable dnsmasq forwarding to nixops-dns. This allows to use
           nixops-dns for `services.nixops-dns.domain` resolution
           while forwarding the rest of the queries to original resolvers.
diff --git a/nixos/modules/services/networking/nntp-proxy.nix b/nixos/modules/services/networking/nntp-proxy.nix
index a5973cd5933..b887c0e16ef 100644
--- a/nixos/modules/services/networking/nntp-proxy.nix
+++ b/nixos/modules/services/networking/nntp-proxy.nix
@@ -59,21 +59,21 @@ in
   options = {
 
     services.nntp-proxy = {
-      enable = mkEnableOption "NNTP-Proxy";
+      enable = mkEnableOption (lib.mdDoc "NNTP-Proxy");
 
       upstreamServer = mkOption {
         type = types.str;
         default = "";
         example = "ssl-eu.astraweb.com";
-        description = ''
+        description = lib.mdDoc ''
           Upstream server address
         '';
       };
 
       upstreamPort = mkOption {
-        type = types.int;
+        type = types.port;
         default = 563;
-        description = ''
+        description = lib.mdDoc ''
           Upstream server port
         '';
       };
@@ -81,7 +81,7 @@ in
       upstreamMaxConnections = mkOption {
         type = types.int;
         default = 20;
-        description = ''
+        description = lib.mdDoc ''
           Upstream server maximum allowed concurrent connections
         '';
       };
@@ -89,7 +89,7 @@ in
       upstreamUser = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Upstream server username
         '';
       };
@@ -97,7 +97,7 @@ in
       upstreamPassword = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Upstream server password
         '';
       };
@@ -106,15 +106,15 @@ in
         type = types.str;
         default = "127.0.0.1";
         example = "[::]";
-        description = ''
+        description = lib.mdDoc ''
           Proxy listen address (IPv6 literal addresses need to be enclosed in "[" and "]" characters)
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 5555;
-        description = ''
+        description = lib.mdDoc ''
           Proxy listen port
         '';
       };
@@ -123,7 +123,7 @@ in
         type = types.str;
         default = "key.pem";
         example = "/path/to/your/key.file";
-        description = ''
+        description = lib.mdDoc ''
           Proxy ssl key path
         '';
       };
@@ -132,7 +132,7 @@ in
         type = types.str;
         default = "cert.pem";
         example = "/path/to/your/cert.file";
-        description = ''
+        description = lib.mdDoc ''
           Proxy ssl certificate path
         '';
       };
@@ -140,7 +140,7 @@ in
       prohibitPosting = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to prohibit posting to the upstream server
         '';
       };
@@ -149,7 +149,7 @@ in
         type = types.enum [ "error" "warning" "notice" "info" "debug" ];
         default = "info";
         example = "error";
-        description = ''
+        description = lib.mdDoc ''
           Verbosity level
         '';
       };
@@ -159,7 +159,7 @@ in
           options = {
             username = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Username
               '';
             };
@@ -167,22 +167,22 @@ in
             passwordHash = mkOption {
               type = types.str;
               example = "$6$GtzE7FrpE$wwuVgFYU.TZH4Rz.Snjxk9XGua89IeVwPQ/fEUD8eujr40q5Y021yhn0aNcsQ2Ifw.BLclyzvzgegopgKcneL0";
-              description = ''
+              description = lib.mdDoc ''
                 SHA-512 password hash (can be generated by
-                <code>mkpasswd -m sha-512 &lt;password&gt;</code>)
+                `mkpasswd -m sha-512 <password>`)
               '';
             };
 
             maxConnections = mkOption {
               type = types.int;
               default = 1;
-              description = ''
+              description = lib.mdDoc ''
                 Maximum number of concurrent connections to the proxy for this user
               '';
             };
           };
         });
-        description = ''
+        description = lib.mdDoc ''
           NNTP-Proxy user configuration
         '';
 
diff --git a/nixos/modules/services/networking/nomad.nix b/nixos/modules/services/networking/nomad.nix
index 43333af5e2f..5e5d9469efc 100644
--- a/nixos/modules/services/networking/nomad.nix
+++ b/nixos/modules/services/networking/nomad.nix
@@ -8,13 +8,13 @@ in
   ##### interface
   options = {
     services.nomad = {
-      enable = mkEnableOption "Nomad, a distributed, highly available, datacenter-aware scheduler";
+      enable = mkEnableOption (lib.mdDoc "Nomad, a distributed, highly available, datacenter-aware scheduler");
 
       package = mkOption {
         type = types.package;
         default = pkgs.nomad;
         defaultText = literalExpression "pkgs.nomad";
-        description = ''
+        description = lib.mdDoc ''
           The package used for the Nomad agent and CLI.
         '';
       };
@@ -22,8 +22,8 @@ in
       extraPackages = mkOption {
         type = types.listOf types.package;
         default = [ ];
-        description = ''
-          Extra packages to add to <envar>PATH</envar> for the Nomad agent process.
+        description = lib.mdDoc ''
+          Extra packages to add to {env}`PATH` for the Nomad agent process.
         '';
         example = literalExpression ''
           with pkgs; [ cni-plugins ]
@@ -33,7 +33,7 @@ in
       dropPrivileges = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether the nomad agent should be run as a non-root nomad user.
         '';
       };
@@ -41,7 +41,7 @@ in
       enableDocker = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Enable Docker support. Needed for Nomad's docker driver.
 
           Note that the docker group membership is effectively equivalent
@@ -52,7 +52,7 @@ in
       extraSettingsPaths = mkOption {
         type = types.listOf types.path;
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           Additional settings paths used to configure nomad. These can be files or directories.
         '';
         example = literalExpression ''
@@ -63,7 +63,7 @@ in
       extraSettingsPlugins = mkOption {
         type = types.listOf (types.either types.package types.path);
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           Additional plugins dir used to configure nomad.
         '';
         example = literalExpression ''
@@ -75,23 +75,23 @@ in
       settings = mkOption {
         type = format.type;
         default = { };
-        description = ''
-          Configuration for Nomad. See the <link xlink:href="https://www.nomadproject.io/docs/configuration">documentation</link>
+        description = lib.mdDoc ''
+          Configuration for Nomad. See the [documentation](https://www.nomadproject.io/docs/configuration)
           for supported values.
 
-          Notes about <literal>data_dir</literal>:
+          Notes about `data_dir`:
 
-          If <literal>data_dir</literal> is set to a value other than the
-          default value of <literal>"/var/lib/nomad"</literal> it is the Nomad
+          If `data_dir` is set to a value other than the
+          default value of `"/var/lib/nomad"` it is the Nomad
           cluster manager's responsibility to make sure that this directory
           exists and has the appropriate permissions.
 
-          Additionally, if <literal>dropPrivileges</literal> is
-          <literal>true</literal> then <literal>data_dir</literal>
-          <emphasis>cannot</emphasis> be customized. Setting
-          <literal>dropPrivileges</literal> to <literal>true</literal> enables
-          the <literal>DynamicUser</literal> feature of systemd which directly
-          manages and operates on <literal>StateDirectory</literal>.
+          Additionally, if `dropPrivileges` is
+          `true` then `data_dir`
+          *cannot* be customized. Setting
+          `dropPrivileges` to `true` enables
+          the `DynamicUser` feature of systemd which directly
+          manages and operates on `StateDirectory`.
         '';
         example = literalExpression ''
           {
diff --git a/nixos/modules/services/networking/nsd.nix b/nixos/modules/services/networking/nsd.nix
index a51fc534534..57da208bd7a 100644
--- a/nixos/modules/services/networking/nsd.nix
+++ b/nixos/modules/services/networking/nsd.nix
@@ -201,7 +201,7 @@ let
       allowAXFRFallback = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           If NSD as secondary server should be allowed to AXFR if the primary
           server does not allow IXFR.
         '';
@@ -213,24 +213,24 @@ let
         example = [ "192.0.2.0/24 NOKEY" "10.0.0.1-10.0.0.5 my_tsig_key_name"
                     "10.0.3.4&255.255.0.0 BLOCKED"
                   ];
-        description = ''
+        description = lib.mdDoc ''
           Listed primary servers are allowed to notify this secondary server.
-          <screen><![CDATA[
-          Format: <ip> <key-name | NOKEY | BLOCKED>
 
-          <ip> either a plain IPv4/IPv6 address or range. Valid patters for ranges:
-          * 10.0.0.0/24            # via subnet size
-          * 10.0.0.0&255.255.255.0 # via subnet mask
-          * 10.0.0.1-10.0.0.254    # via range
+          Format: `<ip> <key-name | NOKEY | BLOCKED>`
+
+          `<ip>` either a plain IPv4/IPv6 address or range.
+          Valid patters for ranges:
+          * `10.0.0.0/24`: via subnet size
+          * `10.0.0.0&255.255.255.0`: via subnet mask
+          * `10.0.0.1-10.0.0.254`: via range
 
           A optional port number could be added with a '@':
-          * 2001:1234::1@1234
+          * `2001:1234::1@1234`
 
-          <key-name | NOKEY | BLOCKED>
-          * <key-name> will use the specified TSIG key
-          * NOKEY      no TSIG signature is required
-          * BLOCKED    notifies from non-listed or blocked IPs will be ignored
-          * ]]></screen>
+          `<key-name | NOKEY | BLOCKED>`
+          * `<key-name>` will use the specified TSIG key
+          * `NOKEY` no TSIG signature is required
+          * `BLOCKED`notifies from non-listed or blocked IPs will be ignored
         '';
       };
 
@@ -243,7 +243,7 @@ let
         # to default values, breaking the parent inheriting function.
         type = types.attrsOf types.anything;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Children zones inherit all options of their parents. Attributes
           defined in a child will overwrite the ones of its parent. Only
           leaf zones will be actually served. This way it's possible to
@@ -256,29 +256,29 @@ let
       data = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           The actual zone data. This is the content of your zone file.
           Use imports or pkgs.lib.readFile if you don't want this data in your config file.
         '';
       };
 
-      dnssec = mkEnableOption "DNSSEC";
+      dnssec = mkEnableOption (lib.mdDoc "DNSSEC");
 
       dnssecPolicy = {
         algorithm = mkOption {
           type = types.str;
           default = "RSASHA256";
-          description = "Which algorithm to use for DNSSEC";
+          description = lib.mdDoc "Which algorithm to use for DNSSEC";
         };
         keyttl = mkOption {
           type = types.str;
           default = "1h";
-          description = "TTL for dnssec records";
+          description = lib.mdDoc "TTL for dnssec records";
         };
         coverage = mkOption {
           type = types.str;
           default = "1y";
-          description = ''
+          description = lib.mdDoc ''
             The length of time to ensure that keys will be correct; no action will be taken to create new keys to be activated after this time.
           '';
         };
@@ -289,7 +289,7 @@ let
                       postPublish = "1w";
                       rollPeriod = "1mo";
                     };
-          description = "Key policy for zone signing keys";
+          description = lib.mdDoc "Key policy for zone signing keys";
         };
         ksk = mkOption {
           type = keyPolicy;
@@ -298,14 +298,14 @@ let
                       postPublish = "1mo";
                       rollPeriod = "0";
                     };
-          description = "Key policy for key signing keys";
+          description = lib.mdDoc "Key policy for key signing keys";
         };
       };
 
       maxRefreshSecs = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Limit refresh time for secondary zones. This is the timer which
           checks to see if the zone has to be refetched when it expires.
           Normally the value from the SOA record is used, but this  option
@@ -316,7 +316,7 @@ let
       minRefreshSecs = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Limit refresh time for secondary zones.
         '';
       };
@@ -324,7 +324,7 @@ let
       maxRetrySecs = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Limit retry time for secondary zones. This is the timeout after
           a failed fetch attempt for the zone. Normally the value from
           the SOA record is used, but this option restricts that value.
@@ -334,7 +334,7 @@ let
       minRetrySecs = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Limit retry time for secondary zones.
         '';
       };
@@ -344,25 +344,24 @@ let
         type = types.listOf types.str;
         default = [];
         example = [ "10.0.0.1@3721 my_key" "::5 NOKEY" ];
-        description = ''
+        description = lib.mdDoc ''
           This primary server will notify all given secondary servers about
           zone changes.
-          <screen><![CDATA[
-          Format: <ip> <key-name | NOKEY>
 
-          <ip> a plain IPv4/IPv6 address with on optional port number (ip@port)
+          Format: `<ip> <key-name | NOKEY>`
+
+          `<ip>` a plain IPv4/IPv6 address with on optional port number (ip@port)
 
-          <key-name | NOKEY>
-          * <key-name> sign notifies with the specified key
-          * NOKEY      don't sign notifies
-          ]]></screen>
+          `<key-name | NOKEY>`
+          - `<key-name>` sign notifies with the specified key
+          - `NOKEY` don't sign notifies
         '';
       };
 
       notifyRetry = mkOption {
         type = types.int;
         default = 5;
-        description = ''
+        description = lib.mdDoc ''
           Specifies the number of retries for failed notifies. Set this along with notify.
         '';
       };
@@ -371,7 +370,7 @@ let
         type = types.nullOr types.str;
         default = null;
         example = "2000::1@1234";
-        description = ''
+        description = lib.mdDoc ''
           This address will be used for zone-transfere requests if configured
           as a secondary server or notifications in case of a primary server.
           Supply either a plain IPv4 or IPv6 address with an optional port
@@ -383,24 +382,24 @@ let
         type = types.listOf types.str;
         default = [];
         example = [ "192.0.2.0/24 NOKEY" "192.0.2.0/24 my_tsig_key_name" ];
-        description = ''
+        description = lib.mdDoc ''
           Allow these IPs and TSIG to transfer zones, addr TSIG|NOKEY|BLOCKED
-          address range 192.0.2.0/24, 1.2.3.4&amp;255.255.0.0, 3.0.2.20-3.0.2.40
+          address range 192.0.2.0/24, 1.2.3.4&255.255.0.0, 3.0.2.20-3.0.2.40
         '';
       };
 
       requestXFR = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
-          Format: <code>[AXFR|UDP] &lt;ip-address&gt; &lt;key-name | NOKEY&gt;</code>
+        description = lib.mdDoc ''
+          Format: `[AXFR|UDP] <ip-address> <key-name | NOKEY>`
         '';
       };
 
       rrlWhitelist = mkOption {
         type = with types; listOf (enum [ "nxdomain" "error" "referral" "any" "rrsig" "wildcard" "nodata" "dnskey" "positive" "all" ]);
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Whitelists the given rrl-types.
         '';
       };
@@ -409,7 +408,7 @@ let
         type = types.nullOr types.str;
         default = null;
         example = "%s";
-        description = ''
+        description = lib.mdDoc ''
           When set to something distinct to null NSD is able to collect
           statistics per zone. All statistics of this zone(s) will be added
           to the group specified by this given name. Use "%s" to use the zones
@@ -424,19 +423,19 @@ let
     options = {
       keySize = mkOption {
         type = types.int;
-        description = "Key size in bits";
+        description = lib.mdDoc "Key size in bits";
       };
       prePublish = mkOption {
         type = types.str;
-        description = "How long in advance to publish new keys";
+        description = lib.mdDoc "How long in advance to publish new keys";
       };
       postPublish = mkOption {
         type = types.str;
-        description = "How long after deactivation to keep a key in the zone";
+        description = lib.mdDoc "How long after deactivation to keep a key in the zone";
       };
       rollPeriod = mkOption {
         type = types.str;
-        description = "How frequently to change keys";
+        description = lib.mdDoc "How frequently to change keys";
       };
     };
   };
@@ -479,14 +478,14 @@ in
   # options are ordered alphanumerically
   options.services.nsd = {
 
-    enable = mkEnableOption "NSD authoritative DNS server";
+    enable = mkEnableOption (lib.mdDoc "NSD authoritative DNS server");
 
-    bind8Stats = mkEnableOption "BIND8 like statistics";
+    bind8Stats = mkEnableOption (lib.mdDoc "BIND8 like statistics");
 
     dnssecInterval = mkOption {
       type = types.str;
       default = "1h";
-      description = ''
+      description = lib.mdDoc ''
         How often to check whether dnssec key rollover is required
       '';
     };
@@ -494,7 +493,7 @@ in
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Extra nsd config.
       '';
     };
@@ -502,7 +501,7 @@ in
     hideVersion = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether NSD should answer VERSION.BIND and VERSION.SERVER CHAOS class queries.
       '';
     };
@@ -510,7 +509,7 @@ in
     identity = mkOption {
       type = types.str;
       default = "unidentified server";
-      description = ''
+      description = lib.mdDoc ''
         Identify the server (CH TXT ID.SERVER entry).
       '';
     };
@@ -518,7 +517,7 @@ in
     interfaces = mkOption {
       type = types.listOf types.str;
       default = [ "127.0.0.0" "::1" ];
-      description = ''
+      description = lib.mdDoc ''
         What addresses the server should listen to.
       '';
     };
@@ -526,7 +525,7 @@ in
     ipFreebind = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to bind to nonlocal addresses and interfaces that are down.
         Similar to ip-transparent.
       '';
@@ -535,7 +534,7 @@ in
     ipTransparent = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Allow binding to non local addresses.
       '';
     };
@@ -543,7 +542,7 @@ in
     ipv4 = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to listen on IPv4 connections.
       '';
     };
@@ -551,7 +550,7 @@ in
     ipv4EDNSSize = mkOption {
       type = types.int;
       default = 4096;
-      description = ''
+      description = lib.mdDoc ''
         Preferred EDNS buffer size for IPv4.
       '';
     };
@@ -559,7 +558,7 @@ in
     ipv6 = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to listen on IPv6 connections.
       '';
     };
@@ -567,7 +566,7 @@ in
     ipv6EDNSSize = mkOption {
       type = types.int;
       default = 4096;
-      description = ''
+      description = lib.mdDoc ''
         Preferred EDNS buffer size for IPv6.
       '';
     };
@@ -575,7 +574,7 @@ in
     logTimeAscii = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Log time in ascii, if false then in unix epoch seconds.
       '';
     };
@@ -583,7 +582,7 @@ in
     nsid = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         NSID identity (hex string, or "ascii_somestring").
       '';
     };
@@ -591,7 +590,7 @@ in
     port = mkOption {
       type = types.int;
       default = 53;
-      description = ''
+      description = lib.mdDoc ''
         Port the service should bind do.
       '';
     };
@@ -600,7 +599,7 @@ in
       type = types.bool;
       default = pkgs.stdenv.isLinux;
       defaultText = literalExpression "pkgs.stdenv.isLinux";
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable SO_REUSEPORT on all used sockets. This lets multiple
         processes bind to the same port. This speeds up operation especially
         if the server count is greater than one and makes fast restarts less
@@ -611,18 +610,18 @@ in
     rootServer = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether this server will be a root server (a DNS root server, you
         usually don't want that).
       '';
     };
 
-    roundRobin = mkEnableOption "round robin rotation of records";
+    roundRobin = mkEnableOption (lib.mdDoc "round robin rotation of records");
 
     serverCount = mkOption {
       type = types.int;
       default = 1;
-      description = ''
+      description = lib.mdDoc ''
         Number of NSD servers to fork. Put the number of CPUs to use here.
       '';
     };
@@ -630,7 +629,7 @@ in
     statistics = mkOption {
       type = types.nullOr types.int;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Statistics are produced every number of seconds. Prints to log.
         If null no statistics are logged.
       '';
@@ -639,7 +638,7 @@ in
     tcpCount = mkOption {
       type = types.int;
       default = 100;
-      description = ''
+      description = lib.mdDoc ''
         Maximum number of concurrent TCP connections per server.
       '';
     };
@@ -647,7 +646,7 @@ in
     tcpQueryCount = mkOption {
       type = types.int;
       default = 0;
-      description = ''
+      description = lib.mdDoc ''
         Maximum number of queries served on a single TCP connection.
         0 means no maximum.
       '';
@@ -656,7 +655,7 @@ in
     tcpTimeout = mkOption {
       type = types.int;
       default = 120;
-      description = ''
+      description = lib.mdDoc ''
         TCP timeout in seconds.
       '';
     };
@@ -664,7 +663,7 @@ in
     verbosity = mkOption {
       type = types.int;
       default = 0;
-      description = ''
+      description = lib.mdDoc ''
         Verbosity level.
       '';
     };
@@ -672,7 +671,7 @@ in
     version = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The version string replied for CH TXT version.server and version.bind
         queries. Will use the compiled package version on null.
         See hideVersion for enabling/disabling this responses.
@@ -682,7 +681,7 @@ in
     xfrdReloadTimeout = mkOption {
       type = types.int;
       default = 1;
-      description = ''
+      description = lib.mdDoc ''
         Number of seconds between reloads triggered by xfrd.
       '';
     };
@@ -690,7 +689,7 @@ in
     zonefilesCheck = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to check mtime of all zone files on start and sighup.
       '';
     };
@@ -703,14 +702,14 @@ in
           algorithm = mkOption {
             type = types.str;
             default = "hmac-sha256";
-            description = ''
+            description = lib.mdDoc ''
               Authentication algorithm for this key.
             '';
           };
 
           keyFile = mkOption {
             type = types.path;
-            description = ''
+            description = lib.mdDoc ''
               Path to the file which contains the actual base64 encoded
               key. The key will be copied into "${stateDir}/private" before
               NSD starts. The copied file is only accessibly by the NSD
@@ -728,7 +727,7 @@ in
           };
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Define your TSIG keys here.
       '';
     };
@@ -736,12 +735,12 @@ in
 
     ratelimit = {
 
-      enable = mkEnableOption "ratelimit capabilities";
+      enable = mkEnableOption (lib.mdDoc "ratelimit capabilities");
 
       ipv4PrefixLength = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           IPv4 prefix length. Addresses are grouped by netblock.
         '';
       };
@@ -749,7 +748,7 @@ in
       ipv6PrefixLength = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           IPv6 prefix length. Addresses are grouped by netblock.
         '';
       };
@@ -757,7 +756,7 @@ in
       ratelimit = mkOption {
         type = types.int;
         default = 200;
-        description = ''
+        description = lib.mdDoc ''
           Max qps allowed from any query source.
           0 means unlimited. With an verbosity of 2 blocked and
           unblocked subnets will be logged.
@@ -767,7 +766,7 @@ in
       slip = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Number of packets that get discarded before replying a SLIP response.
           0 disables SLIP responses. 1 will make every response a SLIP response.
         '';
@@ -776,7 +775,7 @@ in
       size = mkOption {
         type = types.int;
         default = 1000000;
-        description = ''
+        description = lib.mdDoc ''
           Size of the hashtable. More buckets use more memory but lower
           the chance of hash hash collisions.
         '';
@@ -785,7 +784,7 @@ in
       whitelistRatelimit = mkOption {
         type = types.int;
         default = 2000;
-        description = ''
+        description = lib.mdDoc ''
           Max qps allowed from whitelisted sources.
           0 means unlimited. Set the rrl-whitelist option for specific
           queries to apply this limit instead of the default to them.
@@ -797,12 +796,12 @@ in
 
     remoteControl = {
 
-      enable = mkEnableOption "remote control via nsd-control";
+      enable = mkEnableOption (lib.mdDoc "remote control via nsd-control");
 
       controlCertFile = mkOption {
         type = types.path;
         default = "/etc/nsd/nsd_control.pem";
-        description = ''
+        description = lib.mdDoc ''
           Path to the client certificate signed with the server certificate.
           This file is used by nsd-control and generated by nsd-control-setup.
         '';
@@ -811,7 +810,7 @@ in
       controlKeyFile = mkOption {
         type = types.path;
         default = "/etc/nsd/nsd_control.key";
-        description = ''
+        description = lib.mdDoc ''
           Path to the client private key, which is used by nsd-control
           but not by the server. This file is generated by nsd-control-setup.
         '';
@@ -820,7 +819,7 @@ in
       interfaces = mkOption {
         type = types.listOf types.str;
         default = [ "127.0.0.1" "::1" ];
-        description = ''
+        description = lib.mdDoc ''
           Which interfaces NSD should bind to for remote control.
         '';
       };
@@ -828,7 +827,7 @@ in
       port = mkOption {
         type = types.int;
         default = 8952;
-        description = ''
+        description = lib.mdDoc ''
           Port number for remote control operations (uses TLS over TCP).
         '';
       };
@@ -836,7 +835,7 @@ in
       serverCertFile = mkOption {
         type = types.path;
         default = "/etc/nsd/nsd_server.pem";
-        description = ''
+        description = lib.mdDoc ''
           Path to the server self signed certificate, which is used by the server
           but and by nsd-control. This file is generated by nsd-control-setup.
         '';
@@ -845,7 +844,7 @@ in
       serverKeyFile = mkOption {
         type = types.path;
         default = "/etc/nsd/nsd_server.key";
-        description = ''
+        description = lib.mdDoc ''
           Path to the server private key, which is used by the server
           but not by nsd-control. This file is generated by nsd-control-setup.
         '';
@@ -887,7 +886,7 @@ in
           };
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Define your zones here. Zones can cascade other zones and therefore
         inherit settings from parent zones. Look at the definition of
         children to learn about inheritance and child zones.
diff --git a/nixos/modules/services/networking/ntopng.nix b/nixos/modules/services/networking/ntopng.nix
index 022fc923eda..e6344d7ff3b 100644
--- a/nixos/modules/services/networking/ntopng.nix
+++ b/nixos/modules/services/networking/ntopng.nix
@@ -43,7 +43,7 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Enable ntopng, a high-speed web-based traffic analysis and flow
           collection tool.
 
@@ -63,7 +63,7 @@ in
         default = [ "any" ];
         example = [ "eth0" "wlan0" ];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           List of interfaces to monitor. Use "any" to monitor all interfaces.
         '';
       };
@@ -71,7 +71,7 @@ in
       httpPort = mkOption {
         default = 3000;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           Sets the HTTP port of the embedded web server.
         '';
       };
@@ -79,7 +79,7 @@ in
       redis.address = mkOption {
         type = types.str;
         example = literalExpression "config.services.redis.ntopng.unixSocket";
-        description = ''
+        description = lib.mdDoc ''
           Redis address - may be a Unix socket or a network host and port.
         '';
       };
@@ -87,10 +87,10 @@ in
       redis.createInstance = mkOption {
         type = types.nullOr types.str;
         default = if versionAtLeast config.system.stateVersion "22.05" then "ntopng" else "";
-        description = ''
-          Local Redis instance name. Set to <literal>null</literal> to disable
-          local Redis instance. Defaults to <literal>""</literal> for
-          <literal>system.stateVersion</literal> older than 22.05.
+        description = lib.mdDoc ''
+          Local Redis instance name. Set to `null` to disable
+          local Redis instance. Defaults to `""` for
+          `system.stateVersion` older than 22.05.
         '';
       };
 
@@ -102,7 +102,7 @@ in
           --disable-login
         '';
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Overridable configuration file contents to use for ntopng. By
           default, use the contents automatically generated by NixOS.
         '';
@@ -111,10 +111,10 @@ in
       extraConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Configuration lines that will be appended to the generated ntopng
           configuration file. Note that this mechanism does not work when the
-          manual <option>configText</option> option is used.
+          manual {option}`configText` option is used.
         '';
       };
 
diff --git a/nixos/modules/services/networking/ntp/chrony.nix b/nixos/modules/services/networking/ntp/chrony.nix
index 34728455a21..7e3bb565d10 100644
--- a/nixos/modules/services/networking/ntp/chrony.nix
+++ b/nixos/modules/services/networking/ntp/chrony.nix
@@ -27,7 +27,7 @@ let
     ${cfg.extraConfig}
   '';
 
-  chronyFlags = "-n -m -u chrony -f ${configFile} ${toString cfg.extraFlags}";
+  chronyFlags = [ "-n" "-m" "-u" "chrony" "-f" "${configFile}" ] ++ cfg.extraFlags;
 in
 {
   options = {
@@ -35,7 +35,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to synchronise your machine's time using chrony.
           Make sure you disable NTP if you enable this service.
         '';
@@ -45,7 +45,7 @@ in
         type = types.package;
         default = pkgs.chrony;
         defaultText = literalExpression "pkgs.chrony";
-        description = ''
+        description = lib.mdDoc ''
           Which chrony package to use.
         '';
       };
@@ -54,7 +54,7 @@ in
         default = config.networking.timeServers;
         defaultText = literalExpression "config.networking.timeServers";
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The set of NTP servers from which to synchronise.
         '';
       };
@@ -62,7 +62,7 @@ in
       serverOption = mkOption {
         default = "iburst";
         type = types.enum [ "iburst" "offline" ];
-        description = ''
+        description = lib.mdDoc ''
           Set option for server directives.
 
           Use "iburst" to rapidly poll on startup. Recommended if your machine
@@ -76,7 +76,7 @@ in
       enableNTS = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Network Time Security authentication.
           Make sure it is supported by your selected NTP server(s).
         '';
@@ -86,7 +86,7 @@ in
         enabled = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Allow chronyd to make a rapid measurement of the system clock error
             at boot time, and to correct the system clock by stepping before
             normal operation begins.
@@ -96,7 +96,7 @@ in
         threshold = mkOption {
           type = types.either types.float types.int;
           default = 1000; # by default, same threshold as 'ntpd -g' (1000s)
-          description = ''
+          description = lib.mdDoc ''
             The threshold of system clock error (in seconds) above which the
             clock will be stepped. If the correction required is less than the
             threshold, a slew is used instead.
@@ -107,15 +107,15 @@ in
       directory = mkOption {
         type = types.str;
         default = "/var/lib/chrony";
-        description = "Directory where chrony state is stored.";
+        description = lib.mdDoc "Directory where chrony state is stored.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration directives that should be added to
-          <literal>chrony.conf</literal>
+          `chrony.conf`
         '';
       };
 
@@ -123,7 +123,7 @@ in
         default = [];
         example = [ "-s" ];
         type = types.listOf types.str;
-        description = "Extra flags passed to the chronyd command.";
+        description = lib.mdDoc "Extra flags passed to the chronyd command.";
       };
     };
   };
@@ -166,7 +166,7 @@ in
         unitConfig.ConditionCapability = "CAP_SYS_TIME";
         serviceConfig =
           { Type = "simple";
-            ExecStart = "${chronyPkg}/bin/chronyd ${chronyFlags}";
+            ExecStart = "${chronyPkg}/bin/chronyd ${builtins.toString chronyFlags}";
 
             ProtectHome = "yes";
             ProtectSystem = "full";
diff --git a/nixos/modules/services/networking/ntp/ntpd.nix b/nixos/modules/services/networking/ntp/ntpd.nix
index 12be0d045a8..036a8df635d 100644
--- a/nixos/modules/services/networking/ntp/ntpd.nix
+++ b/nixos/modules/services/networking/ntp/ntpd.nix
@@ -25,7 +25,7 @@ let
     ${cfg.extraConfig}
   '';
 
-  ntpFlags = "-c ${configFile} -u ntp:ntp ${toString cfg.extraFlags}";
+  ntpFlags = [ "-c" "${configFile}" "-u" "ntp:ntp" ] ++ cfg.extraFlags;
 
 in
 
@@ -40,21 +40,19 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to synchronise your machine's time using ntpd, as a peer in
           the NTP network.
-          </para>
-          <para>
-          Disables <literal>systemd.timesyncd</literal> if enabled.
+
+          Disables `systemd.timesyncd` if enabled.
         '';
       };
 
       restrictDefault = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The restriction flags to be set by default.
-          </para>
-          <para>
+
           The default flags prevent external hosts from using ntpd as a DDoS
           reflector, setting system time, and querying OS/ntpd version. As
           recommended in section 6.5.1.1.3, answer "No" of
@@ -65,10 +63,9 @@ in
 
       restrictSource = mkOption {
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The restriction flags to be set on source.
-          </para>
-          <para>
+
           The default flags allow peers to be added by ntpd from configured
           pool(s), but not by other means.
         '';
@@ -79,7 +76,7 @@ in
         default = config.networking.timeServers;
         defaultText = literalExpression "config.networking.timeServers";
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           The set of NTP servers from which to synchronise.
         '';
       };
@@ -90,14 +87,14 @@ in
         example = ''
           fudge 127.127.1.0 stratum 10
         '';
-        description = ''
-          Additional text appended to <filename>ntp.conf</filename>.
+        description = lib.mdDoc ''
+          Additional text appended to {file}`ntp.conf`.
         '';
       };
 
       extraFlags = mkOption {
         type = types.listOf types.str;
-        description = "Extra flags passed to the ntpd command.";
+        description = lib.mdDoc "Extra flags passed to the ntpd command.";
         example = literalExpression ''[ "--interface=eth0" ]'';
         default = [];
       };
@@ -140,7 +137,7 @@ in
           '';
 
         serviceConfig = {
-          ExecStart = "@${ntp}/bin/ntpd ntpd -g ${ntpFlags}";
+          ExecStart = "@${ntp}/bin/ntpd ntpd -g ${builtins.toString ntpFlags}";
           Type = "forking";
         };
       };
diff --git a/nixos/modules/services/networking/ntp/openntpd.nix b/nixos/modules/services/networking/ntp/openntpd.nix
index e86b71291f9..05df1f6e626 100644
--- a/nixos/modules/services/networking/ntp/openntpd.nix
+++ b/nixos/modules/services/networking/ntp/openntpd.nix
@@ -19,7 +19,7 @@ in
   ###### interface
 
   options.services.openntpd = {
-    enable = mkEnableOption "OpenNTP time synchronization server";
+    enable = mkEnableOption (lib.mdDoc "OpenNTP time synchronization server");
 
     servers = mkOption {
       default = config.services.ntp.servers;
@@ -35,8 +35,8 @@ in
         listen on 127.0.0.1
         listen on ::1
       '';
-      description = ''
-        Additional text appended to <filename>openntpd.conf</filename>.
+      description = lib.mdDoc ''
+        Additional text appended to {file}`openntpd.conf`.
       '';
     };
 
@@ -44,7 +44,7 @@ in
       type = with types; separatedString " ";
       default = "";
       example = "-s";
-      description = ''
+      description = lib.mdDoc ''
         Extra options used when launching openntpd.
       '';
     };
diff --git a/nixos/modules/services/networking/nullidentdmod.nix b/nixos/modules/services/networking/nullidentdmod.nix
index b0d338a2794..e74e1dd6b79 100644
--- a/nixos/modules/services/networking/nullidentdmod.nix
+++ b/nixos/modules/services/networking/nullidentdmod.nix
@@ -3,11 +3,11 @@
 
 in {
   options.services.nullidentdmod = with types; {
-    enable = mkEnableOption "the nullidentdmod identd daemon";
+    enable = mkEnableOption (lib.mdDoc "the nullidentdmod identd daemon");
 
     userid = mkOption {
       type = nullOr str;
-      description = "User ID to return. Set to null to return a random string each time.";
+      description = lib.mdDoc "User ID to return. Set to null to return a random string each time.";
       default = null;
       example = "alice";
     };
diff --git a/nixos/modules/services/networking/nylon.nix b/nixos/modules/services/networking/nylon.nix
index a20fa615af8..6ed832b6fa1 100644
--- a/nixos/modules/services/networking/nylon.nix
+++ b/nixos/modules/services/networking/nylon.nix
@@ -29,7 +29,7 @@ let
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enables nylon as a running service upon activation.
         '';
       };
@@ -37,13 +37,13 @@ let
       name = mkOption {
         type = types.str;
         default = "";
-        description = "The name of this nylon instance.";
+        description = lib.mdDoc "The name of this nylon instance.";
       };
 
       nrConnections = mkOption {
         type = types.int;
         default = 10;
-        description = ''
+        description = lib.mdDoc ''
           The number of allowed simultaneous connections to the daemon, default 10.
         '';
       };
@@ -51,7 +51,7 @@ let
       logging = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable logging, default is no logging.
         '';
       };
@@ -59,7 +59,7 @@ let
       verbosity = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable verbose output, default is to not be verbose.
         '';
       };
@@ -67,7 +67,7 @@ let
       acceptInterface = mkOption {
         type = types.str;
         default = "lo";
-        description = ''
+        description = lib.mdDoc ''
           Tell nylon which interface to listen for client requests on, default is "lo".
         '';
       };
@@ -75,7 +75,7 @@ let
       bindInterface = mkOption {
         type = types.str;
         default = "enp3s0f0";
-        description = ''
+        description = lib.mdDoc ''
           Tell nylon which interface to use as an uplink, default is "enp3s0f0".
         '';
       };
@@ -83,7 +83,7 @@ let
       port = mkOption {
         type = types.int;
         default = 1080;
-        description = ''
+        description = lib.mdDoc ''
           What port to listen for client requests, default is 1080.
         '';
       };
@@ -91,7 +91,7 @@ let
       allowedIPRanges = mkOption {
         type = with types; listOf str;
         default = [ "192.168.0.0/16" "127.0.0.1/8" "172.16.0.1/12" "10.0.0.0/8" ];
-        description = ''
+        description = lib.mdDoc ''
            Allowed client IP ranges are evaluated first, defaults to ARIN IPv4 private ranges:
              [ "192.168.0.0/16" "127.0.0.0/8" "172.16.0.0/12" "10.0.0.0/8" ]
         '';
@@ -100,7 +100,7 @@ let
       deniedIPRanges = mkOption {
         type = with types; listOf str;
         default = [ "0.0.0.0/0" ];
-        description = ''
+        description = lib.mdDoc ''
           Denied client IP ranges, these gets evaluated after the allowed IP ranges, defaults to all IPv4 addresses:
             [ "0.0.0.0/0" ]
           To block all other access than the allowed.
@@ -139,7 +139,7 @@ in
 
     services.nylon = mkOption {
       default = {};
-      description = "Collection of named nylon instances";
+      description = lib.mdDoc "Collection of named nylon instances";
       type = with types; attrsOf (submodule nylonOpts);
       internal = true;
     };
diff --git a/nixos/modules/services/networking/ocserv.nix b/nixos/modules/services/networking/ocserv.nix
index dc26ffeafee..9548fd92dbd 100644
--- a/nixos/modules/services/networking/ocserv.nix
+++ b/nixos/modules/services/networking/ocserv.nix
@@ -10,12 +10,12 @@ in
 
 {
   options.services.ocserv = {
-    enable = mkEnableOption "ocserv";
+    enable = mkEnableOption (lib.mdDoc "ocserv");
 
     config = mkOption {
       type = types.lines;
 
-      description = ''
+      description = lib.mdDoc ''
         Configuration content to start an OCServ server.
 
         For a full configuration reference,please refer to the online documentation
diff --git a/nixos/modules/services/networking/ofono.nix b/nixos/modules/services/networking/ofono.nix
index 460b06443c4..960fc35a70a 100644
--- a/nixos/modules/services/networking/ofono.nix
+++ b/nixos/modules/services/networking/ofono.nix
@@ -19,13 +19,13 @@ in
   ###### interface
   options = {
     services.ofono = {
-      enable = mkEnableOption "Ofono";
+      enable = mkEnableOption (lib.mdDoc "Ofono");
 
       plugins = mkOption {
         type = types.listOf types.package;
         default = [];
         example = literalExpression "[ pkgs.modem-manager-gui ]";
-        description = ''
+        description = lib.mdDoc ''
           The list of plugins to install.
         '';
       };
diff --git a/nixos/modules/services/networking/oidentd.nix b/nixos/modules/services/networking/oidentd.nix
index feb84806ba9..7c7883c9461 100644
--- a/nixos/modules/services/networking/oidentd.nix
+++ b/nixos/modules/services/networking/oidentd.nix
@@ -11,7 +11,7 @@ with lib;
     services.oidentd.enable = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable ‘oidentd’, an implementation of the Ident
         protocol (RFC 1413).  It allows remote systems to identify the
         name of the user associated with a TCP connection.
diff --git a/nixos/modules/services/networking/onedrive.nix b/nixos/modules/services/networking/onedrive.nix
index 0256a6a4111..d782ec05352 100644
--- a/nixos/modules/services/networking/onedrive.nix
+++ b/nixos/modules/services/networking/onedrive.nix
@@ -26,17 +26,13 @@ in {
   ### Interface
 
   options.services.onedrive = {
-    enable = lib.mkOption {
-      type = lib.types.bool;
-      default = false;
-      description = "Enable OneDrive service";
-    };
+     enable = lib.mkEnableOption (lib.mdDoc "OneDrive service");
 
      package = lib.mkOption {
        type = lib.types.package;
        default = pkgs.onedrive;
        defaultText = lib.literalExpression "pkgs.onedrive";
-       description = ''
+       description = lib.mdDoc ''
          OneDrive package to use.
        '';
      };
diff --git a/nixos/modules/services/networking/openconnect.nix b/nixos/modules/services/networking/openconnect.nix
new file mode 100644
index 00000000000..469f0a3bc3b
--- /dev/null
+++ b/nixos/modules/services/networking/openconnect.nix
@@ -0,0 +1,143 @@
+{ config, lib, options, pkgs, ... }:
+with lib;
+let
+  cfg = config.networking.openconnect;
+  openconnect = cfg.package;
+  pkcs11 = types.strMatching "pkcs11:.+" // {
+    name = "pkcs11";
+    description = "PKCS#11 URI";
+  };
+  interfaceOptions = {
+    options = {
+      autoStart = mkOption {
+        default = true;
+        description = lib.mdDoc "Whether this VPN connection should be started automatically.";
+        type = types.bool;
+      };
+
+      gateway = mkOption {
+        description = lib.mdDoc "Gateway server to connect to.";
+        example = "gateway.example.com";
+        type = types.str;
+      };
+
+      protocol = mkOption {
+        description = lib.mdDoc "Protocol to use.";
+        example = "anyconnect";
+        type =
+          types.enum [ "anyconnect" "array" "nc" "pulse" "gp" "f5" "fortinet" ];
+      };
+
+      user = mkOption {
+        description = lib.mdDoc "Username to authenticate with.";
+        example = "example-user";
+        type = types.nullOr types.str;
+      };
+
+      # Note: It does not make sense to provide a way to declaratively
+      # set an authentication cookie, because they have to be requested
+      # for every new connection and would only work once.
+      passwordFile = mkOption {
+        description = lib.mdDoc ''
+          File containing the password to authenticate with. This
+          is passed to `openconnect` via the
+          `--passwd-on-stdin` option.
+        '';
+        default = null;
+        example = "/var/lib/secrets/openconnect-passwd";
+        type = types.nullOr types.path;
+      };
+
+      certificate = mkOption {
+        description = lib.mdDoc "Certificate to authenticate with.";
+        default = null;
+        example = "/var/lib/secrets/openconnect_certificate.pem";
+        type = with types; nullOr (either path pkcs11);
+      };
+
+      privateKey = mkOption {
+        description = lib.mdDoc "Private key to authenticate with.";
+        example = "/var/lib/secrets/openconnect_private_key.pem";
+        default = null;
+        type = with types; nullOr (either path pkcs11);
+      };
+
+      extraOptions = mkOption {
+        description = lib.mdDoc ''
+          Extra config to be appended to the interface config. It should
+          contain long-format options as would be accepted on the command
+          line by `openconnect`
+          (see https://www.infradead.org/openconnect/manual.html).
+          Non-key-value options like `deflate` can be used by
+          declaring them as booleans, i. e. `deflate = true;`.
+        '';
+        default = { };
+        example = {
+          compression = "stateless";
+
+          no-http-keepalive = true;
+          no-dtls = true;
+        };
+        type = with types; attrsOf (either str bool);
+      };
+    };
+  };
+  generateExtraConfig = extra_cfg:
+    strings.concatStringsSep "\n" (attrsets.mapAttrsToList
+      (name: value: if (value == true) then name else "${name}=${value}")
+      (attrsets.filterAttrs (_: value: value != false) extra_cfg));
+  generateConfig = name: icfg:
+    pkgs.writeText "config" ''
+      interface=${name}
+      ${optionalString (icfg.user != null) "user=${icfg.user}"}
+      ${optionalString (icfg.passwordFile != null) "passwd-on-stdin"}
+      ${optionalString (icfg.certificate != null)
+      "certificate=${icfg.certificate}"}
+      ${optionalString (icfg.privateKey != null) "sslkey=${icfg.privateKey}"}
+
+      ${generateExtraConfig icfg.extraOptions}
+    '';
+  generateUnit = name: icfg: {
+    description = "OpenConnect Interface - ${name}";
+    requires = [ "network-online.target" ];
+    after = [ "network.target" "network-online.target" ];
+    wantedBy = optional icfg.autoStart "multi-user.target";
+
+    serviceConfig = {
+      Type = "simple";
+      ExecStart = "${openconnect}/bin/openconnect --config=${
+          generateConfig name icfg
+        } ${icfg.gateway}";
+      StandardInput = "file:${icfg.passwordFile}";
+
+      ProtectHome = true;
+    };
+  };
+in {
+  options.networking.openconnect = {
+    package = mkPackageOption pkgs "openconnect" { };
+
+    interfaces = mkOption {
+      description = lib.mdDoc "OpenConnect interfaces.";
+      default = { };
+      example = {
+        openconnect0 = {
+          gateway = "gateway.example.com";
+          protocol = "anyconnect";
+          user = "example-user";
+          passwordFile = "/var/lib/secrets/openconnect-passwd";
+        };
+      };
+      type = with types; attrsOf (submodule interfaceOptions);
+    };
+  };
+
+  config = {
+    systemd.services = mapAttrs' (name: value: {
+      name = "openconnect-${name}";
+      value = generateUnit name value;
+    }) cfg.interfaces;
+  };
+
+  meta.maintainers = with maintainers; [ alyaeanyx ];
+}
diff --git a/nixos/modules/services/networking/openfire.nix b/nixos/modules/services/networking/openfire.nix
deleted file mode 100644
index fe0499d5232..00000000000
--- a/nixos/modules/services/networking/openfire.nix
+++ /dev/null
@@ -1,56 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-{
-  ###### interface
-
-  options = {
-
-    services.openfire = {
-
-      enable = mkEnableOption "OpenFire XMPP server";
-
-      usePostgreSQL = mkOption {
-        type = types.bool;
-        default = true;
-        description = "
-          Whether you use PostgreSQL service for your storage back-end.
-        ";
-      };
-
-    };
-
-  };
-
-
-  ###### implementation
-
-  config = mkIf config.services.openfire.enable {
-
-    assertions = singleton
-      { assertion = !(config.services.openfire.usePostgreSQL -> config.services.postgresql.enable);
-        message = "OpenFire configured to use PostgreSQL but services.postgresql.enable is not enabled.";
-      };
-
-    systemd.services.openfire = {
-      description = "OpenFire XMPP server";
-      wantedBy = [ "multi-user.target" ];
-      after = [ "networking.target" ] ++
-        optional config.services.openfire.usePostgreSQL "postgresql.service";
-      path = with pkgs; [ jre openfire coreutils which gnugrep gawk gnused ];
-      script = ''
-        export HOME=/tmp
-        mkdir /var/log/openfire || true
-        mkdir /etc/openfire || true
-        for i in ${pkgs.openfire}/conf.inst/*; do
-            if ! test -f /etc/openfire/$(basename $i); then
-                cp $i /etc/openfire/
-            fi
-        done
-        openfire start
-      ''; # */
-    };
-  };
-
-}
diff --git a/nixos/modules/services/networking/openvpn.nix b/nixos/modules/services/networking/openvpn.nix
index cf3f79fc578..492a0936fdb 100644
--- a/nixos/modules/services/networking/openvpn.nix
+++ b/nixos/modules/services/networking/openvpn.nix
@@ -115,12 +115,12 @@ in
         }
       '';
 
-      description = ''
+      description = lib.mdDoc ''
         Each attribute of this option defines a systemd service that
         runs an OpenVPN instance.  These can be OpenVPN servers or
         clients.  The name of each systemd service is
-        <literal>openvpn-<replaceable>name</replaceable>.service</literal>,
-        where <replaceable>name</replaceable> is the corresponding
+        `openvpn-«name».service`,
+        where «name» is the corresponding
         attribute name.
       '';
 
@@ -130,20 +130,20 @@ in
 
           config = mkOption {
             type = types.lines;
-            description = ''
+            description = lib.mdDoc ''
               Configuration of this OpenVPN instance.  See
-              <citerefentry><refentrytitle>openvpn</refentrytitle><manvolnum>8</manvolnum></citerefentry>
+              {manpage}`openvpn(8)`
               for details.
 
               To import an external config file, use the following definition:
-              <literal>config = "config /path/to/config.ovpn"</literal>
+              `config = "config /path/to/config.ovpn"`
             '';
           };
 
           up = mkOption {
             default = "";
             type = types.lines;
-            description = ''
+            description = lib.mdDoc ''
               Shell commands executed when the instance is starting.
             '';
           };
@@ -151,7 +151,7 @@ in
           down = mkOption {
             default = "";
             type = types.lines;
-            description = ''
+            description = lib.mdDoc ''
               Shell commands executed when the instance is shutting down.
             '';
           };
@@ -159,13 +159,13 @@ in
           autoStart = mkOption {
             default = true;
             type = types.bool;
-            description = "Whether this OpenVPN instance should be started automatically.";
+            description = lib.mdDoc "Whether this OpenVPN instance should be started automatically.";
           };
 
           updateResolvConf = mkOption {
             default = false;
             type = types.bool;
-            description = ''
+            description = lib.mdDoc ''
               Use the script from the update-resolv-conf package to automatically
               update resolv.conf with the DNS information provided by openvpn. The
               script will be run after the "up" commands and before the "down" commands.
@@ -174,7 +174,7 @@ in
 
           authUserPass = mkOption {
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               This option can be used to store the username / password credentials
               with the "auth-user-pass" authentication method.
 
@@ -184,12 +184,12 @@ in
 
               options = {
                 username = mkOption {
-                  description = "The username to store inside the credentials file.";
+                  description = lib.mdDoc "The username to store inside the credentials file.";
                   type = types.str;
                 };
 
                 password = mkOption {
-                  description = "The password to store inside the credentials file.";
+                  description = lib.mdDoc "The password to store inside the credentials file.";
                   type = types.str;
                 };
               };
diff --git a/nixos/modules/services/networking/ostinato.nix b/nixos/modules/services/networking/ostinato.nix
index 4da11984b9f..40c227ea0c6 100644
--- a/nixos/modules/services/networking/ostinato.nix
+++ b/nixos/modules/services/networking/ostinato.nix
@@ -26,12 +26,12 @@ in
 
     services.ostinato = {
 
-      enable = mkEnableOption "Ostinato agent-controller (Drone)";
+      enable = mkEnableOption (lib.mdDoc "Ostinato agent-controller (Drone)");
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 7878;
-        description = ''
+        description = lib.mdDoc ''
           Port to listen on.
         '';
       };
@@ -39,7 +39,7 @@ in
       rateAccuracy = mkOption {
         type = types.enum [ "High" "Low" ];
         default = "High";
-        description = ''
+        description = lib.mdDoc ''
           To ensure that the actual transmit rate is as close as possible to
           the configured transmit rate, Drone runs a busy-wait loop.
           While this provides the maximum accuracy possible, the CPU
@@ -52,7 +52,7 @@ in
         address = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = ''
+          description = lib.mdDoc ''
             By default, the Drone RPC server will listen on all interfaces and
             local IPv4 adresses for incoming connections from clients.  Specify
             a single IPv4 or IPv6 address if you want to restrict that.
@@ -66,7 +66,7 @@ in
           type = types.listOf types.str;
           default = [];
           example = [ "eth*" "lo*" ];
-          description = ''
+          description = lib.mdDoc ''
             For a port to pass the filter and appear on the port list managed
             by drone, it be allowed by this include list.
           '';
@@ -75,7 +75,7 @@ in
           type = types.listOf types.str;
           default = [];
           example = [ "usbmon*" "eth0" ];
-          description = ''
+          description = lib.mdDoc ''
             A list of ports does not appear on the port list managed by drone.
           '';
         };
diff --git a/nixos/modules/services/networking/owamp.nix b/nixos/modules/services/networking/owamp.nix
index baf64347b09..32b2dab9e3c 100644
--- a/nixos/modules/services/networking/owamp.nix
+++ b/nixos/modules/services/networking/owamp.nix
@@ -10,7 +10,7 @@ in
   ###### interface
 
   options = {
-    services.owamp.enable = mkEnableOption "Enable OWAMP server";
+    services.owamp.enable = mkEnableOption (lib.mdDoc "OWAMP server");
   };
 
 
diff --git a/nixos/modules/services/networking/pdns-recursor.nix b/nixos/modules/services/networking/pdns-recursor.nix
index 0579d314a9b..473c2a1f1fb 100644
--- a/nixos/modules/services/networking/pdns-recursor.nix
+++ b/nixos/modules/services/networking/pdns-recursor.nix
@@ -27,29 +27,33 @@ let
 
 in {
   options.services.pdns-recursor = {
-    enable = mkEnableOption "PowerDNS Recursor, a recursive DNS server";
+    enable = mkEnableOption (lib.mdDoc "PowerDNS Recursor, a recursive DNS server");
 
     dns.address = mkOption {
-      type = types.str;
-      default = "0.0.0.0";
-      description = ''
-        IP address Recursor DNS server will bind to.
+      type = oneOrMore types.str;
+      default = [ "::" "0.0.0.0" ];
+      description = lib.mdDoc ''
+        IP addresses Recursor DNS server will bind to.
       '';
     };
 
     dns.port = mkOption {
       type = types.int;
       default = 53;
-      description = ''
+      description = lib.mdDoc ''
         Port number Recursor DNS server will bind to.
       '';
     };
 
     dns.allowFrom = mkOption {
       type = types.listOf types.str;
-      default = [ "10.0.0.0/8" "172.16.0.0/12" "192.168.0.0/16" ];
-      example = [ "0.0.0.0/0" ];
-      description = ''
+      default = [
+        "127.0.0.0/8" "10.0.0.0/8" "100.64.0.0/10"
+        "169.254.0.0/16" "192.168.0.0/16" "172.16.0.0/12"
+        "::1/128" "fc00::/7" "fe80::/10"
+      ];
+      example = [ "0.0.0.0/0" "::/0" ];
+      description = lib.mdDoc ''
         IP address ranges of clients allowed to make DNS queries.
       '';
     };
@@ -57,7 +61,7 @@ in {
     api.address = mkOption {
       type = types.str;
       default = "0.0.0.0";
-      description = ''
+      description = lib.mdDoc ''
         IP address Recursor REST API server will bind to.
       '';
     };
@@ -65,15 +69,16 @@ in {
     api.port = mkOption {
       type = types.int;
       default = 8082;
-      description = ''
+      description = lib.mdDoc ''
         Port number Recursor REST API server will bind to.
       '';
     };
 
     api.allowFrom = mkOption {
       type = types.listOf types.str;
-      default = [ "0.0.0.0/0" ];
-      description = ''
+      default = [ "127.0.0.1" "::1" ];
+      example = [ "0.0.0.0/0" "::/0" ];
+      description = lib.mdDoc ''
         IP address ranges of clients allowed to make API requests.
       '';
     };
@@ -81,7 +86,7 @@ in {
     exportHosts = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
        Whether to export names and IP addresses defined in /etc/hosts.
       '';
     };
@@ -89,16 +94,16 @@ in {
     forwardZones = mkOption {
       type = types.attrs;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         DNS zones to be forwarded to other authoritative servers.
       '';
     };
 
     forwardZonesRecurse = mkOption {
       type = types.attrs;
-      example = { eth = "127.0.0.1:5353"; };
+      example = { eth = "[::1]:5353"; };
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         DNS zones to be forwarded to other recursive servers.
       '';
     };
@@ -106,7 +111,7 @@ in {
     dnssecValidation = mkOption {
       type = types.enum ["off" "process-no-validate" "process" "log-fail" "validate"];
       default = "validate";
-      description = ''
+      description = lib.mdDoc ''
         Controls the level of DNSSEC processing done by the PowerDNS Recursor.
         See https://doc.powerdns.com/md/recursor/dnssec/ for a detailed explanation.
       '';
@@ -115,11 +120,11 @@ in {
     serveRFC1918 = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to directly resolve the RFC1918 reverse-mapping domains:
-        <literal>10.in-addr.arpa</literal>,
-        <literal>168.192.in-addr.arpa</literal>,
-        <literal>16-31.172.in-addr.arpa</literal>
+        `10.in-addr.arpa`,
+        `168.192.in-addr.arpa`,
+        `16-31.172.in-addr.arpa`
         This saves load on the AS112 servers.
       '';
     };
@@ -133,11 +138,11 @@ in {
           log-common-errors = true;
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         PowerDNS Recursor settings. Use this option to configure Recursor
         settings not exposed in a NixOS option or to bypass one.
         See the full documentation at
-        <link xlink:href="https://doc.powerdns.com/recursor/settings.html"/>
+        <https://doc.powerdns.com/recursor/settings.html>
         for the available options.
       '';
     };
@@ -145,9 +150,9 @@ in {
     luaConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         The content Lua configuration file for PowerDNS Recursor. See
-        <link xlink:href="https://doc.powerdns.com/recursor/lua-config/index.html"/>.
+        <https://doc.powerdns.com/recursor/lua-config/index.html>.
       '';
     };
   };
diff --git a/nixos/modules/services/networking/pdnsd.nix b/nixos/modules/services/networking/pdnsd.nix
index 24b5bbc5104..8fe27a44eee 100644
--- a/nixos/modules/services/networking/pdnsd.nix
+++ b/nixos/modules/services/networking/pdnsd.nix
@@ -24,38 +24,38 @@ in
 
 { options =
     { services.pdnsd =
-        { enable = mkEnableOption "pdnsd";
+        { enable = mkEnableOption (lib.mdDoc "pdnsd");
 
           cacheDir = mkOption {
             type = types.str;
             default = "/var/cache/pdnsd";
-            description = "Directory holding the pdnsd cache";
+            description = lib.mdDoc "Directory holding the pdnsd cache";
           };
 
           globalConfig = mkOption {
             type = types.lines;
             default = "";
-            description = ''
+            description = lib.mdDoc ''
               Global configuration that should be added to the global directory
-              of <literal>pdnsd.conf</literal>.
+              of `pdnsd.conf`.
             '';
           };
 
           serverConfig = mkOption {
             type = types.lines;
             default = "";
-            description = ''
+            description = lib.mdDoc ''
               Server configuration that should be added to the server directory
-              of <literal>pdnsd.conf</literal>.
+              of `pdnsd.conf`.
             '';
           };
 
           extraConfig = mkOption {
             type = types.lines;
             default = "";
-            description = ''
+            description = lib.mdDoc ''
               Extra configuration directives that should be added to
-              <literal>pdnsd.conf</literal>.
+              `pdnsd.conf`.
             '';
           };
         };
diff --git a/nixos/modules/services/networking/pixiecore.nix b/nixos/modules/services/networking/pixiecore.nix
index d2642c82c2d..ea4008d4d51 100644
--- a/nixos/modules/services/networking/pixiecore.nix
+++ b/nixos/modules/services/networking/pixiecore.nix
@@ -10,18 +10,18 @@ in
 
   options = {
     services.pixiecore = {
-      enable = mkEnableOption "Pixiecore";
+      enable = mkEnableOption (lib.mdDoc "Pixiecore");
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports (67, 69 UDP and 4011, 'port', 'statusPort' TCP) in the firewall for Pixiecore.
         '';
       };
 
       mode = mkOption {
-        description = "Which mode to use";
+        description = lib.mdDoc "Which mode to use";
         default = "boot";
         type = types.enum [ "api" "boot" ];
       };
@@ -29,61 +29,61 @@ in
       debug = mkOption {
         type = types.bool;
         default = false;
-        description = "Log more things that aren't directly related to booting a recognized client";
+        description = lib.mdDoc "Log more things that aren't directly related to booting a recognized client";
       };
 
       dhcpNoBind = mkOption {
         type = types.bool;
         default = false;
-        description = "Handle DHCP traffic without binding to the DHCP server port";
+        description = lib.mdDoc "Handle DHCP traffic without binding to the DHCP server port";
       };
 
       kernel = mkOption {
         type = types.str or types.path;
         default = "";
-        description = "Kernel path. Ignored unless mode is set to 'boot'";
+        description = lib.mdDoc "Kernel path. Ignored unless mode is set to 'boot'";
       };
 
       initrd = mkOption {
         type = types.str or types.path;
         default = "";
-        description = "Initrd path. Ignored unless mode is set to 'boot'";
+        description = lib.mdDoc "Initrd path. Ignored unless mode is set to 'boot'";
       };
 
       cmdLine = mkOption {
         type = types.str;
         default = "";
-        description = "Kernel commandline arguments. Ignored unless mode is set to 'boot'";
+        description = lib.mdDoc "Kernel commandline arguments. Ignored unless mode is set to 'boot'";
       };
 
       listen = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = "IPv4 address to listen on";
+        description = lib.mdDoc "IPv4 address to listen on";
       };
 
       port = mkOption {
         type = types.port;
         default = 80;
-        description = "Port to listen on for HTTP";
+        description = lib.mdDoc "Port to listen on for HTTP";
       };
 
       statusPort = mkOption {
         type = types.port;
         default = 80;
-        description = "HTTP port for status information (can be the same as --port)";
+        description = lib.mdDoc "HTTP port for status information (can be the same as --port)";
       };
 
       apiServer = mkOption {
         type = types.str;
         example = "localhost:8080";
-        description = "host:port to connect to the API. Ignored unless mode is set to 'api'";
+        description = lib.mdDoc "host:port to connect to the API. Ignored unless mode is set to 'api'";
       };
 
       extraArguments = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Additional command line arguments to pass to Pixiecore";
+        description = lib.mdDoc "Additional command line arguments to pass to Pixiecore";
       };
     };
   };
diff --git a/nixos/modules/services/networking/pleroma.nix b/nixos/modules/services/networking/pleroma.nix
index c6d4c14dcb7..dfd1ed4036a 100644
--- a/nixos/modules/services/networking/pleroma.nix
+++ b/nixos/modules/services/networking/pleroma.nix
@@ -1,41 +1,40 @@
 { config, options, lib, pkgs, stdenv, ... }:
 let
   cfg = config.services.pleroma;
-  cookieFile = "/var/lib/pleroma/.cookie";
 in {
   options = {
     services.pleroma = with lib; {
-      enable = mkEnableOption "pleroma";
+      enable = mkEnableOption (lib.mdDoc "pleroma");
 
       package = mkOption {
         type = types.package;
-        default = pkgs.pleroma.override { inherit cookieFile; };
+        default = pkgs.pleroma;
         defaultText = literalExpression "pkgs.pleroma";
-        description = "Pleroma package to use.";
+        description = lib.mdDoc "Pleroma package to use.";
       };
 
       user = mkOption {
         type = types.str;
         default = "pleroma";
-        description = "User account under which pleroma runs.";
+        description = lib.mdDoc "User account under which pleroma runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "pleroma";
-        description = "Group account under which pleroma runs.";
+        description = lib.mdDoc "Group account under which pleroma runs.";
       };
 
       stateDir = mkOption {
         type = types.str;
         default = "/var/lib/pleroma";
         readOnly = true;
-        description = "Directory where the pleroma service will save the uploads and static files.";
+        description = lib.mdDoc "Directory where the pleroma service will save the uploads and static files.";
       };
 
       configs = mkOption {
         type = with types; listOf str;
-        description = ''
+        description = lib.mdDoc ''
           Pleroma public configuration.
 
           This list gets appended from left to
@@ -43,9 +42,9 @@ in {
           configuration imperatively, meaning you can override a
           setting by appending a new str to this NixOS option list.
 
-          <emphasis>DO NOT STORE ANY PLEROMA SECRET
-          HERE</emphasis>, use
-          <link linkend="opt-services.pleroma.secretConfigFile">services.pleroma.secretConfigFile</link>
+          *DO NOT STORE ANY PLEROMA SECRET
+          HERE*, use
+          [services.pleroma.secretConfigFile](#opt-services.pleroma.secretConfigFile)
           instead.
 
           This setting is going to be stored in a file part of
@@ -60,11 +59,11 @@ in {
       secretConfigFile = mkOption {
         type = types.str;
         default = "/var/lib/pleroma/secrets.exs";
-        description = ''
+        description = lib.mdDoc ''
           Path to the file containing your secret pleroma configuration.
 
-          <emphasis>DO NOT POINT THIS OPTION TO THE NIX
-          STORE</emphasis>, the store being world-readable, it'll
+          *DO NOT POINT THIS OPTION TO THE NIX
+          STORE*, the store being world-readable, it'll
           compromise all your secrets.
         '';
       };
@@ -101,6 +100,7 @@ in {
       after = [ "network-online.target" "postgresql.service" ];
       wantedBy = [ "multi-user.target" ];
       restartTriggers = [ config.environment.etc."/pleroma/config.exs".source ];
+      environment.RELEASE_COOKIE = "/var/lib/pleroma/.cookie";
       serviceConfig = {
         User = cfg.user;
         Group = cfg.group;
@@ -118,10 +118,10 @@ in {
         # Better be safe than sorry migration-wise.
         ExecStartPre =
           let preScript = pkgs.writers.writeBashBin "pleromaStartPre" ''
-            if [ ! -f "${cookieFile}" ] || [ ! -s "${cookieFile}" ]
+            if [ ! -f /var/lib/pleroma/.cookie ]
             then
               echo "Creating cookie file"
-              dd if=/dev/urandom bs=1 count=16 | ${pkgs.hexdump}/bin/hexdump -e '16/1 "%02x"' > "${cookieFile}"
+              dd if=/dev/urandom bs=1 count=16 | hexdump -e '16/1 "%02x"' > /var/lib/pleroma/.cookie
             fi
             ${cfg.package}/bin/pleroma_ctl migrate
           '';
diff --git a/nixos/modules/services/networking/polipo.nix b/nixos/modules/services/networking/polipo.nix
index 1ff9388346b..8581553829b 100644
--- a/nixos/modules/services/networking/polipo.nix
+++ b/nixos/modules/services/networking/polipo.nix
@@ -23,29 +23,25 @@ in
 
     services.polipo = {
 
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Whether to run the polipo caching web proxy.";
-      };
+      enable = mkEnableOption (lib.mdDoc "polipo caching web proxy");
 
       proxyAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "IP address on which Polipo will listen.";
+        description = lib.mdDoc "IP address on which Polipo will listen.";
       };
 
       proxyPort = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8123;
-        description = "TCP port on which Polipo will listen.";
+        description = lib.mdDoc "TCP port on which Polipo will listen.";
       };
 
       allowedClients = mkOption {
         type = types.listOf types.str;
         default = [ "127.0.0.1" "::1" ];
         example = [ "127.0.0.1" "::1" "134.157.168.0/24" "2001:660:116::/48" ];
-        description = ''
+        description = lib.mdDoc ''
           List of IP addresses or network addresses that may connect to Polipo.
         '';
       };
@@ -54,7 +50,7 @@ in
         type = types.str;
         default = "";
         example = "localhost:8124";
-        description = ''
+        description = lib.mdDoc ''
           Hostname and port number of an HTTP parent proxy;
           it should have the form ‘host:port’.
         '';
@@ -64,7 +60,7 @@ in
         type = types.str;
         default = "";
         example = "localhost:9050";
-        description = ''
+        description = lib.mdDoc ''
           Hostname and port number of an SOCKS parent proxy;
           it should have the form ‘host:port’.
         '';
@@ -73,7 +69,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Polio configuration. Contents will be added
           verbatim to the configuration file.
         '';
diff --git a/nixos/modules/services/networking/powerdns.nix b/nixos/modules/services/networking/powerdns.nix
index 8cae61b8354..6aa5928d637 100644
--- a/nixos/modules/services/networking/powerdns.nix
+++ b/nixos/modules/services/networking/powerdns.nix
@@ -8,14 +8,14 @@ let
 in {
   options = {
     services.powerdns = {
-      enable = mkEnableOption "PowerDNS domain name server";
+      enable = mkEnableOption (lib.mdDoc "PowerDNS domain name server");
 
       extraConfig = mkOption {
         type = types.lines;
         default = "launch=bind";
-        description = ''
+        description = lib.mdDoc ''
           PowerDNS configuration. Refer to
-          <link xlink:href="https://doc.powerdns.com/authoritative/settings.html"/>
+          <https://doc.powerdns.com/authoritative/settings.html>
           for details on supported values.
         '';
       };
@@ -24,14 +24,14 @@ in {
 
   config = mkIf cfg.enable {
 
-    systemd.packages = [ pkgs.powerdns ];
+    systemd.packages = [ pkgs.pdns ];
 
     systemd.services.pdns = {
       wantedBy = [ "multi-user.target" ];
       after = [ "network.target" "mysql.service" "postgresql.service" "openldap.service" ];
 
       serviceConfig = {
-        ExecStart = [ "" "${pkgs.powerdns}/bin/pdns_server --config-dir=${configDir} --guardian=no --daemon=no --disable-syslog --log-timestamp=no --write-pid=no" ];
+        ExecStart = [ "" "${pkgs.pdns}/bin/pdns_server --config-dir=${configDir} --guardian=no --daemon=no --disable-syslog --log-timestamp=no --write-pid=no" ];
       };
     };
 
diff --git a/nixos/modules/services/networking/pppd.nix b/nixos/modules/services/networking/pppd.nix
index d1ed25b0238..75fc04c6757 100644
--- a/nixos/modules/services/networking/pppd.nix
+++ b/nixos/modules/services/networking/pppd.nix
@@ -12,18 +12,18 @@ in
 
   options = {
     services.pppd = {
-      enable = mkEnableOption "pppd";
+      enable = mkEnableOption (lib.mdDoc "pppd");
 
       package = mkOption {
         default = pkgs.ppp;
         defaultText = literalExpression "pkgs.ppp";
         type = types.package;
-        description = "pppd package to use.";
+        description = lib.mdDoc "pppd package to use.";
       };
 
       peers = mkOption {
         default = {};
-        description = "pppd peers.";
+        description = lib.mdDoc "pppd peers.";
         type = types.attrsOf (types.submodule (
           { name, ... }:
           {
@@ -32,27 +32,27 @@ in
                 type = types.str;
                 default = name;
                 example = "dialup";
-                description = "Name of the PPP peer.";
+                description = lib.mdDoc "Name of the PPP peer.";
               };
 
               enable = mkOption {
                 type = types.bool;
                 default = true;
                 example = false;
-                description = "Whether to enable this PPP peer.";
+                description = lib.mdDoc "Whether to enable this PPP peer.";
               };
 
               autostart = mkOption {
                 type = types.bool;
                 default = true;
                 example = false;
-                description = "Whether the PPP session is automatically started at boot time.";
+                description = lib.mdDoc "Whether the PPP session is automatically started at boot time.";
               };
 
               config = mkOption {
                 type = types.lines;
                 default = "";
-                description = "pppd configuration for this peer, see the pppd(8) man page.";
+                description = lib.mdDoc "pppd configuration for this peer, see the pppd(8) man page.";
               };
             };
           }));
diff --git a/nixos/modules/services/networking/pptpd.nix b/nixos/modules/services/networking/pptpd.nix
index 3e7753b9dd3..703dda99803 100644
--- a/nixos/modules/services/networking/pptpd.nix
+++ b/nixos/modules/services/networking/pptpd.nix
@@ -5,35 +5,35 @@ with lib;
 {
   options = {
     services.pptpd = {
-      enable = mkEnableOption "pptpd, the Point-to-Point Tunneling Protocol daemon";
+      enable = mkEnableOption (lib.mdDoc "pptpd, the Point-to-Point Tunneling Protocol daemon");
 
       serverIp = mkOption {
         type        = types.str;
-        description = "The server-side IP address.";
+        description = lib.mdDoc "The server-side IP address.";
         default     = "10.124.124.1";
       };
 
       clientIpRange = mkOption {
         type        = types.str;
-        description = "The range from which client IPs are drawn.";
+        description = lib.mdDoc "The range from which client IPs are drawn.";
         default     = "10.124.124.2-11";
       };
 
       maxClients = mkOption {
         type        = types.int;
-        description = "The maximum number of simultaneous connections.";
+        description = lib.mdDoc "The maximum number of simultaneous connections.";
         default     = 10;
       };
 
       extraPptpdOptions = mkOption {
         type        = types.lines;
-        description = "Adds extra lines to the pptpd configuration file.";
+        description = lib.mdDoc "Adds extra lines to the pptpd configuration file.";
         default     = "";
       };
 
       extraPppdOptions = mkOption {
         type        = types.lines;
-        description = "Adds extra lines to the pppd options file.";
+        description = lib.mdDoc "Adds extra lines to the pppd options file.";
         default     = "";
         example     = ''
           ms-dns 8.8.8.8
@@ -82,7 +82,7 @@ with lib;
       ppp-pptpd-wrapped = pkgs.stdenv.mkDerivation {
         name         = "ppp-pptpd-wrapped";
         phases       = [ "installPhase" ];
-        buildInputs  = with pkgs; [ makeWrapper ];
+        nativeBuildInputs  = with pkgs; [ makeWrapper ];
         installPhase = ''
           mkdir -p $out/bin
           makeWrapper ${pkgs.ppp}/bin/pppd $out/bin/pppd \
@@ -108,7 +108,7 @@ with lib;
         #username	pptpd	password	*
         EOF
 
-        chown root.root "$secrets"
+        chown root:root "$secrets"
         chmod 600 "$secrets"
       '';
 
diff --git a/nixos/modules/services/networking/prayer.nix b/nixos/modules/services/networking/prayer.nix
index ae9258b2712..197aa8a6f44 100644
--- a/nixos/modules/services/networking/prayer.nix
+++ b/nixos/modules/services/networking/prayer.nix
@@ -41,12 +41,12 @@ in
 
     services.prayer = {
 
-      enable = mkEnableOption "the prayer webmail http server";
+      enable = mkEnableOption (lib.mdDoc "the prayer webmail http server");
 
       port = mkOption {
         default = 2080;
         type = types.port;
-        description = ''
+        description = lib.mdDoc ''
           Port the prayer http server is listening to.
         '';
       };
@@ -54,7 +54,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "" ;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration. Contents will be added verbatim to the configuration file.
         '';
       };
@@ -82,7 +82,7 @@ in
       serviceConfig.Type = "forking";
       preStart = ''
         mkdir -m 0755 -p ${stateDir}
-        chown ${prayerUser}.${prayerGroup} ${stateDir}
+        chown ${prayerUser}:${prayerGroup} ${stateDir}
       '';
       script = "${prayer}/sbin/prayer --config-file=${prayerCfg}";
     };
diff --git a/nixos/modules/services/networking/privoxy.nix b/nixos/modules/services/networking/privoxy.nix
index 7bc964d5f34..78d02aaa112 100644
--- a/nixos/modules/services/networking/privoxy.nix
+++ b/nixos/modules/services/networking/privoxy.nix
@@ -53,12 +53,12 @@ in
 
   options.services.privoxy = {
 
-    enable = mkEnableOption "Privoxy, non-caching filtering proxy";
+    enable = mkEnableOption (lib.mdDoc "Privoxy, non-caching filtering proxy");
 
     enableTor = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to configure Privoxy to use Tor's faster SOCKS port,
         suitable for HTTP.
       '';
@@ -67,21 +67,21 @@ in
     inspectHttps = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to configure Privoxy to inspect HTTPS requests, meaning all
         encrypted traffic will be filtered as well. This works by decrypting
         and re-encrypting the requests using a per-domain generated certificate.
 
         To issue per-domain certificates, Privoxy must be provided with a CA
-        certificate, using the <literal>ca-cert-file</literal>,
-        <literal>ca-key-file</literal> settings.
-
-        <warning><para>
-          The CA certificate must also be added to the system trust roots,
-          otherwise browsers will reject all Privoxy certificates as invalid.
-          You can do so by using the option
-          <option>security.pki.certificateFiles</option>.
-        </para></warning>
+        certificate, using the `ca-cert-file`,
+        `ca-key-file` settings.
+
+        ::: {.warning}
+        The CA certificate must also be added to the system trust roots,
+        otherwise browsers will reject all Privoxy certificates as invalid.
+        You can do so by using the option
+        {option}`security.pki.certificateFiles`.
+        :::
       '';
     };
 
@@ -89,8 +89,8 @@ in
       type = ageType;
       default = "10d";
       example = "12h";
-      description = ''
-        If <literal>inspectHttps</literal> is enabled, the time generated HTTPS
+      description = lib.mdDoc ''
+        If `inspectHttps` is enabled, the time generated HTTPS
         certificates will be stored in a temporary directory for reuse. Once
         the lifetime has expired the directory will cleared and the certificate
         will have to be generated again, on-demand.
@@ -98,16 +98,18 @@ in
         Depending on the traffic, you may want to reduce the lifetime to limit
         the disk usage, since Privoxy itself never deletes the certificates.
 
-        <note><para>The format is that of the <literal>tmpfiles.d(5)</literal>
-        Age parameter.</para></note>
+        ::: {.note}
+        The format is that of the `tmpfiles.d(5)`
+        Age parameter.
+        :::
       '';
     };
 
     userActions = mkOption {
       type = types.lines;
       default = "";
-      description = ''
-        Actions to be included in a <literal>user.action</literal> file. This
+      description = lib.mdDoc ''
+        Actions to be included in a `user.action` file. This
         will have a higher priority and can be used to override all other
         actions.
       '';
@@ -116,8 +118,8 @@ in
     userFilters = mkOption {
       type = types.lines;
       default = "";
-      description = ''
-        Filters to be included in a <literal>user.filter</literal> file. This
+      description = lib.mdDoc ''
+        Filters to be included in a `user.filter` file. This
         will have a higher priority and can be used to override all other
         filters definitions.
       '';
@@ -130,13 +132,13 @@ in
         options.listen-address = mkOption {
           type = types.str;
           default = "127.0.0.1:8118";
-          description = "Pair of address:port the proxy server is listening to.";
+          description = lib.mdDoc "Pair of address:port the proxy server is listening to.";
         };
 
         options.enable-edit-actions = mkOption {
           type = types.bool;
           default = false;
-          description = "Whether the web-based actions file editor may be used.";
+          description = lib.mdDoc "Whether the web-based actions file editor may be used.";
         };
 
         options.actionsfile = mkOption {
@@ -146,7 +148,7 @@ in
           apply = x: x ++ optional (cfg.userActions != "")
             (toString (pkgs.writeText "user.actions" cfg.userActions));
           default = [ "match-all.action" "default.action" ];
-          description = ''
+          description = lib.mdDoc ''
             List of paths to Privoxy action files. These paths may either be
             absolute or relative to the privoxy configuration directory.
           '';
@@ -157,7 +159,7 @@ in
           default = [ "default.filter" ];
           apply = x: x ++ optional (cfg.userFilters != "")
             (toString (pkgs.writeText "user.filter" cfg.userFilters));
-          description = ''
+          description = lib.mdDoc ''
             List of paths to Privoxy filter files. These paths may either be
             absolute or relative to the privoxy configuration directory.
           '';
@@ -179,15 +181,15 @@ in
           # debug 64
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         This option is mapped to the main Privoxy configuration file.
         Check out the Privoxy user manual at
-        <link xlink:href="https://www.privoxy.org/user-manual/config.html"/>
+        <https://www.privoxy.org/user-manual/config.html>
         for available settings and documentation.
 
-        <note><para>
-          Repeated settings can be represented by using a list.
-        </para></note>
+        ::: {.note}
+        Repeated settings can be represented by using a list.
+        :::
       '';
     };
 
diff --git a/nixos/modules/services/networking/prosody.nix b/nixos/modules/services/networking/prosody.nix
index 42596ccfefd..2d122bcf655 100644
--- a/nixos/modules/services/networking/prosody.nix
+++ b/nixos/modules/services/networking/prosody.nix
@@ -10,19 +10,19 @@ let
 
       key = mkOption {
         type = types.path;
-        description = "Path to the key file.";
+        description = lib.mdDoc "Path to the key file.";
       };
 
       # TODO: rename to certificate to match the prosody config
       cert = mkOption {
         type = types.path;
-        description = "Path to the certificate file.";
+        description = lib.mdDoc "Path to the certificate file.";
       };
 
       extraOptions = mkOption {
         type = types.attrs;
         default = {};
-        description = "Extra SSL configuration options.";
+        description = lib.mdDoc "Extra SSL configuration options.";
       };
 
     };
@@ -32,11 +32,11 @@ let
     options = {
       url = mkOption {
         type = types.str;
-        description = "URL of the endpoint you want to make discoverable";
+        description = lib.mdDoc "URL of the endpoint you want to make discoverable";
       };
       description = mkOption {
         type = types.str;
-        description = "A short description of the endpoint you want to advertise";
+        description = lib.mdDoc "A short description of the endpoint you want to advertise";
       };
     };
   };
@@ -46,216 +46,216 @@ let
     roster = mkOption {
       type = types.bool;
       default = true;
-      description = "Allow users to have a roster";
+      description = lib.mdDoc "Allow users to have a roster";
     };
 
     saslauth = mkOption {
       type = types.bool;
       default = true;
-      description = "Authentication for clients and servers. Recommended if you want to log in.";
+      description = lib.mdDoc "Authentication for clients and servers. Recommended if you want to log in.";
     };
 
     tls = mkOption {
       type = types.bool;
       default = true;
-      description = "Add support for secure TLS on c2s/s2s connections";
+      description = lib.mdDoc "Add support for secure TLS on c2s/s2s connections";
     };
 
     dialback = mkOption {
       type = types.bool;
       default = true;
-      description = "s2s dialback support";
+      description = lib.mdDoc "s2s dialback support";
     };
 
     disco = mkOption {
       type = types.bool;
       default = true;
-      description = "Service discovery";
+      description = lib.mdDoc "Service discovery";
     };
 
     # Not essential, but recommended
     carbons = mkOption {
       type = types.bool;
       default = true;
-      description = "Keep multiple clients in sync";
+      description = lib.mdDoc "Keep multiple clients in sync";
     };
 
     csi = mkOption {
       type = types.bool;
       default = true;
-      description = "Implements the CSI protocol that allows clients to report their active/inactive state to the server";
+      description = lib.mdDoc "Implements the CSI protocol that allows clients to report their active/inactive state to the server";
     };
 
     cloud_notify = mkOption {
       type = types.bool;
       default = true;
-      description = "Push notifications to inform users of new messages or other pertinent information even when they have no XMPP clients online";
+      description = lib.mdDoc "Push notifications to inform users of new messages or other pertinent information even when they have no XMPP clients online";
     };
 
     pep = mkOption {
       type = types.bool;
       default = true;
-      description = "Enables users to publish their mood, activity, playing music and more";
+      description = lib.mdDoc "Enables users to publish their mood, activity, playing music and more";
     };
 
     private = mkOption {
       type = types.bool;
       default = true;
-      description = "Private XML storage (for room bookmarks, etc.)";
+      description = lib.mdDoc "Private XML storage (for room bookmarks, etc.)";
     };
 
     blocklist = mkOption {
       type = types.bool;
       default = true;
-      description = "Allow users to block communications with other users";
+      description = lib.mdDoc "Allow users to block communications with other users";
     };
 
     vcard = mkOption {
       type = types.bool;
       default = false;
-      description = "Allow users to set vCards";
+      description = lib.mdDoc "Allow users to set vCards";
     };
 
     vcard_legacy = mkOption {
       type = types.bool;
       default = true;
-      description = "Converts users profiles and Avatars between old and new formats";
+      description = lib.mdDoc "Converts users profiles and Avatars between old and new formats";
     };
 
     bookmarks = mkOption {
       type = types.bool;
       default = true;
-      description = "Allows interop between older clients that use XEP-0048: Bookmarks in its 1.0 version and recent clients which use it in PEP";
+      description = lib.mdDoc "Allows interop between older clients that use XEP-0048: Bookmarks in its 1.0 version and recent clients which use it in PEP";
     };
 
     # Nice to have
     version = mkOption {
       type = types.bool;
       default = true;
-      description = "Replies to server version requests";
+      description = lib.mdDoc "Replies to server version requests";
     };
 
     uptime = mkOption {
       type = types.bool;
       default = true;
-      description = "Report how long server has been running";
+      description = lib.mdDoc "Report how long server has been running";
     };
 
     time = mkOption {
       type = types.bool;
       default = true;
-      description = "Let others know the time here on this server";
+      description = lib.mdDoc "Let others know the time here on this server";
     };
 
     ping = mkOption {
       type = types.bool;
       default = true;
-      description = "Replies to XMPP pings with pongs";
+      description = lib.mdDoc "Replies to XMPP pings with pongs";
     };
 
     register = mkOption {
       type = types.bool;
       default = true;
-      description = "Allow users to register on this server using a client and change passwords";
+      description = lib.mdDoc "Allow users to register on this server using a client and change passwords";
     };
 
     mam = mkOption {
       type = types.bool;
       default = true;
-      description = "Store messages in an archive and allow users to access it";
+      description = lib.mdDoc "Store messages in an archive and allow users to access it";
     };
 
     smacks = mkOption {
       type = types.bool;
       default = true;
-      description = "Allow a client to resume a disconnected session, and prevent message loss";
+      description = lib.mdDoc "Allow a client to resume a disconnected session, and prevent message loss";
     };
 
     # Admin interfaces
     admin_adhoc = mkOption {
       type = types.bool;
       default = true;
-      description = "Allows administration via an XMPP client that supports ad-hoc commands";
+      description = lib.mdDoc "Allows administration via an XMPP client that supports ad-hoc commands";
     };
 
     http_files = mkOption {
       type = types.bool;
       default = true;
-      description = "Serve static files from a directory over HTTP";
+      description = lib.mdDoc "Serve static files from a directory over HTTP";
     };
 
     proxy65 = mkOption {
       type = types.bool;
       default = true;
-      description = "Enables a file transfer proxy service which clients behind NAT can use";
+      description = lib.mdDoc "Enables a file transfer proxy service which clients behind NAT can use";
     };
 
     admin_telnet = mkOption {
       type = types.bool;
       default = false;
-      description = "Opens telnet console interface on localhost port 5582";
+      description = lib.mdDoc "Opens telnet console interface on localhost port 5582";
     };
 
     # HTTP modules
     bosh = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable BOSH clients, aka 'Jabber over HTTP'";
+      description = lib.mdDoc "Enable BOSH clients, aka 'Jabber over HTTP'";
     };
 
     websocket = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable WebSocket support";
+      description = lib.mdDoc "Enable WebSocket support";
     };
 
     # Other specific functionality
     limits = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable bandwidth limiting for XMPP connections";
+      description = lib.mdDoc "Enable bandwidth limiting for XMPP connections";
     };
 
     groups = mkOption {
       type = types.bool;
       default = false;
-      description = "Shared roster support";
+      description = lib.mdDoc "Shared roster support";
     };
 
     server_contact_info = mkOption {
       type = types.bool;
       default = false;
-      description = "Publish contact information for this service";
+      description = lib.mdDoc "Publish contact information for this service";
     };
 
     announce = mkOption {
       type = types.bool;
       default = false;
-      description = "Send announcement to all online users";
+      description = lib.mdDoc "Send announcement to all online users";
     };
 
     welcome = mkOption {
       type = types.bool;
       default = false;
-      description = "Welcome users who register accounts";
+      description = lib.mdDoc "Welcome users who register accounts";
     };
 
     watchregistrations = mkOption {
       type = types.bool;
       default = false;
-      description = "Alert admins of registrations";
+      description = lib.mdDoc "Alert admins of registrations";
     };
 
     motd = mkOption {
       type = types.bool;
       default = false;
-      description = "Send a message to users when they log in";
+      description = lib.mdDoc "Send a message to users when they log in";
     };
 
     legacyauth = mkOption {
       type = types.bool;
       default = false;
-      description = "Legacy authentication. Only used by some old clients and bots";
+      description = lib.mdDoc "Legacy authentication. Only used by some old clients and bots";
     };
   };
 
@@ -263,7 +263,7 @@ let
     if builtins.isString x then ''"${x}"''
     else if builtins.isBool x then boolToString x
     else if builtins.isInt x then toString x
-    else if builtins.isList x then ''{ ${lib.concatStringsSep ", " (map (n: toLua n) x) } }''
+    else if builtins.isList x then "{ ${lib.concatMapStringsSep ", " toLua x} }"
     else throw "Invalid Lua value";
 
   createSSLOptsStr = o: ''
@@ -279,27 +279,27 @@ let
     options = {
       domain = mkOption {
         type = types.str;
-        description = "Domain name of the MUC";
+        description = lib.mdDoc "Domain name of the MUC";
       };
       name = mkOption {
         type = types.str;
-        description = "The name to return in service discovery responses for the MUC service itself";
+        description = lib.mdDoc "The name to return in service discovery responses for the MUC service itself";
         default = "Prosody Chatrooms";
       };
       restrictRoomCreation = mkOption {
         type = types.enum [ true false "admin" "local" ];
         default = false;
-        description = "Restrict room creation to server admins";
+        description = lib.mdDoc "Restrict room creation to server admins";
       };
       maxHistoryMessages = mkOption {
         type = types.int;
         default = 20;
-        description = "Specifies a limit on what each room can be configured to keep";
+        description = lib.mdDoc "Specifies a limit on what each room can be configured to keep";
       };
       roomLocking = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Enables room locking, which means that a room must be
           configured before it can be used. Locked rooms are invisible
           and cannot be entered by anyone but the creator
@@ -308,7 +308,7 @@ let
       roomLockTimeout = mkOption {
         type = types.int;
         default = 300;
-        description = ''
+        description = lib.mdDoc ''
           Timout after which the room is destroyed or unlocked if not
           configured, in seconds
        '';
@@ -316,7 +316,7 @@ let
       tombstones = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           When a room is destroyed, it leaves behind a tombstone which
           prevents the room being entered or recreated. It also allows
           anyone who was not in the room at the time it was destroyed
@@ -329,7 +329,7 @@ let
       tombstoneExpiry = mkOption {
         type = types.int;
         default = 2678400;
-        description = ''
+        description = lib.mdDoc ''
           This settings controls how long a tombstone is considered
           valid. It defaults to 31 days. After this time, the room in
           question can be created again.
@@ -339,7 +339,7 @@ let
       vcard_muc = mkOption {
         type = types.bool;
         default = true;
-      description = "Adds the ability to set vCard for Multi User Chat rooms";
+      description = lib.mdDoc "Adds the ability to set vCard for Multi User Chat rooms";
       };
 
       # Extra parameters. Defaulting to prosody default values.
@@ -350,42 +350,42 @@ let
       roomDefaultPublic = mkOption {
         type = types.bool;
         default = true;
-        description = "If set, the MUC rooms will be public by default.";
+        description = lib.mdDoc "If set, the MUC rooms will be public by default.";
       };
       roomDefaultMembersOnly = mkOption {
         type = types.bool;
         default = false;
-        description = "If set, the MUC rooms will only be accessible to the members by default.";
+        description = lib.mdDoc "If set, the MUC rooms will only be accessible to the members by default.";
       };
       roomDefaultModerated = mkOption {
         type = types.bool;
         default = false;
-        description = "If set, the MUC rooms will be moderated by default.";
+        description = lib.mdDoc "If set, the MUC rooms will be moderated by default.";
       };
       roomDefaultPublicJids = mkOption {
         type = types.bool;
         default = false;
-        description = "If set, the MUC rooms will display the public JIDs by default.";
+        description = lib.mdDoc "If set, the MUC rooms will display the public JIDs by default.";
       };
       roomDefaultChangeSubject = mkOption {
         type = types.bool;
         default = false;
-        description = "If set, the rooms will display the public JIDs by default.";
+        description = lib.mdDoc "If set, the rooms will display the public JIDs by default.";
       };
       roomDefaultHistoryLength = mkOption {
         type = types.int;
         default = 20;
-        description = "Number of history message sent to participants by default.";
+        description = lib.mdDoc "Number of history message sent to participants by default.";
       };
       roomDefaultLanguage = mkOption {
         type = types.str;
         default = "en";
-        description = "Default room language.";
+        description = lib.mdDoc "Default room language.";
       };
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Additional MUC specific configuration";
+        description = lib.mdDoc "Additional MUC specific configuration";
       };
     };
   };
@@ -394,30 +394,30 @@ let
     options = {
       domain = mkOption {
         type = types.nullOr types.str;
-        description = "Domain name for the http-upload service";
+        description = lib.mdDoc "Domain name for the http-upload service";
       };
       uploadFileSizeLimit = mkOption {
         type = types.str;
         default = "50 * 1024 * 1024";
-        description = "Maximum file size, in bytes. Defaults to 50MB.";
+        description = lib.mdDoc "Maximum file size, in bytes. Defaults to 50MB.";
       };
       uploadExpireAfter = mkOption {
         type = types.str;
         default = "60 * 60 * 24 * 7";
-        description = "Max age of a file before it gets deleted, in seconds.";
+        description = lib.mdDoc "Max age of a file before it gets deleted, in seconds.";
       };
       userQuota = mkOption {
         type = types.nullOr types.int;
         default = null;
         example = 1234;
-        description = ''
+        description = lib.mdDoc ''
           Maximum size of all uploaded files per user, in bytes. There
           will be no quota if this option is set to null.
         '';
       };
       httpUploadPath = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Directory where the uploaded files will be stored. By
           default, uploaded files are put in a sub-directory of the
           default Prosody storage path (usually /var/lib/prosody).
@@ -434,25 +434,25 @@ let
       # TODO: require attribute
       domain = mkOption {
         type = types.str;
-        description = "Domain name";
+        description = lib.mdDoc "Domain name";
       };
 
       enabled = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the virtual host";
+        description = lib.mdDoc "Whether to enable the virtual host";
       };
 
       ssl = mkOption {
         type = types.nullOr (types.submodule sslOpts);
         default = null;
-        description = "Paths to SSL files";
+        description = lib.mdDoc "Paths to SSL files";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Additional virtual host specific configuration";
+        description = lib.mdDoc "Additional virtual host specific configuration";
       };
 
     };
@@ -472,13 +472,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the prosody server";
+        description = lib.mdDoc "Whether to enable the prosody server";
       };
 
       xmppComplianceSuite = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           The XEP-0423 defines a set of recommended XEPs to implement
           for a server. It's generally a good idea to implement this
           set of extensions if you want to provide your users with a
@@ -498,7 +498,7 @@ in
 
       package = mkOption {
         type = types.package;
-        description = "Prosody package to use";
+        description = lib.mdDoc "Prosody package to use";
         default = pkgs.prosody;
         defaultText = literalExpression "pkgs.prosody";
         example = literalExpression ''
@@ -511,63 +511,84 @@ in
 
       dataDir = mkOption {
         type = types.path;
-        description = "Directory where Prosody stores its data";
         default = "/var/lib/prosody";
+        description = lib.mdDoc ''
+          The prosody home directory used to store all data. If left as the default value
+          this directory will automatically be created before the prosody server starts, otherwise
+          you are responsible for ensuring the directory exists with appropriate ownership
+          and permissions.
+        '';
       };
 
       disco_items = mkOption {
         type = types.listOf (types.submodule discoOpts);
         default = [];
-        description = "List of discoverable items you want to advertise.";
+        description = lib.mdDoc "List of discoverable items you want to advertise.";
       };
 
       user = mkOption {
         type = types.str;
         default = "prosody";
-        description = "User account under which prosody runs.";
+        description = lib.mdDoc ''
+          User account under which prosody runs.
+
+          ::: {.note}
+          If left as the default value this user will automatically be created
+          on system activation, otherwise you are responsible for
+          ensuring the user exists before the prosody service starts.
+          :::
+        '';
       };
 
       group = mkOption {
         type = types.str;
         default = "prosody";
-        description = "Group account under which prosody runs.";
+        description = lib.mdDoc ''
+          Group account under which prosody runs.
+
+          ::: {.note}
+          If left as the default value this group will automatically be created
+          on system activation, otherwise you are responsible for
+          ensuring the group exists before the prosody service starts.
+          :::
+        '';
       };
 
       allowRegistration = mkOption {
         type = types.bool;
         default = false;
-        description = "Allow account creation";
+        description = lib.mdDoc "Allow account creation";
       };
 
       # HTTP server-related options
       httpPorts = mkOption {
         type = types.listOf types.int;
-        description = "Listening HTTP ports list for this service.";
+        description = lib.mdDoc "Listening HTTP ports list for this service.";
         default = [ 5280 ];
       };
 
       httpInterfaces = mkOption {
         type = types.listOf types.str;
         default = [ "*" "::" ];
-        description = "Interfaces on which the HTTP server will listen on.";
+        description = lib.mdDoc "Interfaces on which the HTTP server will listen on.";
       };
 
       httpsPorts = mkOption {
         type = types.listOf types.int;
-        description = "Listening HTTPS ports list for this service.";
+        description = lib.mdDoc "Listening HTTPS ports list for this service.";
         default = [ 5281 ];
       };
 
       httpsInterfaces = mkOption {
         type = types.listOf types.str;
         default = [ "*" "::" ];
-        description = "Interfaces on which the HTTPS server will listen on.";
+        description = lib.mdDoc "Interfaces on which the HTTPS server will listen on.";
       };
 
       c2sRequireEncryption = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Force clients to use encrypted connections? This option will
           prevent clients from authenticating unless they are using encryption.
         '';
@@ -576,7 +597,7 @@ in
       s2sRequireEncryption = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Force servers to use encrypted connections? This option will
           prevent servers from authenticating unless they are using encryption.
           Note that this is different from authentication.
@@ -586,7 +607,7 @@ in
       s2sSecureAuth = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Force certificate authentication for server-to-server connections?
           This provides ideal security, but requires servers you communicate
           with to support encryption AND present valid, trusted certificates.
@@ -598,7 +619,7 @@ in
         type = types.listOf types.str;
         default = [];
         example = [ "insecure.example.com" ];
-        description = ''
+        description = lib.mdDoc ''
           Some servers have invalid or self-signed certificates. You can list
           remote domains here that will not be required to authenticate using
           certificates. They will be authenticated using DNS instead, even
@@ -610,7 +631,7 @@ in
         type = types.listOf types.str;
         default = [];
         example = [ "jabber.org" ];
-        description = ''
+        description = lib.mdDoc ''
           Even if you leave s2s_secure_auth disabled, you can still require valid
           certificates for some domains by specifying a list here.
         '';
@@ -622,17 +643,17 @@ in
       extraModules = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Enable custom modules";
+        description = lib.mdDoc "Enable custom modules";
       };
 
       extraPluginPaths = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = "Addtional path in which to look find plugins/modules";
+        description = lib.mdDoc "Addtional path in which to look find plugins/modules";
       };
 
       uploadHttp = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Configures the Prosody builtin HTTP server to handle user uploads.
         '';
         type = types.nullOr (types.submodule uploadHttpOpts);
@@ -648,12 +669,12 @@ in
         example = [ {
           domain = "conference.my-xmpp-example-host.org";
         } ];
-        description = "Multi User Chat (MUC) configuration";
+        description = lib.mdDoc "Multi User Chat (MUC) configuration";
       };
 
       virtualHosts = mkOption {
 
-        description = "Define the virtual hosts";
+        description = lib.mdDoc "Define the virtual hosts";
 
         type = with types; attrsOf (submodule vHostOpts);
 
@@ -676,27 +697,27 @@ in
       ssl = mkOption {
         type = types.nullOr (types.submodule sslOpts);
         default = null;
-        description = "Paths to SSL files";
+        description = lib.mdDoc "Paths to SSL files";
       };
 
       admins = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "admin1@example.com" "admin2@example.com" ];
-        description = "List of administrators of the current host";
+        description = lib.mdDoc "List of administrators of the current host";
       };
 
       authentication = mkOption {
         type = types.enum [ "internal_plain" "internal_hashed" "cyrus" "anonymous" ];
         default = "internal_hashed";
         example = "internal_plain";
-        description = "Authentication mechanism used for logins.";
+        description = lib.mdDoc "Authentication mechanism used for logins.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Additional prosody configuration";
+        description = lib.mdDoc "Additional prosody configuration";
       };
 
     };
@@ -820,6 +841,7 @@ in
         '') cfg.muc}
 
       ${ lib.optionalString (cfg.uploadHttp != null) ''
+        -- TODO: think about migrating this to mod-http_file_share instead.
         Component ${toLua cfg.uploadHttp.domain} "http_upload"
             http_upload_file_size_limit = ${cfg.uploadHttp.uploadFileSizeLimit}
             http_upload_expire_after = ${cfg.uploadHttp.uploadExpireAfter}
@@ -838,9 +860,8 @@ in
     users.users.prosody = mkIf (cfg.user == "prosody") {
       uid = config.ids.uids.prosody;
       description = "Prosody user";
-      createHome = true;
       inherit (cfg) group;
-      home = "${cfg.dataDir}";
+      home = cfg.dataDir;
     };
 
     users.groups.prosody = mkIf (cfg.group == "prosody") {
@@ -853,28 +874,33 @@ in
       wants = [ "network-online.target" ];
       wantedBy = [ "multi-user.target" ];
       restartTriggers = [ config.environment.etc."prosody/prosody.cfg.lua".source ];
-      serviceConfig = {
-        User = cfg.user;
-        Group = cfg.group;
-        Type = "forking";
-        RuntimeDirectory = [ "prosody" ];
-        PIDFile = "/run/prosody/prosody.pid";
-        ExecStart = "${cfg.package}/bin/prosodyctl start";
-        ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
-
-        MemoryDenyWriteExecute = true;
-        PrivateDevices = true;
-        PrivateMounts = true;
-        PrivateTmp = true;
-        ProtectControlGroups = true;
-        ProtectHome = true;
-        ProtectHostname = true;
-        ProtectKernelModules = true;
-        ProtectKernelTunables = true;
-        RestrictNamespaces = true;
-        RestrictRealtime = true;
-        RestrictSUIDSGID = true;
-      };
+      serviceConfig = mkMerge [
+        {
+          User = cfg.user;
+          Group = cfg.group;
+          Type = "forking";
+          RuntimeDirectory = [ "prosody" ];
+          PIDFile = "/run/prosody/prosody.pid";
+          ExecStart = "${cfg.package}/bin/prosodyctl start";
+          ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
+
+          MemoryDenyWriteExecute = true;
+          PrivateDevices = true;
+          PrivateMounts = true;
+          PrivateTmp = true;
+          ProtectControlGroups = true;
+          ProtectHome = true;
+          ProtectHostname = true;
+          ProtectKernelModules = true;
+          ProtectKernelTunables = true;
+          RestrictNamespaces = true;
+          RestrictRealtime = true;
+          RestrictSUIDSGID = true;
+        }
+        (mkIf (cfg.dataDir == "/var/lib/prosody") {
+          StateDirectory = "prosody";
+        })
+      ];
     };
 
   };
diff --git a/nixos/modules/services/networking/quassel.nix b/nixos/modules/services/networking/quassel.nix
index 844c9a6b8b3..a074023b5ee 100644
--- a/nixos/modules/services/networking/quassel.nix
+++ b/nixos/modules/services/networking/quassel.nix
@@ -17,12 +17,12 @@ in
 
     services.quassel = {
 
-      enable = mkEnableOption "the Quassel IRC client daemon";
+      enable = mkEnableOption (lib.mdDoc "the Quassel IRC client daemon");
 
       certificateFile = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to the certificate used for SSL connections with clients.
         '';
       };
@@ -30,7 +30,7 @@ in
       requireSSL = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Require SSL for connections from clients.
         '';
       };
@@ -39,7 +39,7 @@ in
         type = types.package;
         default = pkgs.quasselDaemon;
         defaultText = literalExpression "pkgs.quasselDaemon";
-        description = ''
+        description = lib.mdDoc ''
           The package of the quassel daemon.
         '';
       };
@@ -47,9 +47,9 @@ in
       interfaces = mkOption {
         type = types.listOf types.str;
         default = [ "127.0.0.1" ];
-        description = ''
-          The interfaces the Quassel daemon will be listening to.  If `[ 127.0.0.1 ]',
-          only clients on the local host can connect to it; if `[ 0.0.0.0 ]', clients
+        description = lib.mdDoc ''
+          The interfaces the Quassel daemon will be listening to.  If `[ 127.0.0.1 ]`,
+          only clients on the local host can connect to it; if `[ 0.0.0.0 ]`, clients
           can access it from any network interface.
         '';
       };
@@ -57,7 +57,7 @@ in
       portNumber = mkOption {
         type = types.port;
         default = 4242;
-        description = ''
+        description = lib.mdDoc ''
           The port number the Quassel daemon will be listening to.
         '';
       };
@@ -68,7 +68,7 @@ in
           "/home/''${config.${opt.user}}/.config/quassel-irc.org"
         '';
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The directory holding configuration files, the SQlite database and the SSL Cert.
         '';
       };
@@ -76,7 +76,7 @@ in
       user = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           The existing user the Quassel daemon should run as. If left empty, a default "quassel" user will be created.
         '';
       };
diff --git a/nixos/modules/services/networking/quicktun.nix b/nixos/modules/services/networking/quicktun.nix
index 438e67d5ebb..7aed972adc8 100644
--- a/nixos/modules/services/networking/quicktun.nix
+++ b/nixos/modules/services/networking/quicktun.nix
@@ -13,72 +13,72 @@ with lib;
 
     services.quicktun = mkOption {
       default = { };
-      description = "QuickTun tunnels";
+      description = lib.mdDoc "QuickTun tunnels";
       type = types.attrsOf (types.submodule {
         options = {
           tunMode = mkOption {
             type = types.int;
             default = 0;
             example = 1;
-            description = "";
+            description = lib.mdDoc "";
           };
 
           remoteAddress = mkOption {
             type = types.str;
             example = "tunnel.example.com";
-            description = "";
+            description = lib.mdDoc "";
           };
 
           localAddress = mkOption {
             type = types.str;
             example = "0.0.0.0";
-            description = "";
+            description = lib.mdDoc "";
           };
 
           localPort = mkOption {
             type = types.int;
             default = 2998;
-            description = "";
+            description = lib.mdDoc "";
           };
 
           remotePort = mkOption {
             type = types.int;
             default = 2998;
-            description = "";
+            description = lib.mdDoc "";
           };
 
           remoteFloat = mkOption {
             type = types.int;
             default = 0;
-            description = "";
+            description = lib.mdDoc "";
           };
 
           protocol = mkOption {
             type = types.str;
             default = "nacltai";
-            description = "";
+            description = lib.mdDoc "";
           };
 
           privateKey = mkOption {
             type = types.str;
-            description = "";
+            description = lib.mdDoc "";
           };
 
           publicKey = mkOption {
             type = types.str;
-            description = "";
+            description = lib.mdDoc "";
           };
 
           timeWindow = mkOption {
             type = types.int;
             default = 5;
-            description = "";
+            description = lib.mdDoc "";
           };
 
           upScript = mkOption {
             type = types.lines;
             default = "";
-            description = "";
+            description = lib.mdDoc "";
           };
         };
       });
diff --git a/nixos/modules/services/networking/quorum.nix b/nixos/modules/services/networking/quorum.nix
index bddcd18c7fb..4b90b12f86f 100644
--- a/nixos/modules/services/networking/quorum.nix
+++ b/nixos/modules/services/networking/quorum.nix
@@ -13,87 +13,87 @@ in {
   options = {
 
     services.quorum = {
-      enable = mkEnableOption "Quorum blockchain daemon";
+      enable = mkEnableOption (lib.mdDoc "Quorum blockchain daemon");
 
       user = mkOption {
         type = types.str;
         default = "quorum";
-        description = "The user as which to run quorum.";
+        description = lib.mdDoc "The user as which to run quorum.";
       };
 
       group = mkOption {
         type = types.str;
         default = cfg.user;
         defaultText = literalExpression "config.${opt.user}";
-        description = "The group as which to run quorum.";
+        description = lib.mdDoc "The group as which to run quorum.";
       };
 
       port = mkOption {
         type = types.port;
         default = 21000;
-        description = "Override the default port on which to listen for connections.";
+        description = lib.mdDoc "Override the default port on which to listen for connections.";
       };
 
       nodekeyFile = mkOption {
         type = types.path;
         default = "${dataDir}/nodekey";
-        description = "Path to the nodekey.";
+        description = lib.mdDoc "Path to the nodekey.";
       };
 
       staticNodes = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "enode://dd333ec28f0a8910c92eb4d336461eea1c20803eed9cf2c056557f986e720f8e693605bba2f4e8f289b1162e5ac7c80c914c7178130711e393ca76abc1d92f57@0.0.0.0:30303?discport=0" ];
-        description = "List of validator nodes.";
+        description = lib.mdDoc "List of validator nodes.";
       };
 
       privateconfig = mkOption {
         type = types.str;
         default = "ignore";
-        description = "Configuration of privacy transaction manager.";
+        description = lib.mdDoc "Configuration of privacy transaction manager.";
       };
 
       syncmode = mkOption {
         type = types.enum [ "fast" "full" "light" ];
         default = "full";
-        description = "Blockchain sync mode.";
+        description = lib.mdDoc "Blockchain sync mode.";
       };
 
       blockperiod = mkOption {
         type = types.int;
         default = 5;
-        description = "Default minimum difference between two consecutive block's timestamps in seconds.";
+        description = lib.mdDoc "Default minimum difference between two consecutive block's timestamps in seconds.";
       };
 
       permissioned = mkOption {
         type = types.bool;
         default = true;
-        description = "Allow only a defined list of nodes to connect.";
+        description = lib.mdDoc "Allow only a defined list of nodes to connect.";
       };
 
       rpc = {
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = "Enable RPC interface.";
+          description = lib.mdDoc "Enable RPC interface.";
         };
 
         address = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = "Listening address for RPC connections.";
+          description = lib.mdDoc "Listening address for RPC connections.";
         };
 
         port = mkOption {
           type = types.port;
           default = 22004;
-          description = "Override the default port on which to listen for RPC connections.";
+          description = lib.mdDoc "Override the default port on which to listen for RPC connections.";
         };
 
         api = mkOption {
           type = types.str;
           default = "admin,db,eth,debug,miner,net,shh,txpool,personal,web3,quorum,istanbul";
-          description = "API's offered over the HTTP-RPC interface.";
+          description = lib.mdDoc "API's offered over the HTTP-RPC interface.";
         };
       };
 
@@ -101,31 +101,31 @@ in {
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = "Enable WS-RPC interface.";
+          description = lib.mdDoc "Enable WS-RPC interface.";
         };
 
         address = mkOption {
           type = types.str;
           default = "0.0.0.0";
-          description = "Listening address for WS-RPC connections.";
+          description = lib.mdDoc "Listening address for WS-RPC connections.";
         };
 
         port = mkOption {
           type = types.port;
           default = 8546;
-          description = "Override the default port on which to listen for WS-RPC connections.";
+          description = lib.mdDoc "Override the default port on which to listen for WS-RPC connections.";
         };
 
         api = mkOption {
           type = types.str;
           default = "admin,db,eth,debug,miner,net,shh,txpool,personal,web3,quorum,istanbul";
-          description = "API's offered over the WS-RPC interface.";
+          description = lib.mdDoc "API's offered over the WS-RPC interface.";
         };
 
        origins = mkOption {
           type = types.str;
           default = "*";
-          description = "Origins from which to accept websockets requests";
+          description = lib.mdDoc "Origins from which to accept websockets requests";
        };
      };
 
@@ -160,7 +160,7 @@ in {
           parentHash = "0x0000000000000000000000000000000000000000000000000000000000000000";
           timestamp = "0x00";
           }'';
-        description = "Blockchain genesis settings.";
+        description = lib.mdDoc "Blockchain genesis settings.";
       };
      };
   };
diff --git a/nixos/modules/services/networking/r53-ddns.nix b/nixos/modules/services/networking/r53-ddns.nix
new file mode 100644
index 00000000000..277b65dcecd
--- /dev/null
+++ b/nixos/modules/services/networking/r53-ddns.nix
@@ -0,0 +1,72 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.r53-ddns;
+  pkg = pkgs.r53-ddns;
+in
+{
+  options = {
+    services.r53-ddns = {
+
+      enable = mkEnableOption (lib.mdDoc "r53-ddyns");
+
+      interval = mkOption {
+        type = types.str;
+        default = "15min";
+        description = lib.mdDoc "How often to update the entry";
+      };
+
+      zoneID = mkOption {
+        type = types.str;
+        description = lib.mdDoc "The ID of your zone in Route53";
+      };
+
+      domain = mkOption {
+        type = types.str;
+        description = lib.mdDoc "The name of your domain in Route53";
+      };
+
+      hostname = mkOption {
+        type = types.str;
+        description = lib.mdDoc ''
+          Manually specify the hostname. Otherwise the tool will try to use the name
+          returned by the OS (Call to gethostname)
+        '';
+      };
+
+      environmentFile = mkOption {
+        type = types.str;
+        description = lib.mdDoc ''
+          File containing the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
+          in the format of an EnvironmentFile as described by systemd.exec(5)
+        '';
+      };
+
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    systemd.timers.r53-ddns = {
+      description = "r53-ddns timer";
+      wantedBy = [ "timers.target" ];
+      timerConfig = {
+        OnBootSec = cfg.interval;
+        OnUnitActiveSec = cfg.interval;
+      };
+    };
+
+    systemd.services.r53-ddns = {
+      description = "r53-ddns service";
+      serviceConfig = {
+        ExecStart = "${pkg}/bin/r53-ddns -zone-id ${cfg.zoneID} -domain ${cfg.domain}"
+          + lib.optionalString (cfg.hostname != null) " -hostname ${cfg.hostname}";
+        EnvironmentFile = "${cfg.environmentFile}";
+        DynamicUser = true;
+      };
+    };
+
+  };
+}
diff --git a/nixos/modules/services/networking/radicale.nix b/nixos/modules/services/networking/radicale.nix
index c6c40777ed7..a343dab7af2 100644
--- a/nixos/modules/services/networking/radicale.nix
+++ b/nixos/modules/services/networking/radicale.nix
@@ -25,10 +25,10 @@ let
 
 in {
   options.services.radicale = {
-    enable = mkEnableOption "Radicale CalDAV and CardDAV server";
+    enable = mkEnableOption (lib.mdDoc "Radicale CalDAV and CardDAV server");
 
     package = mkOption {
-      description = "Radicale package to use.";
+      description = lib.mdDoc "Radicale package to use.";
       # Default cannot be pkgs.radicale because non-null values suppress
       # warnings about incompatible configuration and storage formats.
       type = with types; nullOr package // { inherit (package) description; };
@@ -39,21 +39,21 @@ in {
     config = mkOption {
       type = types.str;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Radicale configuration, this will set the service
         configuration file.
-        This option is mutually exclusive with <option>settings</option>.
-        This option is deprecated.  Use <option>settings</option> instead.
+        This option is mutually exclusive with {option}`settings`.
+        This option is deprecated.  Use {option}`settings` instead.
       '';
     };
 
     settings = mkOption {
       type = format.type;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Configuration for Radicale. See
-        <link xlink:href="https://radicale.org/3.0.html#documentation/configuration" />.
-        This option is mutually exclusive with <option>config</option>.
+        <https://radicale.org/3.0.html#documentation/configuration>.
+        This option is mutually exclusive with {option}`config`.
       '';
       example = literalExpression ''
         server = {
@@ -72,12 +72,12 @@ in {
 
     rights = mkOption {
       type = format.type;
-      description = ''
+      description = lib.mdDoc ''
         Configuration for Radicale's rights file. See
-        <link xlink:href="https://radicale.org/3.0.html#documentation/authentication-and-rights" />.
-        This option only works in conjunction with <option>settings</option>.
-        Setting this will also set <option>settings.rights.type</option> and
-        <option>settings.rights.file</option> to approriate values.
+        <https://radicale.org/3.0.html#documentation/authentication-and-rights>.
+        This option only works in conjunction with {option}`settings`.
+        Setting this will also set {option}`settings.rights.type` and
+        {option}`settings.rights.file` to approriate values.
       '';
       default = { };
       example = literalExpression ''
@@ -102,7 +102,7 @@ in {
     extraArgs = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = "Extra arguments passed to the Radicale daemon.";
+      description = lib.mdDoc "Extra arguments passed to the Radicale daemon.";
     };
   };
 
@@ -164,7 +164,7 @@ in {
         StateDirectoryMode = "0750";
         # Hardening
         CapabilityBoundingSet = [ "" ];
-        DeviceAllow = [ "/dev/stdin" ];
+        DeviceAllow = [ "/dev/stdin" "/dev/urandom" ];
         DevicePolicy = "strict";
         IPAddressAllow = mkIf bindLocalhost "localhost";
         IPAddressDeny = mkIf bindLocalhost "any";
diff --git a/nixos/modules/services/networking/radvd.nix b/nixos/modules/services/networking/radvd.nix
index 6e8db55bbf0..72590eda4ee 100644
--- a/nixos/modules/services/networking/radvd.nix
+++ b/nixos/modules/services/networking/radvd.nix
@@ -16,15 +16,15 @@ in
 
   ###### interface
 
-  options = {
+  options.services.radvd = {
 
-    services.radvd.enable = mkOption {
+    enable = mkOption {
       type = types.bool;
       default = false;
       description =
-        ''
+        lib.mdDoc ''
           Whether to enable the Router Advertisement Daemon
-          (<command>radvd</command>), which provides link-local
+          ({command}`radvd`), which provides link-local
           advertisements of IPv6 router addresses and prefixes using
           the Neighbor Discovery Protocol (NDP).  This enables
           stateless address autoconfiguration in IPv6 clients on the
@@ -32,7 +32,16 @@ in
         '';
     };
 
-    services.radvd.config = mkOption {
+    package = mkOption {
+      type = types.package;
+      default = pkgs.radvd;
+      defaultText = literalExpression "pkgs.radvd";
+      description = lib.mdDoc ''
+        The RADVD package to use for the RADVD service.
+      '';
+    };
+
+    config = mkOption {
       type = types.lines;
       example =
         ''
@@ -42,7 +51,7 @@ in
           };
         '';
       description =
-        ''
+        lib.mdDoc ''
           The contents of the radvd configuration file.
         '';
     };
@@ -67,7 +76,7 @@ in
         wantedBy = [ "multi-user.target" ];
         after = [ "network.target" ];
         serviceConfig =
-          { ExecStart = "@${pkgs.radvd}/bin/radvd radvd -n -u radvd -C ${confFile}";
+          { ExecStart = "@${cfg.package}/bin/radvd radvd -n -u radvd -C ${confFile}";
             Restart = "always";
           };
       };
diff --git a/nixos/modules/services/networking/rdnssd.nix b/nixos/modules/services/networking/rdnssd.nix
index fd04bb8108f..c63356e7346 100644
--- a/nixos/modules/services/networking/rdnssd.nix
+++ b/nixos/modules/services/networking/rdnssd.nix
@@ -21,10 +21,10 @@ in
       default = false;
       #default = config.networking.enableIPv6;
       description =
-        ''
+        lib.mdDoc ''
           Whether to enable the RDNSS daemon
-          (<command>rdnssd</command>), which configures DNS servers in
-          <filename>/etc/resolv.conf</filename> from RDNSS
+          ({command}`rdnssd`), which configures DNS servers in
+          {file}`/etc/resolv.conf` from RDNSS
           advertisements sent by IPv6 routers.
         '';
     };
diff --git a/nixos/modules/services/networking/redsocks.nix b/nixos/modules/services/networking/redsocks.nix
index 8481f9debf3..85ae3125ded 100644
--- a/nixos/modules/services/networking/redsocks.nix
+++ b/nixos/modules/services/networking/redsocks.nix
@@ -11,26 +11,26 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable redsocks.";
+        description = lib.mdDoc "Whether to enable redsocks.";
       };
 
       log_debug = mkOption {
         type = types.bool;
         default = false;
-        description = "Log connection progress.";
+        description = lib.mdDoc "Log connection progress.";
       };
 
       log_info = mkOption {
         type = types.bool;
         default = false;
-        description = "Log start and end of client sessions.";
+        description = lib.mdDoc "Log start and end of client sessions.";
       };
 
       log = mkOption {
         type = types.str;
         default = "stderr";
         description =
-          ''
+          lib.mdDoc ''
             Where to send logs.
 
             Possible values are:
@@ -45,7 +45,7 @@ in
         type = with types; nullOr str;
         default = null;
         description =
-          ''
+          lib.mdDoc ''
             Chroot under which to run redsocks. Log file is opened before
             chroot, but if logging to syslog /etc/localtime may be required.
           '';
@@ -53,7 +53,7 @@ in
 
       redsocks = mkOption {
         description =
-          ''
+          lib.mdDoc ''
             Local port to proxy associations to be performed.
 
             The example shows how to configure a proxy to handle port 80 as HTTP
@@ -74,7 +74,7 @@ in
             type = types.str;
             default = "127.0.0.1";
             description =
-              ''
+              lib.mdDoc ''
                 IP on which redsocks should listen. Defaults to 127.0.0.1 for
                 security reasons.
               '';
@@ -83,13 +83,13 @@ in
           port = mkOption {
             type = types.int;
             default = 12345;
-            description = "Port on which redsocks should listen.";
+            description = lib.mdDoc "Port on which redsocks should listen.";
           };
 
           proxy = mkOption {
             type = types.str;
             description =
-              ''
+              lib.mdDoc ''
                 Proxy through which redsocks should forward incoming traffic.
                 Example: "example.org:8080"
               '';
@@ -97,20 +97,20 @@ in
 
           type = mkOption {
             type = types.enum [ "socks4" "socks5" "http-connect" "http-relay" ];
-            description = "Type of proxy.";
+            description = lib.mdDoc "Type of proxy.";
           };
 
           login = mkOption {
             type = with types; nullOr str;
             default = null;
-            description = "Login to send to proxy.";
+            description = lib.mdDoc "Login to send to proxy.";
           };
 
           password = mkOption {
             type = with types; nullOr str;
             default = null;
             description =
-              ''
+              lib.mdDoc ''
                 Password to send to proxy. WARNING, this will end up
                 world-readable in the store! Awaiting
                 https://github.com/NixOS/nix/issues/8 to be able to fix.
@@ -122,7 +122,7 @@ in
                                 "Forwarded_ipport" ];
             default = "false";
             description =
-              ''
+              lib.mdDoc ''
                 Way to disclose client IP to the proxy.
                   - "false": do not disclose
                 http-connect supports the following ways:
@@ -135,14 +135,14 @@ in
           redirectInternetOnly = mkOption {
             type = types.bool;
             default = true;
-            description = "Exclude all non-globally-routable IPs from redsocks";
+            description = lib.mdDoc "Exclude all non-globally-routable IPs from redsocks";
           };
 
           doNotRedirect = mkOption {
             type = with types; listOf str;
             default = [];
             description =
-              ''
+              lib.mdDoc ''
                 Iptables filters that if matched will get the packet off of
                 redsocks.
               '';
@@ -153,7 +153,7 @@ in
             type = with types; either bool str;
             default = false;
             description =
-              ''
+              lib.mdDoc ''
                 Conditions to make outbound packets go through this redsocks
                 instance.
 
diff --git a/nixos/modules/services/networking/resilio.nix b/nixos/modules/services/networking/resilio.nix
index 89127850641..cc9495bf238 100644
--- a/nixos/modules/services/networking/resilio.nix
+++ b/nixos/modules/services/networking/resilio.nix
@@ -8,7 +8,6 @@ let
   resilioSync = pkgs.resilio-sync;
 
   sharedFoldersRecord = map (entry: {
-    secret = entry.secret;
     dir = entry.directory;
 
     use_relay_server = entry.useRelayServer;
@@ -40,6 +39,31 @@ let
     shared_folders = sharedFoldersRecord;
   }));
 
+  sharedFoldersSecretFiles = map (entry: {
+    dir = entry.directory;
+    secretFile = if builtins.hasAttr "secret" entry then
+      toString (pkgs.writeTextFile {
+        name = "secret-file";
+        text = entry.secret;
+      })
+    else
+      entry.secretFile;
+  }) cfg.sharedFolders;
+
+  runConfigPath = "/run/rslsync/config.json";
+
+  createConfig = pkgs.writeShellScriptBin "create-resilio-config" ''
+    ${pkgs.jq}/bin/jq \
+      '.shared_folders |= map(.secret = $ARGS.named[.dir])' \
+      ${
+        lib.concatMapStringsSep " \\\n  "
+        (entry: ''--arg '${entry.dir}' "$(cat '${entry.secretFile}')"'')
+        sharedFoldersSecretFiles
+      } \
+      <${configFile} \
+      >${runConfigPath}
+  '';
+
 in
 {
   options = {
@@ -47,7 +71,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, start the Resilio Sync daemon. Once enabled, you can
           interact with the service through the Web UI, or configure it in your
           NixOS configuration.
@@ -59,7 +83,7 @@ in
         example = "Voltron";
         default = config.networking.hostName;
         defaultText = literalExpression "config.networking.hostName";
-        description = ''
+        description = lib.mdDoc ''
           Name of the Resilio Sync device.
         '';
       };
@@ -68,7 +92,7 @@ in
         type = types.int;
         default = 0;
         example = 44444;
-        description = ''
+        description = lib.mdDoc ''
           Listening port. Defaults to 0 which randomizes the port.
         '';
       };
@@ -76,7 +100,7 @@ in
       checkForUpdates = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Determines whether to check for updates and alert the user
           about them in the UI.
         '';
@@ -85,7 +109,7 @@ in
       useUpnp = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Use Universal Plug-n-Play (UPnP)
         '';
       };
@@ -94,7 +118,7 @@ in
         type = types.int;
         default = 0;
         example = 1024;
-        description = ''
+        description = lib.mdDoc ''
           Download speed limit. 0 is unlimited (default).
         '';
       };
@@ -103,7 +127,7 @@ in
         type = types.int;
         default = 0;
         example = 1024;
-        description = ''
+        description = lib.mdDoc ''
           Upload speed limit. 0 is unlimited (default).
         '';
       };
@@ -112,7 +136,7 @@ in
         type = types.str;
         default = "[::1]";
         example = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           HTTP address to bind to.
         '';
       };
@@ -120,7 +144,7 @@ in
       httpListenPort = mkOption {
         type = types.int;
         default = 9000;
-        description = ''
+        description = lib.mdDoc ''
           HTTP port to bind on.
         '';
       };
@@ -129,7 +153,7 @@ in
         type = types.str;
         example = "allyourbase";
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           HTTP web login username.
         '';
       };
@@ -138,7 +162,7 @@ in
         type = types.str;
         example = "arebelongtous";
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           HTTP web login password.
         '';
       };
@@ -146,23 +170,23 @@ in
       encryptLAN = mkOption {
         type = types.bool;
         default = true;
-        description = "Encrypt LAN data.";
+        description = lib.mdDoc "Encrypt LAN data.";
       };
 
       enableWebUI = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable Web UI for administration. Bound to the specified
-          <literal>httpListenAddress</literal> and
-          <literal>httpListenPort</literal>.
+          `httpListenAddress` and
+          `httpListenPort`.
           '';
       };
 
       storagePath = mkOption {
         type = types.path;
         default = "/var/lib/resilio-sync/";
-        description = ''
+        description = lib.mdDoc ''
           Where BitTorrent Sync will store it's database files (containing
           things like username info and licenses). Generally, you should not
           need to ever change this.
@@ -172,21 +196,21 @@ in
       apiKey = mkOption {
         type = types.str;
         default = "";
-        description = "API key, which enables the developer API.";
+        description = lib.mdDoc "API key, which enables the developer API.";
       };
 
       directoryRoot = mkOption {
         type = types.str;
         default = "";
         example = "/media";
-        description = "Default directory to add folders in the web UI.";
+        description = lib.mdDoc "Default directory to add folders in the web UI.";
       };
 
       sharedFolders = mkOption {
         default = [];
         type = types.listOf (types.attrsOf types.anything);
         example =
-          [ { secret         = "AHMYFPCQAHBM7LQPFXQ7WV6Y42IGUXJ5Y";
+          [ { secretFile     = "/run/resilio-secret";
               directory      = "/home/user/sync_test";
               useRelayServer = true;
               useTracker     = true;
@@ -199,25 +223,22 @@ in
               ];
             }
           ];
-        description = ''
+        description = lib.mdDoc ''
           Shared folder list. If enabled, web UI must be
-          disabled. Secrets can be generated using <literal>rslsync
-          --generate-secret</literal>. Note that this secret will be
-          put inside the Nix store, so it is realistically not very
-          secret.
+          disabled. Secrets can be generated using `rslsync --generate-secret`.
 
           If you would like to be able to modify the contents of this
           directories, it is recommended that you make your user a
-          member of the <literal>rslsync</literal> group.
+          member of the `rslsync` group.
 
           Directories in this list should be in the
-          <literal>rslsync</literal> group, and that group must have
+          `rslsync` group, and that group must have
           write access to the directory. It is also recommended that
-          <literal>chmod g+s</literal> is applied to the directory
+          `chmod g+s` is applied to the directory
           so that any sub directories created will also belong to
-          the <literal>rslsync</literal> group. Also,
-          <literal>setfacl -d -m group:rslsync:rwx</literal> and
-          <literal>setfacl -m group:rslsync:rwx</literal> should also
+          the `rslsync` group. Also,
+          `setfacl -d -m group:rslsync:rwx` and
+          `setfacl -m group:rslsync:rwx` should also
           be applied so that the sub directories are writable by
           the group.
         '';
@@ -256,10 +277,14 @@ in
         Restart   = "on-abort";
         UMask     = "0002";
         User      = "rslsync";
+        RuntimeDirectory = "rslsync";
+        ExecStartPre = "${createConfig}/bin/create-resilio-config";
         ExecStart = ''
-          ${resilioSync}/bin/rslsync --nodaemon --config ${configFile}
+          ${resilioSync}/bin/rslsync --nodaemon --config ${runConfigPath}
         '';
       };
     };
   };
+
+  meta.maintainers = with maintainers; [ jwoudenberg ];
 }
diff --git a/nixos/modules/services/networking/robustirc-bridge.nix b/nixos/modules/services/networking/robustirc-bridge.nix
index 255af79ec04..9b93828c396 100644
--- a/nixos/modules/services/networking/robustirc-bridge.nix
+++ b/nixos/modules/services/networking/robustirc-bridge.nix
@@ -8,12 +8,12 @@ in
 {
   options = {
     services.robustirc-bridge = {
-      enable = mkEnableOption "RobustIRC bridge";
+      enable = mkEnableOption (lib.mdDoc "RobustIRC bridge");
 
       extraFlags = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''Extra flags passed to the <command>robustirc-bridge</command> command. See <link xlink:href="https://robustirc.net/docs/adminguide.html#_bridge">RobustIRC Documentation</link> or robustirc-bridge(1) for details.'';
+        description = lib.mdDoc ''Extra flags passed to the {command}`robustirc-bridge` command. See [RobustIRC Documentation](https://robustirc.net/docs/adminguide.html#_bridge) or robustirc-bridge(1) for details.'';
         example = [
           "-network robustirc.net"
         ];
diff --git a/nixos/modules/services/networking/routedns.nix b/nixos/modules/services/networking/routedns.nix
new file mode 100644
index 00000000000..2a29a06700c
--- /dev/null
+++ b/nixos/modules/services/networking/routedns.nix
@@ -0,0 +1,84 @@
+{ config
+, lib
+, pkgs
+, ...
+}:
+
+with lib;
+
+let
+  cfg = config.services.routedns;
+  settingsFormat = pkgs.formats.toml { };
+in
+{
+  options.services.routedns = {
+    enable = mkEnableOption (lib.mdDoc "RouteDNS - DNS stub resolver, proxy and router");
+
+    settings = mkOption {
+      type = settingsFormat.type;
+      example = literalExpression ''
+        {
+          resolvers.cloudflare-dot = {
+            address = "1.1.1.1:853";
+            protocol = "dot";
+          };
+          groups.cloudflare-cached = {
+            type = "cache";
+            resolvers = ["cloudflare-dot"];
+          };
+          listeners.local-udp = {
+            address = "127.0.0.1:53";
+            protocol = "udp";
+            resolver = "cloudflare-cached";
+          };
+          listeners.local-tcp = {
+            address = "127.0.0.1:53";
+            protocol = "tcp";
+            resolver = "cloudflare-cached";
+          };
+        }
+      '';
+      description = lib.mdDoc ''
+        Configuration for RouteDNS, see <https://github.com/folbricht/routedns/blob/master/doc/configuration.md>
+        for more information.
+      '';
+    };
+
+    configFile = mkOption {
+      default = settingsFormat.generate "routedns.toml" cfg.settings;
+      defaultText = "A RouteDNS configuration file automatically generated by values from services.routedns.*";
+      type = types.path;
+      example = literalExpression ''"''${pkgs.routedns}/cmd/routedns/example-config/use-case-1.toml"'';
+      description = lib.mdDoc "Path to RouteDNS TOML configuration file.";
+    };
+
+    package = mkOption {
+      default = pkgs.routedns;
+      defaultText = literalExpression "pkgs.routedns";
+      type = types.package;
+      description = lib.mdDoc "RouteDNS package to use.";
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.routedns = {
+      description = "RouteDNS - DNS stub resolver, proxy and router";
+      after = [ "network.target" ]; # in case a bootstrap resolver is used, this might fail a few times until the respective server is actually reachable
+      wantedBy = [ "multi-user.target" ];
+      wants = [ "network.target" ];
+      startLimitIntervalSec = 30;
+      startLimitBurst = 5;
+      serviceConfig = {
+        Restart = "on-failure";
+        RestartSec = "5s";
+        LimitNPROC = 512;
+        LimitNOFILE = 1048576;
+        DynamicUser = true;
+        AmbientCapabilities = "CAP_NET_BIND_SERVICE";
+        NoNewPrivileges = true;
+        ExecStart = "${getBin cfg.package}/bin/routedns -l 4 ${cfg.configFile}";
+      };
+    };
+  };
+  meta.maintainers = with maintainers; [ jsimonetti ];
+}
diff --git a/nixos/modules/services/networking/rpcbind.nix b/nixos/modules/services/networking/rpcbind.nix
index 0a5df698709..aa04214debb 100644
--- a/nixos/modules/services/networking/rpcbind.nix
+++ b/nixos/modules/services/networking/rpcbind.nix
@@ -13,7 +13,7 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable `rpcbind', an ONC RPC directory service
           notably used by NFS and NIS, and which can be queried
           using the rpcinfo(1) command. `rpcbind` is a replacement for
diff --git a/nixos/modules/services/networking/rxe.nix b/nixos/modules/services/networking/rxe.nix
index 868e2c81ccb..7dbb4823b4b 100644
--- a/nixos/modules/services/networking/rxe.nix
+++ b/nixos/modules/services/networking/rxe.nix
@@ -10,14 +10,14 @@ in {
 
   options = {
     networking.rxe = {
-      enable = mkEnableOption "RDMA over converged ethernet";
+      enable = mkEnableOption (lib.mdDoc "RDMA over converged ethernet");
       interfaces = mkOption {
         type = types.listOf types.str;
         default = [ ];
         example = [ "eth0" ];
-        description = ''
+        description = lib.mdDoc ''
           Enable RDMA on the listed interfaces. The corresponding virtual
-          RDMA interfaces will be named rxe_&lt;interface&gt;.
+          RDMA interfaces will be named rxe_\<interface\>.
           UDP port 4791 must be open on the respective ethernet interfaces.
         '';
       };
diff --git a/nixos/modules/services/networking/sabnzbd.nix b/nixos/modules/services/networking/sabnzbd.nix
index 54eeba1a9ec..8486be1bc66 100644
--- a/nixos/modules/services/networking/sabnzbd.nix
+++ b/nixos/modules/services/networking/sabnzbd.nix
@@ -15,31 +15,31 @@ in
 
   options = {
     services.sabnzbd = {
-      enable = mkEnableOption "the sabnzbd server";
+      enable = mkEnableOption (lib.mdDoc "the sabnzbd server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.sabnzbd;
         defaultText = "pkgs.sabnzbd";
-        description = "The sabnzbd executable package run by the service.";
+        description = lib.mdDoc "The sabnzbd executable package run by the service.";
       };
 
       configFile = mkOption {
         type = types.path;
         default = "/var/lib/sabnzbd/sabnzbd.ini";
-        description = "Path to config file.";
+        description = lib.mdDoc "Path to config file.";
       };
 
       user = mkOption {
         default = "sabnzbd";
         type = types.str;
-        description = "User to run the service as";
+        description = lib.mdDoc "User to run the service as";
       };
 
       group = mkOption {
         type = types.str;
         default = "sabnzbd";
-        description = "Group to run the service as";
+        description = lib.mdDoc "Group to run the service as";
       };
     };
   };
diff --git a/nixos/modules/services/networking/seafile.nix b/nixos/modules/services/networking/seafile.nix
index 2839ffb60a1..b07d51b9b49 100644
--- a/nixos/modules/services/networking/seafile.nix
+++ b/nixos/modules/services/networking/seafile.nix
@@ -19,6 +19,8 @@ let
     MEDIA_ROOT = '${seahubDir}/media/'
     THUMBNAIL_ROOT = '${seahubDir}/thumbnail/'
 
+    SERVICE_URL = '${cfg.ccnetSettings.General.SERVICE_URL}'
+
     with open('${seafRoot}/.seahubSecret') as f:
         SECRET_KEY = f.readline().rstrip()
 
@@ -35,7 +37,7 @@ in {
   ###### Interface
 
   options.services.seafile = {
-    enable = mkEnableOption "Seafile server";
+    enable = mkEnableOption (lib.mdDoc "Seafile server");
 
     ccnetSettings = mkOption {
       type = types.submodule {
@@ -46,7 +48,7 @@ in {
             SERVICE_URL = mkOption {
               type = types.str;
               example = "https://www.example.com";
-              description = ''
+              description = lib.mdDoc ''
                 Seahub public URL.
               '';
             };
@@ -54,9 +56,9 @@ in {
         };
       };
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Configuration for ccnet, see
-        <link xlink:href="https://manual.seafile.com/config/ccnet-conf/"/>
+        <https://manual.seafile.com/config/ccnet-conf/>
         for supported values.
       '';
     };
@@ -70,7 +72,7 @@ in {
             port = mkOption {
               type = types.port;
               default = 8082;
-              description = ''
+              description = lib.mdDoc ''
                 The tcp port used by seafile fileserver.
               '';
             };
@@ -78,7 +80,7 @@ in {
               type = types.str;
               default = "127.0.0.1";
               example = "0.0.0.0";
-              description = ''
+              description = lib.mdDoc ''
                 The binding address used by seafile fileserver.
               '';
             };
@@ -86,9 +88,9 @@ in {
         };
       };
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Configuration for seafile-server, see
-        <link xlink:href="https://manual.seafile.com/config/seafile-conf/"/>
+        <https://manual.seafile.com/config/seafile-conf/>
         for supported values.
       '';
     };
@@ -97,7 +99,7 @@ in {
       type = types.int;
       default = 4;
       example = 10;
-      description = ''
+      description = lib.mdDoc ''
         The number of gunicorn worker processes for handling requests.
       '';
     };
@@ -105,7 +107,7 @@ in {
     adminEmail = mkOption {
       example = "john@example.com";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Seafile Seahub Admin Account Email.
       '';
     };
@@ -113,7 +115,7 @@ in {
     initialAdminPassword = mkOption {
       example = "someStrongPass";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Seafile Seahub Admin Account initial password.
         Should be change via Seahub web front-end.
       '';
@@ -121,7 +123,7 @@ in {
 
     seafilePackage = mkOption {
       type = types.package;
-      description = "Which package to use for the seafile server.";
+      description = lib.mdDoc "Which package to use for the seafile server.";
       default = pkgs.seafile-server;
       defaultText = literalExpression "pkgs.seafile-server";
     };
@@ -129,9 +131,9 @@ in {
     seahubExtraConf = mkOption {
       default = "";
       type = types.lines;
-      description = ''
+      description = lib.mdDoc ''
         Extra config to append to `seahub_settings.py` file.
-        Refer to <link xlink:href="https://manual.seafile.com/config/seahub_settings_py/" />
+        Refer to <https://manual.seafile.com/config/seahub_settings_py/>
         for all available options.
       '';
     };
@@ -177,6 +179,7 @@ in {
         after = [ "network.target" ];
         wantedBy = [ "seafile.target" ];
         restartTriggers = [ ccnetConf seafileConf ];
+        path = [ pkgs.sqlite ];
         serviceConfig = securityOptions // {
           User = "seafile";
           Group = "seafile";
@@ -200,11 +203,11 @@ in {
           if [ ! -f "${seafRoot}/server-setup" ]; then
               mkdir -p ${dataDir}/library-template
               mkdir -p ${ccnetDir}/{GroupMgr,misc,OrgMgr,PeerMgr}
-              ${pkgs.sqlite}/bin/sqlite3 ${ccnetDir}/GroupMgr/groupmgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/groupmgr.sql"
-              ${pkgs.sqlite}/bin/sqlite3 ${ccnetDir}/misc/config.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/config.sql"
-              ${pkgs.sqlite}/bin/sqlite3 ${ccnetDir}/OrgMgr/orgmgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/org.sql"
-              ${pkgs.sqlite}/bin/sqlite3 ${ccnetDir}/PeerMgr/usermgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/user.sql"
-              ${pkgs.sqlite}/bin/sqlite3 ${dataDir}/seafile.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/seafile.sql"
+              sqlite3 ${ccnetDir}/GroupMgr/groupmgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/groupmgr.sql"
+              sqlite3 ${ccnetDir}/misc/config.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/config.sql"
+              sqlite3 ${ccnetDir}/OrgMgr/orgmgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/org.sql"
+              sqlite3 ${ccnetDir}/PeerMgr/usermgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/user.sql"
+              sqlite3 ${dataDir}/seafile.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/seafile.sql"
               echo "${cfg.seafilePackage.version}-sqlite" > "${seafRoot}"/server-setup
           fi
           # checking for upgrades and handling them
@@ -213,7 +216,14 @@ in {
           installedMinor=$(cat "${seafRoot}/server-setup" | cut -d"-" -f1 | cut -d"." -f2)
           pkgMajor=$(echo "${cfg.seafilePackage.version}" | cut -d"." -f1)
           pkgMinor=$(echo "${cfg.seafilePackage.version}" | cut -d"." -f2)
-          if [ $installedMajor != $pkgMajor ] || [ $installedMinor != $pkgMinor ]; then
+
+          if [[ $installedMajor == $pkgMajor && $installedMinor == $pkgMinor ]]; then
+             :
+          elif [[ $installedMajor == 8 && $installedMinor == 0 && $pkgMajor == 9 && $pkgMinor == 0 ]]; then
+              # Upgrade from 8.0 to 9.0
+              sqlite3 ${dataDir}/seafile.db ".read ${pkgs.seahub}/scripts/upgrade/sql/9.0.0/sqlite3/seafile.sql"
+              echo "${cfg.seafilePackage.version}-sqlite" > "${seafRoot}"/server-setup
+          else
               echo "Unsupported upgrade" >&2
               exit 1
           fi
diff --git a/nixos/modules/services/networking/searx.nix b/nixos/modules/services/networking/searx.nix
index b73f255eb9d..214b6c6a787 100644
--- a/nixos/modules/services/networking/searx.nix
+++ b/nixos/modules/services/networking/searx.nix
@@ -51,14 +51,14 @@ in
         type = types.bool;
         default = false;
         relatedPackages = [ "searx" ];
-        description = "Whether to enable Searx, the meta search engine.";
+        description = lib.mdDoc "Whether to enable Searx, the meta search engine.";
       };
 
       environmentFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
-          Environment file (see <literal>systemd.exec(5)</literal>
+        description = lib.mdDoc ''
+          Environment file (see `systemd.exec(5)`
           "EnvironmentFile=" section for the syntax) to define variables for
           Searx. This option can be used to safely include secret keys into the
           Searx configuration.
@@ -81,35 +81,33 @@ in
               };
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Searx settings. These will be merged with (taking precedence over)
           the default configuration. It's also possible to refer to
           environment variables
-          (defined in <xref linkend="opt-services.searx.environmentFile"/>)
-          using the syntax <literal>@VARIABLE_NAME@</literal>.
-          <note>
-            <para>
-              For available settings, see the Searx
-              <link xlink:href="https://searx.github.io/searx/admin/settings.html">docs</link>.
-            </para>
-          </note>
+          (defined in [](#opt-services.searx.environmentFile))
+          using the syntax `@VARIABLE_NAME@`.
+
+          ::: {.note}
+          For available settings, see the Searx
+          [docs](https://searx.github.io/searx/admin/settings.html).
+          :::
         '';
       };
 
       settingsFile = mkOption {
         type = types.path;
         default = "${runDir}/settings.yml";
-        description = ''
+        description = lib.mdDoc ''
           The path of the Searx server settings.yml file. If no file is
           specified, a default file is used (default config file has debug mode
           enabled). Note: setting this options overrides
-          <xref linkend="opt-services.searx.settings"/>.
-          <warning>
-            <para>
-              This file, along with any secret key it contains, will be copied
-              into the world-readable Nix store.
-            </para>
-          </warning>
+          [](#opt-services.searx.settings).
+
+          ::: {.warning}
+          This file, along with any secret key it contains, will be copied
+          into the world-readable Nix store.
+          :::
         '';
       };
 
@@ -117,21 +115,20 @@ in
         type = types.package;
         default = pkgs.searx;
         defaultText = literalExpression "pkgs.searx";
-        description = "searx package to use.";
+        description = lib.mdDoc "searx package to use.";
       };
 
       runInUwsgi = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run searx in uWSGI as a "vassal", instead of using its
           built-in HTTP server. This is the recommended mode for public or
           large instances, but is unecessary for LAN or local-only use.
-          <warning>
-            <para>
-              The built-in HTTP server logs all queries by default.
-            </para>
-          </warning>
+
+          ::: {.warning}
+          The built-in HTTP server logs all queries by default.
+          :::
         '';
       };
 
@@ -143,9 +140,10 @@ in
             disable-logging = true;
             http = ":8080";                   # serve via HTTP...
             socket = "/run/searx/searx.sock"; # ...or UNIX socket
+            chmod-socket = "660";             # allow the searx group to read/write to the socket
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Additional configuration of the uWSGI vassal running searx. It
           should notably specify on which interfaces and ports the vassal
           should listen.
@@ -194,7 +192,10 @@ in
         ExecStart = "${cfg.package}/bin/searx-run";
       } // optionalAttrs (cfg.environmentFile != null)
         { EnvironmentFile = builtins.toPath cfg.environmentFile; };
-      environment.SEARX_SETTINGS_PATH = cfg.settingsFile;
+      environment = {
+        SEARX_SETTINGS_PATH = cfg.settingsFile;
+        SEARXNG_SETTINGS_PATH = cfg.settingsFile;
+      };
     };
 
     systemd.services.uwsgi = mkIf (cfg.runInUwsgi)
@@ -220,7 +221,12 @@ in
         lazy-apps = true;
         enable-threads = true;
         module = "searx.webapp";
-        env = [ "SEARX_SETTINGS_PATH=${cfg.settingsFile}" ];
+        env = [
+          "SEARX_SETTINGS_PATH=${cfg.settingsFile}"
+          # searxng compatiblity https://github.com/searxng/searxng/issues/1519
+          "SEARXNG_SETTINGS_PATH=${cfg.settingsFile}"
+        ];
+        buffer-size = 32768;
         pythonPackages = self: [ cfg.package ];
       } // cfg.uwsgiConfig;
     };
diff --git a/nixos/modules/services/networking/shadowsocks.nix b/nixos/modules/services/networking/shadowsocks.nix
index 7bea269a9ed..2034dca6f26 100644
--- a/nixos/modules/services/networking/shadowsocks.nix
+++ b/nixos/modules/services/networking/shadowsocks.nix
@@ -34,7 +34,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run shadowsocks-libev shadowsocks server.
         '';
       };
@@ -42,15 +42,15 @@ in
       localAddress = mkOption {
         type = types.coercedTo types.str singleton (types.listOf types.str);
         default = [ "[::0]" "0.0.0.0" ];
-        description = ''
+        description = lib.mdDoc ''
           Local addresses to which the server binds.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8388;
-        description = ''
+        description = lib.mdDoc ''
           Port which the server uses.
         '';
       };
@@ -58,7 +58,7 @@ in
       password = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Password for connecting clients.
         '';
       };
@@ -66,7 +66,7 @@ in
       passwordFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Password file with a password for connecting clients.
         '';
       };
@@ -74,7 +74,7 @@ in
       mode = mkOption {
         type = types.enum [ "tcp_only" "tcp_and_udp" "udp_only" ];
         default = "tcp_and_udp";
-        description = ''
+        description = lib.mdDoc ''
           Relay protocols.
         '';
       };
@@ -82,7 +82,7 @@ in
       fastOpen = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           use TCP fast-open
         '';
       };
@@ -90,8 +90,8 @@ in
       encryptionMethod = mkOption {
         type = types.str;
         default = "chacha20-ietf-poly1305";
-        description = ''
-          Encryption method. See <link xlink:href="https://github.com/shadowsocks/shadowsocks-org/wiki/AEAD-Ciphers"/>.
+        description = lib.mdDoc ''
+          Encryption method. See <https://github.com/shadowsocks/shadowsocks-org/wiki/AEAD-Ciphers>.
         '';
       };
 
@@ -99,7 +99,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = literalExpression ''"''${pkgs.shadowsocks-v2ray-plugin}/bin/v2ray-plugin"'';
-        description = ''
+        description = lib.mdDoc ''
           SIP003 plugin for shadowsocks
         '';
       };
@@ -108,7 +108,7 @@ in
         type = types.str;
         default = "";
         example = "server;host=example.com";
-        description = ''
+        description = lib.mdDoc ''
           Options to pass to the plugin if one was specified
         '';
       };
@@ -119,13 +119,13 @@ in
         example = {
           nameserver = "8.8.8.8";
         };
-        description = ''
+        description = lib.mdDoc ''
           Additional configuration for shadowsocks that is not covered by the
           provided options. The provided attrset will be serialized to JSON and
           has to contain valid shadowsocks options. Unfortunately most
           additional options are undocumented but it's easy to find out what is
           available by looking into the source code of
-          <link xlink:href="https://github.com/shadowsocks/shadowsocks-libev/blob/master/src/jconf.c"/>
+          <https://github.com/shadowsocks/shadowsocks-libev/blob/master/src/jconf.c>
         '';
       };
     };
diff --git a/nixos/modules/services/networking/shairport-sync.nix b/nixos/modules/services/networking/shairport-sync.nix
index eb61663e4d9..75684eea3ad 100644
--- a/nixos/modules/services/networking/shairport-sync.nix
+++ b/nixos/modules/services/networking/shairport-sync.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the shairport-sync daemon.
 
           Running with a local system-wide or remote pulseaudio server
@@ -30,7 +30,7 @@ in
       arguments = mkOption {
         type = types.str;
         default = "-v -o pa";
-        description = ''
+        description = lib.mdDoc ''
           Arguments to pass to the daemon. Defaults to a local pulseaudio
           server.
         '';
@@ -39,7 +39,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to automatically open ports in the firewall.
         '';
       };
@@ -47,7 +47,7 @@ in
       user = mkOption {
         type = types.str;
         default = "shairport";
-        description = ''
+        description = lib.mdDoc ''
           User account name under which to run shairport-sync. The account
           will be created.
         '';
@@ -56,7 +56,7 @@ in
       group = mkOption {
         type = types.str;
         default = "shairport";
-        description = ''
+        description = lib.mdDoc ''
           Group account name under which to run shairport-sync. The account
           will be created.
         '';
diff --git a/nixos/modules/services/networking/shellhub-agent.nix b/nixos/modules/services/networking/shellhub-agent.nix
index a45ef148544..ad33c50f9d6 100644
--- a/nixos/modules/services/networking/shellhub-agent.nix
+++ b/nixos/modules/services/networking/shellhub-agent.nix
@@ -1,38 +1,44 @@
 { config, lib, pkgs, ... }:
 
 with lib;
+
 let
   cfg = config.services.shellhub-agent;
-in {
-
+in
+{
   ###### interface
 
   options = {
 
     services.shellhub-agent = {
 
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Whether to enable the ShellHub Agent daemon, which allows
-          secure remote logins.
+      enable = mkEnableOption (lib.mdDoc "ShellHub Agent daemon");
+
+      package = mkPackageOption pkgs "shellhub-agent" { };
+
+      preferredHostname = mkOption {
+        type = types.str;
+        default = "";
+        description = lib.mdDoc ''
+          Set the device preferred hostname. This provides a hint to
+          the server to use this as hostname if it is available.
         '';
       };
 
-      package = mkOption {
-        type = types.package;
-        default = pkgs.shellhub-agent;
-        defaultText = literalExpression "pkgs.shellhub-agent";
-        description = ''
-          Which ShellHub Agent package to use.
+      keepAliveInterval = mkOption {
+        type = types.int;
+        default = 30;
+        description = lib.mdDoc ''
+          Determine the interval to send the keep alive message to
+          the server. This has a direct impact of the bandwidth
+          used by the device.
         '';
       };
 
       tenantId = mkOption {
         type = types.str;
         example = "ba0a880c-2ada-11eb-a35e-17266ef329d6";
-        description = ''
+        description = lib.mdDoc ''
           The tenant ID to use when connecting to the ShellHub
           Gateway.
         '';
@@ -41,7 +47,7 @@ in {
       server = mkOption {
         type = types.str;
         default = "https://cloud.shellhub.io";
-        description = ''
+        description = lib.mdDoc ''
           Server address of ShellHub Gateway to connect.
         '';
       };
@@ -49,7 +55,7 @@ in {
       privateKey = mkOption {
         type = types.path;
         default = "/var/lib/shellhub-agent/private.key";
-        description = ''
+        description = lib.mdDoc ''
           Location where to store the ShellHub Agent private
           key.
         '';
@@ -74,9 +80,13 @@ in {
         "time-sync.target"
       ];
 
-      environment.SERVER_ADDRESS = cfg.server;
-      environment.PRIVATE_KEY = cfg.privateKey;
-      environment.TENANT_ID = cfg.tenantId;
+      environment = {
+        SHELLHUB_SERVER_ADDRESS = cfg.server;
+        SHELLHUB_PRIVATE_KEY = cfg.privateKey;
+        SHELLHUB_TENANT_ID = cfg.tenantId;
+        SHELLHUB_KEEPALIVE_INTERVAL = toString cfg.keepAliveInterval;
+        SHELLHUB_PREFERRED_HOSTNAME = cfg.preferredHostname;
+      };
 
       serviceConfig = {
         # The service starts sessions for different users.
@@ -85,7 +95,6 @@ in {
         ExecStart = "${cfg.package}/bin/agent";
       };
     };
-
-    environment.systemPackages = [ cfg.package ];
   };
 }
+
diff --git a/nixos/modules/services/networking/shorewall.nix b/nixos/modules/services/networking/shorewall.nix
index ac732d4b12e..ba59d71120d 100644
--- a/nixos/modules/services/networking/shorewall.nix
+++ b/nixos/modules/services/networking/shorewall.nix
@@ -8,27 +8,26 @@ in {
       enable = lib.mkOption {
         type        = types.bool;
         default     = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Shorewall IPv4 Firewall.
-          <warning>
-            <para>
-            Enabling this service WILL disable the existing NixOS
-            firewall! Default firewall rules provided by packages are not
-            considered at the moment.
-            </para>
-          </warning>
+
+          ::: {.warning}
+          Enabling this service WILL disable the existing NixOS
+          firewall! Default firewall rules provided by packages are not
+          considered at the moment.
+          :::
         '';
       };
       package = lib.mkOption {
         type        = types.package;
         default     = pkgs.shorewall;
         defaultText = lib.literalExpression "pkgs.shorewall";
-        description = "The shorewall package to use.";
+        description = lib.mdDoc "The shorewall package to use.";
       };
       configs = lib.mkOption {
         type        = types.attrsOf types.lines;
         default     = {};
-        description = ''
+        description = lib.mdDoc ''
           This option defines the Shorewall configs.
           The attribute name defines the name of the config,
           and the attribute value defines the content of the config.
diff --git a/nixos/modules/services/networking/shorewall6.nix b/nixos/modules/services/networking/shorewall6.nix
index 4235c74a3f8..e54be290bfb 100644
--- a/nixos/modules/services/networking/shorewall6.nix
+++ b/nixos/modules/services/networking/shorewall6.nix
@@ -8,27 +8,26 @@ in {
       enable = lib.mkOption {
         type        = types.bool;
         default     = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Shorewall IPv6 Firewall.
-          <warning>
-            <para>
-            Enabling this service WILL disable the existing NixOS
-            firewall! Default firewall rules provided by packages are not
-            considered at the moment.
-            </para>
-          </warning>
+
+          ::: {.warning}
+          Enabling this service WILL disable the existing NixOS
+          firewall! Default firewall rules provided by packages are not
+          considered at the moment.
+          :::
         '';
       };
       package = lib.mkOption {
         type        = types.package;
         default     = pkgs.shorewall;
         defaultText = lib.literalExpression "pkgs.shorewall";
-        description = "The shorewall package to use.";
+        description = lib.mdDoc "The shorewall package to use.";
       };
       configs = lib.mkOption {
         type        = types.attrsOf types.lines;
         default     = {};
-        description = ''
+        description = lib.mdDoc ''
           This option defines the Shorewall configs.
           The attribute name defines the name of the config,
           and the attribute value defines the content of the config.
diff --git a/nixos/modules/services/networking/shout.nix b/nixos/modules/services/networking/shout.nix
index cca03a8f88a..0b1687d44d9 100644
--- a/nixos/modules/services/networking/shout.nix
+++ b/nixos/modules/services/networking/shout.nix
@@ -23,37 +23,37 @@ let
 
 in {
   options.services.shout = {
-    enable = mkEnableOption "Shout web IRC client";
+    enable = mkEnableOption (lib.mdDoc "Shout web IRC client");
 
     private = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Make your shout instance private. You will need to configure user
-        accounts by adding entries in <filename>${shoutHome}/users</filename>.
+        accounts by adding entries in {file}`${shoutHome}/users`.
       '';
     };
 
     listenAddress = mkOption {
       type = types.str;
       default = "0.0.0.0";
-      description = "IP interface to listen on for http connections.";
+      description = lib.mdDoc "IP interface to listen on for http connections.";
     };
 
     port = mkOption {
       type = types.port;
       default = 9000;
-      description = "TCP port to listen on for http connections.";
+      description = lib.mdDoc "TCP port to listen on for http connections.";
     };
 
     configFile = mkOption {
       type = types.nullOr types.lines;
       default = null;
-      description = ''
-        Contents of Shout's <filename>config.js</filename> file.
+      description = lib.mdDoc ''
+        Contents of Shout's {file}`config.js` file.
 
         Used for backward compatibility, recommended way is now to use
-        the <literal>config</literal> option.
+        the `config` option.
 
         Documentation: http://shout-irc.com/docs/server/configuration.html
       '';
@@ -70,8 +70,8 @@ in {
           port = 6697;
         };
       };
-      description = ''
-        Shout <filename>config.js</filename> contents as attribute set (will be
+      description = lib.mdDoc ''
+        Shout {file}`config.js` contents as attribute set (will be
         converted to JSON to generate the configuration file).
 
         The options defined here will be merged to the default configuration file.
diff --git a/nixos/modules/services/networking/skydns.nix b/nixos/modules/services/networking/skydns.nix
index dea60a3862a..84cf6b0deac 100644
--- a/nixos/modules/services/networking/skydns.nix
+++ b/nixos/modules/services/networking/skydns.nix
@@ -7,51 +7,51 @@ let
 
 in {
   options.services.skydns = {
-    enable = mkEnableOption "skydns service";
+    enable = mkEnableOption (lib.mdDoc "skydns service");
 
     etcd = {
       machines = mkOption {
         default = [ "http://127.0.0.1:2379" ];
         type = types.listOf types.str;
-        description = "Skydns list of etcd endpoints to connect to.";
+        description = lib.mdDoc "Skydns list of etcd endpoints to connect to.";
       };
 
       tlsKey = mkOption {
         default = null;
         type = types.nullOr types.path;
-        description = "Skydns path of TLS client certificate - private key.";
+        description = lib.mdDoc "Skydns path of TLS client certificate - private key.";
       };
 
       tlsPem = mkOption {
         default = null;
         type = types.nullOr types.path;
-        description = "Skydns path of TLS client certificate - public key.";
+        description = lib.mdDoc "Skydns path of TLS client certificate - public key.";
       };
 
       caCert = mkOption {
         default = null;
         type = types.nullOr types.path;
-        description = "Skydns path of TLS certificate authority public key.";
+        description = lib.mdDoc "Skydns path of TLS certificate authority public key.";
       };
     };
 
     address = mkOption {
       default = "0.0.0.0:53";
       type = types.str;
-      description = "Skydns address to bind to.";
+      description = lib.mdDoc "Skydns address to bind to.";
     };
 
     domain = mkOption {
       default = "skydns.local.";
       type = types.str;
-      description = "Skydns default domain if not specified by etcd config.";
+      description = lib.mdDoc "Skydns default domain if not specified by etcd config.";
     };
 
     nameservers = mkOption {
       default = map (n: n + ":53") config.networking.nameservers;
       defaultText = literalExpression ''map (n: n + ":53") config.networking.nameservers'';
       type = types.listOf types.str;
-      description = "Skydns list of nameservers to forward DNS requests to when not authoritative for a domain.";
+      description = lib.mdDoc "Skydns list of nameservers to forward DNS requests to when not authoritative for a domain.";
       example = ["8.8.8.8:53" "8.8.4.4:53"];
     };
 
@@ -59,13 +59,13 @@ in {
       default = pkgs.skydns;
       defaultText = literalExpression "pkgs.skydns";
       type = types.package;
-      description = "Skydns package to use.";
+      description = lib.mdDoc "Skydns package to use.";
     };
 
     extraConfig = mkOption {
       default = {};
       type = types.attrsOf types.str;
-      description = "Skydns attribute set of extra config options passed as environment variables.";
+      description = lib.mdDoc "Skydns attribute set of extra config options passed as environment variables.";
     };
   };
 
diff --git a/nixos/modules/services/networking/smartdns.nix b/nixos/modules/services/networking/smartdns.nix
index 7f9df42ce9c..af8ee8b00c0 100644
--- a/nixos/modules/services/networking/smartdns.nix
+++ b/nixos/modules/services/networking/smartdns.nix
@@ -20,12 +20,12 @@ let
     } cfg.settings);
 in {
   options.services.smartdns = {
-    enable = mkEnableOption "SmartDNS DNS server";
+    enable = mkEnableOption (lib.mdDoc "SmartDNS DNS server");
 
     bindPort = mkOption {
       type = types.port;
       default = 53;
-      description = "DNS listening port number.";
+      description = lib.mdDoc "DNS listening port number.";
     };
 
     settings = mkOption {
@@ -42,9 +42,9 @@ in {
           speed-check-mode = "ping,tcp:80";
         };
       '';
-      description = ''
-        A set that will be generated into configuration file, see the <link xlink:href="https://github.com/pymumu/smartdns/blob/master/ReadMe_en.md#configuration-parameter">SmartDNS README</link> for details of configuration parameters.
-        You could override the options here like <option>services.smartdns.bindPort</option> by writing <literal>settings.bind = ":5353 -no-rule -group example";</literal>.
+      description = lib.mdDoc ''
+        A set that will be generated into configuration file, see the [SmartDNS README](https://github.com/pymumu/smartdns/blob/master/ReadMe_en.md#configuration-parameter) for details of configuration parameters.
+        You could override the options here like {option}`services.smartdns.bindPort` by writing `settings.bind = ":5353 -no-rule -group example";`.
       '';
     };
   };
diff --git a/nixos/modules/services/networking/smokeping.nix b/nixos/modules/services/networking/smokeping.nix
index bd71b158dbe..2e67f8b77c0 100644
--- a/nixos/modules/services/networking/smokeping.nix
+++ b/nixos/modules/services/networking/smokeping.nix
@@ -49,11 +49,8 @@ in
 {
   options = {
     services.smokeping = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Enable the smokeping service";
-      };
+      enable = mkEnableOption (lib.mdDoc "smokeping service");
+
       alertConfig = mkOption {
         type = types.lines;
         default = ''
@@ -70,20 +67,22 @@ in
           pattern = >0%,*12*,>0%,*12*,>0%
           comment = loss 3 times  in a row;
         '';
-        description = "Configuration for alerts.";
+        description = lib.mdDoc "Configuration for alerts.";
       };
       cgiUrl = mkOption {
         type = types.str;
         default = "http://${cfg.hostName}:${toString cfg.port}/smokeping.cgi";
         defaultText = literalExpression ''"http://''${hostName}:''${toString port}/smokeping.cgi"'';
         example = "https://somewhere.example.com/smokeping.cgi";
-        description = "URL to the smokeping cgi.";
+        description = lib.mdDoc "URL to the smokeping cgi.";
       };
       config = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = "Full smokeping config supplied by the user. Overrides " +
-          "and replaces any other configuration supplied.";
+        description = lib.mdDoc ''
+          Full smokeping config supplied by the user. Overrides
+          and replaces any other configuration supplied.
+        '';
       };
       databaseConfig = mkOption {
         type = types.lines;
@@ -113,28 +112,28 @@ in
               MAX  0.5 144   7200
               MIN  0.5 144   7200
         '';
-        description = ''Configure the ping frequency and retention of the rrd files.
+        description = lib.mdDoc ''Configure the ping frequency and retention of the rrd files.
           Once set, changing the interval will require deletion or migration of all
           the collected data.'';
       };
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Any additional customization not already included.";
+        description = lib.mdDoc "Any additional customization not already included.";
       };
       hostName = mkOption {
         type = types.str;
         default = config.networking.fqdn;
         defaultText = literalExpression "config.networking.fqdn";
         example = "somewhere.example.com";
-        description = "DNS name for the urls generated in the cgi.";
+        description = lib.mdDoc "DNS name for the urls generated in the cgi.";
       };
       imgUrl = mkOption {
         type = types.str;
         default = "cache";
         defaultText = literalExpression ''"cache"'';
         example = "https://somewhere.example.com/cache";
-        description = ''
+        description = lib.mdDoc ''
           Base url for images generated in the cgi.
 
           The default is a relative URL to ensure it works also when e.g. forwarding
@@ -145,48 +144,48 @@ in
         type = types.enum ["original" "absolute" "relative"];
         default = "relative";
         example = "absolute";
-        description = "DNS name for the urls generated in the cgi.";
+        description = lib.mdDoc "DNS name for the urls generated in the cgi.";
       };
       mailHost = mkOption {
         type = types.str;
         default = "";
         example = "localhost";
-        description = "Use this SMTP server to send alerts";
+        description = lib.mdDoc "Use this SMTP server to send alerts";
       };
       owner = mkOption {
         type = types.str;
         default = "nobody";
-        example = "Joe Admin";
-        description = "Real name of the owner of the instance";
+        example = "Bob Foobawr";
+        description = lib.mdDoc "Real name of the owner of the instance";
       };
       ownerEmail = mkOption {
         type = types.str;
         default = "no-reply@${cfg.hostName}";
         defaultText = literalExpression ''"no-reply@''${hostName}"'';
         example = "no-reply@yourdomain.com";
-        description = "Email contact for owner";
+        description = lib.mdDoc "Email contact for owner";
       };
       package = mkOption {
         type = types.package;
         default = pkgs.smokeping;
         defaultText = literalExpression "pkgs.smokeping";
-        description = "Specify a custom smokeping package";
+        description = lib.mdDoc "Specify a custom smokeping package";
       };
       host = mkOption {
         type = types.nullOr types.str;
         default = "localhost";
         example = "192.0.2.1"; # rfc5737 example IP for documentation
-        description = ''
+        description = lib.mdDoc ''
           Host/IP to bind to for the web server.
 
-          Setting it to <literal>null</literal> skips passing the -h option to thttpd,
+          Setting it to `null` skips passing the -h option to thttpd,
           which makes it bind to all interfaces.
         '';
       };
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8081;
-        description = "TCP port to use for the web server.";
+        description = lib.mdDoc "TCP port to use for the web server.";
       };
       presentationConfig = mkOption {
         type = types.lines;
@@ -227,13 +226,13 @@ in
           "Last 10 Days"    10d
           "Last 360 Days"   360d
         '';
-        description = "presentation graph style";
+        description = lib.mdDoc "presentation graph style";
       };
       presentationTemplate = mkOption {
         type = types.str;
         default = "${pkgs.smokeping}/etc/basepage.html.dist";
         defaultText = literalExpression ''"''${pkgs.smokeping}/etc/basepage.html.dist"'';
-        description = "Default page layout for the web UI.";
+        description = lib.mdDoc "Default page layout for the web UI.";
       };
       probeConfig = mkOption {
         type = types.lines;
@@ -247,19 +246,19 @@ in
             binary = ''${config.security.wrapperDir}/fping
           '''
         '';
-        description = "Probe configuration";
+        description = lib.mdDoc "Probe configuration";
       };
       sendmail = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/run/wrappers/bin/sendmail";
-        description = "Use this sendmail compatible script to deliver alerts";
+        description = lib.mdDoc "Use this sendmail compatible script to deliver alerts";
       };
       smokeMailTemplate = mkOption {
         type = types.str;
         default = "${cfg.package}/etc/smokemail.dist";
         defaultText = literalExpression ''"''${package}/etc/smokemail.dist"'';
-        description = "Specify the smokemail template for alerts.";
+        description = lib.mdDoc "Specify the smokemail template for alerts.";
       };
       targetConfig = mkOption {
         type = types.lines;
@@ -277,17 +276,17 @@ in
           title = This host
           host = localhost
         '';
-        description = "Target configuration";
+        description = lib.mdDoc "Target configuration";
       };
       user = mkOption {
         type = types.str;
         default = "smokeping";
-        description = "User that runs smokeping and (optionally) thttpd. A group of the same name will be created as well.";
+        description = lib.mdDoc "User that runs smokeping and (optionally) thttpd. A group of the same name will be created as well.";
       };
       webService = mkOption {
         type = types.bool;
         default = true;
-        description = "Enable a smokeping web interface";
+        description = lib.mdDoc "Enable a smokeping web interface";
       };
     };
 
@@ -316,6 +315,17 @@ in
       description = "smokeping daemon user";
       home = smokepingHome;
       createHome = true;
+      # When `cfg.webService` is enabled, `thttpd` makes SmokePing available
+      # under `${cfg.host}:${cfg.port}/smokeping.fcgi` as per the `ln -s` below.
+      # We also want that going to `${cfg.host}:${cfg.port}` without `smokeping.fcgi`
+      # makes it easy for the user to find SmokePing.
+      # However `thttpd` does not seem to support easy redirections from `/` to `smokeping.fcgi`
+      # and only allows directory listings or `/` -> `index.html` resolution if the directory
+      # has `chmod 755` (see https://acme.com/software/thttpd/thttpd_man.html#PERMISSIONS,
+      # " directories should be 755 if you want to allow indexing").
+      # Otherwise it shows `403 Forbidden` on `/`.
+      # Thus, we need to make `smokepingHome` (which is given to `thttpd -d` below) `755`.
+      homeMode = "755";
     };
     users.groups.${cfg.user} = {};
     systemd.services.smokeping = {
diff --git a/nixos/modules/services/networking/sniproxy.nix b/nixos/modules/services/networking/sniproxy.nix
index adca5398e4a..b805b7b44d7 100644
--- a/nixos/modules/services/networking/sniproxy.nix
+++ b/nixos/modules/services/networking/sniproxy.nix
@@ -18,24 +18,24 @@ in
 
   options = {
     services.sniproxy = {
-      enable = mkEnableOption "sniproxy server";
+      enable = mkEnableOption (lib.mdDoc "sniproxy server");
 
       user = mkOption {
         type = types.str;
         default = "sniproxy";
-        description = "User account under which sniproxy runs.";
+        description = lib.mdDoc "User account under which sniproxy runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "sniproxy";
-        description = "Group under which sniproxy runs.";
+        description = lib.mdDoc "Group under which sniproxy runs.";
       };
 
       config = mkOption {
         type = types.lines;
         default = "";
-        description = "sniproxy.conf configuration excluding the daemon username and pid file.";
+        description = lib.mdDoc "sniproxy.conf configuration excluding the daemon username and pid file.";
         example = ''
           error_log {
             filename /var/log/sniproxy/error.log
diff --git a/nixos/modules/services/networking/snowflake-proxy.nix b/nixos/modules/services/networking/snowflake-proxy.nix
index 2124644ed9b..ca015ed9d44 100644
--- a/nixos/modules/services/networking/snowflake-proxy.nix
+++ b/nixos/modules/services/networking/snowflake-proxy.nix
@@ -8,28 +8,28 @@ in
 {
   options = {
     services.snowflake-proxy = {
-      enable = mkEnableOption "System to defeat internet censorship";
+      enable = mkEnableOption (lib.mdDoc "System to defeat internet censorship");
 
       broker = mkOption {
-        description = "Broker URL (default \"https://snowflake-broker.torproject.net/\")";
+        description = lib.mdDoc "Broker URL (default \"https://snowflake-broker.torproject.net/\")";
         type = with types; nullOr str;
         default = null;
       };
 
       capacity = mkOption {
-        description = "Limits the amount of maximum concurrent clients allowed.";
+        description = lib.mdDoc "Limits the amount of maximum concurrent clients allowed.";
         type = with types; nullOr int;
         default = null;
       };
 
       relay = mkOption {
-        description = "websocket relay URL (default \"wss://snowflake.bamsoftware.com/\")";
+        description = lib.mdDoc "websocket relay URL (default \"wss://snowflake.bamsoftware.com/\")";
         type = with types; nullOr str;
         default = null;
       };
 
       stun = mkOption {
-        description = "STUN broker URL (default \"stun:stun.stunprotocol.org:3478\")";
+        description = lib.mdDoc "STUN broker URL (default \"stun:stun.stunprotocol.org:3478\")";
         type = with types; nullOr str;
         default = null;
       };
@@ -71,7 +71,7 @@ in
         RestrictNamespaces = true;
         RestrictRealtime = true;
         SystemCallArchitectures = "native";
-        SystemCallFilter = "~@clock @cpu-emulation @debug @mount @obsolete @reboot @swap @privileged @resources";
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
         UMask = "0077";
       };
     };
diff --git a/nixos/modules/services/networking/softether.nix b/nixos/modules/services/networking/softether.nix
index 5405f56871e..c8e888eafcc 100644
--- a/nixos/modules/services/networking/softether.nix
+++ b/nixos/modules/services/networking/softether.nix
@@ -5,7 +5,7 @@ with lib;
 let
   cfg = config.services.softether;
 
-  package = cfg.package.override { dataDir = cfg.dataDir; };
+  package = cfg.package.override { inherit (cfg) dataDir; };
 
 in
 {
@@ -16,34 +16,34 @@ in
 
     services.softether = {
 
-      enable = mkEnableOption "SoftEther VPN services";
+      enable = mkEnableOption (lib.mdDoc "SoftEther VPN services");
 
       package = mkOption {
         type = types.package;
         default = pkgs.softether;
         defaultText = literalExpression "pkgs.softether";
-        description = ''
+        description = lib.mdDoc ''
           softether derivation to use.
         '';
       };
 
-      vpnserver.enable = mkEnableOption "SoftEther VPN Server";
+      vpnserver.enable = mkEnableOption (lib.mdDoc "SoftEther VPN Server");
 
-      vpnbridge.enable = mkEnableOption "SoftEther VPN Bridge";
+      vpnbridge.enable = mkEnableOption (lib.mdDoc "SoftEther VPN Bridge");
 
       vpnclient = {
-        enable = mkEnableOption "SoftEther VPN Client";
+        enable = mkEnableOption (lib.mdDoc "SoftEther VPN Client");
         up = mkOption {
           type = types.lines;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Shell commands executed when the Virtual Network Adapter(s) is/are starting.
           '';
         };
         down = mkOption {
           type = types.lines;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Shell commands executed when the Virtual Network Adapter(s) is/are shutting down.
           '';
         };
@@ -52,7 +52,7 @@ in
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/softether";
-        description = ''
+        description = lib.mdDoc ''
           Data directory for SoftEther VPN.
         '';
       };
@@ -88,7 +88,7 @@ in
       };
     }
 
-    (mkIf (cfg.vpnserver.enable) {
+    (mkIf cfg.vpnserver.enable {
       systemd.services.vpnserver = {
         description = "SoftEther VPN Server";
         after = [ "softether-init.service" ];
@@ -109,7 +109,7 @@ in
       };
     })
 
-    (mkIf (cfg.vpnbridge.enable) {
+    (mkIf cfg.vpnbridge.enable {
       systemd.services.vpnbridge = {
         description = "SoftEther VPN Bridge";
         after = [ "softether-init.service" ];
@@ -130,7 +130,7 @@ in
       };
     })
 
-    (mkIf (cfg.vpnclient.enable) {
+    (mkIf cfg.vpnclient.enable {
       systemd.services.vpnclient = {
         description = "SoftEther VPN Client";
         after = [ "softether-init.service" ];
diff --git a/nixos/modules/services/networking/soju.nix b/nixos/modules/services/networking/soju.nix
index cb0acf4765f..d4c4ca47bc8 100644
--- a/nixos/modules/services/networking/soju.nix
+++ b/nixos/modules/services/networking/soju.nix
@@ -27,16 +27,15 @@ in
   ###### interface
 
   options.services.soju = {
-    enable = mkEnableOption "soju";
+    enable = mkEnableOption (lib.mdDoc "soju");
 
     listen = mkOption {
       type = types.listOf types.str;
       default = [ ":6697" ];
-      description = ''
+      description = lib.mdDoc ''
         Where soju should listen for incoming connections. See the
-        <literal>listen</literal> directive in
-        <citerefentry><refentrytitle>soju</refentrytitle>
-        <manvolnum>1</manvolnum></citerefentry>.
+        `listen` directive in
+        {manpage}`soju(1)`.
       '';
     };
 
@@ -44,42 +43,43 @@ in
       type = types.str;
       default = config.networking.hostName;
       defaultText = literalExpression "config.networking.hostName";
-      description = "Server hostname.";
+      description = lib.mdDoc "Server hostname.";
     };
 
     tlsCertificate = mkOption {
       type = types.nullOr types.path;
+      default = null;
       example = "/var/host.cert";
-      description = "Path to server TLS certificate.";
+      description = lib.mdDoc "Path to server TLS certificate.";
     };
 
     tlsCertificateKey = mkOption {
       type = types.nullOr types.path;
+      default = null;
       example = "/var/host.key";
-      description = "Path to server TLS certificate key.";
+      description = lib.mdDoc "Path to server TLS certificate key.";
     };
 
     enableMessageLogging = mkOption {
       type = types.bool;
       default = true;
-      description = "Whether to enable message logging.";
+      description = lib.mdDoc "Whether to enable message logging.";
     };
 
     httpOrigins = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         List of allowed HTTP origins for WebSocket listeners. The parameters are
         interpreted as shell patterns, see
-        <citerefentry><refentrytitle>glob</refentrytitle>
-        <manvolnum>7</manvolnum></citerefentry>.
+        {manpage}`glob(7)`.
       '';
     };
 
     acceptProxyIP = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Allow the specified IPs to act as a proxy. Proxys have the ability to
         overwrite the remote and local connection addresses (via the X-Forwarded-\*
         HTTP header fields). The special name "localhost" accepts the loopback
@@ -90,13 +90,23 @@ in
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = "Lines added verbatim to the configuration file.";
+      description = lib.mdDoc "Lines added verbatim to the configuration file.";
     };
   };
 
   ###### implementation
 
   config = mkIf cfg.enable {
+    assertions = [
+      {
+        assertion = (cfg.tlsCertificate != null) == (cfg.tlsCertificateKey != null);
+        message = ''
+          services.soju.tlsCertificate and services.soju.tlsCertificateKey
+          must both be specified to enable TLS.
+        '';
+      }
+    ];
+
     systemd.services.soju = {
       description = "soju IRC bouncer";
       wantedBy = [ "multi-user.target" ];
diff --git a/nixos/modules/services/networking/solanum.nix b/nixos/modules/services/networking/solanum.nix
index dc066a24549..07a37279fec 100644
--- a/nixos/modules/services/networking/solanum.nix
+++ b/nixos/modules/services/networking/solanum.nix
@@ -16,7 +16,7 @@ in
 
     services.solanum = {
 
-      enable = mkEnableOption "Solanum IRC daemon";
+      enable = mkEnableOption (lib.mdDoc "Solanum IRC daemon");
 
       config = mkOption {
         type = types.str;
@@ -44,16 +44,16 @@ in
             default_split_user_count = 0;
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Solanum IRC daemon configuration file.
-          check <link xlink:href="https://github.com/solanum-ircd/solanum/blob/main/doc/reference.conf"/> for all options.
+          check <https://github.com/solanum-ircd/solanum/blob/main/doc/reference.conf> for all options.
         '';
       };
 
       openFilesLimit = mkOption {
         type = types.int;
         default = 1024;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of open files. Limits the clients and server connections.
         '';
       };
@@ -61,10 +61,10 @@ in
       motd = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Solanum MOTD text.
 
-          Solanum will read its MOTD from <literal>/etc/solanum/ircd.motd</literal>.
+          Solanum will read its MOTD from `/etc/solanum/ircd.motd`.
           If set, the value of this option will be written to this path.
         '';
       };
diff --git a/nixos/modules/services/networking/spacecookie.nix b/nixos/modules/services/networking/spacecookie.nix
index 400f3e26cc9..b2956edfcb7 100644
--- a/nixos/modules/services/networking/spacecookie.nix
+++ b/nixos/modules/services/networking/spacecookie.nix
@@ -25,14 +25,14 @@ in {
 
     services.spacecookie = {
 
-      enable = mkEnableOption "spacecookie";
+      enable = mkEnableOption (lib.mdDoc "spacecookie");
 
       package = mkOption {
         type = types.package;
         default = pkgs.spacecookie;
         defaultText = literalExpression "pkgs.spacecookie";
         example = literalExpression "pkgs.haskellPackages.spacecookie";
-        description = ''
+        description = lib.mdDoc ''
           The spacecookie derivation to use. This can be used to
           override the used package or to use another version.
         '';
@@ -41,7 +41,7 @@ in {
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to open the necessary port in the firewall for spacecookie.
         '';
       };
@@ -49,7 +49,7 @@ in {
       port = mkOption {
         type = types.port;
         default = 70;
-        description = ''
+        description = lib.mdDoc ''
           Port the gopher service should be exposed on.
         '';
       };
@@ -57,10 +57,10 @@ in {
       address = mkOption {
         type = types.str;
         default = "[::]";
-        description = ''
+        description = lib.mdDoc ''
           Address to listen on. Must be in the
-          <literal>ListenStream=</literal> syntax of
-          <link xlink:href="https://www.freedesktop.org/software/systemd/man/systemd.socket.html">systemd.socket(5)</link>.
+          `ListenStream=` syntax of
+          [systemd.socket(5)](https://www.freedesktop.org/software/systemd/man/systemd.socket.html).
         '';
       };
 
@@ -71,7 +71,7 @@ in {
           options.hostname = mkOption {
             type = types.str;
             default = "localhost";
-            description = ''
+            description = lib.mdDoc ''
               The hostname the service is reachable via. Clients
               will use this hostname for further requests after
               loading the initial gopher menu.
@@ -81,22 +81,22 @@ in {
           options.root = mkOption {
             type = types.path;
             default = "/srv/gopher";
-            description = ''
+            description = lib.mdDoc ''
               The directory spacecookie should serve via gopher.
               Files in there need to be world-readable since
               the spacecookie service file sets
-              <literal>DynamicUser=true</literal>.
+              `DynamicUser=true`.
             '';
           };
 
           options.log = {
-            enable = mkEnableOption "logging for spacecookie"
+            enable = mkEnableOption (lib.mdDoc "logging for spacecookie")
               // { default = true; example = false; };
 
             hide-ips = mkOption {
               type = types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 If enabled, spacecookie will hide personal
                 information of users like IP addresses from
                 log output.
@@ -110,7 +110,7 @@ in {
               # journald will add timestamps, so no need
               # to double up.
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 If enabled, spacecookie will not print timestamps
                 at the beginning of every log line.
               '';
@@ -123,18 +123,18 @@ in {
                 "error"
               ];
               default = "info";
-              description = ''
+              description = lib.mdDoc ''
                 Log level for the spacecookie service.
               '';
             };
           };
         };
 
-        description = ''
+        description = lib.mdDoc ''
           Settings for spacecookie. The settings set here are
           directly translated to the spacecookie JSON config
           file. See
-          <link xlink:href="https://sternenseemann.github.io/spacecookie/spacecookie.json.5.html">spacecookie.json(5)</link>
+          [spacecookie.json(5)](https://sternenseemann.github.io/spacecookie/spacecookie.json.5.html)
           for explanations of all options.
         '';
       };
diff --git a/nixos/modules/services/networking/spiped.nix b/nixos/modules/services/networking/spiped.nix
index 3c229ecfc72..3e01ace54ad 100644
--- a/nixos/modules/services/networking/spiped.nix
+++ b/nixos/modules/services/networking/spiped.nix
@@ -11,7 +11,7 @@ in
       enable = mkOption {
         type        = types.bool;
         default     = false;
-        description = "Enable the spiped service module.";
+        description = lib.mdDoc "Enable the spiped service module.";
       };
 
       config = mkOption {
@@ -21,32 +21,32 @@ in
               encrypt = mkOption {
                 type    = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Take unencrypted connections from the
-                  <literal>source</literal> socket and send encrypted
-                  connections to the <literal>target</literal> socket.
+                  `source` socket and send encrypted
+                  connections to the `target` socket.
                 '';
               };
 
               decrypt = mkOption {
                 type    = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Take encrypted connections from the
-                  <literal>source</literal> socket and send unencrypted
-                  connections to the <literal>target</literal> socket.
+                  `source` socket and send unencrypted
+                  connections to the `target` socket.
                 '';
               };
 
               source = mkOption {
                 type    = types.str;
-                description = ''
+                description = lib.mdDoc ''
                   Address on which spiped should listen for incoming
                   connections.  Must be in one of the following formats:
-                  <literal>/absolute/path/to/unix/socket</literal>,
-                  <literal>host.name:port</literal>,
-                  <literal>[ip.v4.ad.dr]:port</literal> or
-                  <literal>[ipv6::addr]:port</literal> - note that
+                  `/absolute/path/to/unix/socket`,
+                  `host.name:port`,
+                  `[ip.v4.ad.dr]:port` or
+                  `[ipv6::addr]:port` - note that
                   hostnames are resolved when spiped is launched and are
                   not re-resolved later; thus if DNS entries change
                   spiped will continue to connect to the expired
@@ -56,24 +56,24 @@ in
 
               target = mkOption {
                 type    = types.str;
-                description = "Address to which spiped should connect.";
+                description = lib.mdDoc "Address to which spiped should connect.";
               };
 
               keyfile = mkOption {
                 type    = types.path;
-                description = ''
+                description = lib.mdDoc ''
                   Name of a file containing the spiped key. As the
-                  daemon runs as the <literal>spiped</literal> user, the
+                  daemon runs as the `spiped` user, the
                   key file must be somewhere owned by that user. By
                   default, we recommend putting the keys for any spipe
-                  services in <literal>/var/lib/spiped</literal>.
+                  services in `/var/lib/spiped`.
                 '';
               };
 
               timeout = mkOption {
                 type = types.int;
                 default = 5;
-                description = ''
+                description = lib.mdDoc ''
                   Timeout, in seconds, after which an attempt to connect to
                   the target or a protocol handshake will be aborted (and the
                   connection dropped) if not completed
@@ -83,7 +83,7 @@ in
               maxConns = mkOption {
                 type = types.int;
                 default = 100;
-                description = ''
+                description = lib.mdDoc ''
                   Limit on the number of simultaneous connections allowed.
                 '';
               };
@@ -91,14 +91,14 @@ in
               waitForDNS = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
-                  Wait for DNS. Normally when <literal>spiped</literal> is
+                description = lib.mdDoc ''
+                  Wait for DNS. Normally when `spiped` is
                   launched it resolves addresses and binds to its source
                   socket before the parent process returns; with this option
                   it will daemonize first and retry failed DNS lookups until
-                  they succeed. This allows <literal>spiped</literal> to
+                  they succeed. This allows `spiped` to
                   launch even if DNS isn't set up yet, but at the expense of
-                  losing the guarantee that once <literal>spiped</literal> has
+                  losing the guarantee that once `spiped` has
                   finished launching it will be ready to create pipes.
                 '';
               };
@@ -106,13 +106,13 @@ in
               disableKeepalives = mkOption {
                 type = types.bool;
                 default = false;
-                description = "Disable transport layer keep-alives.";
+                description = lib.mdDoc "Disable transport layer keep-alives.";
               };
 
               weakHandshake = mkOption {
                 type = types.bool;
                 default = false;
-                description = ''
+                description = lib.mdDoc ''
                   Use fast/weak handshaking: This reduces the CPU time spent
                   in the initial connection setup, at the expense of losing
                   perfect forward secrecy.
@@ -122,7 +122,7 @@ in
               resolveRefresh = mkOption {
                 type = types.int;
                 default = 60;
-                description = ''
+                description = lib.mdDoc ''
                   Resolution refresh time for the target socket, in seconds.
                 '';
               };
@@ -130,7 +130,7 @@ in
               disableReresolution = mkOption {
                 type = types.bool;
                 default = false;
-                description = "Disable target address re-resolution.";
+                description = lib.mdDoc "Disable target address re-resolution.";
               };
             };
           }
@@ -155,11 +155,11 @@ in
           }
         '';
 
-        description = ''
+        description = lib.mdDoc ''
           Configuration for a secure pipe daemon. The daemon can be
           started, stopped, or examined using
-          <literal>systemctl</literal>, under the name
-          <literal>spiped@foo</literal>.
+          `systemctl`, under the name
+          `spiped@foo`.
         '';
       };
     };
diff --git a/nixos/modules/services/networking/squid.nix b/nixos/modules/services/networking/squid.nix
index db4f0d26b6f..914cd7f320c 100644
--- a/nixos/modules/services/networking/squid.nix
+++ b/nixos/modules/services/networking/squid.nix
@@ -108,32 +108,32 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to run squid web proxy.";
+        description = lib.mdDoc "Whether to run squid web proxy.";
       };
 
       package = mkOption {
         default = pkgs.squid;
         defaultText = literalExpression "pkgs.squid";
         type = types.package;
-        description = "Squid package to use.";
+        description = lib.mdDoc "Squid package to use.";
       };
 
       proxyAddress = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "IP address on which squid will listen.";
+        description = lib.mdDoc "IP address on which squid will listen.";
       };
 
       proxyPort = mkOption {
         type = types.int;
         default = 3128;
-        description = "TCP port on which squid will listen.";
+        description = lib.mdDoc "TCP port on which squid will listen.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Squid configuration. Contents will be added
           verbatim to the configuration file.
         '';
@@ -142,7 +142,7 @@ in
       configText = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Verbatim contents of squid.conf. If null (default), use the
           autogenerated file from NixOS instead.
         '';
diff --git a/nixos/modules/services/networking/ssh/lshd.nix b/nixos/modules/services/networking/ssh/lshd.nix
index 862ff7df054..41c4ec2d295 100644
--- a/nixos/modules/services/networking/ssh/lshd.nix
+++ b/nixos/modules/services/networking/ssh/lshd.nix
@@ -21,7 +21,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the GNU lshd SSH2 daemon, which allows
           secure remote login.
         '';
@@ -30,7 +30,7 @@ in
       portNumber = mkOption {
         default = 22;
         type = types.port;
-        description = ''
+        description = lib.mdDoc ''
           The port on which to listen for connections.
         '';
       };
@@ -38,7 +38,7 @@ in
       interfaces = mkOption {
         default = [];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           List of network interfaces where listening for connections.
           When providing the empty list, `[]', lshd listens on all
           network interfaces.
@@ -49,7 +49,7 @@ in
       hostKey = mkOption {
         default = "/etc/lsh/host-key";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Path to the server's private key.  Note that this key must
           have been created, e.g., using "lsh-keygen --server |
           lsh-writekey --server", so that you can run lshd.
@@ -59,31 +59,31 @@ in
       syslog = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable syslog output.";
+        description = lib.mdDoc "Whether to enable syslog output.";
       };
 
       passwordAuthentication = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable password authentication.";
+        description = lib.mdDoc "Whether to enable password authentication.";
       };
 
       publicKeyAuthentication = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable public key authentication.";
+        description = lib.mdDoc "Whether to enable public key authentication.";
       };
 
       rootLogin = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable remote root login.";
+        description = lib.mdDoc "Whether to enable remote root login.";
       };
 
       loginShell = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           If non-null, override the default login shell with the
           specified value.
         '';
@@ -93,7 +93,7 @@ in
       srpKeyExchange = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable SRP key exchange and user authentication.
         '';
       };
@@ -101,18 +101,18 @@ in
       tcpForwarding = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable TCP/IP forwarding.";
+        description = lib.mdDoc "Whether to enable TCP/IP forwarding.";
       };
 
       x11Forwarding = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable X11 forwarding.";
+        description = lib.mdDoc "Whether to enable X11 forwarding.";
       };
 
       subsystems = mkOption {
         type = types.listOf types.path;
-        description = ''
+        description = lib.mdDoc ''
           List of subsystem-path pairs, where the head of the pair
           denotes the subsystem name, and the tail denotes the path to
           an executable implementing it.
diff --git a/nixos/modules/services/networking/ssh/sshd.nix b/nixos/modules/services/networking/ssh/sshd.nix
index 230ab673a97..af8200c7e29 100644
--- a/nixos/modules/services/networking/ssh/sshd.nix
+++ b/nixos/modules/services/networking/ssh/sshd.nix
@@ -32,13 +32,13 @@ let
       keys = mkOption {
         type = types.listOf types.singleLineStr;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of verbatim OpenSSH public keys that should be added to the
           user's authorized keys. The keys are added to a file that the SSH
           daemon reads in addition to the the user's authorized_keys file.
-          You can combine the <literal>keys</literal> and
-          <literal>keyFiles</literal> options.
-          Warning: If you are using <literal>NixOps</literal> then don't use this
+          You can combine the `keys` and
+          `keyFiles` options.
+          Warning: If you are using `NixOps` then don't use this
           option since it will replace the key required for deployment via ssh.
         '';
         example = [
@@ -50,12 +50,12 @@ let
       keyFiles = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of files each containing one OpenSSH public key that should be
           added to the user's authorized keys. The contents of the files are
           read at build time and added to a file that the SSH daemon reads in
           addition to the the user's authorized_keys file. You can combine the
-          <literal>keyFiles</literal> and <literal>keys</literal> options.
+          `keyFiles` and `keys` options.
         '';
       };
     };
@@ -93,7 +93,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the OpenSSH secure shell daemon, which
           allows secure remote logins.
         '';
@@ -102,8 +102,8 @@ in
       startWhenNeeded = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          If set, <command>sshd</command> is socket-activated; that
+        description = lib.mdDoc ''
+          If set, {command}`sshd` is socket-activated; that
           is, instead of having it permanently running as a daemon,
           systemd will start an instance for each incoming connection.
         '';
@@ -112,7 +112,7 @@ in
       forwardX11 = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to allow X11 connections to be forwarded.
         '';
       };
@@ -120,17 +120,17 @@ in
       allowSFTP = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the SFTP subsystem in the SSH daemon.  This
-          enables the use of commands such as <command>sftp</command> and
-          <command>sshfs</command>.
+          enables the use of commands such as {command}`sftp` and
+          {command}`sshfs`.
         '';
       };
 
       sftpServerExecutable = mkOption {
         type = types.str;
         example = "internal-sftp";
-        description = ''
+        description = lib.mdDoc ''
           The sftp server executable.  Can be a path or "internal-sftp" to use
           the sftp server built into the sshd binary.
         '';
@@ -140,7 +140,7 @@ in
         type = with types; listOf str;
         default = [];
         example = [ "-f AUTHPRIV" "-l INFO" ];
-        description = ''
+        description = lib.mdDoc ''
           Commandline flags to add to sftp-server.
         '';
       };
@@ -148,7 +148,7 @@ in
       permitRootLogin = mkOption {
         default = "prohibit-password";
         type = types.enum ["yes" "without-password" "prohibit-password" "forced-commands-only" "no"];
-        description = ''
+        description = lib.mdDoc ''
           Whether the root user can login using ssh.
         '';
       };
@@ -156,18 +156,17 @@ in
       gatewayPorts = mkOption {
         type = types.str;
         default = "no";
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether remote hosts are allowed to connect to
           ports forwarded for the client.  See
-          <citerefentry><refentrytitle>sshd_config</refentrytitle>
-          <manvolnum>5</manvolnum></citerefentry>.
+          {manpage}`sshd_config(5)`.
         '';
       };
 
       ports = mkOption {
         type = types.listOf types.port;
         default = [22];
-        description = ''
+        description = lib.mdDoc ''
           Specifies on which ports the SSH daemon listens.
         '';
       };
@@ -175,7 +174,7 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to automatically open the specified ports in the firewall.
         '';
       };
@@ -186,14 +185,14 @@ in
             addr = mkOption {
               type = types.nullOr types.str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Host, IPv4 or IPv6 address to listen to.
               '';
             };
             port = mkOption {
               type = types.nullOr types.int;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Port to listen to.
               '';
             };
@@ -201,10 +200,10 @@ in
         });
         default = [];
         example = [ { addr = "192.168.3.1"; port = 22; } { addr = "0.0.0.0"; port = 64022; } ];
-        description = ''
+        description = lib.mdDoc ''
           List of addresses and ports to listen on (ListenAddress directive
           in config). If port is not specified for address sshd will listen
-          on all ports specified by <literal>ports</literal> option.
+          on all ports specified by `ports` option.
           NOTE: this will override default listening on all local addresses and port 22.
           NOTE: setting this option won't automatically enable given ports
           in firewall configuration.
@@ -214,7 +213,7 @@ in
       passwordAuthentication = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether password authentication is allowed.
         '';
       };
@@ -222,7 +221,7 @@ in
       kbdInteractiveAuthentication = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether keyboard-interactive authentication is allowed.
         '';
       };
@@ -237,11 +236,10 @@ in
           [ { type = "rsa"; bits = 4096; path = "/etc/ssh/ssh_host_rsa_key"; rounds = 100; openSSHFormat = true; }
             { type = "ed25519"; path = "/etc/ssh/ssh_host_ed25519_key"; rounds = 100; comment = "key comment"; }
           ];
-        description = ''
+        description = lib.mdDoc ''
           NixOS can automatically generate SSH host keys.  This option
           specifies the path, type and size of each key.  See
-          <citerefentry><refentrytitle>ssh-keygen</refentrytitle>
-          <manvolnum>1</manvolnum></citerefentry> for supported types
+          {manpage}`ssh-keygen(1)` for supported types
           and sizes.
         '';
       };
@@ -249,7 +247,7 @@ in
       banner = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Message to display to the remote user before authentication is allowed.
         '';
       };
@@ -257,12 +255,12 @@ in
       authorizedKeysFiles = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Specify the rules for which files to read on the host.
 
           This is an advanced option. If you're looking to configure user
-          keys, you can generally use <xref linkend="opt-users.users._name_.openssh.authorizedKeys.keys"/>
-          or <xref linkend="opt-users.users._name_.openssh.authorizedKeys.keyFiles"/>.
+          keys, you can generally use [](#opt-users.users._name_.openssh.authorizedKeys.keys)
+          or [](#opt-users.users._name_.openssh.authorizedKeys.keyFiles).
 
           These are paths relative to the host root file system or home
           directories and they are subject to certain token expansion rules.
@@ -273,7 +271,7 @@ in
       authorizedKeysCommand = mkOption {
         type = types.str;
         default = "none";
-        description = ''
+        description = lib.mdDoc ''
           Specifies a program to be used to look up the user's public
           keys. The program must be owned by root, not writable by group
           or others and specified by an absolute path.
@@ -283,7 +281,7 @@ in
       authorizedKeysCommandUser = mkOption {
         type = types.str;
         default = "nobody";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the user under whose account the AuthorizedKeysCommand
           is run. It is recommended to use a dedicated user that has no
           other role on the host than running authorized keys commands.
@@ -293,18 +291,18 @@ in
       kexAlgorithms = mkOption {
         type = types.listOf types.str;
         default = [
+          "sntrup761x25519-sha512@openssh.com"
           "curve25519-sha256"
           "curve25519-sha256@libssh.org"
           "diffie-hellman-group-exchange-sha256"
         ];
-        description = ''
+        description = lib.mdDoc ''
           Allowed key exchange algorithms
-          </para>
-          <para>
-          Defaults to recommended settings from both
-          <link xlink:href="https://stribika.github.io/2015/01/04/secure-secure-shell.html" />
+
+          Uses the lower bound recommended in both
+          <https://stribika.github.io/2015/01/04/secure-secure-shell.html>
           and
-          <link xlink:href="https://infosec.mozilla.org/guidelines/openssh#modern-openssh-67" />
+          <https://infosec.mozilla.org/guidelines/openssh#modern-openssh-67>
         '';
       };
 
@@ -318,14 +316,13 @@ in
           "aes192-ctr"
           "aes128-ctr"
         ];
-        description = ''
+        description = lib.mdDoc ''
           Allowed ciphers
-          </para>
-          <para>
+
           Defaults to recommended settings from both
-          <link xlink:href="https://stribika.github.io/2015/01/04/secure-secure-shell.html" />
+          <https://stribika.github.io/2015/01/04/secure-secure-shell.html>
           and
-          <link xlink:href="https://infosec.mozilla.org/guidelines/openssh#modern-openssh-67" />
+          <https://infosec.mozilla.org/guidelines/openssh#modern-openssh-67>
         '';
       };
 
@@ -339,21 +336,20 @@ in
           "hmac-sha2-256"
           "umac-128@openssh.com"
         ];
-        description = ''
+        description = lib.mdDoc ''
           Allowed MACs
-          </para>
-          <para>
+
           Defaults to recommended settings from both
-          <link xlink:href="https://stribika.github.io/2015/01/04/secure-secure-shell.html" />
+          <https://stribika.github.io/2015/01/04/secure-secure-shell.html>
           and
-          <link xlink:href="https://infosec.mozilla.org/guidelines/openssh#modern-openssh-67" />
+          <https://infosec.mozilla.org/guidelines/openssh#modern-openssh-67>
         '';
       };
 
       logLevel = mkOption {
         type = types.enum [ "QUIET" "FATAL" "ERROR" "INFO" "VERBOSE" "DEBUG" "DEBUG1" "DEBUG2" "DEBUG3" ];
         default = "INFO"; # upstream default
-        description = ''
+        description = lib.mdDoc ''
           Gives the verbosity level that is used when logging messages from sshd(8). The possible values are:
           QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1
           are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level
@@ -364,7 +360,7 @@ in
       useDns = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether sshd(8) should look up the remote host name, and to check that the resolved host name for
           the remote IP address maps back to the very same IP address.
           If this option is set to no (the default) then only addresses and not host names may be used in
@@ -375,16 +371,16 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Verbatim contents of <filename>sshd_config</filename>.";
+        description = lib.mdDoc "Verbatim contents of {file}`sshd_config`.";
       };
 
       moduliFile = mkOption {
         example = "/etc/my-local-ssh-moduli;";
         type = types.path;
-        description = ''
-          Path to <literal>moduli</literal> file to install in
-          <literal>/etc/ssh/moduli</literal>. If this option is unset, then
-          the <literal>moduli</literal> file shipped with OpenSSH will be used.
+        description = lib.mdDoc ''
+          Path to `moduli` file to install in
+          `/etc/ssh/moduli`. If this option is unset, then
+          the `moduli` file shipped with OpenSSH will be used.
         '';
       };
 
@@ -437,10 +433,12 @@ in
                 # socket activation, it goes to the remote side (#19589).
                 exec >&2
 
-                mkdir -m 0755 -p /etc/ssh
-
                 ${flip concatMapStrings cfg.hostKeys (k: ''
                   if ! [ -s "${k.path}" ]; then
+                      if ! [ -h "${k.path}" ]; then
+                          rm -f "${k.path}"
+                      fi
+                      mkdir -m 0755 -p "$(dirname '${k.path}')"
                       ssh-keygen \
                         -t "${k.type}" \
                         ${if k ? bits then "-b ${toString k.bits}" else ""} \
diff --git a/nixos/modules/services/networking/sslh.nix b/nixos/modules/services/networking/sslh.nix
index abe96f60f81..daf2f2f3668 100644
--- a/nixos/modules/services/networking/sslh.nix
+++ b/nixos/modules/services/networking/sslh.nix
@@ -43,42 +43,42 @@ in
 
   options = {
     services.sslh = {
-      enable = mkEnableOption "sslh";
+      enable = mkEnableOption (lib.mdDoc "sslh");
 
       verbose = mkOption {
         type = types.bool;
         default = false;
-        description = "Verbose logs.";
+        description = lib.mdDoc "Verbose logs.";
       };
 
       timeout = mkOption {
         type = types.int;
         default = 2;
-        description = "Timeout in seconds.";
+        description = lib.mdDoc "Timeout in seconds.";
       };
 
       transparent = mkOption {
         type = types.bool;
         default = false;
-        description = "Will the services behind sslh (Apache, sshd and so on) see the external IP and ports as if the external world connected directly to them";
+        description = lib.mdDoc "Will the services behind sslh (Apache, sshd and so on) see the external IP and ports as if the external world connected directly to them";
       };
 
       listenAddresses = mkOption {
         type = types.coercedTo types.str singleton (types.listOf types.str);
         default = [ "0.0.0.0" "[::]" ];
-        description = "Listening addresses or hostnames.";
+        description = lib.mdDoc "Listening addresses or hostnames.";
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 443;
-        description = "Listening port.";
+        description = lib.mdDoc "Listening port.";
       };
 
       appendConfig = mkOption {
         type = types.str;
         default = defaultAppendConfig;
-        description = "Verbatim configuration file.";
+        description = lib.mdDoc "Verbatim configuration file.";
       };
     };
   };
diff --git a/nixos/modules/services/networking/strongswan-swanctl/module.nix b/nixos/modules/services/networking/strongswan-swanctl/module.nix
index 9287943fcde..c51e8ad9f5f 100644
--- a/nixos/modules/services/networking/strongswan-swanctl/module.nix
+++ b/nixos/modules/services/networking/strongswan-swanctl/module.nix
@@ -8,13 +8,13 @@ let
   swanctlParams = import ./swanctl-params.nix lib;
 in  {
   options.services.strongswan-swanctl = {
-    enable = mkEnableOption "strongswan-swanctl service";
+    enable = mkEnableOption (lib.mdDoc "strongswan-swanctl service");
 
     package = mkOption {
       type = types.package;
       default = pkgs.strongswan;
       defaultText = literalExpression "pkgs.strongswan";
-      description = ''
+      description = lib.mdDoc ''
         The strongswan derivation to use.
       '';
     };
@@ -22,8 +22,8 @@ in  {
     strongswan.extraConfig = mkOption {
       type = types.str;
       default = "";
-      description = ''
-        Contents of the <literal>strongswan.conf</literal> file.
+      description = lib.mdDoc ''
+        Contents of the `strongswan.conf` file.
       '';
     };
 
diff --git a/nixos/modules/services/networking/strongswan-swanctl/param-constructors.nix b/nixos/modules/services/networking/strongswan-swanctl/param-constructors.nix
index dfdfc50d8ae..dc6d8f48e62 100644
--- a/nixos/modules/services/networking/strongswan-swanctl/param-constructors.nix
+++ b/nixos/modules/services/networking/strongswan-swanctl/param-constructors.nix
@@ -57,11 +57,12 @@ rec {
 
   documentDefault = description : strongswanDefault :
     if strongswanDefault == null
-    then description
-    else description + ''
-      </para><para>
-      StrongSwan default: <literal><![CDATA[${builtins.toJSON strongswanDefault}]]></literal>
-    '';
+    then mdDoc description
+    else mdDoc (description + ''
+
+
+      StrongSwan default: ````${builtins.toJSON strongswanDefault}````
+    '');
 
   single = f: name: value: { ${name} = f value; };
 
@@ -120,7 +121,7 @@ rec {
     option = mkOption {
       type = types.attrsOf option;
       default = {};
-      inherit description;
+      description = mdDoc description;
     };
     render = single (attrs:
       (paramsToRenderedStrings attrs
@@ -138,7 +139,7 @@ rec {
     option = mkOption {
       type = types.attrsOf option;
       default = {};
-      inherit description;
+      description = mdDoc description;
     };
     render = prefix: attrs:
       let prefixedAttrs = mapAttrs' (name: nameValuePair "${prefix}-${name}") attrs;
@@ -151,7 +152,7 @@ rec {
     option = mkOption {
       type = types.attrsOf (types.submodule {options = paramsToOptions params;});
       default = {};
-      inherit description;
+      description = lib.mdDoc description;
     };
     render = postfix: attrs:
       let postfixedAttrs = mapAttrs' (name: nameValuePair "${name}-${postfix}") attrs;
diff --git a/nixos/modules/services/networking/strongswan-swanctl/swanctl-params.nix b/nixos/modules/services/networking/strongswan-swanctl/swanctl-params.nix
index cca61b9ce93..84ac4fef26e 100644
--- a/nixos/modules/services/networking/strongswan-swanctl/swanctl-params.nix
+++ b/nixos/modules/services/networking/strongswan-swanctl/swanctl-params.nix
@@ -15,15 +15,15 @@ let
     file = mkOptionalStrParam ''
       Absolute path to the certificate to load. Passed as-is to the daemon, so
       it must be readable by it.
-      </para><para>
-      Configure either this or <option>handle</option>, but not both, in one section.
+
+      Configure either this or {option}`handle`, but not both, in one section.
     '';
 
     handle = mkOptionalHexParam ''
       Hex-encoded CKA_ID or handle of the certificate on a token or TPM,
       respectively.
-      </para><para>
-      Configure either this or <option>file</option>, but not both, in one section.
+
+      Configure either this or {option}`file`, but not both, in one section.
     '';
 
     slot = mkOptionalIntParam ''
@@ -39,11 +39,11 @@ in {
 
     cacert = mkOptionalStrParam ''
       The certificates may use a relative path from the swanctl
-      <literal>x509ca</literal> directory or an absolute path.
-      </para><para>
-      Configure one of <option>cacert</option>,
-      <option>file</option>, or
-      <option>handle</option> per section.
+      `x509ca` directory or an absolute path.
+
+      Configure one of {option}`cacert`,
+      {option}`file`, or
+      {option}`handle` per section.
     '';
 
     cert_uri_base = mkOptionalStrParam ''
@@ -71,22 +71,21 @@ in {
 
     version = mkIntParam 0 ''
       IKE major version to use for connection.
-      <itemizedlist>
-      <listitem><para>1 uses IKEv1 aka ISAKMP,</para></listitem>
-      <listitem><para>2 uses IKEv2.</para></listitem>
-      <listitem><para>A connection using the default of 0 accepts both IKEv1 and IKEv2 as
-      responder, and initiates the connection actively with IKEv2.</para></listitem>
-      </itemizedlist>
+
+      - 1 uses IKEv1 aka ISAKMP,
+      - 2 uses IKEv2.
+      - A connection using the default of 0 accepts both IKEv1 and IKEv2 as
+        responder, and initiates the connection actively with IKEv2.
     '';
 
     local_addrs	= mkCommaSepListParam [] ''
       Local address(es) to use for IKE communication. Takes
       single IPv4/IPv6 addresses, DNS names, CIDR subnets or IP address ranges.
-      </para><para>
+
       As initiator, the first non-range/non-subnet is used to initiate the
       connection from. As responder, the local destination address must match at
       least to one of the specified addresses, subnets or ranges.
-      </para><para>
+
       If FQDNs are assigned they are resolved every time a configuration lookup
       is done. If DNS resolution times out, the lookup is delayed for that time.
     '';
@@ -94,11 +93,11 @@ in {
     remote_addrs = mkCommaSepListParam [] ''
       Remote address(es) to use for IKE communication. Takes
       single IPv4/IPv6 addresses, DNS names, CIDR subnets or IP address ranges.
-      </para><para>
+
       As initiator, the first non-range/non-subnet is used to initiate the
       connection to. As responder, the initiator source address must match at
       least to one of the specified addresses, subnets or ranges.
-      </para><para>
+
       If FQDNs are assigned they are resolved every time a configuration lookup
       is done. If DNS resolution times out, the lookup is delayed for that time.
       To initiate a connection, at least one specific address or DNS name must
@@ -107,18 +106,18 @@ in {
 
     local_port = mkIntParam 500 ''
       Local UDP port for IKE communication. By default the port of the socket
-      backend is used, which is usually <literal>500</literal>. If port
-      <literal>500</literal> is used, automatic IKE port floating to port
-      <literal>4500</literal> is used to work around NAT issues.
-      </para><para>
+      backend is used, which is usually `500`. If port
+      `500` is used, automatic IKE port floating to port
+      `4500` is used to work around NAT issues.
+
       Using a non-default local IKE port requires support from the socket
       backend in use (socket-dynamic).
     '';
 
     remote_port = mkIntParam 500 ''
       Remote UDP port for IKE communication. If the default of port
-      <literal>500</literal> is used, automatic IKE port floating to port
-      <literal>4500</literal> is used to work around NAT issues.
+      `500` is used, automatic IKE port floating to port
+      `4500` is used to work around NAT issues.
     '';
 
     proposals = mkCommaSepListParam ["default"] ''
@@ -126,23 +125,23 @@ in {
       for IKE an encryption algorithm, an integrity algorithm, a pseudo random
       function and a Diffie-Hellman group. For AEAD algorithms, instead of
       encryption and integrity algorithms, a combined algorithm is used.
-      </para><para>
+
       In IKEv2, multiple algorithms of the same kind can be specified in a
       single proposal, from which one gets selected. In IKEv1, only one
       algorithm per kind is allowed per proposal, more algorithms get implicitly
       stripped. Use multiple proposals to offer different algorithms
       combinations in IKEv1.
-      </para><para>
+
       Algorithm keywords get separated using dashes. Multiple proposals may be
-      specified in a list. The special value <literal>default</literal> forms a
+      specified in a list. The special value `default` forms a
       default proposal of supported algorithms considered safe, and is usually a
       good choice for interoperability.
     '';
 
     vips = mkCommaSepListParam [] ''
       List of virtual IPs to request in IKEv2 configuration payloads or IKEv1
-      Mode Config. The wildcard addresses <literal>0.0.0.0</literal> and
-      <literal>::</literal> request an arbitrary address, specific addresses may
+      Mode Config. The wildcard addresses `0.0.0.0` and
+      `::` request an arbitrary address, specific addresses may
       be defined. The responder may return a different address, though, or none
       at all.
     '';
@@ -159,7 +158,7 @@ in {
       If the default of yes is used, Mode Config works in pull mode, where the
       initiator actively requests a virtual IP. With no, push mode is used,
       where the responder pushes down a virtual IP to the initiating peer.
-      </para><para>
+
       Push mode is currently supported for IKEv1, but not in IKEv2. It is used
       by a few implementations only, pull mode is recommended.
     '';
@@ -174,7 +173,7 @@ in {
       To enforce UDP encapsulation of ESP packets, the IKE daemon can fake the
       NAT detection payloads. This makes the peer believe that NAT takes place
       on the path, forcing it to encapsulate ESP packets in UDP.
-      </para><para>
+
       Usually this is not required, but it can help to work around connectivity
       issues with too restrictive intermediary firewalls.
     '';
@@ -183,7 +182,7 @@ in {
       Enables MOBIKE on IKEv2 connections. MOBIKE is enabled by default on IKEv2
       connections, and allows mobility of clients and multi-homing on servers by
       migrating active IPsec tunnels.
-      </para><para>
+
       Usually keeping MOBIKE enabled is unproblematic, as it is not used if the
       peer does not indicate support for it. However, due to the design of
       MOBIKE, IKEv2 always floats to port 4500 starting from the second
@@ -207,39 +206,38 @@ in {
 
     fragmentation = mkEnumParam ["yes" "accept" "force" "no"] "yes" ''
       Use IKE fragmentation (proprietary IKEv1 extension or RFC 7383 IKEv2
-      fragmentation). Acceptable values are <literal>yes</literal> (the default
-      since 5.5.1), <literal>accept</literal> (since versions:5.5.3),
-      <literal>force</literal> and <literal>no</literal>.
-      <itemizedlist>
-      <listitem><para>If set to <literal>yes</literal>, and the peer
-      supports it, oversized IKE messages will be sent in fragments.</para></listitem>
-      <listitem><para>If set to
-      <literal>accept</literal>, support for fragmentation is announced to the peer but the daemon
-      does not send its own messages in fragments.</para></listitem>
-      <listitem><para>If set to <literal>force</literal> (only
-      supported for IKEv1) the initial IKE message will already be fragmented if
-      required.</para></listitem>
-      <listitem><para>Finally, setting the option to <literal>no</literal> will disable announcing
-      support for this feature.</para></listitem>
-      </itemizedlist>
-      </para><para>
+      fragmentation). Acceptable values are `yes` (the default
+      since 5.5.1), `accept` (since versions:5.5.3),
+      `force` and `no`.
+
+      - If set to `yes`, and the peer
+        supports it, oversized IKE messages will be sent in fragments.
+      - If set to
+        `accept`, support for fragmentation is announced to the peer but the daemon
+        does not send its own messages in fragments.
+      - If set to `force` (only
+        supported for IKEv1) the initial IKE message will already be fragmented if
+        required.
+      - Finally, setting the option to `no` will disable announcing
+        support for this feature.
+
       Note that fragmented IKE messages sent by a peer are always processed
       irrespective of the value of this option (even when set to no).
     '';
 
     childless = mkEnumParam [ "allow" "force" "never" ] "allow" ''
       Use childless IKE_SA initiation (RFC 6023) for IKEv2.  Acceptable values
-      are <literal>allow</literal> (the default), <literal>force</literal> and
-      <literal>never</literal>. If set to <literal>allow</literal>, responders
+      are `allow` (the default), `force` and
+      `never`. If set to `allow`, responders
       will accept childless IKE_SAs (as indicated via notify in the IKE_SA_INIT
       response) while initiators continue to create regular IKE_SAs with the
       first CHILD_SA created during IKE_AUTH, unless the IKE_SA is initiated
       explicitly without any children (which will fail if the responder does not
       support or has disabled this extension).  If set to
-      <literal>force</literal>, only childless initiation is accepted and the
+      `force`, only childless initiation is accepted and the
       first CHILD_SA is created with a separate CREATE_CHILD_SA exchange
       (e.g. to use an independent DH exchange for all CHILD_SAs). Finally,
-      setting the option to <literal>never</literal> disables support for
+      setting the option to `never` disables support for
       childless IKE_SAs as responder.
     '';
 
@@ -254,14 +252,13 @@ in {
 
     send_cert = mkEnumParam ["always" "never" "ifasked" ] "ifasked" ''
       Send certificate payloads when using certificate authentication.
-      <itemizedlist>
-      <listitem><para>With the default of <literal>ifasked</literal> the daemon sends
-      certificate payloads only if certificate requests have been received.</para></listitem>
-      <listitem><para><literal>never</literal> disables sending of certificate payloads
-      altogether,</para></listitem>
-      <listitem><para><literal>always</literal> causes certificate payloads to be sent
-      unconditionally whenever certificate authentication is used.</para></listitem>
-      </itemizedlist>
+
+      - With the default of `ifasked` the daemon sends
+        certificate payloads only if certificate requests have been received.
+      - `never` disables sending of certificate payloads
+        altogether,
+      - `always` causes certificate payloads to be sent
+        unconditionally whenever certificate authentication is used.
     '';
 
     ppk_id = mkOptionalStrParam ''
@@ -275,42 +272,33 @@ in {
     keyingtries = mkIntParam 1 ''
       Number of retransmission sequences to perform during initial
       connect. Instead of giving up initiation after the first retransmission
-      sequence with the default value of <literal>1</literal>, additional
+      sequence with the default value of `1`, additional
       sequences may be started according to the configured value. A value of
-      <literal>0</literal> initiates a new sequence until the connection
+      `0` initiates a new sequence until the connection
       establishes or fails with a permanent error.
     '';
 
     unique = mkEnumParam ["no" "never" "keep" "replace"] "no" ''
       Connection uniqueness policy to enforce. To avoid multiple connections
       from the same user, a uniqueness policy can be enforced.
-      </para><para>
-      <itemizedlist>
-      <listitem><para>
-      The value <literal>never</literal> does never enforce such a policy, even
-      if a peer included INITIAL_CONTACT notification messages,
-      </para></listitem>
-      <listitem><para>
-      whereas <literal>no</literal> replaces existing connections for the same
-      identity if a new one has the INITIAL_CONTACT notify.
-      </para></listitem>
-      <listitem><para>
-      <literal>keep</literal> rejects new connection attempts if the same user
-      already has an active connection,
-      </para></listitem>
-      <listitem><para>
-      <literal>replace</literal> deletes any existing connection if a new one
-      for the same user gets established.
-      </para></listitem>
-      </itemizedlist>
+
+      - The value `never` does never enforce such a policy, even
+        if a peer included INITIAL_CONTACT notification messages,
+      - whereas `no` replaces existing connections for the same
+        identity if a new one has the INITIAL_CONTACT notify.
+      - `keep` rejects new connection attempts if the same user
+        already has an active connection,
+      - `replace` deletes any existing connection if a new one
+        for the same user gets established.
+
       To compare connections for uniqueness, the remote IKE identity is used. If
       EAP or XAuth authentication is involved, the EAP-Identity or XAuth
       username is used to enforce the uniqueness policy instead.
-      </para><para>
+
       On initiators this setting specifies whether an INITIAL_CONTACT notify is
       sent during IKE_AUTH if no existing connection is found with the remote
       peer (determined by the identities of the first authentication
-      round). Unless set to <literal>never</literal> the client will send a notify.
+      round). Unless set to `never` the client will send a notify.
     '';
 
     reauth_time	= mkDurationParam "0s" ''
@@ -320,7 +308,7 @@ in {
       possible to actively reauthenticate as responder. The IKEv2
       reauthentication lifetime negotiation can instruct the client to perform
       reauthentication.
-      </para><para>
+
       Reauthentication is disabled by default. Enabling it usually may lead to
       small connection interruptions, as strongSwan uses a break-before-make
       policy with IKEv2 to avoid any conflicts with associated tunnel resources.
@@ -330,7 +318,7 @@ in {
       IKE rekeying refreshes key material using a Diffie-Hellman exchange, but
       does not re-check associated credentials. It is supported in IKEv2 only,
       IKEv1 performs a reauthentication procedure instead.
-      </para><para>
+
       With the default value IKE rekeying is scheduled every 4 hours, minus the
       configured rand_time. If a reauth_time is configured, rekey_time defaults
       to zero, disabling rekeying; explicitly set both to enforce rekeying and
@@ -343,12 +331,12 @@ in {
       perpetually, a maximum hard lifetime may be specified. If the IKE_SA fails
       to rekey or reauthenticate within the specified time, the IKE_SA gets
       closed.
-      </para><para>
+
       In contrast to CHILD_SA rekeying, over_time is relative in time to the
       rekey_time and reauth_time values, as it applies to both.
-      </para><para>
-      The default is 10% of the longer of <option>rekey_time</option> and
-      <option>reauth_time</option>.
+
+      The default is 10% of the longer of {option}`rekey_time` and
+      {option}`reauth_time`.
     '';
 
     rand_time = mkOptionalDurationParam ''
@@ -356,8 +344,8 @@ in {
       rekey/reauth times. To avoid having both peers initiating the rekey/reauth
       procedure simultaneously, a random time gets subtracted from the
       rekey/reauth times.
-      </para><para>
-      The default is equal to the configured <option>over_time</option>.
+
+      The default is equal to the configured {option}`over_time`.
     '';
 
     pools = mkCommaSepListParam [] ''
@@ -409,8 +397,8 @@ in {
       certs = mkCommaSepListParam [] ''
         List of certificate candidates to use for
         authentication. The certificates may use a relative path from the
-        swanctl <literal>x509</literal> directory or an absolute path.
-        </para><para>
+        swanctl `x509` directory or an absolute path.
+
         The certificate used for authentication is selected based on the
         received certificate request payloads. If no appropriate CA can be
         located, the first certificate is used.
@@ -425,67 +413,52 @@ in {
       pubkeys = mkCommaSepListParam [] ''
         List of raw public key candidates to use for
         authentication. The public keys may use a relative path from the swanctl
-        <literal>pubkey</literal> directory or an absolute path.
-        </para><para>
+        `pubkey` directory or an absolute path.
+
         Even though multiple local public keys could be defined in principle,
         only the first public key in the list is used for authentication.
       '';
 
       auth = mkStrParam "pubkey" ''
         Authentication to perform locally.
-        <itemizedlist>
-        <listitem><para>
-        The default <literal>pubkey</literal> uses public key authentication
-        using a private key associated to a usable certificate.
-        </para></listitem>
-        <listitem><para>
-        <literal>psk</literal> uses pre-shared key authentication.
-        </para></listitem>
-        <listitem><para>
-        The IKEv1 specific <literal>xauth</literal> is used for XAuth or Hybrid
-        authentication,
-        </para></listitem>
-        <listitem><para>
-        while the IKEv2 specific <literal>eap</literal> keyword defines EAP
-        authentication.
-        </para></listitem>
-        <listitem><para>
-        For <literal>xauth</literal>, a specific backend name may be appended,
-        separated by a dash. The appropriate <literal>xauth</literal> backend is
-        selected to perform the XAuth exchange. For traditional XAuth, the
-        <literal>xauth</literal> method is usually defined in the second
-        authentication round following an initial <literal>pubkey</literal> (or
-        <literal>psk</literal>) round. Using <literal>xauth</literal> in the
-        first round performs Hybrid Mode client authentication.
-        </para></listitem>
-        <listitem><para>
-        For <literal>eap</literal>, a specific EAP method name may be appended, separated by a
-        dash. An EAP module implementing the appropriate method is selected to
-        perform the EAP conversation.
-        </para></listitem>
-        <listitem><para>
-        Since 5.4.0, if both peers support RFC 7427 ("Signature Authentication
-        in IKEv2") specific hash algorithms to be used during IKEv2
-        authentication may be configured. To do so use <literal>ike:</literal>
-        followed by a trust chain signature scheme constraint (see description
-        of the <option>remote</option> section's <option>auth</option>
-        keyword). For example, with <literal>ike:pubkey-sha384-sha256</literal>
-        a public key signature scheme with either SHA-384 or SHA-256 would get
-        used for authentication, in that order and depending on the hash
-        algorithms supported by the peer. If no specific hash algorithms are
-        configured, the default is to prefer an algorithm that matches or
-        exceeds the strength of the signature key. If no constraints with
-        <literal>ike:</literal> prefix are configured any signature scheme
-        constraint (without <literal>ike:</literal> prefix) will also apply to
-        IKEv2 authentication, unless this is disabled in
-        <literal>strongswan.conf</literal>. To use RSASSA-PSS signatures use
-        <literal>rsa/pss</literal> instead of <literal>pubkey</literal> or
-        <literal>rsa</literal> as in e.g.
-        <literal>ike:rsa/pss-sha256</literal>. If <literal>pubkey</literal> or
-        <literal>rsa</literal> constraints are configured RSASSA-PSS signatures
-        will only be used if enabled in <literal>strongswan.conf</literal>(5).
-        </para></listitem>
-        </itemizedlist>
+
+        - The default `pubkey` uses public key authentication
+          using a private key associated to a usable certificate.
+        - `psk` uses pre-shared key authentication.
+        - The IKEv1 specific `xauth` is used for XAuth or Hybrid
+          authentication,
+        - while the IKEv2 specific `eap` keyword defines EAP
+          authentication.
+        - For `xauth`, a specific backend name may be appended,
+          separated by a dash. The appropriate `xauth` backend is
+          selected to perform the XAuth exchange. For traditional XAuth, the
+          `xauth` method is usually defined in the second
+          authentication round following an initial `pubkey` (or
+          `psk`) round. Using `xauth` in the
+          first round performs Hybrid Mode client authentication.
+        - For `eap`, a specific EAP method name may be appended, separated by a
+          dash. An EAP module implementing the appropriate method is selected to
+          perform the EAP conversation.
+        - Since 5.4.0, if both peers support RFC 7427 ("Signature Authentication
+          in IKEv2") specific hash algorithms to be used during IKEv2
+          authentication may be configured. To do so use `ike:`
+          followed by a trust chain signature scheme constraint (see description
+          of the {option}`remote` section's {option}`auth`
+          keyword). For example, with `ike:pubkey-sha384-sha256`
+          a public key signature scheme with either SHA-384 or SHA-256 would get
+          used for authentication, in that order and depending on the hash
+          algorithms supported by the peer. If no specific hash algorithms are
+          configured, the default is to prefer an algorithm that matches or
+          exceeds the strength of the signature key. If no constraints with
+          `ike:` prefix are configured any signature scheme
+          constraint (without `ike:` prefix) will also apply to
+          IKEv2 authentication, unless this is disabled in
+          `strongswan.conf`. To use RSASSA-PSS signatures use
+          `rsa/pss` instead of `pubkey` or
+          `rsa` as in e.g.
+          `ike:rsa/pss-sha256`. If `pubkey` or
+          `rsa` constraints are configured RSASSA-PSS signatures
+          will only be used if enabled in `strongswan.conf`(5).
       '';
 
       id = mkOptionalStrParam ''
@@ -504,7 +477,7 @@ in {
         authentication. This identity may differ from the IKE identity,
         especially when EAP authentication is delegated from the IKE responder
         to an AAA backend.
-        </para><para>
+
         For EAP-(T)TLS, this defines the identity for which the server must
         provide a certificate in the TLS exchange.
       '';
@@ -518,8 +491,8 @@ in {
       defines the rules how authentication is performed for the local
       peer. Multiple rounds may be defined to use IKEv2 RFC 4739 Multiple
       Authentication or IKEv1 XAuth.
-      </para><para>
-      Each round is defined in a section having <literal>local</literal> as
+
+      Each round is defined in a section having `local` as
       prefix, and an optional unique suffix. To define a single authentication
       round, the suffix may be omitted.
     '';
@@ -540,7 +513,7 @@ in {
 
       eap_id = mkOptionalStrParam ''
         Identity to use as peer identity during EAP authentication. If set to
-        <literal>%any</literal> the EAP-Identity method will be used to ask the
+        `%any` the EAP-Identity method will be used to ask the
         client for an EAP identity.
       '';
 
@@ -559,7 +532,7 @@ in {
 
       certs = mkCommaSepListParam [] ''
         List of certificates to accept for authentication. The certificates may
-        use a relative path from the swanctl <literal>x509</literal> directory
+        use a relative path from the swanctl `x509` directory
         or an absolute path.
       '';
 
@@ -573,7 +546,7 @@ in {
         Identity in CA certificate to accept for authentication. The specified
         identity must be contained in one (intermediate) CA of the remote peer
         trustchain, either as subject or as subjectAltName. This has the same
-        effect as specifying <literal>cacerts</literal> to force clients under
+        effect as specifying `cacerts` to force clients under
         a CA to specific connections; it does not require the CA certificate
         to be available locally, and can be received from the peer during the
         IKE exchange.
@@ -582,7 +555,7 @@ in {
       cacerts = mkCommaSepListParam [] ''
         List of CA certificates to accept for
         authentication. The certificates may use a relative path from the
-        swanctl <literal>x509ca</literal> directory or an absolute path.
+        swanctl `x509ca` directory or an absolute path.
       '';
 
       cacert = mkPostfixedAttrsOfParams certParams ''
@@ -594,57 +567,50 @@ in {
       pubkeys = mkCommaSepListParam [] ''
         List of raw public keys to accept for
         authentication. The public keys may use a relative path from the swanctl
-        <literal>pubkey</literal> directory or an absolute path.
+        `pubkey` directory or an absolute path.
       '';
 
       revocation = mkEnumParam ["strict" "ifuri" "relaxed"] "relaxed" ''
         Certificate revocation policy for CRL or OCSP revocation.
-        <itemizedlist>
-        <listitem><para>
-        A <literal>strict</literal> revocation policy fails if no revocation information is
-        available, i.e. the certificate is not known to be unrevoked.
-        </para></listitem>
-        <listitem><para>
-        <literal>ifuri</literal> fails only if a CRL/OCSP URI is available, but certificate
-        revocation checking fails, i.e. there should be revocation information
-        available, but it could not be obtained.
-        </para></listitem>
-        <listitem><para>
-        The default revocation policy <literal>relaxed</literal> fails only if a certificate is
-        revoked, i.e. it is explicitly known that it is bad.
-        </para></listitem>
-        </itemizedlist>
+
+        - A `strict` revocation policy fails if no revocation information is
+          available, i.e. the certificate is not known to be unrevoked.
+        - `ifuri` fails only if a CRL/OCSP URI is available, but certificate
+          revocation checking fails, i.e. there should be revocation information
+          available, but it could not be obtained.
+        - The default revocation policy `relaxed` fails only if a certificate is
+          revoked, i.e. it is explicitly known that it is bad.
       '';
 
       auth = mkStrParam "pubkey" ''
-        Authentication to expect from remote. See the <option>local</option>
-        section's <option>auth</option> keyword description about the details of
+        Authentication to expect from remote. See the {option}`local`
+        section's {option}`auth` keyword description about the details of
         supported mechanisms.
-        </para><para>
+
         Since 5.4.0, to require a trustchain public key strength for the remote
         side, specify the key type followed by the minimum strength in bits (for
-        example <literal>ecdsa-384</literal> or
-        <literal>rsa-2048-ecdsa-256</literal>). To limit the acceptable set of
+        example `ecdsa-384` or
+        `rsa-2048-ecdsa-256`). To limit the acceptable set of
         hashing algorithms for trustchain validation, append hash algorithms to
         pubkey or a key strength definition (for example
-        <literal>pubkey-sha256-sha512</literal>,
-        <literal>rsa-2048-sha256-sha384-sha512</literal> or
-        <literal>rsa-2048-sha256-ecdsa-256-sha256-sha384</literal>).
-        Unless disabled in <literal>strongswan.conf</literal>, or explicit IKEv2
+        `pubkey-sha256-sha512`,
+        `rsa-2048-sha256-sha384-sha512` or
+        `rsa-2048-sha256-ecdsa-256-sha256-sha384`).
+        Unless disabled in `strongswan.conf`, or explicit IKEv2
         signature constraints are configured (refer to the description of the
-        <option>local</option> section's <option>auth</option> keyword for
+        {option}`local` section's {option}`auth` keyword for
         details), such key types and hash algorithms are also applied as
         constraints against IKEv2 signature authentication schemes used by the
         remote side. To require RSASSA-PSS signatures use
-        <literal>rsa/pss</literal> instead of <literal>pubkey</literal> or
-        <literal>rsa</literal> as in e.g. <literal>rsa/pss-sha256</literal>. If
-        <literal>pubkey</literal> or <literal>rsa</literal> constraints are
+        `rsa/pss` instead of `pubkey` or
+        `rsa` as in e.g. `rsa/pss-sha256`. If
+        `pubkey` or `rsa` constraints are
         configured RSASSA-PSS signatures will only be accepted if enabled in
-        <literal>strongswan.conf</literal>(5).
-        </para><para>
+        `strongswan.conf`(5).
+
         To specify trust chain constraints for EAP-(T)TLS, append a colon to the
         EAP method, followed by the key type/size and hash algorithm as
-        discussed above (e.g. <literal>eap-tls:ecdsa-384-sha384</literal>).
+        discussed above (e.g. `eap-tls:ecdsa-384-sha384`).
       '';
 
     } ''
@@ -652,8 +618,8 @@ in {
       defines the constraints how the peers must authenticate to use this
       connection. Multiple rounds may be defined to use IKEv2 RFC 4739 Multiple
       Authentication or IKEv1 XAuth.
-      </para><para>
-      Each round is defined in a section having <literal>remote</literal> as
+
+      Each round is defined in a section having `remote` as
       prefix, and an optional unique suffix. To define a single authentication
       round, the suffix may be omitted.
     '';
@@ -665,15 +631,15 @@ in {
         Diffie-Hellman group. If a DH group is specified, CHILD_SA/Quick Mode
         rekeying and initial negotiation uses a separate Diffie-Hellman exchange
         using the specified group (refer to esp_proposals for details).
-        </para><para>
+
         In IKEv2, multiple algorithms of the same kind can be specified in a
         single proposal, from which one gets selected. In IKEv1, only one
         algorithm per kind is allowed per proposal, more algorithms get
         implicitly stripped. Use multiple proposals to offer different algorithms
         combinations in IKEv1.
-        </para><para>
+
         Algorithm keywords get separated using dashes. Multiple proposals may be
-        specified in a list. The special value <literal>default</literal> forms
+        specified in a list. The special value `default` forms
         a default proposal of supported algorithms considered safe, and is
         usually a good choice for interoperability. By default no AH proposals
         are included, instead ESP is proposed.
@@ -686,7 +652,7 @@ in {
         an optional Extended Sequence Number Mode indicator. For AEAD proposals,
         a combined mode algorithm is used instead of the separate
         encryption/integrity algorithms.
-        </para><para>
+
         If a DH group is specified, CHILD_SA/Quick Mode rekeying and initial
         negotiation use a separate Diffie-Hellman exchange using the specified
         group. However, for IKEv2, the keys of the CHILD_SA created implicitly
@@ -695,20 +661,20 @@ in {
         rekeyed or is created with a separate CREATE_CHILD_SA exchange. A
         proposal mismatch might, therefore, not immediately be noticed when the
         SA is established, but may later cause rekeying to fail.
-        </para><para>
+
         Extended Sequence Number support may be indicated with the
-        <literal>esn</literal> and <literal>noesn</literal> values, both may be
+        `esn` and `noesn` values, both may be
         included to indicate support for both modes. If omitted,
-        <literal>noesn</literal> is assumed.
-        </para><para>
+        `noesn` is assumed.
+
         In IKEv2, multiple algorithms of the same kind can be specified in a
         single proposal, from which one gets selected. In IKEv1, only one
         algorithm per kind is allowed per proposal, more algorithms get
         implicitly stripped. Use multiple proposals to offer different algorithms
         combinations in IKEv1.
-        </para><para>
+
         Algorithm keywords get separated using dashes. Multiple proposals may be
-        specified as a list. The special value <literal>default</literal> forms
+        specified as a list. The special value `default` forms
         a default proposal of supported algorithms considered safe, and is
         usually a good choice for interoperability. If no algorithms are
         specified for AH nor ESP, the default set of algorithms for ESP is
@@ -726,19 +692,19 @@ in {
       local_ts = mkCommaSepListParam ["dynamic"] ''
         List of local traffic selectors to include in CHILD_SA. Each selector is
         a CIDR subnet definition, followed by an optional proto/port
-        selector. The special value <literal>dynamic</literal> may be used
+        selector. The special value `dynamic` may be used
         instead of a subnet definition, which gets replaced by the tunnel outer
         address or the virtual IP, if negotiated. This is the default.
-        </para><para>
+
         A protocol/port selector is surrounded by opening and closing square
         brackets. Between these brackets, a numeric or getservent(3) protocol
         name may be specified. After the optional protocol restriction, an
         optional port restriction may be specified, separated by a slash. The
         port restriction may be numeric, a getservent(3) service name, or the
-        special value <literal>opaque</literal> for RFC 4301 OPAQUE
+        special value `opaque` for RFC 4301 OPAQUE
         selectors. Port ranges may be specified as well, none of the kernel
         backends currently support port ranges, though.
-        </para><para>
+
         When IKEv1 is used only the first selector is interpreted, except if the
         Cisco Unity extension plugin is used. This is due to a limitation of the
         IKEv1 protocol, which only allows a single pair of selectors per
@@ -752,42 +718,42 @@ in {
 
       remote_ts = mkCommaSepListParam ["dynamic"] ''
         List of remote selectors to include in CHILD_SA. See
-        <option>local_ts</option> for a description of the selector syntax.
+        {option}`local_ts` for a description of the selector syntax.
       '';
 
       rekey_time = mkDurationParam "1h" ''
         Time to schedule CHILD_SA rekeying. CHILD_SA rekeying refreshes key
         material, optionally using a Diffie-Hellman exchange if a group is
         specified in the proposal.  To avoid rekey collisions initiated by both
-        ends simultaneously, a value in the range of <option>rand_time</option>
+        ends simultaneously, a value in the range of {option}`rand_time`
         gets subtracted to form the effective soft lifetime.
-        </para><para>
+
         By default CHILD_SA rekeying is scheduled every hour, minus
-        <option>rand_time</option>.
+        {option}`rand_time`.
       '';
 
       life_time = mkOptionalDurationParam ''
         Maximum lifetime before CHILD_SA gets closed. Usually this hard lifetime
         is never reached, because the CHILD_SA gets rekeyed before. If that fails
         for whatever reason, this limit closes the CHILD_SA.  The default is 10%
-        more than the <option>rekey_time</option>.
+        more than the {option}`rekey_time`.
       '';
 
       rand_time = mkOptionalDurationParam ''
         Time range from which to choose a random value to subtract from
-        <option>rekey_time</option>. The default is the difference between
-        <option>life_time</option> and <option>rekey_time</option>.
+        {option}`rekey_time`. The default is the difference between
+        {option}`life_time` and {option}`rekey_time`.
       '';
 
       rekey_bytes = mkIntParam 0 ''
         Number of bytes processed before initiating CHILD_SA rekeying. CHILD_SA
         rekeying refreshes key material, optionally using a Diffie-Hellman
         exchange if a group is specified in the proposal.
-        </para><para>
+
         To avoid rekey collisions initiated by both ends simultaneously, a value
-        in the range of <option>rand_bytes</option> gets subtracted to form the
+        in the range of {option}`rand_bytes` gets subtracted to form the
         effective soft volume limit.
-        </para><para>
+
         Volume based CHILD_SA rekeying is disabled by default.
       '';
 
@@ -795,24 +761,24 @@ in {
         Maximum bytes processed before CHILD_SA gets closed. Usually this hard
         volume limit is never reached, because the CHILD_SA gets rekeyed
         before. If that fails for whatever reason, this limit closes the
-        CHILD_SA.  The default is 10% more than <option>rekey_bytes</option>.
+        CHILD_SA.  The default is 10% more than {option}`rekey_bytes`.
       '';
 
       rand_bytes = mkOptionalIntParam ''
         Byte range from which to choose a random value to subtract from
-        <option>rekey_bytes</option>. The default is the difference between
-        <option>life_bytes</option> and <option>rekey_bytes</option>.
+        {option}`rekey_bytes`. The default is the difference between
+        {option}`life_bytes` and {option}`rekey_bytes`.
       '';
 
       rekey_packets = mkIntParam 0 ''
         Number of packets processed before initiating CHILD_SA rekeying. CHILD_SA
         rekeying refreshes key material, optionally using a Diffie-Hellman
         exchange if a group is specified in the proposal.
-        </para><para>
+
         To avoid rekey collisions initiated by both ends simultaneously, a value
-        in the range of <option>rand_packets</option> gets subtracted to form
+        in the range of {option}`rand_packets` gets subtracted to form
         the effective soft packet count limit.
-        </para><para>
+
         Packet count based CHILD_SA rekeying is disabled by default.
       '';
 
@@ -821,14 +787,14 @@ in {
         this hard packets limit is never reached, because the CHILD_SA gets
         rekeyed before. If that fails for whatever reason, this limit closes the
         CHILD_SA.
-        </para><para>
-        The default is 10% more than <option>rekey_bytes</option>.
+
+        The default is 10% more than {option}`rekey_bytes`.
       '';
 
       rand_packets = mkOptionalIntParam ''
         Packet range from which to choose a random value to subtract from
-        <option>rekey_packets</option>. The default is the difference between
-        <option>life_packets</option> and <option>rekey_packets</option>.
+        {option}`rekey_packets`. The default is the difference between
+        {option}`life_packets` and {option}`rekey_packets`.
       '';
 
       updown = mkOptionalStrParam ''
@@ -836,7 +802,7 @@ in {
       '';
 
       hostaccess = mkYesNoParam no ''
-        Hostaccess variable to pass to <literal>updown</literal> script.
+        Hostaccess variable to pass to `updown` script.
       '';
 
       mode = mkEnumParam [ "tunnel"
@@ -847,33 +813,20 @@ in {
                            "drop"
                          ] "tunnel" ''
         IPsec Mode to establish CHILD_SA with.
-        <itemizedlist>
-        <listitem><para>
-        <literal>tunnel</literal> negotiates the CHILD_SA in IPsec Tunnel Mode,
-        </para></listitem>
-        <listitem><para>
-        whereas <literal>transport</literal> uses IPsec Transport Mode.
-        </para></listitem>
-        <listitem><para>
-        <literal>transport_proxy</literal> signifying the special Mobile IPv6
-        Transport Proxy Mode.
-        </para></listitem>
-        <listitem><para>
-        <literal>beet</literal> is the Bound End to End Tunnel mixture mode,
-        working with fixed inner addresses without the need to include them in
-        each packet.
-        </para></listitem>
-        <listitem><para>
-        Both <literal>transport</literal> and <literal>beet</literal> modes are
-        subject to mode negotiation; <literal>tunnel</literal> mode is
-        negotiated if the preferred mode is not available.
-        </para></listitem>
-        <listitem><para>
-        <literal>pass</literal> and <literal>drop</literal> are used to install
-        shunt policies which explicitly bypass the defined traffic from IPsec
-        processing or drop it, respectively.
-        </para></listitem>
-        </itemizedlist>
+
+        - `tunnel` negotiates the CHILD_SA in IPsec Tunnel Mode,
+        - whereas `transport` uses IPsec Transport Mode.
+        - `transport_proxy` signifying the special Mobile IPv6
+          Transport Proxy Mode.
+        - `beet` is the Bound End to End Tunnel mixture mode,
+          working with fixed inner addresses without the need to include them in
+          each packet.
+        - Both `transport` and `beet` modes are
+          subject to mode negotiation; `tunnel` mode is
+          negotiated if the preferred mode is not available.
+        - `pass` and `drop` are used to install
+          shunt policies which explicitly bypass the defined traffic from IPsec
+          processing or drop it, respectively.
       '';
 
       policies = mkYesNoParam yes ''
@@ -932,18 +885,18 @@ in {
         set. This allows installing duplicate policies and enables Netfilter
         rules to select specific SAs/policies for incoming traffic. Note that
         inbound marks are only set on policies, by default, unless
-        <option>mark_in_sa</option> is enabled. The special value
-        <literal>%unique</literal> sets a unique mark on each CHILD_SA instance,
-        beyond that the value <literal>%unique-dir</literal> assigns a different
+        {option}`mark_in_sa` is enabled. The special value
+        `%unique` sets a unique mark on each CHILD_SA instance,
+        beyond that the value `%unique-dir` assigns a different
         unique mark for each
-        </para><para>
+
         An additional mask may be appended to the mark, separated by
-        <literal>/</literal>. The default mask if omitted is
-        <literal>0xffffffff</literal>.
+        `/`. The default mask if omitted is
+        `0xffffffff`.
       '';
 
       mark_in_sa = mkYesNoParam no ''
-        Whether to set <option>mark_in</option> on the inbound SA. By default,
+        Whether to set {option}`mark_in` on the inbound SA. By default,
         the inbound mark is only set on the inbound policy. The tuple destination
         address, protocol and SPI is unique and the mark is not required to find
         the correct SA, allowing to mark traffic after decryption instead (where
@@ -957,13 +910,13 @@ in {
         require marks on each packet to match a policy/SA having that option
         set. This allows installing duplicate policies and enables Netfilter
         rules to select specific policies/SAs for outgoing traffic. The special
-        value <literal>%unique</literal> sets a unique mark on each CHILD_SA
-        instance, beyond that the value <literal>%unique-dir</literal> assigns a
+        value `%unique` sets a unique mark on each CHILD_SA
+        instance, beyond that the value `%unique-dir` assigns a
         different unique mark for each CHILD_SA direction (in/out).
-        </para><para>
+
         An additional mask may be appended to the mark, separated by
-        <literal>/</literal>. The default mask if omitted is
-        <literal>0xffffffff</literal>.
+        `/`. The default mask if omitted is
+        `0xffffffff`.
       '';
 
       set_mark_in = mkStrParam "0/0x00000000" ''
@@ -973,10 +926,10 @@ in {
         differently (e.g. via policy routing).
 
         An additional mask may be appended to the mark, separated by
-        <literal>/</literal>. The default mask if omitted is 0xffffffff. The
-        special value <literal>%same</literal> uses the value (but not the mask)
-        from <option>mark_in</option> as mark value, which can be fixed,
-        <literal>%unique</literal> or <literal>%unique-dir</literal>.
+        `/`. The default mask if omitted is 0xffffffff. The
+        special value `%same` uses the value (but not the mask)
+        from {option}`mark_in` as mark value, which can be fixed,
+        `%unique` or `%unique-dir`.
 
         Setting marks in XFRM input requires Linux 4.19 or higher.
       '';
@@ -987,10 +940,10 @@ in {
         traffic (e.g. via policy routing).
 
         An additional mask may be appended to the mark, separated by
-        <literal>/</literal>. The default mask if omitted is 0xffffffff. The
-        special value <literal>%same</literal> uses the value (but not the mask)
-        from <option>mark_out</option> as mark value, which can be fixed,
-        <literal>%unique_</literal> or <literal>%unique-dir</literal>.
+        `/`. The default mask if omitted is 0xffffffff. The
+        special value `%same` uses the value (but not the mask)
+        from {option}`mark_out` as mark value, which can be fixed,
+        `%unique_` or `%unique-dir`.
 
         Setting marks in XFRM output is supported since Linux 4.14. Setting a
         mask requires at least Linux 4.19.
@@ -999,18 +952,18 @@ in {
       if_id_in = mkStrParam "0" ''
         XFRM interface ID set on inbound policies/SA. This allows installing
         duplicate policies/SAs and associates them with an interface with the
-        same ID. The special value <literal>%unique</literal> sets a unique
+        same ID. The special value `%unique` sets a unique
         interface ID on each CHILD_SA instance, beyond that the value
-        <literal>%unique-dir</literal> assigns a different unique interface ID
+        `%unique-dir` assigns a different unique interface ID
         for each CHILD_SA direction (in/out).
       '';
 
       if_id_out = mkStrParam "0" ''
         XFRM interface ID set on outbound policies/SA. This allows installing
         duplicate policies/SAs and associates them with an interface with the
-        same ID. The special value <literal>%unique</literal> sets a unique
+        same ID. The special value `%unique` sets a unique
         interface ID on each CHILD_SA instance, beyond that the value
-        <literal>%unique-dir</literal> assigns a different unique interface ID
+        `%unique-dir` assigns a different unique interface ID
         for each CHILD_SA direction (in/out).
 
         The daemon will not install routes for CHILD_SAs that have this option set.
@@ -1020,23 +973,23 @@ in {
         Pads ESP packets with additional data to have a consistent ESP packet
         size for improved Traffic Flow Confidentiality. The padding defines the
         minimum size of all ESP packets sent.  The default value of
-        <literal>0</literal> disables TFC padding, the special value
-        <literal>mtu</literal> adds TFC padding to create a packet size equal to
+        `0` disables TFC padding, the special value
+        `mtu` adds TFC padding to create a packet size equal to
         the Path Maximum Transfer Unit.
       '';
 
       replay_window = mkIntParam 32 ''
         IPsec replay window to configure for this CHILD_SA. Larger values than
-        the default of <literal>32</literal> are supported using the Netlink
-        backend only, a value of <literal>0</literal> disables IPsec replay
+        the default of `32` are supported using the Netlink
+        backend only, a value of `0` disables IPsec replay
         protection.
       '';
 
       hw_offload = mkEnumParam ["yes" "no" "auto"] "no" ''
         Enable hardware offload for this CHILD_SA, if supported by the IPsec
-        implementation. The value <literal>yes</literal> enforces offloading
+        implementation. The value `yes` enforces offloading
         and the installation will fail if it's not supported by either kernel or
-        device. The value <literal>auto</literal> enables offloading, if it's
+        device. The value `auto` enables offloading, if it's
         supported, but the installation does not fail otherwise.
       '';
 
@@ -1055,55 +1008,42 @@ in {
       copy_dscp = mkEnumParam [ "out" "in" "yes" "no" ] "out" ''
         Whether to copy the DSCP (Differentiated Services Field Codepoint)
         header field to/from the outer IP header in tunnel mode. The value
-        <literal>out</literal> only copies the field from the inner to the outer
-        header, the value <literal>in</literal> does the opposite and only
+        `out` only copies the field from the inner to the outer
+        header, the value `in` does the opposite and only
         copies the field from the outer to the inner header when decapsulating,
-        the value <literal>yes</literal> copies the field in both directions,
-        and the value <literal>no</literal> disables copying the field
-        altogether. Setting this to <literal>yes</literal> or
-        <literal>in</literal> could allow an attacker to adversely affect other
+        the value `yes` copies the field in both directions,
+        and the value `no` disables copying the field
+        altogether. Setting this to `yes` or
+        `in` could allow an attacker to adversely affect other
         traffic at the receiver, which is why the default is
-        <literal>out</literal>. Controlling this behavior is not supported by
+        `out`. Controlling this behavior is not supported by
         all kernel interfaces.
       '';
 
       start_action = mkEnumParam ["none" "trap" "start"] "none" ''
         Action to perform after loading the configuration.
-        <itemizedlist>
-        <listitem><para>
-        The default of <literal>none</literal> loads the connection only, which
-        then can be manually initiated or used as a responder configuration.
-        </para></listitem>
-        <listitem><para>
-        The value <literal>trap</literal> installs a trap policy, which triggers
-        the tunnel as soon as matching traffic has been detected.
-        </para></listitem>
-        <listitem><para>
-        The value <literal>start</literal> initiates the connection actively.
-        </para></listitem>
-        </itemizedlist>
+
+        - The default of `none` loads the connection only, which
+          then can be manually initiated or used as a responder configuration.
+        - The value `trap` installs a trap policy, which triggers
+          the tunnel as soon as matching traffic has been detected.
+        - The value `start` initiates the connection actively.
+
         When unloading or replacing a CHILD_SA configuration having a
-        <option>start_action</option> different from <literal>none</literal>,
+        {option}`start_action` different from `none`,
         the inverse action is performed. Configurations with
-        <literal>start</literal> get closed, while such with
-        <literal>trap</literal> get uninstalled.
+        `start` get closed, while such with
+        `trap` get uninstalled.
       '';
 
       close_action = mkEnumParam ["none" "trap" "start"] "none" ''
         Action to perform after a CHILD_SA gets closed by the peer.
-        <itemizedlist>
-        <listitem><para>
-        The default of <literal>none</literal> does not take any action,
-        </para></listitem>
-        <listitem><para>
-        <literal>trap</literal> installs a trap policy for the CHILD_SA.
-        </para></listitem>
-        <listitem><para>
-        <literal>start</literal> tries to re-create the CHILD_SA.
-        </para></listitem>
-        </itemizedlist>
-        </para><para>
-        <option>close_action</option> does not provide any guarantee that the
+
+        - The default of `none` does not take any action,
+        - `trap` installs a trap policy for the CHILD_SA.
+        - `start` tries to re-create the CHILD_SA.
+
+        {option}`close_action` does not provide any guarantee that the
         CHILD_SA is kept alive. It acts on explicit close messages only, but not
         on negotiation failures. Use trap policies to reliably re-create failed
         CHILD_SAs.
@@ -1111,9 +1051,9 @@ in {
 
     } ''
       CHILD_SA configuration sub-section. Each connection definition may have
-      one or more sections in its <option>children</option> subsection. The
+      one or more sections in its {option}`children` subsection. The
       section name defines the name of the CHILD_SA configuration, which must be
-      unique within the connection (denoted &#60;child&#62; below).
+      unique within the connection (denoted \<child\> below).
     '';
   } ''
     Section defining IKE connection configurations, each in its own subsection
@@ -1130,13 +1070,13 @@ in {
 
       id = mkPrefixedAttrsOfParam (mkOptionalStrParam "") ''
         Identity the EAP/XAuth secret belongs to. Multiple unique identities may
-        be specified, each having an <literal>id</literal> prefix, if a secret
+        be specified, each having an `id` prefix, if a secret
         is shared between multiple users.
       '';
 
     } ''
       EAP secret section for a specific secret. Each EAP secret is defined in a
-      unique section having the <literal>eap</literal> prefix. EAP secrets are
+      unique section having the `eap` prefix. EAP secrets are
       used for XAuth authentication as well.
     '';
 
@@ -1160,7 +1100,7 @@ in {
       '';
     } ''
       NTLM secret section for a specific secret. Each NTLM secret is defined in
-      a unique section having the <literal>ntlm</literal> prefix. NTLM secrets
+      a unique section having the `ntlm` prefix. NTLM secrets
       may only be used for EAP-MSCHAPv2 authentication.
     '';
 
@@ -1173,30 +1113,30 @@ in {
 
       id = mkPrefixedAttrsOfParam (mkOptionalStrParam "") ''
         IKE identity the IKE preshared secret belongs to. Multiple unique
-        identities may be specified, each having an <literal>id</literal>
+        identities may be specified, each having an `id`
         prefix, if a secret is shared between multiple peers.
       '';
     } ''
       IKE preshared secret section for a specific secret. Each IKE PSK is
-      defined in a unique section having the <literal>ike</literal> prefix.
+      defined in a unique section having the `ike` prefix.
     '';
 
     ppk = mkPrefixedAttrsOfParams {
       secret = mkOptionalStrParam ''
         Value of the PPK. It may either be an ASCII string, a hex encoded string
-        if it has a <literal>0x</literal> prefix or a Base64 encoded string if
-        it has a <literal>0s</literal> prefix in its value. Should have at least
+        if it has a `0x` prefix or a Base64 encoded string if
+        it has a `0s` prefix in its value. Should have at least
         256 bits of entropy for 128-bit security.
       '';
 
       id = mkPrefixedAttrsOfParam (mkOptionalStrParam "") ''
         PPK identity the PPK belongs to. Multiple unique identities may be
-        specified, each having an <literal>id</literal> prefix, if a secret is
+        specified, each having an `id` prefix, if a secret is
         shared between multiple peers.
       '';
     } ''
       Postquantum Preshared Key (PPK) section for a specific secret. Each PPK is
-      defined in a unique section having the <literal>ppk</literal> prefix.
+      defined in a unique section having the `ppk` prefix.
     '';
 
     private = mkPrefixedAttrsOfParams {
@@ -1209,25 +1149,25 @@ in {
       '';
     } ''
       Private key decryption passphrase for a key in the
-      <literal>private</literal> folder.
+      `private` folder.
     '';
 
     rsa = mkPrefixedAttrsOfParams {
       file = mkOptionalStrParam ''
-        File name in the <literal>rsa</literal> folder for which this passphrase
+        File name in the `rsa` folder for which this passphrase
         should be used.
       '';
       secret = mkOptionalStrParam ''
         Value of decryption passphrase for RSA key.
       '';
     } ''
-      Private key decryption passphrase for a key in the <literal>rsa</literal>
+      Private key decryption passphrase for a key in the `rsa`
       folder.
     '';
 
     ecdsa = mkPrefixedAttrsOfParams {
       file = mkOptionalStrParam ''
-        File name in the <literal>ecdsa</literal> folder for which this
+        File name in the `ecdsa` folder for which this
         passphrase should be used.
       '';
       secret = mkOptionalStrParam ''
@@ -1235,12 +1175,12 @@ in {
       '';
     } ''
       Private key decryption passphrase for a key in the
-      <literal>ecdsa</literal> folder.
+      `ecdsa` folder.
     '';
 
     pkcs8 = mkPrefixedAttrsOfParams {
       file = mkOptionalStrParam ''
-        File name in the <literal>pkcs8</literal> folder for which this
+        File name in the `pkcs8` folder for which this
         passphrase should be used.
       '';
       secret = mkOptionalStrParam ''
@@ -1248,12 +1188,12 @@ in {
       '';
     } ''
       Private key decryption passphrase for a key in the
-      <literal>pkcs8</literal> folder.
+      `pkcs8` folder.
     '';
 
     pkcs12 = mkPrefixedAttrsOfParams {
       file = mkOptionalStrParam ''
-        File name in the <literal>pkcs12</literal> folder for which this
+        File name in the `pkcs12` folder for which this
         passphrase should be used.
       '';
       secret = mkOptionalStrParam ''
@@ -1261,7 +1201,7 @@ in {
       '';
     } ''
       PKCS#12 decryption passphrase for a container in the
-      <literal>pkcs12</literal> folder.
+      `pkcs12` folder.
     '';
 
     token = mkPrefixedAttrsOfParams {
@@ -1281,7 +1221,7 @@ in {
       pin = mkOptionalStrParam ''
         Optional PIN required to access the key on the token. If none is
         provided the user is prompted during an interactive
-        <literal>--load-creds</literal> call.
+        `--load-creds` call.
       '';
     } "Definition for a private key that's stored on a token/smartcard/TPM.";
 
@@ -1291,7 +1231,7 @@ in {
     addrs = mkOptionalStrParam ''
       Subnet or range defining addresses allocated in pool. Accepts a single
       CIDR subnet defining the pool to allocate addresses from or an address
-      range (&#60;from&#62;-&#60;to&#62;). Pools must be unique and non-overlapping.
+      range (\<from\>-\<to\>). Pools must be unique and non-overlapping.
     '';
 
     dns           = mkCommaSepListParam [] "Address or CIDR subnets";
@@ -1305,6 +1245,6 @@ in {
   } ''
     Section defining named pools. Named pools may be referenced by connections
     with the pools option to assign virtual IPs and other configuration
-    attributes. Each pool must have a unique name (denoted &#60;name&#62; below).
+    attributes. Each pool must have a unique name (denoted \<name\> below).
   '';
 }
diff --git a/nixos/modules/services/networking/strongswan.nix b/nixos/modules/services/networking/strongswan.nix
index e3a97207be7..8b1398bfd47 100644
--- a/nixos/modules/services/networking/strongswan.nix
+++ b/nixos/modules/services/networking/strongswan.nix
@@ -51,16 +51,16 @@ let
 in
 {
   options.services.strongswan = {
-    enable = mkEnableOption "strongSwan";
+    enable = mkEnableOption (lib.mdDoc "strongSwan");
 
     secrets = mkOption {
       type = types.listOf types.str;
       default = [];
       example = [ "/run/keys/ipsec-foo.secret" ];
-      description = ''
+      description = lib.mdDoc ''
         A list of paths to IPSec secret files. These
         files will be included into the main ipsec.secrets file with
-        the <literal>include</literal> directive. It is safer if these
+        the `include` directive. It is safer if these
         paths are absolute.
       '';
     };
@@ -69,9 +69,9 @@ in
       type = types.attrsOf types.str;
       default = {};
       example = { cachecrls = "yes"; strictcrlpolicy = "yes"; };
-      description = ''
+      description = lib.mdDoc ''
         A set of options for the ‘config setup’ section of the
-        <filename>ipsec.conf</filename> file. Defines general
+        {file}`ipsec.conf` file. Defines general
         configuration parameters.
       '';
     };
@@ -94,9 +94,9 @@ in
           };
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         A set of connections and their options for the ‘conn xxx’
-        sections of the <filename>ipsec.conf</filename> file.
+        sections of the {file}`ipsec.conf` file.
       '';
     };
 
@@ -110,9 +110,9 @@ in
           crluri = "http://crl2.strongswan.org/strongswan.crl";
         };
       };
-      description = ''
+      description = lib.mdDoc ''
         A set of CAs (certification authorities) and their options for
-        the ‘ca xxx’ sections of the <filename>ipsec.conf</filename>
+        the ‘ca xxx’ sections of the {file}`ipsec.conf`
         file.
       '';
     };
@@ -120,19 +120,19 @@ in
     managePlugins = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         If set to true, this option will disable automatic plugin loading and
         then tell strongSwan to enable the plugins specified in the
-        <option>enabledPlugins</option> option.
+        {option}`enabledPlugins` option.
       '';
     };
 
     enabledPlugins = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         A list of additional plugins to enable if
-        <option>managePlugins</option> is true.
+        {option}`managePlugins` is true.
       '';
     };
   };
diff --git a/nixos/modules/services/networking/stubby.nix b/nixos/modules/services/networking/stubby.nix
index 78c13798dde..183002ff72b 100644
--- a/nixos/modules/services/networking/stubby.nix
+++ b/nixos/modules/services/networking/stubby.nix
@@ -7,7 +7,9 @@ let
   settingsFormat = pkgs.formats.yaml { };
   confFile = settingsFormat.generate "stubby.yml" cfg.settings;
 in {
-  imports = map (x:
+  imports = [
+    (mkRemovedOptionModule [ "stubby" "debugLogging" ] "Use services.stubby.logLevel = \"debug\"; instead.")
+  ] ++ map (x:
     (mkRemovedOptionModule [ "services" "stubby" x ]
       "Stubby configuration moved to services.stubby.settings.")) [
         "authenticationMode"
@@ -23,7 +25,7 @@ in {
   options = {
     services.stubby = {
 
-      enable = mkEnableOption "Stubby DNS resolver";
+      enable = mkEnableOption (lib.mdDoc "Stubby DNS resolver");
 
       settings = mkOption {
         type = types.attrsOf settingsFormat.type;
@@ -39,20 +41,32 @@ in {
             }];
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Content of the Stubby configuration file. All Stubby settings may be set or queried
           here. The default settings are available at
-          <literal>pkgs.stubby.passthru.settingsExample</literal>. See
-          <link xlink:href="https://dnsprivacy.org/wiki/display/DP/Configuring+Stubby"/>.
+          `pkgs.stubby.passthru.settingsExample`. See
+          <https://dnsprivacy.org/wiki/display/DP/Configuring+Stubby>.
           A list of the public recursive servers can be found here:
-          <link xlink:href="https://dnsprivacy.org/wiki/display/DP/DNS+Privacy+Test+Servers"/>.
+          <https://dnsprivacy.org/wiki/display/DP/DNS+Privacy+Test+Servers>.
         '';
       };
 
-      debugLogging = mkOption {
-        default = false;
-        type = types.bool;
-        description = "Enable or disable debug level logging.";
+      logLevel = let
+        logLevels = {
+          emerg = 0;
+          alert = 1;
+          crit = 2;
+          error = 3;
+          warning = 4;
+          notice = 5;
+          info = 6;
+          debug = 7;
+        };
+      in mkOption {
+        default = null;
+        type = types.nullOr (types.enum (attrNames logLevels ++ attrValues logLevels));
+        apply = v: if isString v then logLevels.${v} else v;
+        description = lib.mdDoc "Log verbosity (syslog keyword or level).";
       };
 
     };
@@ -80,7 +94,7 @@ in {
         Type = "notify";
         AmbientCapabilities = "CAP_NET_BIND_SERVICE";
         CapabilityBoundingSet = "CAP_NET_BIND_SERVICE";
-        ExecStart = "${pkgs.stubby}/bin/stubby -C ${confFile} ${optionalString cfg.debugLogging "-l"}";
+        ExecStart = "${pkgs.stubby}/bin/stubby -C ${confFile} ${optionalString (cfg.logLevel != null) "-v ${toString cfg.logLevel}"}";
         DynamicUser = true;
         CacheDirectory = "stubby";
       };
diff --git a/nixos/modules/services/networking/stunnel.nix b/nixos/modules/services/networking/stunnel.nix
index df4908a0fff..3bd0367a0bb 100644
--- a/nixos/modules/services/networking/stunnel.nix
+++ b/nixos/modules/services/networking/stunnel.nix
@@ -7,80 +7,27 @@ let
   cfg = config.services.stunnel;
   yesNo = val: if val then "yes" else "no";
 
+  verifyRequiredField = type: field: n: c: {
+    assertion = hasAttr field c;
+    message =  "stunnel: \"${n}\" ${type} configuration - Field ${field} is required.";
+  };
+
   verifyChainPathAssert = n: c: {
-    assertion = c.verifyHostname == null || (c.verifyChain || c.verifyPeer);
+    assertion = (c.verifyHostname or null) == null || (c.verifyChain || c.verifyPeer);
     message =  "stunnel: \"${n}\" client configuration - hostname verification " +
       "is not possible without either verifyChain or verifyPeer enabled";
   };
 
-  serverConfig = {
-    options = {
-      accept = mkOption {
-        type = types.either types.str types.int;
-        description = ''
-          On which [host:]port stunnel should listen for incoming TLS connections.
-          Note that unlike other softwares stunnel ipv6 address need no brackets,
-          so to listen on all IPv6 addresses on port 1234 one would use ':::1234'.
-        '';
-      };
-
-      connect = mkOption {
-        type = types.either types.str types.int;
-        description = "Port or IP:Port to which the decrypted connection should be forwarded.";
-      };
-
-      cert = mkOption {
-        type = types.path;
-        description = "File containing both the private and public keys.";
-      };
-    };
-  };
-
-  clientConfig = {
-    options = {
-      accept = mkOption {
-        type = types.str;
-        description = "IP:Port on which connections should be accepted.";
-      };
-
-      connect = mkOption {
-        type = types.str;
-        description = "IP:Port destination to connect to.";
-      };
-
-      verifyChain = mkOption {
-        type = types.bool;
-        default = true;
-        description = "Check if the provided certificate has a valid certificate chain (against CAPath).";
-      };
-
-      verifyPeer = mkOption {
-        type = types.bool;
-        default = false;
-        description = "Check if the provided certificate is contained in CAPath.";
-      };
-
-      CAPath = mkOption {
-        type = types.nullOr types.path;
-        default = null;
-        description = "Path to a directory containing certificates to validate against.";
-      };
-
-      CAFile = mkOption {
-        type = types.nullOr types.path;
-        default = "${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt";
-        defaultText = literalExpression ''"''${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"'';
-        description = "Path to a file containing certificates to validate against.";
-      };
-
-      verifyHostname = mkOption {
-        type = with types; nullOr str;
-        default = null;
-        description = "If set, stunnel checks if the provided certificate is valid for the given hostname.";
-      };
-    };
-  };
-
+  removeNulls = mapAttrs (_: filterAttrs (_: v: v != null));
+  mkValueString = v:
+    if v == true then "yes"
+    else if v == false then "no"
+    else generators.mkValueStringDefault {} v;
+  generateConfig = c:
+    generators.toINI {
+      mkSectionName = id;
+      mkKeyValue = k: v: "${k} = ${mkValueString v}";
+    } (removeNulls c);
 
 in
 
@@ -95,43 +42,47 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the stunnel TLS tunneling service.";
+        description = lib.mdDoc "Whether to enable the stunnel TLS tunneling service.";
       };
 
       user = mkOption {
         type = with types; nullOr str;
         default = "nobody";
-        description = "The user under which stunnel runs.";
+        description = lib.mdDoc "The user under which stunnel runs.";
       };
 
       group = mkOption {
         type = with types; nullOr str;
         default = "nogroup";
-        description = "The group under which stunnel runs.";
+        description = lib.mdDoc "The group under which stunnel runs.";
       };
 
       logLevel = mkOption {
         type = types.enum [ "emerg" "alert" "crit" "err" "warning" "notice" "info" "debug" ];
         default = "info";
-        description = "Verbosity of stunnel output.";
+        description = lib.mdDoc "Verbosity of stunnel output.";
       };
 
       fipsMode = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable FIPS 140-2 mode required for compliance.";
+        description = lib.mdDoc "Enable FIPS 140-2 mode required for compliance.";
       };
 
       enableInsecureSSLv3 = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable support for the insecure SSLv3 protocol.";
+        description = lib.mdDoc "Enable support for the insecure SSLv3 protocol.";
       };
 
 
       servers = mkOption {
-        description = "Define the server configuations.";
-        type = with types; attrsOf (submodule serverConfig);
+        description = lib.mdDoc ''
+          Define the server configuations.
+
+          See "SERVICE-LEVEL OPTIONS" in {manpage}`stunnel(8)`.
+        '';
+        type = with types; attrsOf (attrsOf (nullOr (oneOf [bool int str])));
         example = {
           fancyWebserver = {
             accept = 443;
@@ -143,8 +94,32 @@ in
       };
 
       clients = mkOption {
-        description = "Define the client configurations.";
-        type = with types; attrsOf (submodule clientConfig);
+        description = lib.mdDoc ''
+          Define the client configurations.
+
+          By default, verifyChain and OCSPaia are enabled and a CAFile is provided from pkgs.cacert.
+
+          See "SERVICE-LEVEL OPTIONS" in {manpage}`stunnel(8)`.
+        '';
+        type = with types; attrsOf (attrsOf (nullOr (oneOf [bool int str])));
+
+        apply = let
+          applyDefaults = c:
+            {
+              CAFile = "${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt";
+              OCSPaia = true;
+              verifyChain = true;
+            } // c;
+          setCheckHostFromVerifyHostname = c:
+            # To preserve backward-compatibility with the old NixOS stunnel module
+            # definition, allow "verifyHostname" as an alias for "checkHost".
+            c // {
+              checkHost = c.checkHost or c.verifyHostname or null;
+              verifyHostname = null; # Not a real stunnel configuration setting
+            };
+          forceClient = c: c // { client = true; };
+        in mapAttrs (_: c: forceClient (setCheckHostFromVerifyHostname (applyDefaults c)));
+
         example = {
           foobar = {
             accept = "0.0.0.0:8080";
@@ -169,6 +144,11 @@ in
       })
 
       (mapAttrsToList verifyChainPathAssert cfg.clients)
+      (mapAttrsToList (verifyRequiredField "client" "accept") cfg.clients)
+      (mapAttrsToList (verifyRequiredField "client" "connect") cfg.clients)
+      (mapAttrsToList (verifyRequiredField "server" "accept") cfg.servers)
+      (mapAttrsToList (verifyRequiredField "server" "cert") cfg.servers)
+      (mapAttrsToList (verifyRequiredField "server" "connect") cfg.servers)
     ];
 
     environment.systemPackages = [ pkgs.stunnel ];
@@ -183,36 +163,10 @@ in
       ${ optionalString cfg.enableInsecureSSLv3 "options = -NO_SSLv3" }
 
       ; ----- SERVER CONFIGURATIONS -----
-      ${ lib.concatStringsSep "\n"
-           (lib.mapAttrsToList
-             (n: v: ''
-               [${n}]
-               accept = ${toString v.accept}
-               connect = ${toString v.connect}
-               cert = ${v.cert}
-
-             '')
-           cfg.servers)
-      }
+      ${ generateConfig cfg.servers }
 
       ; ----- CLIENT CONFIGURATIONS -----
-      ${ lib.concatStringsSep "\n"
-           (lib.mapAttrsToList
-             (n: v: ''
-               [${n}]
-               client = yes
-               accept = ${v.accept}
-               connect = ${v.connect}
-               verifyChain = ${yesNo v.verifyChain}
-               verifyPeer = ${yesNo v.verifyPeer}
-               ${optionalString (v.CAPath != null) "CApath = ${v.CAPath}"}
-               ${optionalString (v.CAFile != null) "CAFile = ${v.CAFile}"}
-               ${optionalString (v.verifyHostname != null) "checkHost = ${v.verifyHostname}"}
-               OCSPaia = yes
-
-             '')
-           cfg.clients)
-      }
+      ${ generateConfig cfg.clients }
     '';
 
     systemd.services.stunnel = {
diff --git a/nixos/modules/services/networking/supplicant.nix b/nixos/modules/services/networking/supplicant.nix
index eb24130e519..0a48e73932e 100644
--- a/nixos/modules/services/networking/supplicant.nix
+++ b/nixos/modules/services/networking/supplicant.nix
@@ -43,7 +43,7 @@ let
         path = [ pkgs.coreutils ];
 
         preStart = ''
-          ${optionalString (suppl.configFile.path!=null) ''
+          ${optionalString (suppl.configFile.path!=null && suppl.configFile.writable) ''
             (umask 077 && touch -a "${suppl.configFile.path}")
           ''}
           ${optionalString suppl.userControlled.enable ''
@@ -74,19 +74,19 @@ in
               type = types.nullOr types.path;
               default = null;
               example = literalExpression "/etc/wpa_supplicant.conf";
-              description = ''
-                External <literal>wpa_supplicant.conf</literal> configuration file.
-                The configuration options defined declaratively within <literal>networking.supplicant</literal> have
-                precedence over options defined in <literal>configFile</literal>.
+              description = lib.mdDoc ''
+                External `wpa_supplicant.conf` configuration file.
+                The configuration options defined declaratively within `networking.supplicant` have
+                precedence over options defined in `configFile`.
               '';
             };
 
             writable = mkOption {
               type = types.bool;
               default = false;
-              description = ''
-                Whether the configuration file at <literal>configFile.path</literal> should be written to by
-                <literal>wpa_supplicant</literal>.
+              description = lib.mdDoc ''
+                Whether the configuration file at `configFile.path` should be written to by
+                `wpa_supplicant`.
               '';
             };
 
@@ -109,12 +109,12 @@ in
               model_name=NixOS_Unstable
               model_number=2015
             '';
-            description = ''
-              Configuration options for <literal>wpa_supplicant.conf</literal>.
-              Options defined here have precedence over options in <literal>configFile</literal>.
-              NOTE: Do not write sensitive data into <literal>extraConf</literal> as it will
-              be world-readable in the <literal>nix-store</literal>. For sensitive information
-              use the <literal>configFile</literal> instead.
+            description = lib.mdDoc ''
+              Configuration options for `wpa_supplicant.conf`.
+              Options defined here have precedence over options in `configFile`.
+              NOTE: Do not write sensitive data into `extraConf` as it will
+              be world-readable in the `nix-store`. For sensitive information
+              use the `configFile` instead.
             '';
           };
 
@@ -123,19 +123,19 @@ in
             default = "";
             example = "-e/run/wpa_supplicant/entropy.bin";
             description =
-              "Command line arguments to add when executing <literal>wpa_supplicant</literal>.";
+              lib.mdDoc "Command line arguments to add when executing `wpa_supplicant`.";
           };
 
           driver = mkOption {
             type = types.nullOr types.str;
             default = "nl80211,wext";
-            description = "Force a specific wpa_supplicant driver.";
+            description = lib.mdDoc "Force a specific wpa_supplicant driver.";
           };
 
           bridge = mkOption {
             type = types.str;
             default = "";
-            description = "Name of the bridge interface that wpa_supplicant should listen at.";
+            description = lib.mdDoc "Name of the bridge interface that wpa_supplicant should listen at.";
           };
 
           userControlled = {
@@ -143,7 +143,7 @@ in
             enable = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 Allow normal users to control wpa_supplicant through wpa_gui or wpa_cli.
                 This is useful for laptop users that switch networks a lot and don't want
                 to depend on a large package such as NetworkManager just to pick nearby
@@ -154,14 +154,14 @@ in
             socketDir = mkOption {
               type = types.str;
               default = "/run/wpa_supplicant";
-              description = "Directory of sockets for controlling wpa_supplicant.";
+              description = lib.mdDoc "Directory of sockets for controlling wpa_supplicant.";
             };
 
             group = mkOption {
               type = types.str;
               default = "wheel";
               example = "network";
-              description = "Members of this group can control wpa_supplicant.";
+              description = lib.mdDoc "Members of this group can control wpa_supplicant.";
             };
 
           };
@@ -184,21 +184,21 @@ in
         }
       '';
 
-      description = ''
-        Interfaces for which to start <command>wpa_supplicant</command>.
+      description = lib.mdDoc ''
+        Interfaces for which to start {command}`wpa_supplicant`.
         The supplicant is used to scan for and associate with wireless networks,
         or to authenticate with 802.1x capable network switches.
 
         The value of this option is an attribute set. Each attribute configures a
-        <command>wpa_supplicant</command> service, where the attribute name specifies
-        the name of the interface that <command>wpa_supplicant</command> operates on.
+        {command}`wpa_supplicant` service, where the attribute name specifies
+        the name of the interface that {command}`wpa_supplicant` operates on.
         The attribute name can be a space separated list of interfaces.
-        The attribute names <literal>WLAN</literal>, <literal>LAN</literal> and <literal>DBUS</literal>
-        have a special meaning. <literal>WLAN</literal> and <literal>LAN</literal> are
-        configurations for universal <command>wpa_supplicant</command> service that is
+        The attribute names `WLAN`, `LAN` and `DBUS`
+        have a special meaning. `WLAN` and `LAN` are
+        configurations for universal {command}`wpa_supplicant` service that is
         started for each WLAN interface or for each LAN interface, respectively.
-        <literal>DBUS</literal> defines a device-unrelated <command>wpa_supplicant</command>
-        service that can be accessed through <literal>D-Bus</literal>.
+        `DBUS` defines a device-unrelated {command}`wpa_supplicant`
+        service that can be accessed through `D-Bus`.
       '';
 
     };
@@ -226,10 +226,10 @@ in
               ACTION=="add", SUBSYSTEM=="net", ENV{INTERFACE}=="${i}", TAG+="systemd", ENV{SYSTEMD_WANTS}+="supplicant-${replaceChars [" "] ["-"] iface}.service", TAG+="SUPPLICANT_ASSIGNED"''))}
 
           ${optionalString (hasAttr "WLAN" cfg) ''
-            ACTION=="add", SUBSYSTEM=="net", ENV{DEVTYPE}=="wlan", TAG!="SUPPLICANT_ASSIGNED", TAG+="systemd", PROGRAM="${pkgs.systemd}/bin/systemd-escape -p %E{INTERFACE}", ENV{SYSTEMD_WANTS}+="supplicant-wlan@$result.service"
+            ACTION=="add", SUBSYSTEM=="net", ENV{DEVTYPE}=="wlan", TAG!="SUPPLICANT_ASSIGNED", TAG+="systemd", PROGRAM="/run/current-system/systemd/bin/systemd-escape -p %E{INTERFACE}", ENV{SYSTEMD_WANTS}+="supplicant-wlan@$result.service"
           ''}
           ${optionalString (hasAttr "LAN" cfg) ''
-            ACTION=="add", SUBSYSTEM=="net", ENV{DEVTYPE}=="lan", TAG!="SUPPLICANT_ASSIGNED", TAG+="systemd", PROGRAM="${pkgs.systemd}/bin/systemd-escape -p %E{INTERFACE}", ENV{SYSTEMD_WANTS}+="supplicant-lan@$result.service"
+            ACTION=="add", SUBSYSTEM=="net", ENV{DEVTYPE}=="lan", TAG!="SUPPLICANT_ASSIGNED", TAG+="systemd", PROGRAM="/run/current-system/systemd/bin/systemd-escape -p %E{INTERFACE}", ENV{SYSTEMD_WANTS}+="supplicant-lan@$result.service"
           ''}
         '';
       })];
diff --git a/nixos/modules/services/networking/supybot.nix b/nixos/modules/services/networking/supybot.nix
index 94b79c7e247..22ba015cc55 100644
--- a/nixos/modules/services/networking/supybot.nix
+++ b/nixos/modules/services/networking/supybot.nix
@@ -16,7 +16,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable Supybot, an IRC bot (also known as Limnoria).";
+        description = lib.mdDoc "Enable Supybot, an IRC bot (also known as Limnoria).";
       };
 
       stateDir = mkOption {
@@ -25,12 +25,12 @@ in
           then "/var/lib/supybot"
           else "/home/supybot";
         defaultText = literalExpression "/var/lib/supybot";
-        description = "The root directory, logs and plugins are stored here";
+        description = lib.mdDoc "The root directory, logs and plugins are stored here";
       };
 
       configFile = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to initial supybot config file. This can be generated by
           running supybot-wizard.
 
@@ -42,12 +42,12 @@ in
       plugins = mkOption {
         type = types.attrsOf types.path;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Attribute set of additional plugins that will be symlinked to the
-          <filename>plugin</filename> subdirectory.
+          {file}`plugin` subdirectory.
 
           Please note that you still need to add the plugins to the config
-          file (or with <literal>!load</literal>) using their attribute name.
+          file (or with `!load`) using their attribute name.
         '';
         example = literalExpression ''
           let
@@ -67,10 +67,10 @@ in
         type = types.functionTo (types.listOf types.package);
         default = p: [];
         defaultText = literalExpression "p: []";
-        description = ''
+        description = lib.mdDoc ''
           Extra Python packages available to supybot plugins. The
           value must be a function which receives the attrset defined
-          in <varname>python3Packages</varname> as the sole argument.
+          in {var}`python3Packages` as the sole argument.
         '';
         example = literalExpression "p: [ p.lxml p.requests ]";
       };
diff --git a/nixos/modules/services/networking/syncplay.nix b/nixos/modules/services/networking/syncplay.nix
index b6faf2d3f77..726f6567107 100644
--- a/nixos/modules/services/networking/syncplay.nix
+++ b/nixos/modules/services/networking/syncplay.nix
@@ -17,13 +17,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "If enabled, start the Syncplay server.";
+        description = lib.mdDoc "If enabled, start the Syncplay server.";
       };
 
       port = mkOption {
         type = types.port;
         default = 8999;
-        description = ''
+        description = lib.mdDoc ''
           TCP port to bind to.
         '';
       };
@@ -31,7 +31,7 @@ in
       salt = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Salt to allow room operator passwords generated by this server
           instance to still work when the server is restarted.
         '';
@@ -40,16 +40,16 @@ in
       certDir = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           TLS certificates directory to use for encryption. See
-          <link xlink:href="https://github.com/Syncplay/syncplay/wiki/TLS-support"/>.
+          <https://github.com/Syncplay/syncplay/wiki/TLS-support>.
         '';
       };
 
       user = mkOption {
         type = types.str;
         default = "nobody";
-        description = ''
+        description = lib.mdDoc ''
           User to use when running Syncplay.
         '';
       };
@@ -57,10 +57,19 @@ in
       group = mkOption {
         type = types.str;
         default = "nogroup";
-        description = ''
+        description = lib.mdDoc ''
           Group to use when running Syncplay.
         '';
       };
+
+      passwordFile = mkOption {
+        type = types.nullOr types.path;
+        default = null;
+        description = lib.mdDoc ''
+          Path to the file that contains the server password. If
+          `null`, the server doesn't require a password.
+        '';
+      };
     };
   };
 
@@ -71,10 +80,17 @@ in
       after       = [ "network-online.target" ];
 
       serviceConfig = {
-        ExecStart = "${pkgs.syncplay}/bin/syncplay-server ${escapeShellArgs cmdArgs}";
         User = cfg.user;
         Group = cfg.group;
+        LoadCredential = lib.mkIf (cfg.passwordFile != null) "password:${cfg.passwordFile}";
       };
+
+      script = ''
+        ${lib.optionalString (cfg.passwordFile != null) ''
+          export SYNCPLAY_PASSWORD=$(cat "''${CREDENTIALS_DIRECTORY}/password")
+        ''}
+        exec ${pkgs.syncplay-nogui}/bin/syncplay-server ${escapeShellArgs cmdArgs}
+      '';
     };
   };
 }
diff --git a/nixos/modules/services/networking/syncthing-relay.nix b/nixos/modules/services/networking/syncthing-relay.nix
index f5ca63e7893..64c4e731b98 100644
--- a/nixos/modules/services/networking/syncthing-relay.nix
+++ b/nixos/modules/services/networking/syncthing-relay.nix
@@ -22,13 +22,13 @@ in {
   ###### interface
 
   options.services.syncthing.relay = {
-    enable = mkEnableOption "Syncthing relay service";
+    enable = mkEnableOption (lib.mdDoc "Syncthing relay service");
 
     listenAddress = mkOption {
       type = types.str;
       default = "";
       example = "1.2.3.4";
-      description = ''
+      description = lib.mdDoc ''
         Address to listen on for relay traffic.
       '';
     };
@@ -36,9 +36,9 @@ in {
     port = mkOption {
       type = types.port;
       default = 22067;
-      description = ''
+      description = lib.mdDoc ''
         Port to listen on for relay traffic. This port should be added to
-        <literal>networking.firewall.allowedTCPPorts</literal>.
+        `networking.firewall.allowedTCPPorts`.
       '';
     };
 
@@ -46,7 +46,7 @@ in {
       type = types.str;
       default = "";
       example = "1.2.3.4";
-      description = ''
+      description = lib.mdDoc ''
         Address to listen on for serving the relay status API.
       '';
     };
@@ -54,16 +54,16 @@ in {
     statusPort = mkOption {
       type = types.port;
       default = 22070;
-      description = ''
+      description = lib.mdDoc ''
         Port to listen on for serving the relay status API. This port should be
-        added to <literal>networking.firewall.allowedTCPPorts</literal>.
+        added to `networking.firewall.allowedTCPPorts`.
       '';
     };
 
     pools = mkOption {
       type = types.nullOr (types.listOf types.str);
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Relay pools to join. If null, uses the default global pool.
       '';
     };
@@ -71,7 +71,7 @@ in {
     providedBy = mkOption {
       type = types.str;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Human-readable description of the provider of the relay (you).
       '';
     };
@@ -79,7 +79,7 @@ in {
     globalRateBps = mkOption {
       type = types.nullOr types.ints.positive;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Global bandwidth rate limit in bytes per second.
       '';
     };
@@ -87,7 +87,7 @@ in {
     perSessionRateBps = mkOption {
       type = types.nullOr types.ints.positive;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Per session bandwidth rate limit in bytes per second.
       '';
     };
@@ -95,7 +95,7 @@ in {
     extraOptions = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Extra command line arguments to pass to strelaysrv.
       '';
     };
diff --git a/nixos/modules/services/networking/syncthing.nix b/nixos/modules/services/networking/syncthing.nix
index 3a3d4c80ecf..adbb25ccb9b 100644
--- a/nixos/modules/services/networking/syncthing.nix
+++ b/nixos/modules/services/networking/syncthing.nix
@@ -30,15 +30,22 @@ let
   updateConfig = pkgs.writers.writeDash "merge-syncthing-config" ''
     set -efu
 
+    # be careful not to leak secrets in the filesystem or in process listings
+
+    umask 0077
+
     # get the api key by parsing the config.xml
     while
-        ! api_key=$(${pkgs.libxml2}/bin/xmllint \
+        ! ${pkgs.libxml2}/bin/xmllint \
             --xpath 'string(configuration/gui/apikey)' \
-            ${cfg.configDir}/config.xml)
+            ${cfg.configDir}/config.xml \
+            >"$RUNTIME_DIRECTORY/api_key"
     do sleep 1; done
 
+    (printf "X-API-Key: "; cat "$RUNTIME_DIRECTORY/api_key") >"$RUNTIME_DIRECTORY/headers"
+
     curl() {
-        ${pkgs.curl}/bin/curl -sSLk -H "X-API-Key: $api_key" \
+        ${pkgs.curl}/bin/curl -sSLk -H "@$RUNTIME_DIRECTORY/headers" \
             --retry 1000 --retry-delay 1 --retry-all-errors \
             "$@"
     }
@@ -48,8 +55,8 @@ let
 
     # generate the new config by merging with the NixOS config options
     new_cfg=$(printf '%s\n' "$old_cfg" | ${pkgs.jq}/bin/jq -c '. * {
-        "devices": (${builtins.toJSON devices}${optionalString (! cfg.overrideDevices) " + .devices"}),
-        "folders": (${builtins.toJSON folders}${optionalString (! cfg.overrideFolders) " + .folders"})
+        "devices": (${builtins.toJSON devices}${optionalString (cfg.devices == {} || ! cfg.overrideDevices) " + .devices"}),
+        "folders": (${builtins.toJSON folders}${optionalString (cfg.folders == {} || ! cfg.overrideFolders) " + .folders"})
     } * ${builtins.toJSON cfg.extraOptions}')
 
     # send the new config
@@ -67,44 +74,44 @@ in {
     services.syncthing = {
 
       enable = mkEnableOption
-        "Syncthing, a self-hosted open-source alternative to Dropbox and Bittorrent Sync";
+        (lib.mdDoc "Syncthing, a self-hosted open-source alternative to Dropbox and Bittorrent Sync");
 
       cert = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
-          Path to the <literal>cert.pem</literal> file, which will be copied into Syncthing's
-          <link linkend="opt-services.syncthing.configDir">configDir</link>.
+        description = mdDoc ''
+          Path to the `cert.pem` file, which will be copied into Syncthing's
+          [configDir](#opt-services.syncthing.configDir).
         '';
       };
 
       key = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
-          Path to the <literal>key.pem</literal> file, which will be copied into Syncthing's
-          <link linkend="opt-services.syncthing.configDir">configDir</link>.
+        description = mdDoc ''
+          Path to the `key.pem` file, which will be copied into Syncthing's
+          [configDir](#opt-services.syncthing.configDir).
         '';
       };
 
       overrideDevices = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = mdDoc ''
           Whether to delete the devices which are not configured via the
-          <link linkend="opt-services.syncthing.devices">devices</link> option.
-          If set to <literal>false</literal>, devices added via the web
+          [devices](#opt-services.syncthing.devices) option.
+          If set to `false`, devices added via the web
           interface will persist and will have to be deleted manually.
         '';
       };
 
       devices = mkOption {
         default = {};
-        description = ''
+        description = mdDoc ''
           Peers/devices which Syncthing should communicate with.
 
           Note that you can still add devices manually, but those changes
-          will be reverted on restart if <link linkend="opt-services.syncthing.overrideDevices">overrideDevices</link>
+          will be reverted on restart if [overrideDevices](#opt-services.syncthing.overrideDevices)
           is enabled.
         '';
         example = {
@@ -119,7 +126,7 @@ in {
             name = mkOption {
               type = types.str;
               default = name;
-              description = ''
+              description = lib.mdDoc ''
                 The name of the device.
               '';
             };
@@ -127,7 +134,7 @@ in {
             addresses = mkOption {
               type = types.listOf types.str;
               default = [];
-              description = ''
+              description = lib.mdDoc ''
                 The addresses used to connect to the device.
                 If this is left empty, dynamic configuration is attempted.
               '';
@@ -135,27 +142,27 @@ in {
 
             id = mkOption {
               type = types.str;
-              description = ''
-                The device ID. See <link xlink:href="https://docs.syncthing.net/dev/device-ids.html"/>.
+              description = mdDoc ''
+                The device ID. See <https://docs.syncthing.net/dev/device-ids.html>.
               '';
             };
 
             introducer = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = mdDoc ''
                 Whether the device should act as an introducer and be allowed
                 to add folders on this computer.
-                See <link xlink:href="https://docs.syncthing.net/users/introducer.html"/>.
+                See <https://docs.syncthing.net/users/introducer.html>.
               '';
             };
 
             autoAcceptFolders = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = mdDoc ''
                 Automatically create or share folders that this device advertises at the default path.
-                See <link xlink:href="https://docs.syncthing.net/users/config.html?highlight=autoaccept#config-file-format"/>.
+                See <https://docs.syncthing.net/users/config.html?highlight=autoaccept#config-file-format>.
               '';
             };
 
@@ -166,21 +173,21 @@ in {
       overrideFolders = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = mdDoc ''
           Whether to delete the folders which are not configured via the
-          <link linkend="opt-services.syncthing.folders">folders</link> option.
-          If set to <literal>false</literal>, folders added via the web
+          [folders](#opt-services.syncthing.folders) option.
+          If set to `false`, folders added via the web
           interface will persist and will have to be deleted manually.
         '';
       };
 
       folders = mkOption {
         default = {};
-        description = ''
+        description = mdDoc ''
           Folders which should be shared by Syncthing.
 
-          Note that you can still add devices manually, but those changes
-          will be reverted on restart if <link linkend="opt-services.syncthing.overrideDevices">overrideDevices</link>
+          Note that you can still add folders manually, but those changes
+          will be reverted on restart if [overrideFolders](#opt-services.syncthing.overrideFolders)
           is enabled.
         '';
         example = literalExpression ''
@@ -197,7 +204,7 @@ in {
             enable = mkOption {
               type = types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Whether to share this folder.
                 This option is useful when you want to define all folders
                 in one place, but not every machine should share all folders.
@@ -205,17 +212,25 @@ in {
             };
 
             path = mkOption {
-              type = types.str;
+              # TODO for release 23.05: allow relative paths again and set
+              # working directory to cfg.dataDir
+              type = types.str // {
+                check = x: types.str.check x && (substring 0 1 x == "/" || substring 0 2 x == "~/");
+                description = types.str.description + " starting with / or ~/";
+              };
               default = name;
-              description = ''
+              description = lib.mdDoc ''
                 The path to the folder which should be shared.
+                Only absolute paths (starting with `/`) and paths relative to
+                the [user](#opt-services.syncthing.user)'s home directory
+                (starting with `~/`) are allowed.
               '';
             };
 
             id = mkOption {
               type = types.str;
               default = name;
-              description = ''
+              description = lib.mdDoc ''
                 The ID of the folder. Must be the same on all devices.
               '';
             };
@@ -223,7 +238,7 @@ in {
             label = mkOption {
               type = types.str;
               default = name;
-              description = ''
+              description = lib.mdDoc ''
                 The label of the folder.
               '';
             };
@@ -231,18 +246,18 @@ in {
             devices = mkOption {
               type = types.listOf types.str;
               default = [];
-              description = ''
+              description = mdDoc ''
                 The devices this folder should be shared with. Each device must
-                be defined in the <link linkend="opt-services.syncthing.devices">devices</link> option.
+                be defined in the [devices](#opt-services.syncthing.devices) option.
               '';
             };
 
             versioning = mkOption {
               default = null;
-              description = ''
+              description = mdDoc ''
                 How to keep changed/deleted files with Syncthing.
                 There are 4 different types of versioning with different parameters.
-                See <link xlink:href="https://docs.syncthing.net/users/versioning.html"/>.
+                See <https://docs.syncthing.net/users/versioning.html>.
               '';
               example = literalExpression ''
                 [
@@ -261,10 +276,10 @@ in {
                   {
                     versioning = {
                       type = "staggered";
+                      fsPath = "/syncthing/backup";
                       params = {
                         cleanInterval = "3600";
                         maxAge = "31536000";
-                        versionsPath = "/syncthing/backup";
                       };
                     };
                   }
@@ -284,17 +299,25 @@ in {
                 options = {
                   type = mkOption {
                     type = enum [ "external" "simple" "staggered" "trashcan" ];
-                    description = ''
+                    description = mdDoc ''
                       The type of versioning.
-                      See <link xlink:href="https://docs.syncthing.net/users/versioning.html"/>.
+                      See <https://docs.syncthing.net/users/versioning.html>.
+                    '';
+                  };
+                  fsPath = mkOption {
+                    default = "";
+                    type = either str path;
+                    description = mdDoc ''
+                      Path to the versioning folder.
+                      See <https://docs.syncthing.net/users/versioning.html>.
                     '';
                   };
                   params = mkOption {
                     type = attrsOf (either str path);
-                    description = ''
+                    description = mdDoc ''
                       The parameters for versioning. Structure depends on
-                      <link linkend="opt-services.syncthing.folders._name_.versioning.type">versioning.type</link>.
-                      See <link xlink:href="https://docs.syncthing.net/users/versioning.html"/>.
+                      [versioning.type](#opt-services.syncthing.folders._name_.versioning.type).
+                      See <https://docs.syncthing.net/users/versioning.html>.
                     '';
                   };
                 };
@@ -304,24 +327,25 @@ in {
             rescanInterval = mkOption {
               type = types.int;
               default = 3600;
-              description = ''
+              description = lib.mdDoc ''
                 How often the folder should be rescanned for changes.
               '';
             };
 
             type = mkOption {
-              type = types.enum [ "sendreceive" "sendonly" "receiveonly" ];
+              type = types.enum [ "sendreceive" "sendonly" "receiveonly" "receiveencrypted" ];
               default = "sendreceive";
-              description = ''
+              description = lib.mdDoc ''
                 Whether to only send changes for this folder, only receive them
-                or both.
+                or both. `receiveencrypted` can be used for untrusted devices. See
+                <https://docs.syncthing.net/users/untrusted.html> for reference.
               '';
             };
 
             watch = mkOption {
               type = types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Whether the folder should be watched for changes by inotify.
               '';
             };
@@ -329,7 +353,7 @@ in {
             watchDelay = mkOption {
               type = types.int;
               default = 10;
-              description = ''
+              description = lib.mdDoc ''
                 The delay after an inotify event is triggered.
               '';
             };
@@ -337,7 +361,7 @@ in {
             ignorePerms = mkOption {
               type = types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Whether to ignore permission changes.
               '';
             };
@@ -345,9 +369,9 @@ in {
             ignoreDelete = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = mdDoc ''
                 Whether to skip deleting files that are deleted by peers.
-                See <link xlink:href="https://docs.syncthing.net/advanced/folder-ignoredelete.html"/>.
+                See <https://docs.syncthing.net/advanced/folder-ignoredelete.html>.
               '';
             };
           };
@@ -357,9 +381,9 @@ in {
       extraOptions = mkOption {
         type = types.addCheck (pkgs.formats.json {}).type isAttrs;
         default = {};
-        description = ''
+        description = mdDoc ''
           Extra configuration options for Syncthing.
-          See <link xlink:href="https://docs.syncthing.net/users/config.html"/>.
+          See <https://docs.syncthing.net/users/config.html>.
         '';
         example = {
           options.localAnnounceEnabled = false;
@@ -370,7 +394,7 @@ in {
       guiAddress = mkOption {
         type = types.str;
         default = "127.0.0.1:8384";
-        description = ''
+        description = lib.mdDoc ''
           The address to serve the web interface at.
         '';
       };
@@ -378,7 +402,7 @@ in {
       systemService = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to auto-launch Syncthing as a system service.
         '';
       };
@@ -387,9 +411,10 @@ in {
         type = types.str;
         default = defaultUser;
         example = "yourUser";
-        description = ''
+        description = mdDoc ''
           The user to run Syncthing as.
-          By default, a user named <literal>${defaultUser}</literal> will be created.
+          By default, a user named `${defaultUser}` will be created whose home
+          directory is [dataDir](#opt-services.syncthing.dataDir).
         '';
       };
 
@@ -397,9 +422,9 @@ in {
         type = types.str;
         default = defaultGroup;
         example = "yourGroup";
-        description = ''
+        description = mdDoc ''
           The group to run Syncthing under.
-          By default, a group named <literal>${defaultGroup}</literal> will be created.
+          By default, a group named `${defaultGroup}` will be created.
         '';
       };
 
@@ -407,11 +432,11 @@ in {
         type = with types; nullOr str;
         default = null;
         example = "socks5://address.com:1234";
-        description = ''
+        description = mdDoc ''
           Overwrites the all_proxy environment variable for the Syncthing process to
           the given value. This is normally used to let Syncthing connect
           through a SOCKS5 proxy server.
-          See <link xlink:href="https://docs.syncthing.net/users/proxying.html"/>.
+          See <https://docs.syncthing.net/users/proxying.html>.
         '';
       };
 
@@ -419,7 +444,7 @@ in {
         type = types.path;
         default = "/var/lib/syncthing";
         example = "/home/yourUser";
-        description = ''
+        description = lib.mdDoc ''
           The path where synchronised directories will exist.
         '';
       };
@@ -428,29 +453,17 @@ in {
         cond = versionAtLeast config.system.stateVersion "19.03";
       in mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The path where the settings and keys will exist.
         '';
         default = cfg.dataDir + optionalString cond "/.config/syncthing";
-        defaultText = literalDocBook ''
-          <variablelist>
-            <varlistentry>
-              <term><literal>stateVersion >= 19.03</literal></term>
-              <listitem>
-                <programlisting>
-                  config.${opt.dataDir} + "/.config/syncthing"
-                </programlisting>
-              </listitem>
-            </varlistentry>
-            <varlistentry>
-              <term>otherwise</term>
-              <listitem>
-                <programlisting>
-                  config.${opt.dataDir}
-                </programlisting>
-              </listitem>
-            </varlistentry>
-          </variablelist>
+        defaultText = literalMD ''
+          * if `stateVersion >= 19.03`:
+
+                config.${opt.dataDir} + "/.config/syncthing"
+          * otherwise:
+
+                config.${opt.dataDir}
         '';
       };
 
@@ -458,7 +471,7 @@ in {
         type = types.listOf types.str;
         default = [];
         example = [ "--reset-deltas" ];
-        description = ''
+        description = lib.mdDoc ''
           Extra flags passed to the syncthing command in the service definition.
         '';
       };
@@ -467,7 +480,7 @@ in {
         type = types.bool;
         default = false;
         example = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to open the default ports in the firewall: TCP/UDP 22000 for transfers
           and UDP 21027 for discovery.
 
@@ -482,7 +495,7 @@ in {
         type = types.package;
         default = pkgs.syncthing;
         defaultText = literalExpression "pkgs.syncthing";
-        description = ''
+        description = lib.mdDoc ''
           The Syncthing package to use.
         '';
       };
@@ -525,6 +538,8 @@ in {
     };
 
     systemd.services = {
+      # upstream reference:
+      # https://github.com/syncthing/syncthing/blob/main/etc/linux-systemd/system/syncthing%40.service
       syncthing = mkIf cfg.systemService {
         description = "Syncthing service";
         after = [ "network.target" ];
@@ -536,7 +551,7 @@ in {
         wantedBy = [ "multi-user.target" ];
         serviceConfig = {
           Restart = "on-failure";
-          SuccessExitStatus = "2 3 4";
+          SuccessExitStatus = "3 4";
           RestartForceExitStatus="3 4";
           User = cfg.user;
           Group = cfg.group;
@@ -588,6 +603,7 @@ in {
         serviceConfig = {
           User = cfg.user;
           RemainAfterExit = true;
+          RuntimeDirectory = "syncthing-init";
           Type = "oneshot";
           ExecStart = updateConfig;
         };
diff --git a/nixos/modules/services/networking/tailscale.nix b/nixos/modules/services/networking/tailscale.nix
index 3f41646bf01..26997dd9601 100644
--- a/nixos/modules/services/networking/tailscale.nix
+++ b/nixos/modules/services/networking/tailscale.nix
@@ -2,43 +2,89 @@
 
 with lib;
 
-let cfg = config.services.tailscale;
+let
+  cfg = config.services.tailscale;
+  firewallOn = config.networking.firewall.enable;
+  rpfMode = config.networking.firewall.checkReversePath;
+  isNetworkd = config.networking.useNetworkd;
+  rpfIsStrict = rpfMode == true || rpfMode == "strict";
 in {
-  meta.maintainers = with maintainers; [ danderson mbaillie ];
+  meta.maintainers = with maintainers; [ danderson mbaillie twitchyliquid64 ];
 
   options.services.tailscale = {
-    enable = mkEnableOption "Tailscale client daemon";
+    enable = mkEnableOption (lib.mdDoc "Tailscale client daemon");
 
     port = mkOption {
       type = types.port;
       default = 41641;
-      description = "The port to listen on for tunnel traffic (0=autoselect).";
+      description = lib.mdDoc "The port to listen on for tunnel traffic (0=autoselect).";
     };
 
     interfaceName = mkOption {
       type = types.str;
       default = "tailscale0";
-      description = ''The interface name for tunnel traffic. Use "userspace-networking" (beta) to not use TUN.'';
+      description = lib.mdDoc ''The interface name for tunnel traffic. Use "userspace-networking" (beta) to not use TUN.'';
+    };
+
+    permitCertUid = mkOption {
+      type = types.nullOr types.nonEmptyStr;
+      default = null;
+      description = lib.mdDoc "Username or user ID of the user allowed to to fetch Tailscale TLS certificates for the node.";
     };
 
     package = mkOption {
       type = types.package;
       default = pkgs.tailscale;
       defaultText = literalExpression "pkgs.tailscale";
-      description = "The package to use for tailscale";
+      description = lib.mdDoc "The package to use for tailscale";
     };
   };
 
   config = mkIf cfg.enable {
+    warnings = optional (firewallOn && rpfIsStrict) ''
+      Strict reverse path filtering breaks Tailscale exit node use and some subnet routing setups. Consider setting:
+
+        networking.firewall.checkReversePath = "loose";
+    '';
     environment.systemPackages = [ cfg.package ]; # for the CLI
     systemd.packages = [ cfg.package ];
     systemd.services.tailscaled = {
       wantedBy = [ "multi-user.target" ];
-      path = [ pkgs.openresolv pkgs.procps ];
+      path = [
+        config.networking.resolvconf.package # for configuring DNS in some configs
+        pkgs.procps     # for collecting running services (opt-in feature)
+        pkgs.glibc      # for `getent` to look up user shells
+      ];
       serviceConfig.Environment = [
         "PORT=${toString cfg.port}"
         ''"FLAGS=--tun ${lib.escapeShellArg cfg.interfaceName}"''
-      ];
+      ] ++ (lib.optionals (cfg.permitCertUid != null) [
+        "TS_PERMIT_CERT_UID=${cfg.permitCertUid}"
+      ]);
+      # Restart tailscaled with a single `systemctl restart` at the
+      # end of activation, rather than a `stop` followed by a later
+      # `start`. Activation over Tailscale can hang for tens of
+      # seconds in the stop+start setup, if the activation script has
+      # a significant delay between the stop and start phases
+      # (e.g. script blocked on another unit with a slow shutdown).
+      #
+      # Tailscale is aware of the correctness tradeoff involved, and
+      # already makes its upstream systemd unit robust against unit
+      # version mismatches on restart for compatibility with other
+      # linux distros.
+      stopIfChanged = false;
+    };
+
+    networking.dhcpcd.denyInterfaces = [ cfg.interfaceName ];
+
+    systemd.network.networks."50-tailscale" = mkIf isNetworkd {
+      matchConfig = {
+        Name = cfg.interfaceName;
+      };
+      linkConfig = {
+        Unmanaged = true;
+        ActivationPolicy = "manual";
+      };
     };
   };
 }
diff --git a/nixos/modules/services/networking/tayga.nix b/nixos/modules/services/networking/tayga.nix
new file mode 100644
index 00000000000..299ae2777f7
--- /dev/null
+++ b/nixos/modules/services/networking/tayga.nix
@@ -0,0 +1,195 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let
+  cfg = config.services.tayga;
+
+  # Converts an address set to a string
+  strAddr = addr: "${addr.address}/${toString addr.prefixLength}";
+
+  configFile = pkgs.writeText "tayga.conf" ''
+    tun-device ${cfg.tunDevice}
+
+    ipv4-addr ${cfg.ipv4.address}
+    ${optionalString (cfg.ipv6.address != null) "ipv6-addr ${cfg.ipv6.address}"}
+
+    prefix ${strAddr cfg.ipv6.pool}
+    dynamic-pool ${strAddr cfg.ipv4.pool}
+    data-dir ${cfg.dataDir}
+  '';
+
+  addrOpts = v:
+    assert v == 4 || v == 6;
+    {
+      options = {
+        address = mkOption {
+          type = types.str;
+          description = lib.mdDoc "IPv${toString v} address.";
+        };
+
+        prefixLength = mkOption {
+          type = types.addCheck types.int (n: n >= 0 && n <= (if v == 4 then 32 else 128));
+          description = lib.mdDoc ''
+            Subnet mask of the interface, specified as the number of
+            bits in the prefix ("${if v == 4 then "24" else "64"}").
+          '';
+        };
+      };
+    };
+
+  versionOpts = v: {
+    options = {
+      router = {
+        address = mkOption {
+          type = types.str;
+          description = lib.mdDoc "The IPv${toString v} address of the router.";
+        };
+      };
+
+      address = mkOption {
+        type = types.nullOr types.str;
+        default = null;
+        description = lib.mdDoc "The source IPv${toString v} address of the TAYGA server.";
+      };
+
+      pool = mkOption {
+        type = with types; nullOr (submodule (addrOpts v));
+        description = lib.mdDoc "The pool of IPv${toString v} addresses which are used for translation.";
+      };
+    };
+  };
+in
+{
+  options = {
+    services.tayga = {
+      enable = mkEnableOption (lib.mdDoc "Tayga");
+
+      package = mkOption {
+        type = types.package;
+        default = pkgs.tayga;
+        defaultText = lib.literalMD "pkgs.tayga";
+        description = lib.mdDoc "This option specifies the TAYGA package to use.";
+      };
+
+      ipv4 = mkOption {
+        type = types.submodule (versionOpts 4);
+        description = lib.mdDoc "IPv4-specific configuration.";
+        example = literalExpression ''
+          {
+            address = "192.0.2.0";
+            router = {
+              address = "192.0.2.1";
+            };
+            pool = {
+              address = "192.0.2.1";
+              prefixLength = 24;
+            };
+          }
+        '';
+      };
+
+      ipv6 = mkOption {
+        type = types.submodule (versionOpts 6);
+        description = lib.mdDoc "IPv6-specific configuration.";
+        example = literalExpression ''
+          {
+            address = "2001:db8::1";
+            router = {
+              address = "64:ff9b::1";
+            };
+            pool = {
+              address = "64:ff9b::";
+              prefixLength = 96;
+            };
+          }
+        '';
+      };
+
+      dataDir = mkOption {
+        type = types.path;
+        default = "/var/lib/tayga";
+        description = lib.mdDoc "Directory for persistent data";
+      };
+
+      tunDevice = mkOption {
+        type = types.str;
+        default = "nat64";
+        description = lib.mdDoc "Name of the nat64 tun device";
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    networking.interfaces."${cfg.tunDevice}" = {
+      virtual = true;
+      virtualType = "tun";
+      virtualOwner = mkIf config.networking.useNetworkd "";
+      ipv4 = {
+        addresses = [
+          { address = cfg.ipv4.router.address; prefixLength = 32; }
+        ];
+        routes = [
+          cfg.ipv4.pool
+        ];
+      };
+      ipv6 = {
+        addresses = [
+          { address = cfg.ipv6.router.address; prefixLength = 128; }
+        ];
+        routes = [
+          cfg.ipv6.pool
+        ];
+      };
+    };
+
+    systemd.services.tayga = {
+      description = "Stateless NAT64 implementation";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+
+      serviceConfig = {
+        ExecStart = "${cfg.package}/bin/tayga -d --nodetach --config ${configFile}";
+        ExecReload = "${pkgs.coreutils}/bin/kill -SIGHUP $MAINPID";
+        Restart = "always";
+
+        # Hardening Score:
+        #  - nixos-scripts: 2.1
+        #  - systemd-networkd: 1.6
+        ProtectHome = true;
+        SystemCallFilter = [
+          "@network-io"
+          "@system-service"
+          "~@privileged"
+          "~@resources"
+        ];
+        ProtectKernelLogs = true;
+        AmbientCapabilities = [
+          "CAP_NET_ADMIN"
+        ];
+        CapabilityBoundingSet = "";
+        RestrictAddressFamilies = [
+          "AF_INET"
+          "AF_INET6"
+          "AF_NETLINK"
+        ];
+        StateDirectory = "tayga";
+        DynamicUser = mkIf config.networking.useNetworkd true;
+        MemoryDenyWriteExecute = true;
+        RestrictRealtime = true;
+        RestrictSUIDSGID = true;
+        ProtectHostname = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        RestrictNamespaces = true;
+        NoNewPrivileges = true;
+        ProtectControlGroups = true;
+        SystemCallArchitectures = "native";
+        PrivateTmp = true;
+        LockPersonality = true;
+        ProtectSystem = true;
+        PrivateUsers = true;
+        ProtectProc = "invisible";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/networking/tcpcrypt.nix b/nixos/modules/services/networking/tcpcrypt.nix
index 5a91054e166..f2115a6660c 100644
--- a/nixos/modules/services/networking/tcpcrypt.nix
+++ b/nixos/modules/services/networking/tcpcrypt.nix
@@ -17,7 +17,7 @@ in
     networking.tcpcrypt.enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable opportunistic TCP encryption. If the other end
         speaks Tcpcrypt, then your traffic will be encrypted; otherwise
         it will be sent in clear text. Thus, Tcpcrypt alone provides no
diff --git a/nixos/modules/services/networking/teamspeak3.nix b/nixos/modules/services/networking/teamspeak3.nix
index c0ed08282aa..f09ef1a959e 100644
--- a/nixos/modules/services/networking/teamspeak3.nix
+++ b/nixos/modules/services/networking/teamspeak3.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run the Teamspeak3 voice communication server daemon.
         '';
       };
@@ -27,7 +27,7 @@ in
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/teamspeak3-server";
-        description = ''
+        description = lib.mdDoc ''
           Directory to store TS3 database and other state/data files.
         '';
       };
@@ -35,7 +35,7 @@ in
       logPath = mkOption {
         type = types.path;
         default = "/var/log/teamspeak3-server/";
-        description = ''
+        description = lib.mdDoc ''
           Directory to store log files in.
         '';
       };
@@ -44,7 +44,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "[::]";
-        description = ''
+        description = lib.mdDoc ''
           IP on which the server instance will listen for incoming voice connections. Defaults to any IP.
         '';
       };
@@ -52,7 +52,7 @@ in
       defaultVoicePort = mkOption {
         type = types.int;
         default = 9987;
-        description = ''
+        description = lib.mdDoc ''
           Default UDP port for clients to connect to virtual servers - used for first virtual server, subsequent ones will open on incrementing port numbers by default.
         '';
       };
@@ -61,7 +61,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "[::]";
-        description = ''
+        description = lib.mdDoc ''
           IP on which the server instance will listen for incoming file transfer connections. Defaults to any IP.
         '';
       };
@@ -69,7 +69,7 @@ in
       fileTransferPort = mkOption {
         type = types.int;
         default = 30033;
-        description = ''
+        description = lib.mdDoc ''
           TCP port opened for file transfers.
         '';
       };
@@ -78,7 +78,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "0.0.0.0";
-        description = ''
+        description = lib.mdDoc ''
           IP on which the server instance will listen for incoming ServerQuery connections. Defaults to any IP.
         '';
       };
@@ -86,7 +86,7 @@ in
       queryPort = mkOption {
         type = types.int;
         default = 10011;
-        description = ''
+        description = lib.mdDoc ''
           TCP port opened for ServerQuery connections.
         '';
       };
@@ -94,13 +94,13 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the TeamSpeak3 server.";
+        description = lib.mdDoc "Open ports in the firewall for the TeamSpeak3 server.";
       };
 
       openFirewallServerQuery = mkOption {
         type = types.bool;
         default = false;
-        description = "Open ports in the firewall for the TeamSpeak3 serverquery (administration) system. Requires openFirewall.";
+        description = lib.mdDoc "Open ports in the firewall for the TeamSpeak3 serverquery (administration) system. Requires openFirewall.";
       };
 
     };
@@ -152,6 +152,7 @@ in
         WorkingDirectory = cfg.dataDir;
         User = user;
         Group = group;
+        Restart = "on-failure";
       };
     };
   };
diff --git a/nixos/modules/services/networking/tedicross.nix b/nixos/modules/services/networking/tedicross.nix
index c7830289dca..cee7e11f4fb 100644
--- a/nixos/modules/services/networking/tedicross.nix
+++ b/nixos/modules/services/networking/tedicross.nix
@@ -13,7 +13,7 @@ let
 in {
   options = {
     services.tedicross = {
-      enable = mkEnableOption "the TediCross Telegram-Discord bridge service";
+      enable = mkEnableOption (lib.mdDoc "the TediCross Telegram-Discord bridge service");
 
       config = mkOption {
         type = types.attrs;
@@ -57,9 +57,9 @@ in {
             debug = false;
           }
         '';
-        description = ''
-          <filename>settings.yaml</filename> configuration as a Nix attribute set.
-          Secret tokens should be specified using <option>environmentFile</option>
+        description = lib.mdDoc ''
+          {file}`settings.yaml` configuration as a Nix attribute set.
+          Secret tokens should be specified using {option}`environmentFile`
           instead of this world-readable file.
         '';
       };
@@ -67,10 +67,10 @@ in {
       environmentFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           File containing environment variables to be passed to the TediCross service,
           in which secret tokens can be specified securely using the
-          <literal>TELEGRAM_BOT_TOKEN</literal> and <literal>DISCORD_BOT_TOKEN</literal>
+          `TELEGRAM_BOT_TOKEN` and `DISCORD_BOT_TOKEN`
           keys.
         '';
       };
diff --git a/nixos/modules/services/networking/teleport.nix b/nixos/modules/services/networking/teleport.nix
index 45479162180..6433554f87d 100644
--- a/nixos/modules/services/networking/teleport.nix
+++ b/nixos/modules/services/networking/teleport.nix
@@ -9,7 +9,7 @@ in
 {
   options = {
     services.teleport = with lib.types; {
-      enable = mkEnableOption "the Teleport service";
+      enable = mkEnableOption (lib.mdDoc "the Teleport service");
 
       settings = mkOption {
         type = settingsYaml.type;
@@ -33,15 +33,15 @@ in
             auth_service.enabled = false;
           }
         '';
-        description = ''
-          Contents of the <literal>teleport.yaml</literal> config file.
-          The <literal>--config</literal> arguments will only be passed if this set is not empty.
+        description = lib.mdDoc ''
+          Contents of the `teleport.yaml` config file.
+          The `--config` arguments will only be passed if this set is not empty.
 
-          See <link xlink:href="https://goteleport.com/docs/setup/reference/config/"/>.
+          See <https://goteleport.com/docs/setup/reference/config/>.
         '';
       };
 
-      insecure.enable = mkEnableOption ''
+      insecure.enable = mkEnableOption (lib.mdDoc ''
         starting teleport in insecure mode.
 
         This is dangerous!
@@ -49,25 +49,25 @@ in
         Proceed with caution!
 
         Teleport starts with disabled certificate validation on Proxy Service, validation still occurs on Auth Service
-      '';
+      '');
 
       diag = {
-        enable = mkEnableOption ''
+        enable = mkEnableOption (lib.mdDoc ''
           endpoints for monitoring purposes.
 
-          See <link xlink:href="https://goteleport.com/docs/setup/admin/troubleshooting/#troubleshooting/"/>
-        '';
+          See <https://goteleport.com/docs/setup/admin/troubleshooting/#troubleshooting/>
+        '');
 
         addr = mkOption {
           type = str;
           default = "127.0.0.1";
-          description = "Metrics and diagnostics address.";
+          description = lib.mdDoc "Metrics and diagnostics address.";
         };
 
         port = mkOption {
-          type = int;
+          type = port;
           default = 3000;
-          description = "Metrics and diagnostics port.";
+          description = lib.mdDoc "Metrics and diagnostics port.";
         };
       };
     };
diff --git a/nixos/modules/services/networking/tetrd.nix b/nixos/modules/services/networking/tetrd.nix
index 0801ce12924..6284a5b1fb1 100644
--- a/nixos/modules/services/networking/tetrd.nix
+++ b/nixos/modules/services/networking/tetrd.nix
@@ -1,7 +1,7 @@
 { config, lib, pkgs, ... }:
 
 {
-  options.services.tetrd.enable = lib.mkEnableOption "tetrd";
+  options.services.tetrd.enable = lib.mkEnableOption (lib.mdDoc "tetrd");
 
   config = lib.mkIf config.services.tetrd.enable {
     environment = {
diff --git a/nixos/modules/services/networking/tftpd.nix b/nixos/modules/services/networking/tftpd.nix
index c9c0a2b321d..a4dc137daa4 100644
--- a/nixos/modules/services/networking/tftpd.nix
+++ b/nixos/modules/services/networking/tftpd.nix
@@ -11,7 +11,7 @@ with lib;
     services.tftpd.enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable tftpd, a Trivial File Transfer Protocol server.
         The server will be run as an xinetd service.
       '';
@@ -20,7 +20,7 @@ with lib;
     services.tftpd.path = mkOption {
       type = types.path;
       default = "/srv/tftp";
-      description = ''
+      description = lib.mdDoc ''
         Where the tftp server files are stored.
       '';
     };
diff --git a/nixos/modules/services/networking/thelounge.nix b/nixos/modules/services/networking/thelounge.nix
index a5118fd8b33..a188ffe866b 100644
--- a/nixos/modules/services/networking/thelounge.nix
+++ b/nixos/modules/services/networking/thelounge.nix
@@ -23,16 +23,16 @@ in
   imports = [ (mkRemovedOptionModule [ "services" "thelounge" "private" ] "The option was renamed to `services.thelounge.public` to follow upstream changes.") ];
 
   options.services.thelounge = {
-    enable = mkEnableOption "The Lounge web IRC client";
+    enable = mkEnableOption (lib.mdDoc "The Lounge web IRC client");
 
     public = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Make your The Lounge instance public.
-        Setting this to <literal>false</literal> will require you to configure user
-        accounts by using the (<command>thelounge</command>) command or by adding
-        entries in <filename>${dataDir}/users</filename>. You might need to restart
+        Setting this to `false` will require you to configure user
+        accounts by using the ({command}`thelounge`) command or by adding
+        entries in {file}`${dataDir}/users`. You might need to restart
         The Lounge after making changes to the state directory.
       '';
     };
@@ -40,7 +40,7 @@ in
     port = mkOption {
       type = types.port;
       default = 9000;
-      description = "TCP port to listen on for http connections.";
+      description = lib.mdDoc "TCP port to listen on for http connections.";
     };
 
     extraConfig = mkOption {
@@ -54,14 +54,14 @@ in
           port = 6697;
         };
       }'';
-      description = ''
-        The Lounge's <filename>config.js</filename> contents as attribute set (will be
+      description = lib.mdDoc ''
+        The Lounge's {file}`config.js` contents as attribute set (will be
         converted to JSON to generate the configuration file).
 
         The options defined here will be merged to the default configuration file.
-        Note: In case of duplicate configuration, options from <option>extraConfig</option> have priority.
+        Note: In case of duplicate configuration, options from {option}`extraConfig` have priority.
 
-        Documentation: <link xlink:href="https://thelounge.chat/docs/server/configuration" />
+        Documentation: <https://thelounge.chat/docs/server/configuration>
       '';
     };
 
@@ -69,9 +69,9 @@ in
       default = [ ];
       type = types.listOf types.package;
       example = literalExpression "[ pkgs.theLoungePlugins.themes.solarized ]";
-      description = ''
+      description = lib.mdDoc ''
         The Lounge plugins to install. Plugins can be found in
-        <literal>pkgs.theLoungePlugins.plugins</literal> and <literal>pkgs.theLoungePlugins.themes</literal>.
+        `pkgs.theLoungePlugins.plugins` and `pkgs.theLoungePlugins.themes`.
       '';
     };
   };
diff --git a/nixos/modules/services/networking/tinc.nix b/nixos/modules/services/networking/tinc.nix
index 31731b60d48..09b23a60a4a 100644
--- a/nixos/modules/services/networking/tinc.nix
+++ b/nixos/modules/services/networking/tinc.nix
@@ -24,13 +24,13 @@ let
     options = {
       address = mkOption {
         type = types.str;
-        description = "The external IP address or hostname where the host can be reached.";
+        description = lib.mdDoc "The external IP address or hostname where the host can be reached.";
       };
 
       port = mkOption {
         type = types.nullOr types.port;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The port where the host can be reached.
 
           If no port is specified, the default Port is used.
@@ -43,7 +43,7 @@ let
     options = {
       address = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The subnet of this host.
 
           Subnets can either be single MAC, IPv4 or IPv6 addresses, in which case
@@ -60,7 +60,7 @@ let
       prefixLength = mkOption {
         type = with types; nullOr (addCheck int (n: n >= 0 && n <= 128));
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The prefix length of the subnet.
 
           If null, a subnet consisting of only that single address is assumed.
@@ -72,7 +72,7 @@ let
       weight = mkOption {
         type = types.ints.unsigned;
         default = 10;
-        description = ''
+        description = lib.mdDoc ''
           Indicates the priority over identical Subnets owned by different nodes.
 
           Lower values indicate higher priority. Packets will be sent to the
@@ -89,9 +89,9 @@ let
       addresses = mkOption {
         type = types.listOf (types.submodule addressSubmodule);
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           The external address where the host can be reached. This will set this
-          host's <option>settings.Address</option> option.
+          host's {option}`settings.Address` option.
 
           This variable is only required if you want to connect to this host.
         '';
@@ -100,9 +100,9 @@ let
       subnets = mkOption {
         type = types.listOf (types.submodule subnetSubmodule);
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           The subnets which this tinc daemon will serve. This will set this
-          host's <option>settings.Subnet</option> option.
+          host's {option}`settings.Subnet` option.
 
           Tinc tries to look up which other daemon it should send a packet to by
           searching the appropriate subnet. If the packet matches a subnet, it
@@ -114,24 +114,24 @@ let
       rsaPublicKey = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Legacy RSA public key of the host in PEM format, including start and
           end markers.
 
           This will be appended as-is in the host's configuration file.
 
           The ed25519 public key can be specified using the
-          <option>settings.Ed25519PublicKey</option> option instead.
+          {option}`settings.Ed25519PublicKey` option instead.
         '';
       };
 
       settings = mkOption {
         default = { };
         type = types.submodule { freeformType = tincConfType; };
-        description = ''
+        description = lib.mdDoc ''
           Configuration for this host.
 
-          See <link xlink:href="https://tinc-vpn.org/documentation-1.1/Host-configuration-variables.html"/>
+          See <https://tinc-vpn.org/documentation-1.1/Host-configuration-variables.html>
           for supported values.
         '';
       };
@@ -167,10 +167,10 @@ in
             extraConfig = mkOption {
               default = "";
               type = types.lines;
-              description = ''
+              description = lib.mdDoc ''
                 Extra lines to add to the tinc service configuration file.
 
-                Note that using the declarative <option>service.tinc.networks.&lt;name&gt;.settings</option>
+                Note that using the declarative {option}`service.tinc.networks.<name>.settings`
                 option is preferred.
               '';
             };
@@ -178,7 +178,7 @@ in
             name = mkOption {
               default = null;
               type = types.nullOr types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The name of the node which is used as an identifier when communicating
                 with the remote nodes in the mesh. If null then the hostname of the system
                 is used to derive a name (note that tinc may replace non-alphanumeric characters in
@@ -189,7 +189,7 @@ in
             ed25519PrivateKeyFile = mkOption {
               default = null;
               type = types.nullOr types.path;
-              description = ''
+              description = lib.mdDoc ''
                 Path of the private ed25519 keyfile.
               '';
             };
@@ -197,7 +197,7 @@ in
             rsaPrivateKeyFile = mkOption {
               default = null;
               type = types.nullOr types.path;
-              description = ''
+              description = lib.mdDoc ''
                 Path of the private RSA keyfile.
               '';
             };
@@ -205,9 +205,9 @@ in
             debugLevel = mkOption {
               default = 0;
               type = types.addCheck types.int (l: l >= 0 && l <= 5);
-              description = ''
+              description = lib.mdDoc ''
                 The amount of debugging information to add to the log. 0 means little
-                logging while 5 is the most logging. <command>man tincd</command> for
+                logging while 5 is the most logging. {command}`man tincd` for
                 more details.
               '';
             };
@@ -215,11 +215,11 @@ in
             hosts = mkOption {
               default = { };
               type = types.attrsOf types.lines;
-              description = ''
+              description = lib.mdDoc ''
                 The name of the host in the network as well as the configuration for that host.
                 This name should only contain alphanumerics and underscores.
 
-                Note that using the declarative <option>service.tinc.networks.&lt;name&gt;.hostSettings</option>
+                Note that using the declarative {option}`service.tinc.networks.<name>.hostSettings`
                 option is preferred.
               '';
             };
@@ -249,7 +249,7 @@ in
                 }
               '';
               type = types.attrsOf (types.submodule hostSubmodule);
-              description = ''
+              description = lib.mdDoc ''
                 The name of the host in the network as well as the configuration for that host.
                 This name should only contain alphanumerics and underscores.
               '';
@@ -258,7 +258,7 @@ in
             interfaceType = mkOption {
               default = "tun";
               type = types.enum [ "tun" "tap" ];
-              description = ''
+              description = lib.mdDoc ''
                 The type of virtual interface used for the network connection.
               '';
             };
@@ -266,7 +266,7 @@ in
             listenAddress = mkOption {
               default = null;
               type = types.nullOr types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The ip address to listen on for incoming connections.
               '';
             };
@@ -274,7 +274,7 @@ in
             bindToAddress = mkOption {
               default = null;
               type = types.nullOr types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The ip address to bind to (both listen on and send packets from).
               '';
             };
@@ -283,7 +283,7 @@ in
               type = types.package;
               default = pkgs.tinc_pre;
               defaultText = literalExpression "pkgs.tinc_pre";
-              description = ''
+              description = lib.mdDoc ''
                 The package to use for the tinc daemon's binary.
               '';
             };
@@ -291,7 +291,7 @@ in
             chroot = mkOption {
               default = false;
               type = types.bool;
-              description = ''
+              description = lib.mdDoc ''
                 Change process root directory to the directory where the config file is located (/etc/tinc/netname/), for added security.
                 The chroot is performed after all the initialization is done, after writing pid files and opening network sockets.
 
@@ -309,10 +309,10 @@ in
                   Mode = "switch";
                 }
               '';
-              description = ''
+              description = lib.mdDoc ''
                 Configuration of the Tinc daemon for this network.
 
-                See <link xlink:href="https://tinc-vpn.org/documentation-1.1/Main-configuration-variables.html"/>
+                See <https://tinc-vpn.org/documentation-1.1/Main-configuration-variables.html>
                 for supported values.
               '';
             };
@@ -337,7 +337,7 @@ in
           };
         }));
 
-        description = ''
+        description = lib.mdDoc ''
           Defines the tinc networks which will be started.
           Each network invokes a different daemon.
         '';
@@ -410,7 +410,7 @@ in
     environment.systemPackages = let
       cli-wrappers = pkgs.stdenv.mkDerivation {
         name = "tinc-cli-wrappers";
-        buildInputs = [ pkgs.makeWrapper ];
+        nativeBuildInputs = [ pkgs.makeWrapper ];
         buildCommand = ''
           mkdir -p $out/bin
           ${concatStringsSep "\n" (mapAttrsToList (network: data:
diff --git a/nixos/modules/services/networking/tinydns.nix b/nixos/modules/services/networking/tinydns.nix
index 2c44ad49296..ea91af5f196 100644
--- a/nixos/modules/services/networking/tinydns.nix
+++ b/nixos/modules/services/networking/tinydns.nix
@@ -10,19 +10,19 @@ with lib;
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = "Whether to run the tinydns dns server";
+        description = lib.mdDoc "Whether to run the tinydns dns server";
       };
 
       data = mkOption {
         type = types.lines;
         default = "";
-        description = "The DNS data to serve, in the format described by tinydns-data(8)";
+        description = lib.mdDoc "The DNS data to serve, in the format described by tinydns-data(8)";
       };
 
       ip = mkOption {
         default = "0.0.0.0";
         type = types.str;
-        description = "IP address on which to listen for connections";
+        description = lib.mdDoc "IP address on which to listen for connections";
       };
     };
   };
diff --git a/nixos/modules/services/networking/tmate-ssh-server.nix b/nixos/modules/services/networking/tmate-ssh-server.nix
new file mode 100644
index 00000000000..1b8f6662ef4
--- /dev/null
+++ b/nixos/modules/services/networking/tmate-ssh-server.nix
@@ -0,0 +1,122 @@
+{ config, lib, pkgs, ... }:
+with lib;
+let
+  cfg = config.services.tmate-ssh-server;
+
+  defaultKeysDir = "/etc/tmate-ssh-server-keys";
+  edKey = "${defaultKeysDir}/ssh_host_ed25519_key";
+  rsaKey = "${defaultKeysDir}/ssh_host_rsa_key";
+
+  keysDir =
+    if cfg.keysDir == null
+    then defaultKeysDir
+    else cfg.keysDir;
+
+  domain = config.networking.domain;
+in
+{
+  options.services.tmate-ssh-server = {
+    enable = mkEnableOption (mdDoc "tmate ssh server");
+
+    package = mkOption {
+      type = types.package;
+      description = mdDoc "The package containing tmate-ssh-server";
+      defaultText = literalExpression "pkgs.tmate-ssh-server";
+      default = pkgs.tmate-ssh-server;
+    };
+
+    host = mkOption {
+      type = types.str;
+      description = mdDoc "External host name";
+      defaultText = lib.literalExpression "config.networking.domain or config.networking.hostName ";
+      default =
+        if domain == null then
+          config.networking.hostName
+        else
+          domain;
+    };
+
+    port = mkOption {
+      type = types.port;
+      description = mdDoc "Listen port for the ssh server";
+      default = 2222;
+    };
+
+    openFirewall = mkOption {
+      type = types.bool;
+      default = true;
+      description = mdDoc "Whether to automatically open the specified ports in the firewall.";
+    };
+
+    advertisedPort = mkOption {
+      type = types.port;
+      description = mdDoc "External port advertised to clients";
+    };
+
+    keysDir = mkOption {
+      type = with types; nullOr str;
+      description = mdDoc "Directory containing ssh keys, defaulting to auto-generation";
+      default = null;
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    networking.firewall.allowedTCPPorts = optionals cfg.openFirewall [ cfg.port ];
+
+    services.tmate-ssh-server = {
+      advertisedPort = mkDefault cfg.port;
+    };
+
+    environment.systemPackages =
+      let
+        tmate-config = pkgs.writeText "tmate.conf"
+          ''
+            set -g tmate-server-host "${cfg.host}"
+            set -g tmate-server-port ${toString cfg.port}
+            set -g tmate-server-ed25519-fingerprint "@ed25519_fingerprint@"
+            set -g tmate-server-rsa-fingerprint "@rsa_fingerprint@"
+          '';
+      in
+      [
+        (pkgs.writeShellApplication {
+          name = "tmate-client-config";
+          runtimeInputs = with pkgs;[ openssh coreutils sd ];
+          text = ''
+            RSA_SIG="$(ssh-keygen -l -E SHA256 -f "${keysDir}/ssh_host_rsa_key.pub" | cut -d ' ' -f 2)"
+            ED25519_SIG="$(ssh-keygen -l -E SHA256 -f "${keysDir}/ssh_host_ed25519_key.pub" | cut -d ' ' -f 2)"
+            sd -sp '@ed25519_fingerprint@' "$ED25519_SIG" ${tmate-config} | \
+              sd -sp '@rsa_fingerprint@' "$RSA_SIG"
+          '';
+        })
+      ];
+
+    systemd.services.tmate-ssh-server = {
+      description = "tmate SSH Server";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        ExecStart = "${cfg.package}/bin/tmate-ssh-server -h ${cfg.host} -p ${toString cfg.port} -q ${toString cfg.advertisedPort} -k ${keysDir}";
+      };
+      preStart = mkIf (cfg.keysDir == null) ''
+        if [[ ! -d ${defaultKeysDir} ]]
+        then
+          mkdir -p ${defaultKeysDir}
+        fi
+        if [[ ! -f ${edKey} ]]
+        then
+          ${pkgs.openssh}/bin/ssh-keygen -t ed25519 -f ${edKey} -N ""
+        fi
+        if [[ ! -f ${rsaKey} ]]
+        then
+          ${pkgs.openssh}/bin/ssh-keygen -t rsa -f ${rsaKey} -N ""
+        fi
+      '';
+    };
+  };
+
+  meta = {
+    maintainers = with maintainers; [ jlesquembre ];
+  };
+
+}
diff --git a/nixos/modules/services/networking/tox-bootstrapd.nix b/nixos/modules/services/networking/tox-bootstrapd.nix
index 7c13724e084..5c7e7a4c220 100644
--- a/nixos/modules/services/networking/tox-bootstrapd.nix
+++ b/nixos/modules/services/networking/tox-bootstrapd.nix
@@ -23,31 +23,31 @@ in
             type = types.bool;
             default = false;
             description =
-              ''
+              lib.mdDoc ''
                 Whether to enable the Tox DHT bootstrap daemon.
               '';
           };
 
           port = mkOption {
-            type = types.int;
+            type = types.port;
             default = 33445;
-            description = "Listening port (UDP).";
+            description = lib.mdDoc "Listening port (UDP).";
           };
 
           keysFile = mkOption {
             type = types.str;
             default = "${WorkingDirectory}/keys";
-            description = "Node key file.";
+            description = lib.mdDoc "Node key file.";
           };
 
           extraConfig = mkOption {
             type = types.lines;
             default = "";
             description =
-              ''
+              lib.mdDoc ''
                 Configuration for bootstrap daemon.
-                See <link xlink:href="https://github.com/irungentoo/toxcore/blob/master/other/bootstrap_daemon/tox-bootstrapd.conf"/>
-                and <link xlink:href="http://wiki.tox.im/Nodes"/>.
+                See <https://github.com/irungentoo/toxcore/blob/master/other/bootstrap_daemon/tox-bootstrapd.conf>
+                and <http://wiki.tox.im/Nodes>.
              '';
           };
       };
diff --git a/nixos/modules/services/networking/tox-node.nix b/nixos/modules/services/networking/tox-node.nix
index c6e5c2d6e81..fa5b241f918 100644
--- a/nixos/modules/services/networking/tox-node.nix
+++ b/nixos/modules/services/networking/tox-node.nix
@@ -28,47 +28,47 @@ let
 
 in {
   options.services.tox-node = {
-    enable = mkEnableOption "Tox Node service";
+    enable = mkEnableOption (lib.mdDoc "Tox Node service");
 
     logType = mkOption {
       type = types.enum [ "Stderr" "Stdout" "Syslog" "None" ];
       default = "Stderr";
-      description = "Logging implementation.";
+      description = lib.mdDoc "Logging implementation.";
     };
     keysFile = mkOption {
       type = types.str;
       default = "${homeDir}/keys";
-      description = "Path to the file where DHT keys are stored.";
+      description = lib.mdDoc "Path to the file where DHT keys are stored.";
     };
     udpAddress = mkOption {
       type = types.str;
       default = "0.0.0.0:33445";
-      description = "UDP address to run DHT node.";
+      description = lib.mdDoc "UDP address to run DHT node.";
     };
     tcpAddresses = mkOption {
       type = types.listOf types.str;
       default = [ "0.0.0.0:33445" ];
-      description = "TCP addresses to run TCP relay.";
+      description = lib.mdDoc "TCP addresses to run TCP relay.";
     };
     tcpConnectionLimit = mkOption {
       type = types.int;
       default = 8192;
-      description = "Maximum number of active TCP connections relay can hold";
+      description = lib.mdDoc "Maximum number of active TCP connections relay can hold";
     };
     lanDiscovery = mkOption {
       type = types.bool;
       default = true;
-      description = "Enable local network discovery.";
+      description = lib.mdDoc "Enable local network discovery.";
     };
     threads = mkOption {
       type = types.int;
       default = 1;
-      description = "Number of threads for execution";
+      description = lib.mdDoc "Number of threads for execution";
     };
     motd = mkOption {
       type = types.str;
       default = "Hi from tox-rs! I'm up {{uptime}}. TCP: incoming {{tcp_packets_in}}, outgoing {{tcp_packets_out}}, UDP: incoming {{udp_packets_in}}, outgoing {{udp_packets_out}}";
-      description = "Message of the day";
+      description = lib.mdDoc "Message of the day";
     };
   };
 
diff --git a/nixos/modules/services/networking/toxvpn.nix b/nixos/modules/services/networking/toxvpn.nix
index 18cf7672d5f..3a14b5f7309 100644
--- a/nixos/modules/services/networking/toxvpn.nix
+++ b/nixos/modules/services/networking/toxvpn.nix
@@ -5,25 +5,25 @@ with lib;
 {
   options = {
     services.toxvpn = {
-      enable = mkEnableOption "toxvpn running on startup";
+      enable = mkEnableOption (lib.mdDoc "toxvpn running on startup");
 
       localip = mkOption {
         type        = types.str;
         default     = "10.123.123.1";
-        description = "your ip on the vpn";
+        description = lib.mdDoc "your ip on the vpn";
       };
 
       port = mkOption {
-        type        = types.int;
+        type        = types.port;
         default     = 33445;
-        description = "udp port for toxcore, port-forward to help with connectivity if you run many nodes behind one NAT";
+        description = lib.mdDoc "udp port for toxcore, port-forward to help with connectivity if you run many nodes behind one NAT";
       };
 
       auto_add_peers = mkOption {
         type        = types.listOf types.str;
         default     = [];
         example     = [ "toxid1" "toxid2" ];
-        description = "peers to automatically connect to on startup";
+        description = lib.mdDoc "peers to automatically connect to on startup";
       };
     };
   };
diff --git a/nixos/modules/services/networking/trickster.nix b/nixos/modules/services/networking/trickster.nix
index e48bba8fa58..0b696e412b4 100644
--- a/nixos/modules/services/networking/trickster.nix
+++ b/nixos/modules/services/networking/trickster.nix
@@ -6,13 +6,16 @@ let
   cfg = config.services.trickster;
 in
 {
+  imports = [
+    (mkRenamedOptionModule [ "services" "trickster" "origin" ] [ "services" "trickster" "origin-url" ])
+  ];
 
   options = {
     services.trickster = {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable Trickster.
         '';
       };
@@ -21,7 +24,7 @@ in
         type = types.package;
         default = pkgs.trickster;
         defaultText = literalExpression "pkgs.trickster";
-        description = ''
+        description = lib.mdDoc ''
           Package that should be used for trickster.
         '';
       };
@@ -29,7 +32,7 @@ in
       configFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to configuration file.
         '';
       };
@@ -37,7 +40,7 @@ in
       instance-id = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Instance ID for when running multiple processes (default null).
         '';
       };
@@ -45,7 +48,7 @@ in
       log-level = mkOption {
         type = types.str;
         default = "info";
-        description = ''
+        description = lib.mdDoc ''
           Level of Logging to use (debug, info, warn, error) (default "info").
         '';
       };
@@ -53,23 +56,31 @@ in
       metrics-port = mkOption {
         type = types.port;
         default = 8082;
-        description = ''
+        description = lib.mdDoc ''
           Port that the /metrics endpoint will listen on.
         '';
       };
 
-      origin = mkOption {
+      origin-type = mkOption {
+        type = types.enum [ "prometheus" "influxdb" ];
+        default = "prometheus";
+        description = lib.mdDoc ''
+          Type of origin (prometheus, influxdb)
+        '';
+      };
+
+      origin-url = mkOption {
         type = types.str;
         default = "http://prometheus:9090";
-        description = ''
-          URL to the Prometheus Origin. Enter it like you would in grafana, e.g., http://prometheus:9090 (default http://prometheus:9090).
+        description = lib.mdDoc ''
+          URL to the Origin. Enter it like you would in grafana, e.g., http://prometheus:9090 (default http://prometheus:9090).
         '';
       };
 
       profiler-port = mkOption {
         type = types.nullOr types.port;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Port that the /debug/pprof endpoint will listen on.
         '';
       };
@@ -77,7 +88,7 @@ in
       proxy-port = mkOption {
         type = types.port;
         default = 9090;
-        description = ''
+        description = lib.mdDoc ''
           Port that the Proxy server will listen on.
         '';
       };
@@ -87,7 +98,7 @@ in
 
   config = mkIf cfg.enable {
     systemd.services.trickster = {
-      description = "Dashboard Accelerator for Prometheus";
+      description = "Reverse proxy cache and time series dashboard accelerator";
       after = [ "network.target" ];
       wantedBy = [ "multi-user.target" ];
       serviceConfig = {
@@ -96,7 +107,8 @@ in
           ${cfg.package}/bin/trickster \
           -log-level ${cfg.log-level} \
           -metrics-port ${toString cfg.metrics-port} \
-          -origin ${cfg.origin} \
+          -origin-type ${cfg.origin-type} \
+          -origin-url ${cfg.origin-url} \
           -proxy-port ${toString cfg.proxy-port} \
           ${optionalString (cfg.configFile != null) "-config ${cfg.configFile}"} \
           ${optionalString (cfg.profiler-port != null) "-profiler-port ${cfg.profiler-port}"} \
diff --git a/nixos/modules/services/networking/tvheadend.nix b/nixos/modules/services/networking/tvheadend.nix
index 19a10a03bd9..466dbbccad5 100644
--- a/nixos/modules/services/networking/tvheadend.nix
+++ b/nixos/modules/services/networking/tvheadend.nix
@@ -9,17 +9,17 @@ in
 {
   options = {
     services.tvheadend = {
-      enable = mkEnableOption "Tvheadend";
+      enable = mkEnableOption (lib.mdDoc "Tvheadend");
       httpPort = mkOption {
         type        = types.int;
         default     = 9981;
-        description = "Port to bind HTTP to.";
+        description = lib.mdDoc "Port to bind HTTP to.";
       };
 
       htspPort = mkOption {
         type        = types.int;
         default     = 9982;
-        description = "Port to bind HTSP to.";
+        description = lib.mdDoc "Port to bind HTSP to.";
       };
     };
   };
diff --git a/nixos/modules/services/networking/ucarp.nix b/nixos/modules/services/networking/ucarp.nix
index 189e4f99cef..1214cec63f5 100644
--- a/nixos/modules/services/networking/ucarp.nix
+++ b/nixos/modules/services/networking/ucarp.nix
@@ -28,34 +28,34 @@ let
   );
 in {
   options.networking.ucarp = {
-    enable = mkEnableOption "ucarp, userspace implementation of CARP";
+    enable = mkEnableOption (lib.mdDoc "ucarp, userspace implementation of CARP");
 
     interface = mkOption {
       type = types.str;
-      description = "Network interface to bind to.";
+      description = lib.mdDoc "Network interface to bind to.";
       example = "eth0";
     };
 
     srcIp = mkOption {
       type = types.str;
-      description = "Source (real) IP address of this host.";
+      description = lib.mdDoc "Source (real) IP address of this host.";
     };
 
     vhId = mkOption {
       type = types.ints.between 1 255;
-      description = "Virtual IP identifier shared between CARP hosts.";
+      description = lib.mdDoc "Virtual IP identifier shared between CARP hosts.";
       example = 1;
     };
 
     passwordFile = mkOption {
       type = types.str;
-      description = "File containing shared password between CARP hosts.";
+      description = lib.mdDoc "File containing shared password between CARP hosts.";
       example = "/run/keys/ucarp-password";
     };
 
     preempt = mkOption {
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Enable preemptive failover.
         Thus, this host becomes the CARP master as soon as possible.
       '';
@@ -64,30 +64,30 @@ in {
 
     neutral = mkOption {
       type = types.bool;
-      description = "Do not run downscript at start if the host is the backup.";
+      description = lib.mdDoc "Do not run downscript at start if the host is the backup.";
       default = false;
     };
 
     addr = mkOption {
       type = types.str;
-      description = "Virtual shared IP address.";
+      description = lib.mdDoc "Virtual shared IP address.";
     };
 
     advBase = mkOption {
       type = types.ints.unsigned;
-      description = "Advertisement frequency in seconds.";
+      description = lib.mdDoc "Advertisement frequency in seconds.";
       default = 1;
     };
 
     advSkew = mkOption {
       type = types.ints.unsigned;
-      description = "Advertisement skew in seconds.";
+      description = lib.mdDoc "Advertisement skew in seconds.";
       default = 0;
     };
 
     upscript = mkOption {
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Command to run after become master, the interface name, virtual address
         and optional extra parameters are passed as arguments.
       '';
@@ -101,7 +101,7 @@ in {
 
     downscript = mkOption {
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Command to run after become backup, the interface name, virtual address
         and optional extra parameters are passed as arguments.
       '';
@@ -115,37 +115,37 @@ in {
 
     deadratio = mkOption {
       type = types.ints.unsigned;
-      description = "Ratio to consider a host as dead.";
+      description = lib.mdDoc "Ratio to consider a host as dead.";
       default = 3;
     };
 
     shutdown = mkOption {
       type = types.bool;
-      description = "Call downscript at exit.";
+      description = lib.mdDoc "Call downscript at exit.";
       default = false;
     };
 
     ignoreIfState = mkOption {
       type = types.bool;
-      description = "Ignore interface state, e.g., down or no carrier.";
+      description = lib.mdDoc "Ignore interface state, e.g., down or no carrier.";
       default = false;
     };
 
     noMcast = mkOption {
       type = types.bool;
-      description = "Use broadcast instead of multicast advertisements.";
+      description = lib.mdDoc "Use broadcast instead of multicast advertisements.";
       default = false;
     };
 
     extraParam = mkOption {
       type = types.nullOr types.str;
-      description = "Extra parameter to pass to the up/down scripts.";
+      description = lib.mdDoc "Extra parameter to pass to the up/down scripts.";
       default = null;
     };
 
     package = mkOption {
       type = types.package;
-      description = ''
+      description = lib.mdDoc ''
         Package that should be used for ucarp.
 
         Please note that the default package, pkgs.ucarp, has not received any
diff --git a/nixos/modules/services/networking/unbound.nix b/nixos/modules/services/networking/unbound.nix
index 87873c8c1e8..fa24c70e63d 100644
--- a/nixos/modules/services/networking/unbound.nix
+++ b/nixos/modules/services/networking/unbound.nix
@@ -40,37 +40,37 @@ in {
   options = {
     services.unbound = {
 
-      enable = mkEnableOption "Unbound domain name server";
+      enable = mkEnableOption (lib.mdDoc "Unbound domain name server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.unbound-with-systemd;
         defaultText = literalExpression "pkgs.unbound-with-systemd";
-        description = "The unbound package to use";
+        description = lib.mdDoc "The unbound package to use";
       };
 
       user = mkOption {
         type = types.str;
         default = "unbound";
-        description = "User account under which unbound runs.";
+        description = lib.mdDoc "User account under which unbound runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "unbound";
-        description = "Group under which unbound runs.";
+        description = lib.mdDoc "Group under which unbound runs.";
       };
 
       stateDir = mkOption {
         type = types.path;
         default = "/var/lib/unbound";
-        description = "Directory holding all state for unbound to run.";
+        description = lib.mdDoc "Directory holding all state for unbound to run.";
       };
 
       resolveLocalQueries = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether unbound should resolve local queries (i.e. add 127.0.0.1 to
           /etc/resolv.conf).
         '';
@@ -79,7 +79,7 @@ in {
       enableRootTrustAnchor = mkOption {
         default = true;
         type = types.bool;
-        description = "Use and update root trust anchor for DNSSEC validation.";
+        description = lib.mdDoc "Use and update root trust anchor for DNSSEC validation.";
       };
 
       localControlSocketPath = mkOption {
@@ -90,16 +90,16 @@ in {
         # but I haven't verified yet.
         type = types.nullOr types.str;
         example = "/run/unbound/unbound.ctl";
-        description = ''
-          When not set to <literal>null</literal> this option defines the path
+        description = lib.mdDoc ''
+          When not set to `null` this option defines the path
           at which the unbound remote control socket should be created at. The
-          socket will be owned by the unbound user (<literal>unbound</literal>)
-          and group will be <literal>nogroup</literal>.
+          socket will be owned by the unbound user (`unbound`)
+          and group will be `nogroup`.
 
           Users that should be permitted to access the socket must be in the
-          <literal>config.services.unbound.group</literal> group.
+          `config.services.unbound.group` group.
 
-          If this option is <literal>null</literal> remote control will not be
+          If this option is `null` remote control will not be
           enabled. Unbounds default values apply.
         '';
       };
@@ -150,10 +150,9 @@ in {
             remote-control.control-enable = true;
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Declarative Unbound configuration
-          See the <citerefentry><refentrytitle>unbound.conf</refentrytitle>
-          <manvolnum>5</manvolnum></citerefentry> manpage for a list of
+          See the {manpage}`unbound.conf(5)` manpage for a list of
           available options.
         '';
       };
diff --git a/nixos/modules/services/networking/unifi.nix b/nixos/modules/services/networking/unifi.nix
index a683c537f05..d30f7c89633 100644
--- a/nixos/modules/services/networking/unifi.nix
+++ b/nixos/modules/services/networking/unifi.nix
@@ -17,7 +17,7 @@ in
     services.unifi.enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether or not to enable the unifi controller service.
       '';
     };
@@ -26,7 +26,7 @@ in
       type = types.package;
       default = pkgs.jre8;
       defaultText = literalExpression "pkgs.jre8";
-      description = ''
+      description = lib.mdDoc ''
         The JRE package to use. Check the release notes to ensure it is supported.
       '';
     };
@@ -35,7 +35,7 @@ in
       type = types.package;
       default = pkgs.unifiLTS;
       defaultText = literalExpression "pkgs.unifiLTS";
-      description = ''
+      description = lib.mdDoc ''
         The unifi package to use.
       '';
     };
@@ -44,15 +44,15 @@ in
       type = types.package;
       default = pkgs.mongodb;
       defaultText = literalExpression "pkgs.mongodb";
-      description = ''
+      description = lib.mdDoc ''
         The mongodb package to use.
       '';
     };
 
     services.unifi.openFirewall = mkOption {
       type = types.bool;
-      default = true;
-      description = ''
+      default = false;
+      description = lib.mdDoc ''
         Whether or not to open the minimum required ports on the firewall.
 
         This is necessary to allow firmware upgrades and device discovery to
@@ -65,7 +65,7 @@ in
       type = types.nullOr types.int;
       default = null;
       example = 1024;
-      description = ''
+      description = lib.mdDoc ''
         Set the initial heap size for the JVM in MB. If this option isn't set, the
         JVM will decide this value at runtime.
       '';
@@ -75,7 +75,7 @@ in
       type = types.nullOr types.int;
       default = null;
       example = 4096;
-      description = ''
+      description = lib.mdDoc ''
         Set the maximimum heap size for the JVM in MB. If this option isn't set, the
         JVM will decide this value at runtime.
       '';
@@ -85,10 +85,6 @@ in
 
   config = mkIf cfg.enable {
 
-    warnings = optional
-      (options.services.unifi.openFirewall.highestPrio >= (mkOptionDefault null).priority)
-      "The current services.unifi.openFirewall = true default is deprecated and will change to false in 22.11. Set it explicitly to silence this warning.";
-
     users.users.unifi = {
       isSystemUser = true;
       group = "unifi";
diff --git a/nixos/modules/services/networking/uptermd.nix b/nixos/modules/services/networking/uptermd.nix
new file mode 100644
index 00000000000..f824d617f59
--- /dev/null
+++ b/nixos/modules/services/networking/uptermd.nix
@@ -0,0 +1,109 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.uptermd;
+in
+{
+  options = {
+    services.uptermd = {
+      enable = mkEnableOption (lib.mdDoc "uptermd");
+
+      openFirewall = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to open the firewall for the port in {option}`services.uptermd.port`.
+        '';
+      };
+
+      port = mkOption {
+        type = types.port;
+        default = 2222;
+        description = lib.mdDoc ''
+          Port the server will listen on.
+        '';
+      };
+
+      listenAddress = mkOption {
+        type = types.str;
+        default = "[::]";
+        example = "127.0.0.1";
+        description = lib.mdDoc ''
+          Address the server will listen on.
+        '';
+      };
+
+      hostKey = mkOption {
+        type = types.nullOr types.path;
+        default = null;
+        example = "/run/keys/upterm_host_ed25519_key";
+        description = lib.mdDoc ''
+          Path to SSH host key. If not defined, an ed25519 keypair is generated automatically.
+        '';
+      };
+
+      extraFlags = mkOption {
+        type = types.listOf types.str;
+        default = [];
+        example = [ "--debug" ];
+        description = lib.mdDoc ''
+          Extra flags passed to the uptermd command.
+        '';
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    networking.firewall = mkIf cfg.openFirewall {
+      allowedTCPPorts = [ cfg.port ];
+    };
+
+    systemd.services.uptermd = {
+      description = "Upterm Daemon";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+
+      path = [ pkgs.openssh ];
+
+      preStart = mkIf (cfg.hostKey == null) ''
+        if ! [ -f ssh_host_ed25519_key ]; then
+          ssh-keygen \
+            -t ed25519 \
+            -f ssh_host_ed25519_key \
+            -N ""
+        fi
+      '';
+
+      serviceConfig = {
+        StateDirectory = "uptermd";
+        WorkingDirectory = "/var/lib/uptermd";
+        ExecStart = "${pkgs.upterm}/bin/uptermd --ssh-addr ${cfg.listenAddress}:${toString cfg.port} --private-key ${if cfg.hostKey == null then "ssh_host_ed25519_key" else cfg.hostKey} ${concatStringsSep " " cfg.extraFlags}";
+
+        # Hardening
+        AmbientCapabilities = mkIf (cfg.port < 1024) [ "CAP_NET_BIND_SERVICE" ];
+        CapabilityBoundingSet = mkIf (cfg.port < 1024) [ "CAP_NET_BIND_SERVICE" ];
+        PrivateUsers = cfg.port >= 1024;
+        DynamicUser = true;
+        LockPersonality = true;
+        MemoryDenyWriteExecute = true;
+        PrivateDevices = true;
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectProc = "invisible";
+        # AF_UNIX is for ssh-keygen, which relies on nscd to resolve the uid to a user
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        SystemCallArchitectures = "native";
+        SystemCallFilter = "@system-service";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/networking/v2ray.nix b/nixos/modules/services/networking/v2ray.nix
index 95e8761ba5c..ba2aa5bc1de 100644
--- a/nixos/modules/services/networking/v2ray.nix
+++ b/nixos/modules/services/networking/v2ray.nix
@@ -9,10 +9,10 @@ with lib;
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to run v2ray server.
 
-          Either <literal>configFile</literal> or <literal>config</literal> must be specified.
+          Either `configFile` or `config` must be specified.
         '';
       };
 
@@ -20,7 +20,7 @@ with lib;
         type = types.package;
         default = pkgs.v2ray;
         defaultText = literalExpression "pkgs.v2ray";
-        description = ''
+        description = lib.mdDoc ''
           Which v2ray package to use.
         '';
       };
@@ -29,12 +29,12 @@ with lib;
         type = types.nullOr types.str;
         default = null;
         example = "/etc/v2ray/config.json";
-        description = ''
+        description = lib.mdDoc ''
           The absolute path to the configuration file.
 
-          Either <literal>configFile</literal> or <literal>config</literal> must be specified.
+          Either `configFile` or `config` must be specified.
 
-          See <link xlink:href="https://www.v2fly.org/en_US/config/overview.html"/>.
+          See <https://www.v2fly.org/en_US/v5/config/overview.html>.
         '';
       };
 
@@ -51,12 +51,12 @@ with lib;
             protocol = "freedom";
           }];
         };
-        description = ''
+        description = lib.mdDoc ''
           The configuration object.
 
           Either `configFile` or `config` must be specified.
 
-          See <link xlink:href="https://www.v2fly.org/en_US/config/overview.html"/>.
+          See <https://www.v2fly.org/en_US/v5/config/overview.html>.
         '';
       };
     };
@@ -71,7 +71,7 @@ with lib;
         name = "v2ray.json";
         text = builtins.toJSON cfg.config;
         checkPhase = ''
-          ${cfg.package}/bin/v2ray -test -config $out
+          ${cfg.package}/bin/v2ray test -c $out
         '';
       };
 
@@ -83,13 +83,15 @@ with lib;
       }
     ];
 
+    environment.etc."v2ray/config.json".source = configFile;
+
+    systemd.packages = [ cfg.package ];
+
     systemd.services.v2ray = {
-      description = "v2ray Daemon";
-      after = [ "network.target" ];
+      restartTriggers = [ config.environment.etc."v2ray/config.json".source ];
+
+      # Workaround: https://github.com/NixOS/nixpkgs/issues/81138
       wantedBy = [ "multi-user.target" ];
-      serviceConfig = {
-        ExecStart = "${cfg.package}/bin/v2ray -config ${configFile}";
-      };
     };
   };
 }
diff --git a/nixos/modules/services/networking/vdirsyncer.nix b/nixos/modules/services/networking/vdirsyncer.nix
new file mode 100644
index 00000000000..6a069943434
--- /dev/null
+++ b/nixos/modules/services/networking/vdirsyncer.nix
@@ -0,0 +1,214 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+
+  cfg = config.services.vdirsyncer;
+
+  toIniJson = with generators; toINI {
+    mkKeyValue = mkKeyValueDefault {
+      mkValueString = builtins.toJSON;
+    } "=";
+  };
+
+  toConfigFile = name: cfg':
+    if
+      cfg'.configFile != null
+    then
+      cfg'.configFile
+    else
+      pkgs.writeText "vdirsyncer-${name}.conf" (toIniJson (
+        {
+          general = cfg'.config.general // (lib.optionalAttrs (cfg'.config.statusPath == null) {
+            status_path = "/var/lib/vdirsyncer/${name}";
+          });
+        } // (
+          mapAttrs' (name: nameValuePair "pair ${name}") cfg'.config.pairs
+        ) // (
+          mapAttrs' (name: nameValuePair "storage ${name}") cfg'.config.storages
+        )
+      ));
+
+  userUnitConfig = name: cfg': {
+    serviceConfig = {
+      User = if cfg'.user == null then "vdirsyncer" else cfg'.user;
+      Group = if cfg'.group == null then "vdirsyncer" else cfg'.group;
+    }  // (optionalAttrs (cfg'.user == null) {
+      DynamicUser = true;
+    }) // (optionalAttrs (cfg'.additionalGroups != []) {
+      SupplementaryGroups = cfg'.additionalGroups;
+    }) // (optionalAttrs (cfg'.config.statusPath == null) {
+      StateDirectory = "vdirsyncer/${name}";
+      StateDirectoryMode = "0700";
+    });
+  };
+
+  commonUnitConfig = {
+    after = [ "network.target" ];
+    serviceConfig = {
+      Type = "oneshot";
+      # Sandboxing
+      PrivateTmp = true;
+      NoNewPrivileges = true;
+      ProtectSystem = "strict";
+      ProtectHome = true;
+      ProtectKernelTunables = true;
+      ProtectKernelModules = true;
+      ProtectControlGroups = true;
+      RestrictNamespaces = true;
+      MemoryDenyWriteExecute = true;
+      RestrictRealtime = true;
+      RestrictSUIDSGID = true;
+      RestrictAddressFamilies = "AF_INET AF_INET6";
+      LockPersonality = true;
+    };
+  };
+
+in
+{
+  options = {
+    services.vdirsyncer = {
+      enable = mkEnableOption (mdDoc "vdirsyncer");
+
+      package = mkPackageOption pkgs "vdirsyncer" {};
+
+      jobs = mkOption {
+        description = mdDoc "vdirsyncer job configurations";
+        type = types.attrsOf (types.submodule {
+          options = {
+            enable = (mkEnableOption (mdDoc "this vdirsyncer job")) // {
+              default = true;
+              example = false;
+            };
+
+            user = mkOption {
+              type = types.nullOr types.str;
+              default = null;
+              description = mdDoc ''
+                User account to run vdirsyncer as, otherwise as a systemd
+                dynamic user
+              '';
+            };
+
+            group = mkOption {
+              type = types.nullOr types.str;
+              default = null;
+              description = mdDoc "group to run vdirsyncer as";
+            };
+
+            additionalGroups = mkOption {
+              type = types.listOf types.str;
+              default = [];
+              description = mdDoc "additional groups to add the dynamic user to";
+            };
+
+            forceDiscover = mkOption {
+              type = types.bool;
+              default = false;
+              description = mdDoc ''
+                Run `yes | vdirsyncer discover` prior to `vdirsyncer sync`
+              '';
+            };
+
+            timerConfig = mkOption {
+              type = types.attrs;
+              default = {
+                OnBootSec = "1h";
+                OnUnitActiveSec = "6h";
+              };
+              description = mdDoc "systemd timer configuration";
+            };
+
+            configFile = mkOption {
+              type = types.nullOr types.path;
+              default = null;
+              description = mdDoc "existing configuration file";
+            };
+
+            config = {
+              statusPath = mkOption {
+                type = types.nullOr types.str;
+                default = null;
+                defaultText = literalExpression "/var/lib/vdirsyncer/\${attrName}";
+                description = mdDoc "vdirsyncer's status path";
+              };
+
+              general = mkOption {
+                type = types.attrs;
+                default = {};
+                description = mdDoc "general configuration";
+              };
+
+              pairs = mkOption {
+                type = types.attrsOf types.attrs;
+                default = {};
+                description = mdDoc "vdirsyncer pair configurations";
+                example = literalExpression ''
+                  {
+                    my_contacts = {
+                      a = "my_cloud_contacts";
+                      b = "my_local_contacts";
+                      collections = [ "from a" ];
+                      conflict_resolution = "a wins";
+                      metadata = [ "color" "displayname" ];
+                    };
+                  };
+                '';
+              };
+
+              storages = mkOption {
+                type = types.attrsOf types.attrs;
+                default = {};
+                description = mdDoc "vdirsyncer storage configurations";
+                example = literalExpression ''
+                  {
+                    my_cloud_contacts = {
+                      type = "carddav";
+                      url = "https://dav.example.com/";
+                      read_only = true;
+                      username = "user";
+                      "password.fetch" = [ "command" "cat" "/etc/vdirsyncer/cloud.passwd" ];
+                    };
+                    my_local_contacts = {
+                      type = "carddav";
+                      url = "https://localhost/";
+                      username = "user";
+                      "password.fetch" = [ "command" "cat" "/etc/vdirsyncer/local.passwd" ];
+                    };
+                  }
+                '';
+              };
+            };
+          };
+        });
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services = mapAttrs' (name: cfg': nameValuePair "vdirsyncer@${name}" (
+      foldr recursiveUpdate {} [
+        commonUnitConfig
+        (userUnitConfig name cfg')
+        {
+          description = "synchronize calendars and contacts (${name})";
+          environment.VDIRSYNCER_CONFIG = toConfigFile name cfg';
+          serviceConfig.ExecStart =
+            (optional cfg'.forceDiscover (
+              pkgs.writeShellScript "vdirsyncer-discover-yes" ''
+                set -e
+                yes | ${cfg.package}/bin/vdirsyncer discover
+              ''
+            )) ++ [ "${cfg.package}/bin/vdirsyncer sync" ];
+        }
+      ]
+    )) (filterAttrs (name: cfg': cfg'.enable) cfg.jobs);
+
+    systemd.timers = mapAttrs' (name: cfg': nameValuePair "vdirsyncer@${name}" {
+      wantedBy = [ "timers.target" ];
+      description = "synchronize calendars and contacts (${name})";
+      inherit (cfg') timerConfig;
+    }) cfg.jobs;
+  };
+}
diff --git a/nixos/modules/services/networking/vsftpd.nix b/nixos/modules/services/networking/vsftpd.nix
index d205302051e..5fee7b66a4d 100644
--- a/nixos/modules/services/networking/vsftpd.nix
+++ b/nixos/modules/services/networking/vsftpd.nix
@@ -27,7 +27,8 @@ let
       type = types.bool;
       name = nixosName;
       value = mkOption {
-        inherit description default;
+        description = lib.mdDoc description;
+        inherit default;
         type = types.bool;
       };
     };
@@ -68,16 +69,16 @@ let
       Whether users are included.
     '')
     (yesNoOption "userlistDeny" "userlist_deny" false ''
-      Specifies whether <option>userlistFile</option> is a list of user
+      Specifies whether {option}`userlistFile` is a list of user
       names to allow or deny access.
-      The default <literal>false</literal> means whitelist/allow.
+      The default `false` means whitelist/allow.
     '')
     (yesNoOption "forceLocalLoginsSSL" "force_local_logins_ssl" false ''
-      Only applies if <option>sslEnable</option> is true. Non anonymous (local) users
+      Only applies if {option}`sslEnable` is true. Non anonymous (local) users
       must use a secure SSL connection to send a password.
     '')
     (yesNoOption "forceLocalDataSSL" "force_local_data_ssl" false ''
-      Only applies if <option>sslEnable</option> is true. Non anonymous (local) users
+      Only applies if {option}`sslEnable` is true. Non anonymous (local) users
       must use a secure SSL connection for sending/receiving data on data connection.
     '')
     (yesNoOption "portPromiscuous" "port_promiscuous" false ''
@@ -86,17 +87,17 @@ let
       know what you are doing!
     '')
     (yesNoOption "ssl_tlsv1" "ssl_tlsv1" true  ''
-      Only applies if <option>ssl_enable</option> is activated. If
+      Only applies if {option}`ssl_enable` is activated. If
       enabled, this option will permit TLS v1 protocol connections.
       TLS v1 connections are preferred.
     '')
     (yesNoOption "ssl_sslv2" "ssl_sslv2" false ''
-      Only applies if <option>ssl_enable</option> is activated. If
+      Only applies if {option}`ssl_enable` is activated. If
       enabled, this option will permit SSL v2 protocol connections.
       TLS v1 connections are preferred.
     '')
     (yesNoOption "ssl_sslv3" "ssl_sslv3" false ''
-      Only applies if <option>ssl_enable</option> is activated. If
+      Only applies if {option}`ssl_enable` is activated. If
       enabled, this option will permit SSL v3 protocol connections.
       TLS v1 connections are preferred.
     '')
@@ -149,23 +150,23 @@ in
 
     services.vsftpd = {
 
-      enable = mkEnableOption "vsftpd";
+      enable = mkEnableOption (lib.mdDoc "vsftpd");
 
       userlist = mkOption {
         default = [];
         type = types.listOf types.str;
-        description = "See <option>userlistFile</option>.";
+        description = lib.mdDoc "See {option}`userlistFile`.";
       };
 
       userlistFile = mkOption {
         type = types.path;
         default = pkgs.writeText "userlist" (concatMapStrings (x: "${x}\n") cfg.userlist);
         defaultText = literalExpression ''pkgs.writeText "userlist" (concatMapStrings (x: "''${x}\n") cfg.userlist)'';
-        description = ''
-          Newline separated list of names to be allowed/denied if <option>userlistEnable</option>
-          is <literal>true</literal>. Meaning see <option>userlistDeny</option>.
+        description = lib.mdDoc ''
+          Newline separated list of names to be allowed/denied if {option}`userlistEnable`
+          is `true`. Meaning see {option}`userlistDeny`.
 
-          The default is a file containing the users from <option>userlist</option>.
+          The default is a file containing the users from {option}`userlist`.
 
           If explicitely set to null userlist_file will not be set in vsftpd's config file.
         '';
@@ -174,8 +175,8 @@ in
       enableVirtualUsers = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          Whether to enable the <literal>pam_userdb</literal>-based
+        description = lib.mdDoc ''
+          Whether to enable the `pam_userdb`-based
           virtual user system
         '';
       };
@@ -184,9 +185,9 @@ in
         type = types.nullOr types.str;
         example = "/etc/vsftpd/userDb";
         default = null;
-        description = ''
-          Only applies if <option>enableVirtualUsers</option> is true.
-          Path pointing to the <literal>pam_userdb</literal> user
+        description = lib.mdDoc ''
+          Only applies if {option}`enableVirtualUsers` is true.
+          Path pointing to the `pam_userdb` user
           database used by vsftpd to authenticate the virtual users.
 
           This user list should be stored in the Berkeley DB database
@@ -194,21 +195,21 @@ in
 
           To generate a new user database, create a text file, add
           your users using the following format:
-          <programlisting>
+          ```
           user1
           password1
           user2
           password2
-          </programlisting>
+          ```
 
-          You can then install <literal>pkgs.db</literal> to generate
+          You can then install `pkgs.db` to generate
           the Berkeley DB using
-          <programlisting>
+          ```
           db_load -T -t hash -f logins.txt userDb.db
-          </programlisting>
+          ```
 
-          Caution: <literal>pam_userdb</literal> will automatically
-          append a <literal>.db</literal> suffix to the filename you
+          Caution: `pam_userdb` will automatically
+          append a `.db` suffix to the filename you
           provide though this option. This option shouldn't include
           this filetype suffix.
         '';
@@ -218,7 +219,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "/var/www/$USER";
-        description = ''
+        description = lib.mdDoc ''
           This option represents a directory which vsftpd will try to
           change into after a local (i.e. non- anonymous) login.
 
@@ -229,7 +230,7 @@ in
       anonymousUserHome = mkOption {
         type = types.path;
         default = "/home/ftp/";
-        description = ''
+        description = lib.mdDoc ''
           Directory to consider the HOME of the anonymous user.
         '';
       };
@@ -237,27 +238,27 @@ in
       rsaCertFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "RSA certificate file.";
+        description = lib.mdDoc "RSA certificate file.";
       };
 
       rsaKeyFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "RSA private key file.";
+        description = lib.mdDoc "RSA private key file.";
       };
 
       anonymousUmask = mkOption {
         type = types.str;
         default = "077";
         example = "002";
-        description = "Anonymous write umask.";
+        description = lib.mdDoc "Anonymous write umask.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
         example = "ftpd_banner=Hello";
-        description = "Extra configuration to add at the bottom of the generated configuration file.";
+        description = lib.mdDoc "Extra configuration to add at the bottom of the generated configuration file.";
       };
 
     } // (listToAttrs (catAttrs "nixosOption" optionDescription));
diff --git a/nixos/modules/services/networking/wasabibackend.nix b/nixos/modules/services/networking/wasabibackend.nix
index b6dcd940915..938145b35ee 100644
--- a/nixos/modules/services/networking/wasabibackend.nix
+++ b/nixos/modules/services/networking/wasabibackend.nix
@@ -29,37 +29,37 @@ in {
   options = {
 
     services.wasabibackend = {
-      enable = mkEnableOption "Wasabi backend service";
+      enable = mkEnableOption (lib.mdDoc "Wasabi backend service");
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/wasabibackend";
-        description = "The data directory for the Wasabi backend node.";
+        description = lib.mdDoc "The data directory for the Wasabi backend node.";
       };
 
       customConfigFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "Defines the path to a custom configuration file that is copied to the user's directory. Overrides any config options.";
+        description = lib.mdDoc "Defines the path to a custom configuration file that is copied to the user's directory. Overrides any config options.";
       };
 
       network = mkOption {
         type = types.enum [ "mainnet" "testnet" "regtest" ];
         default = "mainnet";
-        description = "The network to use for the Wasabi backend service.";
+        description = lib.mdDoc "The network to use for the Wasabi backend service.";
       };
 
       endpoint = {
         ip = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "IP address for P2P connection to bitcoind.";
+          description = lib.mdDoc "IP address for P2P connection to bitcoind.";
         };
 
         port = mkOption {
           type = types.port;
           default = 8333;
-          description = "Port for P2P connection to bitcoind.";
+          description = lib.mdDoc "Port for P2P connection to bitcoind.";
         };
       };
 
@@ -67,45 +67,45 @@ in {
         ip = mkOption {
           type = types.str;
           default = "127.0.0.1";
-          description = "IP address for RPC connection to bitcoind.";
+          description = lib.mdDoc "IP address for RPC connection to bitcoind.";
         };
 
         port = mkOption {
           type = types.port;
           default = 8332;
-          description = "Port for RPC connection to bitcoind.";
+          description = lib.mdDoc "Port for RPC connection to bitcoind.";
         };
 
         user = mkOption {
           type = types.str;
           default = "bitcoin";
-          description = "RPC user for the bitcoin endpoint.";
+          description = lib.mdDoc "RPC user for the bitcoin endpoint.";
         };
 
         password = mkOption {
           type = types.str;
           default = "password";
-          description = "RPC password for the bitcoin endpoint. Warning: this is stored in cleartext in the Nix store! Use <literal>configFile</literal> or <literal>passwordFile</literal> if needed.";
+          description = lib.mdDoc "RPC password for the bitcoin endpoint. Warning: this is stored in cleartext in the Nix store! Use `configFile` or `passwordFile` if needed.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
-          description = "File that contains the password of the RPC user.";
+          description = lib.mdDoc "File that contains the password of the RPC user.";
         };
       };
 
       user = mkOption {
         type = types.str;
         default = "wasabibackend";
-        description = "The user as which to run the wasabibackend node.";
+        description = lib.mdDoc "The user as which to run the wasabibackend node.";
       };
 
       group = mkOption {
         type = types.str;
         default = cfg.user;
         defaultText = literalExpression "config.${opt.user}";
-        description = "The group as which to run the wasabibackend node.";
+        description = lib.mdDoc "The group as which to run the wasabibackend node.";
       };
     };
   };
diff --git a/nixos/modules/services/networking/websockify.nix b/nixos/modules/services/networking/websockify.nix
index f7e014e03ef..45a3487bd33 100644
--- a/nixos/modules/services/networking/websockify.nix
+++ b/nixos/modules/services/networking/websockify.nix
@@ -6,7 +6,7 @@ let cfg = config.services.networking.websockify; in {
   options = {
     services.networking.websockify = {
       enable = mkOption {
-        description = "Whether to enable websockify to forward websocket connections to TCP connections.";
+        description = lib.mdDoc "Whether to enable websockify to forward websocket connections to TCP connections.";
 
         default = false;
 
@@ -14,19 +14,19 @@ let cfg = config.services.networking.websockify; in {
       };
 
       sslCert = mkOption {
-        description = "Path to the SSL certificate.";
+        description = lib.mdDoc "Path to the SSL certificate.";
         type = types.path;
       };
 
       sslKey = mkOption {
-        description = "Path to the SSL key.";
+        description = lib.mdDoc "Path to the SSL key.";
         default = cfg.sslCert;
         defaultText = literalExpression "config.services.networking.websockify.sslCert";
         type = types.path;
       };
 
       portMap = mkOption {
-        description = "Ports to map by default.";
+        description = lib.mdDoc "Ports to map by default.";
         default = {};
         type = types.attrsOf types.int;
       };
diff --git a/nixos/modules/services/networking/wg-netmanager.nix b/nixos/modules/services/networking/wg-netmanager.nix
index 493ff7ceba9..b260c573726 100644
--- a/nixos/modules/services/networking/wg-netmanager.nix
+++ b/nixos/modules/services/networking/wg-netmanager.nix
@@ -9,7 +9,7 @@ in
 
   options = {
     services.wg-netmanager = {
-      enable = mkEnableOption "Wireguard network manager";
+      enable = mkEnableOption (lib.mdDoc "Wireguard network manager");
     };
   };
 
diff --git a/nixos/modules/services/networking/wg-quick.nix b/nixos/modules/services/networking/wg-quick.nix
index 61e9fe5096b..a678d743bb7 100644
--- a/nixos/modules/services/networking/wg-quick.nix
+++ b/nixos/modules/services/networking/wg-quick.nix
@@ -10,15 +10,27 @@ let
 
   interfaceOpts = { ... }: {
     options = {
+
+      configFile = mkOption {
+        example = "/secret/wg0.conf";
+        default = null;
+        type = with types; nullOr str;
+        description = lib.mdDoc ''
+          wg-quick .conf file, describing the interface.
+          This overrides any other configuration interface configuration options.
+          See wg-quick manpage for more details.
+        '';
+      };
+
       address = mkOption {
         example = [ "192.168.2.1/24" ];
         default = [];
         type = with types; listOf str;
-        description = "The IP addresses of the interface.";
+        description = lib.mdDoc "The IP addresses of the interface.";
       };
 
       autostart = mkOption {
-        description = "Whether to bring up this interface automatically during boot.";
+        description = lib.mdDoc "Whether to bring up this interface automatically during boot.";
         default = true;
         example = false;
         type = types.bool;
@@ -28,15 +40,15 @@ let
         example = [ "192.168.2.2" ];
         default = [];
         type = with types; listOf str;
-        description = "The IP addresses of DNS servers to configure.";
+        description = lib.mdDoc "The IP addresses of DNS servers to configure.";
       };
 
       privateKey = mkOption {
         example = "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=";
         type = with types; nullOr str;
         default = null;
-        description = ''
-          Base64 private key generated by <command>wg genkey</command>.
+        description = lib.mdDoc ''
+          Base64 private key generated by {command}`wg genkey`.
 
           Warning: Consider using privateKeyFile instead if you do not
           want to store the key in the world-readable Nix store.
@@ -47,8 +59,8 @@ let
         example = "/private/wireguard_key";
         type = with types; nullOr str;
         default = null;
-        description = ''
-          Private key file as generated by <command>wg genkey</command>.
+        description = lib.mdDoc ''
+          Private key file as generated by {command}`wg genkey`.
         '';
       };
 
@@ -56,7 +68,7 @@ let
         default = null;
         type = with types; nullOr int;
         example = 51820;
-        description = ''
+        description = lib.mdDoc ''
           16-bit port for listening. Optional; if not specified,
           automatically generated based on interface name.
         '';
@@ -66,7 +78,7 @@ let
         example = literalExpression ''"''${pkgs.iproute2}/bin/ip netns add foo"'';
         default = "";
         type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
-        description = ''
+        description = lib.mdDoc ''
           Commands called at the start of the interface setup.
         '';
       };
@@ -75,7 +87,7 @@ let
         example = literalExpression ''"''${pkgs.iproute2}/bin/ip netns del foo"'';
         default = "";
         type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
-        description = ''
+        description = lib.mdDoc ''
           Command called before the interface is taken down.
         '';
       };
@@ -84,7 +96,7 @@ let
         example = literalExpression ''"''${pkgs.iproute2}/bin/ip netns add foo"'';
         default = "";
         type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
-        description = ''
+        description = lib.mdDoc ''
           Commands called after the interface setup.
         '';
       };
@@ -93,7 +105,7 @@ let
         example = literalExpression ''"''${pkgs.iproute2}/bin/ip netns del foo"'';
         default = "";
         type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
-        description = ''
+        description = lib.mdDoc ''
           Command called after the interface is taken down.
         '';
       };
@@ -102,7 +114,7 @@ let
         example = "main";
         default = null;
         type = with types; nullOr str;
-        description = ''
+        description = lib.mdDoc ''
           The kernel routing table to add this interface's
           associated routes to. Setting this is useful for e.g. policy routing
           ("ip rule") or virtual routing and forwarding ("ip vrf"). Both
@@ -115,7 +127,7 @@ let
         example = 1248;
         default = null;
         type = with types; nullOr int;
-        description = ''
+        description = lib.mdDoc ''
           If not specified, the MTU is automatically determined
           from the endpoint addresses or the system default route, which is usually
           a sane choice. However, to manually specify an MTU to override this
@@ -125,7 +137,7 @@ let
 
       peers = mkOption {
         default = [];
-        description = "Peers linked to the interface.";
+        description = lib.mdDoc "Peers linked to the interface.";
         type = with types; listOf (submodule peerOpts);
       };
     };
@@ -138,15 +150,15 @@ let
       publicKey = mkOption {
         example = "xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=";
         type = types.str;
-        description = "The base64 public key to the peer.";
+        description = lib.mdDoc "The base64 public key to the peer.";
       };
 
       presharedKey = mkOption {
         default = null;
         example = "rVXs/Ni9tu3oDBLS4hOyAUAa1qTWVA3loR8eL20os3I=";
         type = with types; nullOr str;
-        description = ''
-          Base64 preshared key generated by <command>wg genpsk</command>.
+        description = lib.mdDoc ''
+          Base64 preshared key generated by {command}`wg genpsk`.
           Optional, and may be omitted. This option adds an additional layer of
           symmetric-key cryptography to be mixed into the already existing
           public-key cryptography, for post-quantum resistance.
@@ -160,8 +172,8 @@ let
         default = null;
         example = "/private/wireguard_psk";
         type = with types; nullOr str;
-        description = ''
-          File pointing to preshared key as generated by <command>wg genpsk</command>.
+        description = lib.mdDoc ''
+          File pointing to preshared key as generated by {command}`wg genpsk`.
           Optional, and may be omitted. This option adds an additional layer of
           symmetric-key cryptography to be mixed into the already existing
           public-key cryptography, for post-quantum resistance.
@@ -171,7 +183,7 @@ let
       allowedIPs = mkOption {
         example = [ "10.192.122.3/32" "10.192.124.1/24" ];
         type = with types; listOf str;
-        description = ''List of IP (v4 or v6) addresses with CIDR masks from
+        description = lib.mdDoc ''List of IP (v4 or v6) addresses with CIDR masks from
         which this peer is allowed to send incoming traffic and to which
         outgoing traffic for this peer is directed. The catch-all 0.0.0.0/0 may
         be specified for matching all IPv4 addresses, and ::/0 may be specified
@@ -182,7 +194,7 @@ let
         default = null;
         example = "demo.wireguard.io:12913";
         type = with types; nullOr str;
-        description = ''Endpoint IP or hostname of the peer, followed by a colon,
+        description = lib.mdDoc ''Endpoint IP or hostname of the peer, followed by a colon,
         and then a port number of the peer.'';
       };
 
@@ -190,7 +202,7 @@ let
         default = null;
         type = with types; nullOr int;
         example = 25;
-        description = ''This is optional and is by default off, because most
+        description = lib.mdDoc ''This is optional and is by default off, because most
         users will not need it. It represents, in seconds, between 1 and 65535
         inclusive, how often to send an authenticated empty packet to the peer,
         for the purpose of keeping a stateful firewall or NAT mapping valid
@@ -205,13 +217,13 @@ let
   writeScriptFile = name: text: ((pkgs.writeShellScriptBin name text) + "/bin/${name}");
 
   generateUnit = name: values:
-    assert assertMsg ((values.privateKey != null) != (values.privateKeyFile != null)) "Only one of privateKey or privateKeyFile may be set";
+    assert assertMsg (values.configFile != null || ((values.privateKey != null) != (values.privateKeyFile != null))) "Only one of privateKey, configFile or privateKeyFile may be set";
     let
       preUpFile = if values.preUp != "" then writeScriptFile "preUp.sh" values.preUp else null;
       postUp =
             optional (values.privateKeyFile != null) "wg set ${name} private-key <(cat ${values.privateKeyFile})" ++
             (concatMap (peer: optional (peer.presharedKeyFile != null) "wg set ${name} peer ${peer.publicKey} preshared-key <(cat ${peer.presharedKeyFile})") values.peers) ++
-            optional (values.postUp != null) values.postUp;
+            optional (values.postUp != "") values.postUp;
       postUpFile = if postUp != [] then writeScriptFile "postUp.sh" (concatMapStringsSep "\n" (line: line) postUp) else null;
       preDownFile = if values.preDown != "" then writeScriptFile "preDown.sh" values.preDown else null;
       postDownFile = if values.postDown != "" then writeScriptFile "postDown.sh" values.postDown else null;
@@ -247,7 +259,12 @@ let
           optionalString (peer.allowedIPs != []) "AllowedIPs = ${concatStringsSep "," peer.allowedIPs}\n"
         ) values.peers;
       };
-      configPath = "${configDir}/${name}.conf";
+      configPath =
+        if values.configFile != null then
+          # This uses bind-mounted private tmp folder (/tmp/systemd-private-***)
+          "/tmp/${name}.conf"
+        else
+          "${configDir}/${name}.conf";
     in
     nameValuePair "wg-quick-${name}"
       {
@@ -256,7 +273,7 @@ let
         after = [ "network.target" "network-online.target" ];
         wantedBy = optional values.autostart "multi-user.target";
         environment.DEVICE = name;
-        path = [ pkgs.kmod pkgs.wireguard-tools ];
+        path = [ pkgs.kmod pkgs.wireguard-tools config.networking.resolvconf.package ];
 
         serviceConfig = {
           Type = "oneshot";
@@ -265,9 +282,17 @@ let
 
         script = ''
           ${optionalString (!config.boot.isContainer) "modprobe wireguard"}
+          ${optionalString (values.configFile != null) ''
+            cp ${values.configFile} ${configPath}
+          ''}
           wg-quick up ${configPath}
         '';
 
+        serviceConfig = {
+          # Used to privately store renamed copies of external config files during activation
+          PrivateTmp = true;
+        };
+
         preStop = ''
           wg-quick down ${configPath}
         '';
@@ -279,7 +304,7 @@ in {
   options = {
     networking.wg-quick = {
       interfaces = mkOption {
-        description = "Wireguard interfaces.";
+        description = lib.mdDoc "Wireguard interfaces.";
         default = {};
         example = {
           wg0 = {
@@ -303,9 +328,12 @@ in {
   config = mkIf (cfg.interfaces != {}) {
     boot.extraModulePackages = optional (versionOlder kernel.kernel.version "5.6") kernel.wireguard;
     environment.systemPackages = [ pkgs.wireguard-tools ];
-    # This is forced to false for now because the default "--validmark" rpfilter we apply on reverse path filtering
-    # breaks the wg-quick routing because wireguard packets leave with a fwmark from wireguard.
-    networking.firewall.checkReversePath = false;
     systemd.services = mapAttrs' generateUnit cfg.interfaces;
+
+    # Prevent networkd from clearing the rules set by wg-quick when restarted (e.g. when waking up from suspend).
+    systemd.network.config.networkConfig.ManageForeignRoutingPolicyRules = mkDefault false;
+
+    # WireGuard interfaces should be ignored in determining whether the network is online.
+    systemd.network.wait-online.ignoredInterfaces = builtins.attrNames cfg.interfaces;
   };
 }
diff --git a/nixos/modules/services/networking/wireguard.nix b/nixos/modules/services/networking/wireguard.nix
index 7cd44b2f8a0..ce5616672c1 100644
--- a/nixos/modules/services/networking/wireguard.nix
+++ b/nixos/modules/services/networking/wireguard.nix
@@ -19,15 +19,15 @@ let
         example = [ "192.168.2.1/24" ];
         default = [];
         type = with types; listOf str;
-        description = "The IP addresses of the interface.";
+        description = lib.mdDoc "The IP addresses of the interface.";
       };
 
       privateKey = mkOption {
         example = "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=";
         type = with types; nullOr str;
         default = null;
-        description = ''
-          Base64 private key generated by <command>wg genkey</command>.
+        description = lib.mdDoc ''
+          Base64 private key generated by {command}`wg genkey`.
 
           Warning: Consider using privateKeyFile instead if you do not
           want to store the key in the world-readable Nix store.
@@ -37,9 +37,9 @@ let
       generatePrivateKeyFile = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Automatically generate a private key with
-          <command>wg genkey</command>, at the privateKeyFile location.
+          {command}`wg genkey`, at the privateKeyFile location.
         '';
       };
 
@@ -47,8 +47,8 @@ let
         example = "/private/wireguard_key";
         type = with types; nullOr str;
         default = null;
-        description = ''
-          Private key file as generated by <command>wg genkey</command>.
+        description = lib.mdDoc ''
+          Private key file as generated by {command}`wg genkey`.
         '';
       };
 
@@ -56,7 +56,7 @@ let
         default = null;
         type = with types; nullOr int;
         example = 51820;
-        description = ''
+        description = lib.mdDoc ''
           16-bit port for listening. Optional; if not specified,
           automatically generated based on interface name.
         '';
@@ -66,7 +66,7 @@ let
         example = literalExpression ''"''${pkgs.iproute2}/bin/ip netns add foo"'';
         default = "";
         type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
-        description = ''
+        description = lib.mdDoc ''
           Commands called at the start of the interface setup.
         '';
       };
@@ -77,20 +77,20 @@ let
         '';
         default = "";
         type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
-        description = "Commands called at the end of the interface setup.";
+        description = lib.mdDoc "Commands called at the end of the interface setup.";
       };
 
       postShutdown = mkOption {
         example = literalExpression ''"''${pkgs.openresolv}/bin/resolvconf -d wg0"'';
         default = "";
         type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
-        description = "Commands called after shutting down the interface.";
+        description = lib.mdDoc "Commands called after shutting down the interface.";
       };
 
       table = mkOption {
         default = "main";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The kernel routing table to add this interface's
           associated routes to. Setting this is useful for e.g. policy routing
           ("ip rule") or virtual routing and forwarding ("ip vrf"). Both
@@ -101,7 +101,7 @@ let
 
       peers = mkOption {
         default = [];
-        description = "Peers linked to the interface.";
+        description = lib.mdDoc "Peers linked to the interface.";
         type = with types; listOf (submodule peerOpts);
       };
 
@@ -109,7 +109,7 @@ let
         example = false;
         default = true;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Determines whether to add allowed IPs as routes or not.
         '';
       };
@@ -118,12 +118,11 @@ let
         default = null;
         type = with types; nullOr str;
         example = "container";
-        description = ''The pre-existing network namespace in which the
+        description = lib.mdDoc ''The pre-existing network namespace in which the
         WireGuard interface is created, and which retains the socket even if the
-        interface is moved via <option>interfaceNamespace</option>. When
-        <literal>null</literal>, the interface is created in the init namespace.
-        See <link
-        xlink:href="https://www.wireguard.com/netns/">documentation</link>.
+        interface is moved via {option}`interfaceNamespace`. When
+        `null`, the interface is created in the init namespace.
+        See [documentation](https://www.wireguard.com/netns/).
         '';
       };
 
@@ -131,12 +130,38 @@ let
         default = null;
         type = with types; nullOr str;
         example = "init";
-        description = ''The pre-existing network namespace the WireGuard
-        interface is moved to. The special value <literal>init</literal> means
-        the init namespace. When <literal>null</literal>, the interface is not
+        description = lib.mdDoc ''The pre-existing network namespace the WireGuard
+        interface is moved to. The special value `init` means
+        the init namespace. When `null`, the interface is not
         moved.
-        See <link
-        xlink:href="https://www.wireguard.com/netns/">documentation</link>.
+        See [documentation](https://www.wireguard.com/netns/).
+        '';
+      };
+
+      fwMark = mkOption {
+        default = null;
+        type = with types; nullOr str;
+        example = "0x6e6978";
+        description = lib.mdDoc ''
+          Mark all wireguard packets originating from
+          this interface with the given firewall mark. The firewall mark can be
+          used in firewalls or policy routing to filter the wireguard packets.
+          This can be useful for setup where all traffic goes through the
+          wireguard tunnel, because the wireguard packets need to be routed
+          differently.
+        '';
+      };
+
+      mtu = mkOption {
+        default = null;
+        type = with types; nullOr int;
+        example = 1280;
+        description = lib.mdDoc ''
+          Set the maximum transmission unit in bytes for the wireguard
+          interface. Beware that the wireguard packets have a header that may
+          add up to 80 bytes to the mtu. By default, the MTU is (1500 - 80) =
+          1420. However, if the MTU of the upstream network is lower, the MTU
+          of the wireguard network has to be adjusted as well.
         '';
       };
     };
@@ -152,15 +177,15 @@ let
       publicKey = mkOption {
         example = "xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=";
         type = types.str;
-        description = "The base64 public key of the peer.";
+        description = lib.mdDoc "The base64 public key of the peer.";
       };
 
       presharedKey = mkOption {
         default = null;
         example = "rVXs/Ni9tu3oDBLS4hOyAUAa1qTWVA3loR8eL20os3I=";
         type = with types; nullOr str;
-        description = ''
-          Base64 preshared key generated by <command>wg genpsk</command>.
+        description = lib.mdDoc ''
+          Base64 preshared key generated by {command}`wg genpsk`.
           Optional, and may be omitted. This option adds an additional layer of
           symmetric-key cryptography to be mixed into the already existing
           public-key cryptography, for post-quantum resistance.
@@ -174,8 +199,8 @@ let
         default = null;
         example = "/private/wireguard_psk";
         type = with types; nullOr str;
-        description = ''
-          File pointing to preshared key as generated by <command>wg genpsk</command>.
+        description = lib.mdDoc ''
+          File pointing to preshared key as generated by {command}`wg genpsk`.
           Optional, and may be omitted. This option adds an additional layer of
           symmetric-key cryptography to be mixed into the already existing
           public-key cryptography, for post-quantum resistance.
@@ -185,7 +210,7 @@ let
       allowedIPs = mkOption {
         example = [ "10.192.122.3/32" "10.192.124.1/24" ];
         type = with types; listOf str;
-        description = ''List of IP (v4 or v6) addresses with CIDR masks from
+        description = lib.mdDoc ''List of IP (v4 or v6) addresses with CIDR masks from
         which this peer is allowed to send incoming traffic and to which
         outgoing traffic for this peer is directed. The catch-all 0.0.0.0/0 may
         be specified for matching all IPv4 addresses, and ::/0 may be specified
@@ -196,19 +221,20 @@ let
         default = null;
         example = "demo.wireguard.io:12913";
         type = with types; nullOr str;
-        description = ''Endpoint IP or hostname of the peer, followed by a colon,
-        and then a port number of the peer.
-
-        Warning for endpoints with changing IPs:
-        The WireGuard kernel side cannot perform DNS resolution.
-        Thus DNS resolution is done once by the <literal>wg</literal> userspace
-        utility, when setting up WireGuard. Consequently, if the IP address
-        behind the name changes, WireGuard will not notice.
-        This is especially common for dynamic-DNS setups, but also applies to
-        any other DNS-based setup.
-        If you do not use IP endpoints, you likely want to set
-        <option>networking.wireguard.dynamicEndpointRefreshSeconds</option>
-        to refresh the IPs periodically.
+        description = lib.mdDoc ''
+          Endpoint IP or hostname of the peer, followed by a colon,
+          and then a port number of the peer.
+
+          Warning for endpoints with changing IPs:
+          The WireGuard kernel side cannot perform DNS resolution.
+          Thus DNS resolution is done once by the `wg` userspace
+          utility, when setting up WireGuard. Consequently, if the IP address
+          behind the name changes, WireGuard will not notice.
+          This is especially common for dynamic-DNS setups, but also applies to
+          any other DNS-based setup.
+          If you do not use IP endpoints, you likely want to set
+          {option}`networking.wireguard.dynamicEndpointRefreshSeconds`
+          to refresh the IPs periodically.
         '';
       };
 
@@ -216,12 +242,27 @@ let
         default = 0;
         example = 5;
         type = with types; int;
-        description = ''
-          Periodically re-execute the <literal>wg</literal> utility every
+        description = lib.mdDoc ''
+          Periodically re-execute the `wg` utility every
           this many seconds in order to let WireGuard notice DNS / hostname
           changes.
 
-          Setting this to <literal>0</literal> disables periodic reexecution.
+          Setting this to `0` disables periodic reexecution.
+        '';
+      };
+
+      dynamicEndpointRefreshRestartSeconds = mkOption {
+        default = null;
+        example = 5;
+        type = with types; nullOr ints.unsigned;
+        description = lib.mdDoc ''
+          When the dynamic endpoint refresh that is configured via
+          dynamicEndpointRefreshSeconds exits (likely due to a failure),
+          restart that service after this many seconds.
+
+          If set to `null` the value of
+          {option}`networking.wireguard.dynamicEndpointRefreshSeconds`
+          will be used as the default.
         '';
       };
 
@@ -229,7 +270,7 @@ let
         default = null;
         type = with types; nullOr int;
         example = 25;
-        description = ''This is optional and is by default off, because most
+        description = lib.mdDoc ''This is optional and is by default off, because most
         users will not need it. It represents, in seconds, between 1 and 65535
         inclusive, how often to send an authenticated empty packet to the peer,
         for the purpose of keeping a stateful firewall or NAT mapping valid
@@ -301,8 +342,9 @@ let
       {
         description = "WireGuard Peer - ${interfaceName} - ${peer.publicKey}";
         requires = [ "wireguard-${interfaceName}.service" ];
-        after = [ "wireguard-${interfaceName}.service" ];
-        wantedBy = [ "multi-user.target" "wireguard-${interfaceName}.service" ];
+        wants = [ "network-online.target" ];
+        after = [ "wireguard-${interfaceName}.service" "network-online.target" ];
+        wantedBy = [ "wireguard-${interfaceName}.service" ];
         environment.DEVICE = interfaceName;
         environment.WG_ENDPOINT_RESOLUTION_RETRIES = "infinity";
         path = with pkgs; [ iproute2 wireguard-tools ];
@@ -321,7 +363,16 @@ let
                 # cannot be used with systemd timers (see `man systemd.timer`),
                 # which is why `simple` with a loop is the best choice here.
                 # It also makes starting and stopping easiest.
+                #
+                # Restart if the service exits (e.g. when wireguard gives up after "Name or service not known" dns failures):
+                Restart = "always";
+                RestartSec = if null != peer.dynamicEndpointRefreshRestartSeconds
+                             then peer.dynamicEndpointRefreshRestartSeconds
+                             else peer.dynamicEndpointRefreshSeconds;
               };
+        unitConfig = lib.optionalAttrs dynamicRefreshEnabled {
+          StartLimitIntervalSec = 0;
+        };
 
         script = let
           wg_setup = concatStringsSep " " (
@@ -364,6 +415,19 @@ let
         '';
       };
 
+  # the target is required to start new peer units when they are added
+  generateInterfaceTarget = name: values:
+    let
+      mkPeerUnit = peer: (peerUnitServiceName name peer.publicKey (peer.dynamicEndpointRefreshSeconds != 0)) + ".service";
+    in
+    nameValuePair "wireguard-${name}"
+      rec {
+        description = "WireGuard Tunnel - ${name}";
+        wantedBy = [ "multi-user.target" ];
+        wants = [ "wireguard-${name}.service" ] ++ map mkPeerUnit values.peers;
+        after = wants;
+      };
+
   generateInterfaceUnit = name: values:
     # exactly one way to specify the private key must be set
     #assert (values.privateKey != null) != (values.privateKeyFile != null);
@@ -379,9 +443,9 @@ let
     nameValuePair "wireguard-${name}"
       {
         description = "WireGuard Tunnel - ${name}";
-        requires = [ "network-online.target" ];
-        after = [ "network.target" "network-online.target" ];
-        wantedBy = [ "multi-user.target" ];
+        after = [ "network-pre.target" ];
+        wants = [ "network.target" ];
+        before = [ "network.target" ];
         environment.DEVICE = name;
         path = with pkgs; [ kmod iproute2 wireguard-tools ];
 
@@ -397,6 +461,7 @@ let
 
           ${ipPreMove} link add dev "${name}" type wireguard
           ${optionalString (values.interfaceNamespace != null && values.interfaceNamespace != values.socketNamespace) ''${ipPreMove} link set "${name}" netns "${ns}"''}
+          ${optionalString (values.mtu != null) ''${ipPreMove} link set "${name}" mtu ${toString values.mtu}''}
 
           ${concatMapStringsSep "\n" (ip:
             ''${ipPostMove} address add "${ip}" dev "${name}"''
@@ -405,6 +470,7 @@ let
           ${concatStringsSep " " (
             [ ''${wg} set "${name}" private-key "${privKey}"'' ]
             ++ optional (values.listenPort != null) ''listen-port "${toString values.listenPort}"''
+            ++ optional (values.fwMark != null) ''fwmark "${values.fwMark}"''
           )}
 
           ${ipPostMove} link set up dev "${name}"
@@ -435,7 +501,13 @@ in
     networking.wireguard = {
 
       enable = mkOption {
-        description = "Whether to enable WireGuard.";
+        description = lib.mdDoc ''
+          Whether to enable WireGuard.
+
+          Please note that {option}`systemd.network.netdevs` has more features
+          and is better maintained. When building new things, it is advised to
+          use that instead.
+        '';
         type = types.bool;
         # 2019-05-25: Backwards compatibility.
         default = cfg.interfaces != {};
@@ -444,7 +516,13 @@ in
       };
 
       interfaces = mkOption {
-        description = "WireGuard interfaces.";
+        description = lib.mdDoc ''
+          WireGuard interfaces.
+
+          Please note that {option}`systemd.network.netdevs` has more features
+          and is better maintained. When building new things, it is advised to
+          use that instead.
+        '';
         default = {};
         example = {
           wg0 = {
@@ -498,6 +576,8 @@ in
       // (mapAttrs' generateKeyServiceUnit
       (filterAttrs (name: value: value.generatePrivateKeyFile) cfg.interfaces));
 
-  });
+      systemd.targets = mapAttrs' generateInterfaceTarget cfg.interfaces;
+    }
+  );
 
 }
diff --git a/nixos/modules/services/networking/wpa_supplicant.nix b/nixos/modules/services/networking/wpa_supplicant.nix
index c2e1d37e28b..119575bdddb 100644
--- a/nixos/modules/services/networking/wpa_supplicant.nix
+++ b/nixos/modules/services/networking/wpa_supplicant.nix
@@ -114,7 +114,7 @@ let
 
       script =
       ''
-        ${optionalString configIsGenerated ''
+        ${optionalString (configIsGenerated && !cfg.allowAuxiliaryImperativeNetworks) ''
           if [ -f /etc/wpa_supplicant.conf ]; then
             echo >&2 "<3>/etc/wpa_supplicant.conf present but ignored. Generated ${configFile} is used instead."
           fi
@@ -164,42 +164,42 @@ let
 in {
   options = {
     networking.wireless = {
-      enable = mkEnableOption "wpa_supplicant";
+      enable = mkEnableOption (lib.mdDoc "wpa_supplicant");
 
       interfaces = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "wlan0" "wlan1" ];
-        description = ''
-          The interfaces <command>wpa_supplicant</command> will use. If empty, it will
+        description = lib.mdDoc ''
+          The interfaces {command}`wpa_supplicant` will use. If empty, it will
           automatically use all wireless interfaces.
 
-          <note><para>
-            A separate wpa_supplicant instance will be started for each interface.
-          </para></note>
+          ::: {.note}
+          A separate wpa_supplicant instance will be started for each interface.
+          :::
         '';
       };
 
       driver = mkOption {
         type = types.str;
         default = "nl80211,wext";
-        description = "Force a specific wpa_supplicant driver.";
+        description = lib.mdDoc "Force a specific wpa_supplicant driver.";
       };
 
-      allowAuxiliaryImperativeNetworks = mkEnableOption "support for imperative & declarative networks" // {
-        description = ''
+      allowAuxiliaryImperativeNetworks = mkEnableOption (lib.mdDoc "support for imperative & declarative networks") // {
+        description = lib.mdDoc ''
           Whether to allow configuring networks "imperatively" (e.g. via
-          <package>wpa_supplicant_gui</package>) and declaratively via
-          <xref linkend="opt-networking.wireless.networks" />.
+          `wpa_supplicant_gui`) and declaratively via
+          [](#opt-networking.wireless.networks).
 
-          Please note that this adds a custom patch to <package>wpa_supplicant</package>.
+          Please note that this adds a custom patch to `wpa_supplicant`.
         '';
       };
 
       scanOnLowSignal = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to periodically scan for (better) networks when the signal of
           the current one is low. This will make roaming between access points
           faster, but will consume more power.
@@ -209,7 +209,7 @@ in {
       fallbackToWPA2 = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to fall back to WPA2 authentication protocols if WPA3 failed.
           This allows old wireless cards (that lack recent features required by
           WPA3) to connect to mixed WPA2/WPA3 access points.
@@ -222,26 +222,24 @@ in {
         type = types.nullOr types.path;
         default = null;
         example = "/run/secrets/wireless.env";
-        description = ''
-          File consisting of lines of the form <literal>varname=value</literal>
+        description = lib.mdDoc ''
+          File consisting of lines of the form `varname=value`
           to define variables for the wireless configuration.
 
-          See section "EnvironmentFile=" in <citerefentry>
-          <refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum>
-          </citerefentry> for a syntax reference.
+          See section "EnvironmentFile=" in {manpage}`systemd.exec(5)` for a syntax reference.
 
           Secrets (PSKs, passwords, etc.) can be provided without adding them to
           the world-readable Nix store by defining them in the environment file and
-          referring to them in option <option>networking.wireless.networks</option>
-          with the syntax <literal>@varname@</literal>. Example:
+          referring to them in option {option}`networking.wireless.networks`
+          with the syntax `@varname@`. Example:
 
-          <programlisting>
+          ```
           # content of /run/secrets/wireless.env
           PSK_HOME=mypassword
           PASS_WORK=myworkpassword
-          </programlisting>
+          ```
 
-          <programlisting>
+          ```
           # wireless-related configuration
           networking.wireless.environmentFile = "/run/secrets/wireless.env";
           networking.wireless.networks = {
@@ -252,7 +250,7 @@ in {
               password="@PASS_WORK@"
             ''';
           };
-          </programlisting>
+          ```
         '';
       };
 
@@ -262,36 +260,36 @@ in {
             psk = mkOption {
               type = types.nullOr types.str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The network's pre-shared key in plaintext defaulting
                 to being a network without any authentication.
 
-                <warning><para>
-                  Be aware that this will be written to the nix store
-                  in plaintext! Use an environment variable instead.
-                </para></warning>
+                ::: {.warning}
+                Be aware that this will be written to the nix store
+                in plaintext! Use an environment variable instead.
+                :::
 
-                <note><para>
-                  Mutually exclusive with <varname>pskRaw</varname>.
-                </para></note>
+                ::: {.note}
+                Mutually exclusive with {var}`pskRaw`.
+                :::
               '';
             };
 
             pskRaw = mkOption {
               type = types.nullOr types.str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 The network's pre-shared key in hex defaulting
                 to being a network without any authentication.
 
-                <warning><para>
-                  Be aware that this will be written to the nix store
-                  in plaintext! Use an environment variable instead.
-                </para></warning>
+                ::: {.warning}
+                Be aware that this will be written to the nix store
+                in plaintext! Use an environment variable instead.
+                :::
 
-                <note><para>
-                  Mutually exclusive with <varname>psk</varname>.
-                </para></note>
+                ::: {.note}
+                Mutually exclusive with {var}`psk`.
+                :::
               '';
             };
 
@@ -331,9 +329,9 @@ in {
                 "OWE"
                 "DPP"
               ]);
-              description = ''
+              description = lib.mdDoc ''
                 The list of authentication protocols accepted by this network.
-                This corresponds to the <literal>key_mgmt</literal> option in wpa_supplicant.
+                This corresponds to the `key_mgmt` option in wpa_supplicant.
               '';
             };
 
@@ -345,32 +343,29 @@ in {
                 identity="user@example.com"
                 password="@EXAMPLE_PASSWORD@"
               '';
-              description = ''
+              description = lib.mdDoc ''
                 Use this option to configure advanced authentication methods like EAP.
                 See
-                <citerefentry>
-                  <refentrytitle>wpa_supplicant.conf</refentrytitle>
-                  <manvolnum>5</manvolnum>
-                </citerefentry>
+                {manpage}`wpa_supplicant.conf(5)`
                 for example configurations.
 
-                <warning><para>
-                  Be aware that this will be written to the nix store
-                  in plaintext! Use an environment variable for secrets.
-                </para></warning>
+                ::: {.warning}
+                Be aware that this will be written to the nix store
+                in plaintext! Use an environment variable for secrets.
+                :::
 
-                <note><para>
-                  Mutually exclusive with <varname>psk</varname> and
-                  <varname>pskRaw</varname>.
-                </para></note>
+                ::: {.note}
+                Mutually exclusive with {var}`psk` and
+                {var}`pskRaw`.
+                :::
               '';
             };
 
             hidden = mkOption {
               type = types.bool;
               default = false;
-              description = ''
-                Set this to <literal>true</literal> if the SSID of the network is hidden.
+              description = lib.mdDoc ''
+                Set this to `true` if the SSID of the network is hidden.
               '';
               example = literalExpression ''
                 { echelon = {
@@ -384,7 +379,7 @@ in {
             priority = mkOption {
               type = types.nullOr types.int;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 By default, all networks will get same priority group (0). If some of the
                 networks are more desirable, this field can be used to change the order in
                 which wpa_supplicant goes through the networks when selecting a BSS. The
@@ -401,22 +396,19 @@ in {
               example = ''
                 bssid_blacklist=02:11:22:33:44:55 02:22:aa:44:55:66
               '';
-              description = ''
+              description = lib.mdDoc ''
                 Extra configuration lines appended to the network block.
                 See
-                <citerefentry>
-                  <refentrytitle>wpa_supplicant.conf</refentrytitle>
-                  <manvolnum>5</manvolnum>
-                </citerefentry>
+                {manpage}`wpa_supplicant.conf(5)`
                 for available options.
               '';
             };
 
           };
         });
-        description = ''
+        description = lib.mdDoc ''
           The network definitions to automatically connect to when
-           <command>wpa_supplicant</command> is running. If this
+           {command}`wpa_supplicant` is running. If this
            parameter is left empty wpa_supplicant will use
           /etc/wpa_supplicant.conf as the configuration file.
         '';
@@ -443,7 +435,7 @@ in {
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Allow normal users to control wpa_supplicant through wpa_gui or wpa_cli.
             This is useful for laptop users that switch networks a lot and don't want
             to depend on a large package such as NetworkManager just to pick nearby
@@ -458,7 +450,7 @@ in {
           type = types.str;
           default = "wheel";
           example = "network";
-          description = "Members of this group can control wpa_supplicant.";
+          description = lib.mdDoc "Members of this group can control wpa_supplicant.";
         };
       };
 
@@ -466,7 +458,7 @@ in {
         type = types.bool;
         default = lib.length cfg.interfaces < 2;
         defaultText = literalExpression "length config.${opt.interfaces} < 2";
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the DBus control interface.
           This is only needed when using NetworkManager or connman.
         '';
@@ -478,13 +470,10 @@ in {
         example = ''
           p2p_disabled=1
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra lines appended to the configuration file.
           See
-          <citerefentry>
-            <refentrytitle>wpa_supplicant.conf</refentrytitle>
-            <manvolnum>5</manvolnum>
-          </citerefentry>
+          {manpage}`wpa_supplicant.conf(5)`
           for available options.
         '';
       };
diff --git a/nixos/modules/services/networking/x2goserver.nix b/nixos/modules/services/networking/x2goserver.nix
index d4adf6c5650..1242229a0b6 100644
--- a/nixos/modules/services/networking/x2goserver.nix
+++ b/nixos/modules/services/networking/x2goserver.nix
@@ -22,16 +22,16 @@ in {
   ];
 
   options.services.x2goserver = {
-    enable = mkEnableOption "x2goserver" // {
-      description = ''
+    enable = mkEnableOption (lib.mdDoc "x2goserver") // {
+      description = lib.mdDoc ''
         Enables the x2goserver module.
         NOTE: This will create a good amount of symlinks in `/usr/local/bin`
       '';
     };
 
     superenicer = {
-      enable = mkEnableOption "superenicer" // {
-        description = ''
+      enable = mkEnableOption (lib.mdDoc "superenicer") // {
+        description = lib.mdDoc ''
           Enables the SupeReNicer code in x2gocleansessions, this will renice
           suspended sessions to nice level 19 and renice them to level 0 if the
           session becomes marked as running again
@@ -42,7 +42,7 @@ in {
     nxagentDefaultOptions = mkOption {
       type = types.listOf types.str;
       default = [ "-extension GLX" "-nolisten tcp" ];
-      description = ''
+      description = lib.mdDoc ''
         List of default nx agent options.
       '';
     };
@@ -50,7 +50,7 @@ in {
     settings = mkOption {
       type = types.attrsOf types.attrs;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         x2goserver.conf ini configuration as nix attributes. See
         `x2goserver.conf(5)` for details
       '';
diff --git a/nixos/modules/services/networking/xandikos.nix b/nixos/modules/services/networking/xandikos.nix
index 4bd45a76e67..6d1ddc74c71 100644
--- a/nixos/modules/services/networking/xandikos.nix
+++ b/nixos/modules/services/networking/xandikos.nix
@@ -9,19 +9,19 @@ in
 
   options = {
     services.xandikos = {
-      enable = mkEnableOption "Xandikos CalDAV and CardDAV server";
+      enable = mkEnableOption (lib.mdDoc "Xandikos CalDAV and CardDAV server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.xandikos;
         defaultText = literalExpression "pkgs.xandikos";
-        description = "The Xandikos package to use.";
+        description = lib.mdDoc "The Xandikos package to use.";
       };
 
       address = mkOption {
         type = types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           The IP address on which Xandikos will listen.
           By default listens on localhost.
         '';
@@ -30,13 +30,13 @@ in
       port = mkOption {
         type = types.port;
         default = 8080;
-        description = "The port of the Xandikos web application";
+        description = lib.mdDoc "The port of the Xandikos web application";
       };
 
       routePrefix = mkOption {
         type = types.str;
         default = "/";
-        description = ''
+        description = lib.mdDoc ''
           Path to Xandikos.
           Useful when Xandikos is behind a reverse proxy.
         '';
@@ -52,14 +52,14 @@ in
             "--dump-dav-xml"
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra command line arguments to pass to xandikos.
         '';
       };
 
       nginx = mkOption {
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Configuration for nginx reverse proxy.
         '';
 
@@ -68,14 +68,14 @@ in
             enable = mkOption {
               type = types.bool;
               default = false;
-              description = ''
+              description = lib.mdDoc ''
                 Configure the nginx reverse proxy settings.
               '';
             };
 
             hostName = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 The hostname use to setup the virtualhost configuration
               '';
             };
diff --git a/nixos/modules/services/networking/xinetd.nix b/nixos/modules/services/networking/xinetd.nix
index 2f527ab156a..b9120f37ba2 100644
--- a/nixos/modules/services/networking/xinetd.nix
+++ b/nixos/modules/services/networking/xinetd.nix
@@ -44,19 +44,19 @@ in
 
   options = {
 
-    services.xinetd.enable = mkEnableOption "the xinetd super-server daemon";
+    services.xinetd.enable = mkEnableOption (lib.mdDoc "the xinetd super-server daemon");
 
     services.xinetd.extraDefaults = mkOption {
       default = "";
       type = types.lines;
-      description = ''
+      description = lib.mdDoc ''
         Additional configuration lines added to the default section of xinetd's configuration.
       '';
     };
 
     services.xinetd.services = mkOption {
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         A list of services provided by xinetd.
       '';
 
@@ -67,53 +67,53 @@ in
           name = mkOption {
             type = types.str;
             example = "login";
-            description = "Name of the service.";
+            description = lib.mdDoc "Name of the service.";
           };
 
           protocol = mkOption {
             type = types.str;
             default = "tcp";
             description =
-              "Protocol of the service.  Usually <literal>tcp</literal> or <literal>udp</literal>.";
+              lib.mdDoc "Protocol of the service.  Usually `tcp` or `udp`.";
           };
 
           port = mkOption {
-            type = types.int;
+            type = types.port;
             default = 0;
             example = 123;
-            description = "Port number of the service.";
+            description = lib.mdDoc "Port number of the service.";
           };
 
           user = mkOption {
             type = types.str;
             default = "nobody";
-            description = "User account for the service";
+            description = lib.mdDoc "User account for the service";
           };
 
           server = mkOption {
             type = types.str;
             example = "/foo/bin/ftpd";
-            description = "Path of the program that implements the service.";
+            description = lib.mdDoc "Path of the program that implements the service.";
           };
 
           serverArgs = mkOption {
             type = types.separatedString " ";
             default = "";
-            description = "Command-line arguments for the server program.";
+            description = lib.mdDoc "Command-line arguments for the server program.";
           };
 
           flags = mkOption {
             type = types.str;
             default = "";
-            description = "";
+            description = lib.mdDoc "";
           };
 
           unlisted = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Whether this server is listed in
-              <filename>/etc/services</filename>.  If so, the port
+              {file}`/etc/services`.  If so, the port
               number can be omitted.
             '';
           };
@@ -121,7 +121,7 @@ in
           extraConfig = mkOption {
             type = types.lines;
             default = "";
-            description = "Extra configuration-lines added to the section of the service.";
+            description = lib.mdDoc "Extra configuration-lines added to the section of the service.";
           };
 
         };
diff --git a/nixos/modules/services/networking/xl2tpd.nix b/nixos/modules/services/networking/xl2tpd.nix
index 7dbe51422d9..7d259570761 100644
--- a/nixos/modules/services/networking/xl2tpd.nix
+++ b/nixos/modules/services/networking/xl2tpd.nix
@@ -5,29 +5,29 @@ with lib;
 {
   options = {
     services.xl2tpd = {
-      enable = mkEnableOption "xl2tpd, the Layer 2 Tunnelling Protocol Daemon";
+      enable = mkEnableOption (lib.mdDoc "xl2tpd, the Layer 2 Tunnelling Protocol Daemon");
 
       serverIp = mkOption {
         type        = types.str;
-        description = "The server-side IP address.";
+        description = lib.mdDoc "The server-side IP address.";
         default     = "10.125.125.1";
       };
 
       clientIpRange = mkOption {
         type        = types.str;
-        description = "The range from which client IPs are drawn.";
+        description = lib.mdDoc "The range from which client IPs are drawn.";
         default     = "10.125.125.2-11";
       };
 
       extraXl2tpOptions = mkOption {
         type        = types.lines;
-        description = "Adds extra lines to the xl2tpd configuration file.";
+        description = lib.mdDoc "Adds extra lines to the xl2tpd configuration file.";
         default     = "";
       };
 
       extraPppdOptions = mkOption {
         type        = types.lines;
-        description = "Adds extra lines to the pppd options file.";
+        description = lib.mdDoc "Adds extra lines to the pppd options file.";
         default     = "";
         example     = ''
           ms-dns 8.8.8.8
@@ -84,7 +84,7 @@ with lib;
       xl2tpd-ppp-wrapped = pkgs.stdenv.mkDerivation {
         name         = "xl2tpd-ppp-wrapped";
         phases       = [ "installPhase" ];
-        buildInputs  = with pkgs; [ makeWrapper ];
+        nativeBuildInputs  = with pkgs; [ makeWrapper ];
         installPhase = ''
           mkdir -p $out/bin
 
@@ -116,18 +116,18 @@ with lib;
         #username	xl2tpd	password	*
         EOF
 
-        chown root.root ppp/chap-secrets
+        chown root:root ppp/chap-secrets
         chmod 600 ppp/chap-secrets
 
         # The documentation says this file should be present but doesn't explain why and things work even if not there:
         [ -f l2tp-secrets ] || (echo -n "* * "; ${pkgs.apg}/bin/apg -n 1 -m 32 -x 32 -a 1 -M LCN) > l2tp-secrets
-        chown root.root l2tp-secrets
+        chown root:root l2tp-secrets
         chmod 600 l2tp-secrets
 
         popd > /dev/null
 
         mkdir -p /run/xl2tpd
-        chown root.root /run/xl2tpd
+        chown root:root /run/xl2tpd
         chmod 700       /run/xl2tpd
       '';
 
diff --git a/nixos/modules/services/networking/xray.nix b/nixos/modules/services/networking/xray.nix
new file mode 100644
index 00000000000..e2fd83c4dfd
--- /dev/null
+++ b/nixos/modules/services/networking/xray.nix
@@ -0,0 +1,96 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+{
+  options = {
+
+    services.xray = {
+      enable = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to run xray server.
+
+          Either `settingsFile` or `settings` must be specified.
+        '';
+      };
+
+      package = mkOption {
+        type = types.package;
+        default = pkgs.xray;
+        defaultText = literalExpression "pkgs.xray";
+        description = lib.mdDoc ''
+          Which xray package to use.
+        '';
+      };
+
+      settingsFile = mkOption {
+        type = types.nullOr types.path;
+        default = null;
+        example = "/etc/xray/config.json";
+        description = lib.mdDoc ''
+          The absolute path to the configuration file.
+
+          Either `settingsFile` or `settings` must be specified.
+
+          See <https://www.v2fly.org/en_US/config/overview.html>.
+        '';
+      };
+
+      settings = mkOption {
+        type = types.nullOr (types.attrsOf types.unspecified);
+        default = null;
+        example = {
+          inbounds = [{
+            port = 1080;
+            listen = "127.0.0.1";
+            protocol = "http";
+          }];
+          outbounds = [{
+            protocol = "freedom";
+          }];
+        };
+        description = lib.mdDoc ''
+          The configuration object.
+
+          Either `settingsFile` or `settings` must be specified.
+
+          See <https://www.v2fly.org/en_US/config/overview.html>.
+        '';
+      };
+    };
+
+  };
+
+  config = let
+    cfg = config.services.xray;
+    settingsFile = if cfg.settingsFile != null
+      then cfg.settingsFile
+      else pkgs.writeTextFile {
+        name = "xray.json";
+        text = builtins.toJSON cfg.settings;
+        checkPhase = ''
+          ${cfg.package}/bin/xray -test -config $out
+        '';
+      };
+
+  in mkIf cfg.enable {
+    assertions = [
+      {
+        assertion = (cfg.settingsFile == null) != (cfg.settings == null);
+        message = "Either but not both `settingsFile` and `settings` should be specified for xray.";
+      }
+    ];
+
+    systemd.services.xray = {
+      description = "xray Daemon";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        DynamicUser = true;
+        ExecStart = "${cfg.package}/bin/xray -config ${settingsFile}";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/networking/xrdp.nix b/nixos/modules/services/networking/xrdp.nix
index 747fb7a1f9c..ed7f1dadd37 100644
--- a/nixos/modules/services/networking/xrdp.nix
+++ b/nixos/modules/services/networking/xrdp.nix
@@ -42,21 +42,21 @@ in
 
     services.xrdp = {
 
-      enable = mkEnableOption "xrdp, the Remote Desktop Protocol server";
+      enable = mkEnableOption (lib.mdDoc "xrdp, the Remote Desktop Protocol server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.xrdp;
         defaultText = literalExpression "pkgs.xrdp";
-        description = ''
+        description = lib.mdDoc ''
           The package to use for the xrdp daemon's binary.
         '';
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 3389;
-        description = ''
+        description = lib.mdDoc ''
           Specifies on which port the xrdp daemon listens.
         '';
       };
@@ -64,14 +64,14 @@ in
       openFirewall = mkOption {
         default = false;
         type = types.bool;
-        description = "Whether to open the firewall for the specified RDP port.";
+        description = lib.mdDoc "Whether to open the firewall for the specified RDP port.";
       };
 
       sslKey = mkOption {
         type = types.str;
         default = "/etc/xrdp/key.pem";
         example = "/path/to/your/key.pem";
-        description = ''
+        description = lib.mdDoc ''
           ssl private key path
           A self-signed certificate will be generated if file not exists.
         '';
@@ -81,7 +81,7 @@ in
         type = types.str;
         default = "/etc/xrdp/cert.pem";
         example = "/path/to/your/cert.pem";
-        description = ''
+        description = lib.mdDoc ''
           ssl certificate path
           A self-signed certificate will be generated if file not exists.
         '';
@@ -91,7 +91,7 @@ in
         type = types.str;
         default = "xterm";
         example = "xfce4-session";
-        description = ''
+        description = lib.mdDoc ''
           The script to run when user log in, usually a window manager, e.g. "icewm", "xfce4-session"
           This is per-user overridable, if file ~/startwm.sh exists it will be used instead.
         '';
@@ -100,8 +100,8 @@ in
       confDir = mkOption {
         type = types.path;
         default = confDir;
-        defaultText = literalDocBook "generated from configuration";
-        description = "The location of the config files for xrdp.";
+        defaultText = literalMD "generated from configuration";
+        description = lib.mdDoc "The location of the config files for xrdp.";
       };
     };
   };
diff --git a/nixos/modules/services/networking/yggdrasil.nix b/nixos/modules/services/networking/yggdrasil.nix
index 99c18ae6919..3d5cbdd2dc3 100644
--- a/nixos/modules/services/networking/yggdrasil.nix
+++ b/nixos/modules/services/networking/yggdrasil.nix
@@ -4,16 +4,23 @@ let
   keysPath = "/var/lib/yggdrasil/keys.json";
 
   cfg = config.services.yggdrasil;
-  configProvided = cfg.config != { };
+  settingsProvided = cfg.settings != { };
   configFileProvided = cfg.configFile != null;
 
+  format = pkgs.formats.json { };
 in {
+  imports = [
+    (mkRenamedOptionModule
+      [ "services" "yggdrasil" "config" ]
+      [ "services" "yggdrasil" "settings" ])
+  ];
+
   options = with types; {
     services.yggdrasil = {
-      enable = mkEnableOption "the yggdrasil system service";
+      enable = mkEnableOption (lib.mdDoc "the yggdrasil system service");
 
-      config = mkOption {
-        type = attrs;
+      settings = mkOption {
+        type = format.type;
         default = {};
         example = {
           Peers = [
@@ -24,29 +31,28 @@ in {
             "tcp://0.0.0.0:xxxxx"
           ];
         };
-        description = ''
+        description = lib.mdDoc ''
           Configuration for yggdrasil, as a Nix attribute set.
 
           Warning: this is stored in the WORLD-READABLE Nix store!
           Therefore, it is not appropriate for private keys. If you
-          wish to specify the keys, use <option>configFile</option>.
+          wish to specify the keys, use {option}`configFile`.
 
-          If the <option>persistentKeys</option> is enabled then the
+          If the {option}`persistentKeys` is enabled then the
           keys that are generated during activation will override
-          those in <option>config</option> or
-          <option>configFile</option>.
+          those in {option}`settings` or
+          {option}`configFile`.
 
           If no keys are specified then ephemeral keys are generated
           and the Yggdrasil interface will have a random IPv6 address
           each time the service is started, this is the default.
 
-          If both <option>configFile</option> and <option>config</option>
+          If both {option}`configFile` and {option}`settings`
           are supplied, they will be combined, with values from
-          <option>configFile</option> taking precedence.
+          {option}`configFile` taking precedence.
 
-          You can use the command <code>nix-shell -p yggdrasil --run
-          "yggdrasil -genconf"</code> to generate default
-          configuration values with documentation.
+          You can use the command `nix-shell -p yggdrasil --run "yggdrasil -genconf"`
+          to generate default configuration values with documentation.
         '';
       };
 
@@ -54,31 +60,31 @@ in {
         type = nullOr path;
         default = null;
         example = "/run/keys/yggdrasil.conf";
-        description = ''
+        description = lib.mdDoc ''
           A file which contains JSON configuration for yggdrasil.
-          See the <option>config</option> option for more information.
+          See the {option}`settings` option for more information.
         '';
       };
 
       group = mkOption {
-        type = types.str;
-        default = "root";
+        type = types.nullOr types.str;
+        default = null;
         example = "wheel";
-        description = "Group to grant access to the Yggdrasil control socket.";
+        description = lib.mdDoc "Group to grant access to the Yggdrasil control socket. If `null`, only root can access the socket.";
       };
 
       openMulticastPort = mkOption {
         type = bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to open the UDP port used for multicast peer
           discovery. The NixOS firewall blocks link-local
           communication, so in order to make local peering work you
-          will also need to set <code>LinkLocalTCPPort</code> in your
-          yggdrasil configuration (<option>config</option> or
-          <option>configFile</option>) to a port number other than 0,
+          will also need to set `LinkLocalTCPPort` in your
+          yggdrasil configuration ({option}`settings` or
+          {option}`configFile`) to a port number other than 0,
           and then add that port to
-          <option>networking.firewall.allowedTCPPorts</option>.
+          {option}`networking.firewall.allowedTCPPorts`.
         '';
       };
 
@@ -86,7 +92,7 @@ in {
         type = listOf str;
         default = [];
         example = [ "tap*" ];
-        description = ''
+        description = lib.mdDoc ''
           Disable the DHCP client for any interface whose name matches
           any of the shell glob patterns in this list.  Use this
           option to prevent the DHCP client from broadcasting requests
@@ -100,14 +106,14 @@ in {
         type = package;
         default = pkgs.yggdrasil;
         defaultText = literalExpression "pkgs.yggdrasil";
-        description = "Yggdrasil package to use.";
+        description = lib.mdDoc "Yggdrasil package to use.";
       };
 
-      persistentKeys = mkEnableOption ''
+      persistentKeys = mkEnableOption (lib.mdDoc ''
         If enabled then keys will be generated once and Yggdrasil
         will retain the same IPv6 address when the service is
         restarted. Keys are stored at ${keysPath}.
-      '';
+      '');
 
     };
   };
@@ -132,16 +138,17 @@ in {
 
     systemd.services.yggdrasil = {
       description = "Yggdrasil Network Service";
-      bindsTo = [ "network-online.target" ];
-      after = [ "network-online.target" ];
+      after = [ "network-pre.target" ];
+      wants = [ "network.target" ];
+      before = [ "network.target" ];
       wantedBy = [ "multi-user.target" ];
 
       preStart =
-        (if configProvided || configFileProvided || cfg.persistentKeys then
+        (if settingsProvided || configFileProvided || cfg.persistentKeys then
           "echo "
 
-          + (lib.optionalString configProvided
-            "'${builtins.toJSON cfg.config}'")
+          + (lib.optionalString settingsProvided
+            "'${builtins.toJSON cfg.settings}'")
           + (lib.optionalString configFileProvided "$(cat ${cfg.configFile})")
           + (lib.optionalString cfg.persistentKeys "$(cat ${keysPath})")
           + " | ${pkgs.jq}/bin/jq -s add | ${binYggdrasil} -normaliseconf -useconf"
@@ -154,27 +161,16 @@ in {
         ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
         Restart = "always";
 
-        Group = cfg.group;
+        DynamicUser = true;
+        StateDirectory = "yggdrasil";
         RuntimeDirectory = "yggdrasil";
         RuntimeDirectoryMode = "0750";
         BindReadOnlyPaths = lib.optional configFileProvided cfg.configFile
           ++ lib.optional cfg.persistentKeys keysPath;
+        ReadWritePaths = "/run/yggdrasil";
 
-        # TODO: as of yggdrasil 0.3.8 and systemd 243, yggdrasil fails
-        # to set up the network adapter when DynamicUser is set.  See
-        # github.com/yggdrasil-network/yggdrasil-go/issues/557.  The
-        # following options are implied by DynamicUser according to
-        # the systemd.exec documentation, and can be removed if the
-        # upstream issue is fixed and DynamicUser is set to true:
-        PrivateTmp = true;
-        RemoveIPC = true;
-        NoNewPrivileges = true;
-        ProtectSystem = "strict";
-        RestrictSUIDSGID = true;
-        # End of list of options implied by DynamicUser.
-
-        AmbientCapabilities = "CAP_NET_ADMIN";
-        CapabilityBoundingSet = "CAP_NET_ADMIN";
+        AmbientCapabilities = "CAP_NET_ADMIN CAP_NET_BIND_SERVICE";
+        CapabilityBoundingSet = "CAP_NET_ADMIN CAP_NET_BIND_SERVICE";
         MemoryDenyWriteExecute = true;
         ProtectControlGroups = true;
         ProtectHome = "tmpfs";
@@ -184,8 +180,10 @@ in {
         RestrictNamespaces = true;
         RestrictRealtime = true;
         SystemCallArchitectures = "native";
-        SystemCallFilter = "~@clock @cpu-emulation @debug @keyring @module @mount @obsolete @raw-io @resources";
-      };
+        SystemCallFilter = [ "@system-service" "~@privileged @keyring" ];
+      } // (if (cfg.group != null) then {
+        Group = cfg.group;
+      } else {});
     };
 
     networking.dhcpcd.denyInterfaces = cfg.denyDhcpcdInterfaces;
diff --git a/nixos/modules/services/networking/yggdrasil.xml b/nixos/modules/services/networking/yggdrasil.xml
index a341d5d8153..bc9da84fa43 100644
--- a/nixos/modules/services/networking/yggdrasil.xml
+++ b/nixos/modules/services/networking/yggdrasil.xml
@@ -27,7 +27,7 @@ An annotated example of a simple configuration:
       # The NixOS module will generate new keys and a new IPv6 address each time
       # it is started if persistentKeys is not enabled.
 
-    config = {
+    settings = {
       Peers = [
         # Yggdrasil will automatically connect and "peer" with other nodes it
         # discovers via link-local multicast annoucements. Unless this is the
@@ -58,7 +58,7 @@ in {
   services.yggdrasil = {
     enable = true;
     persistentKeys = true; # Maintain a fixed public key and IPv6 address.
-    config = {
+    settings = {
       Peers = [ "tcp://1.2.3.4:1024" "tcp://1.2.3.5:1024" ];
       NodeInfo = {
         # This information is visible to the network.
diff --git a/nixos/modules/services/networking/zerobin.nix b/nixos/modules/services/networking/zerobin.nix
index 16db25d6230..9e07666f3e1 100644
--- a/nixos/modules/services/networking/zerobin.nix
+++ b/nixos/modules/services/networking/zerobin.nix
@@ -12,12 +12,12 @@ in
   {
     options = {
       services.zerobin = {
-        enable = mkEnableOption "0bin";
+        enable = mkEnableOption (lib.mdDoc "0bin");
 
         dataDir = mkOption {
           type = types.str;
           default = "/var/lib/zerobin";
-          description = ''
+          description = lib.mdDoc ''
           Path to the 0bin data directory
           '';
         };
@@ -25,7 +25,7 @@ in
         user = mkOption {
           type = types.str;
           default = "zerobin";
-          description = ''
+          description = lib.mdDoc ''
           The user 0bin should run as
           '';
         };
@@ -33,7 +33,7 @@ in
         group = mkOption {
           type = types.str;
           default = "zerobin";
-          description = ''
+          description = lib.mdDoc ''
           The group 0bin should run as
           '';
         };
@@ -42,7 +42,7 @@ in
           type = types.int;
           default = 8000;
           example = 1357;
-          description = ''
+          description = lib.mdDoc ''
           The port zerobin should listen on
           '';
         };
@@ -51,7 +51,7 @@ in
           type = types.str;
           default = "localhost";
           example = "127.0.0.1";
-          description = ''
+          description = lib.mdDoc ''
           The address zerobin should listen to
           '';
         };
@@ -65,7 +65,7 @@ in
           )
           COMPRESSED_STATIC_FILE = True
           '';
-          description = ''
+          description = lib.mdDoc ''
           Extra configuration to be appended to the 0bin config file
           (see https://0bin.readthedocs.org/en/latest/en/options.html)
           '';
diff --git a/nixos/modules/services/networking/zeronet.nix b/nixos/modules/services/networking/zeronet.nix
index 3370390a4c6..1f3711bd0d7 100644
--- a/nixos/modules/services/networking/zeronet.nix
+++ b/nixos/modules/services/networking/zeronet.nix
@@ -17,16 +17,23 @@ let
   };
 in with lib; {
   options.services.zeronet = {
-    enable = mkEnableOption "zeronet";
+    enable = mkEnableOption (lib.mdDoc "zeronet");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.zeronet;
+      defaultText = literalExpression "pkgs.zeronet";
+      description = lib.mdDoc "ZeroNet package to use";
+    };
 
     settings = mkOption {
       type = with types; attrsOf (oneOf [ str int bool (listOf str) ]);
       default = {};
       example = literalExpression "{ global.tor = enable; }";
 
-      description = ''
-        <filename>zeronet.conf</filename> configuration. Refer to
-        <link xlink:href="https://zeronet.readthedocs.io/en/latest/faq/#is-it-possible-to-use-a-configuration-file"/>
+      description = lib.mdDoc ''
+        {file}`zeronet.conf` configuration. Refer to
+        <https://zeronet.readthedocs.io/en/latest/faq/#is-it-possible-to-use-a-configuration-file>
         for details on supported values;
       '';
     };
@@ -34,7 +41,7 @@ in with lib; {
     port = mkOption {
       type = types.port;
       default = 43110;
-      description = "Optional zeronet web UI port.";
+      description = lib.mdDoc "Optional zeronet web UI port.";
     };
 
     fileserverPort = mkOption {
@@ -42,19 +49,19 @@ in with lib; {
       # read-only config file and crashes
       type = types.port;
       default = 12261;
-      description = "Zeronet fileserver port.";
+      description = lib.mdDoc "Zeronet fileserver port.";
     };
 
     tor = mkOption {
       type = types.bool;
       default = false;
-      description = "Use TOR for zeronet traffic where possible.";
+      description = lib.mdDoc "Use TOR for zeronet traffic where possible.";
     };
 
     torAlways = mkOption {
       type = types.bool;
       default = false;
-      description = "Use TOR for all zeronet traffic.";
+      description = lib.mdDoc "Use TOR for all zeronet traffic.";
     };
   };
 
@@ -72,7 +79,7 @@ in with lib; {
 
     systemd.services.zeronet = {
       description = "zeronet";
-      after = [ "network.target" (optionalString cfg.tor "tor.service") ];
+      after = [ "network.target" ] ++ optional cfg.tor "tor.service";
       wantedBy = [ "multi-user.target" ];
 
       serviceConfig = {
@@ -80,7 +87,7 @@ in with lib; {
         DynamicUser = true;
         StateDirectory = "zeronet";
         SupplementaryGroups = mkIf cfg.tor [ "tor" ];
-        ExecStart = "${pkgs.zeronet}/bin/zeronet --config_file ${configFile}";
+        ExecStart = "${cfg.package}/bin/zeronet --config_file ${configFile}";
       };
     };
   };
@@ -90,5 +97,5 @@ in with lib; {
     (mkRemovedOptionModule [ "services" "zeronet" "logDir" ] "Zeronet will log by default in /var/lib/zeronet")
   ];
 
-  meta.maintainers = with maintainers; [ chiiruno ];
+  meta.maintainers = with maintainers; [ Madouura ];
 }
diff --git a/nixos/modules/services/networking/zerotierone.nix b/nixos/modules/services/networking/zerotierone.nix
index 3bc7d3ac0db..0d9e25cfc52 100644
--- a/nixos/modules/services/networking/zerotierone.nix
+++ b/nixos/modules/services/networking/zerotierone.nix
@@ -6,21 +6,21 @@ let
   cfg = config.services.zerotierone;
 in
 {
-  options.services.zerotierone.enable = mkEnableOption "ZeroTierOne";
+  options.services.zerotierone.enable = mkEnableOption (lib.mdDoc "ZeroTierOne");
 
   options.services.zerotierone.joinNetworks = mkOption {
     default = [];
     example = [ "a8a2c3c10c1a68de" ];
     type = types.listOf types.str;
-    description = ''
+    description = lib.mdDoc ''
       List of ZeroTier Network IDs to join on startup
     '';
   };
 
   options.services.zerotierone.port = mkOption {
     default = 9993;
-    type = types.int;
-    description = ''
+    type = types.port;
+    description = lib.mdDoc ''
       Network port used by ZeroTier.
     '';
   };
@@ -29,7 +29,7 @@ in
     default = pkgs.zerotierone;
     defaultText = literalExpression "pkgs.zerotierone";
     type = types.package;
-    description = ''
+    description = lib.mdDoc ''
       ZeroTier One package to use.
     '';
   };
diff --git a/nixos/modules/services/networking/znc/default.nix b/nixos/modules/services/networking/znc/default.nix
index a98f92d2d71..2befab373ba 100644
--- a/nixos/modules/services/networking/znc/default.nix
+++ b/nixos/modules/services/networking/znc/default.nix
@@ -81,13 +81,13 @@ in
 
   options = {
     services.znc = {
-      enable = mkEnableOption "ZNC";
+      enable = mkEnableOption (lib.mdDoc "ZNC");
 
       user = mkOption {
         default = "znc";
         example = "john";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The name of an existing user account to use to own the ZNC server
           process. If not specified, a default user will be created.
         '';
@@ -97,7 +97,7 @@ in
         default = defaultUser;
         example = "users";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Group to own the ZNC process.
         '';
       };
@@ -106,7 +106,7 @@ in
         default = "/var/lib/znc";
         example = "/home/john/.znc";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The state directory for ZNC. The config and the modules will be linked
           to from this directory as well.
         '';
@@ -115,10 +115,10 @@ in
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to open ports in the firewall for ZNC. Does work with
           ports for listeners specified in
-          <option>services.znc.config.Listener</option>.
+          {option}`services.znc.config.Listener`.
         '';
       };
 
@@ -149,31 +149,27 @@ in
             };
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Configuration for ZNC, see
-          <link xlink:href="https://wiki.znc.in/Configuration"/> for details. The
+          <https://wiki.znc.in/Configuration> for details. The
           Nix value declared here will be translated directly to the xml-like
           format ZNC expects. This is much more flexible than the legacy options
-          under <option>services.znc.confOptions.*</option>, but also can't do
+          under {option}`services.znc.confOptions.*`, but also can't do
           any type checking.
-          </para>
-          <para>
-          You can use <command>nix-instantiate --eval --strict '&lt;nixpkgs/nixos&gt;' -A config.services.znc.config</command>
+
+          You can use {command}`nix-instantiate --eval --strict '<nixpkgs/nixos>' -A config.services.znc.config`
           to view the current value. By default it contains a listener for port
           5000 with SSL enabled.
-          </para>
-          <para>
-          Nix attributes called <literal>extraConfig</literal> will be inserted
+
+          Nix attributes called `extraConfig` will be inserted
           verbatim into the resulting config file.
-          </para>
-          <para>
-          If <option>services.znc.useLegacyConfig</option> is turned on, the
-          option values in <option>services.znc.confOptions.*</option> will be
+
+          If {option}`services.znc.useLegacyConfig` is turned on, the
+          option values in {option}`services.znc.confOptions.*` will be
           gracefully be applied to this option.
-          </para>
-          <para>
+
           If you intend to update the configuration through this option, be sure
-          to enable <option>services.znc.mutable</option>, otherwise none of the
+          to enable {option}`services.znc.mutable`, otherwise none of the
           changes here will be applied after the initial deploy.
         '';
       };
@@ -181,13 +177,12 @@ in
       configFile = mkOption {
         type = types.path;
         example = literalExpression "~/.znc/configs/znc.conf";
-        description = ''
+        description = lib.mdDoc ''
           Configuration file for ZNC. It is recommended to use the
-          <option>config</option> option instead.
-          </para>
-          <para>
+          {option}`config` option instead.
+
           Setting this option will override any auto-generated config file
-          through the <option>confOptions</option> or <option>config</option>
+          through the {option}`confOptions` or {option}`config`
           options.
         '';
       };
@@ -196,7 +191,7 @@ in
         type = types.listOf types.package;
         default = [ ];
         example = literalExpression "[ pkgs.zncModules.fish pkgs.zncModules.push ]";
-        description = ''
+        description = lib.mdDoc ''
           A list of global znc module packages to add to znc.
         '';
       };
@@ -204,17 +199,15 @@ in
       mutable = mkOption {
         default = true; # TODO: Default to true when config is set, make sure to not delete the old config if present
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Indicates whether to allow the contents of the
-          <literal>dataDir</literal> directory to be changed by the user at
+          `dataDir` directory to be changed by the user at
           run-time.
-          </para>
-          <para>
+
           If enabled, modifications to the ZNC configuration after its initial
           creation are not overwritten by a NixOS rebuild. If disabled, the
           ZNC configuration is rebuilt on every NixOS rebuild.
-          </para>
-          <para>
+
           If the user wants to manage the ZNC service using the web admin
           interface, this option should be enabled.
         '';
@@ -224,7 +217,7 @@ in
         default = [ ];
         example = [ "--debug" ];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Extra arguments to use for executing znc.
         '';
       };
diff --git a/nixos/modules/services/networking/znc/options.nix b/nixos/modules/services/networking/znc/options.nix
index 0db051126e8..ce8e7a89a4d 100644
--- a/nixos/modules/services/networking/znc/options.nix
+++ b/nixos/modules/services/networking/znc/options.nix
@@ -12,7 +12,7 @@ let
       server = mkOption {
         type = types.str;
         example = "irc.libera.chat";
-        description = ''
+        description = lib.mdDoc ''
           IRC server address.
         '';
       };
@@ -20,7 +20,7 @@ let
       port = mkOption {
         type = types.ints.u16;
         default = 6697;
-        description = ''
+        description = lib.mdDoc ''
           IRC server port.
         '';
       };
@@ -28,7 +28,7 @@ let
       password = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           IRC server password, such as for a Slack gateway.
         '';
       };
@@ -36,7 +36,7 @@ let
       useSSL = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use SSL to connect to the IRC server.
         '';
       };
@@ -45,7 +45,7 @@ let
         type = types.listOf types.str;
         default = [ "simple_away" ];
         example = literalExpression ''[ "simple_away" "sasl" ]'';
-        description = ''
+        description = lib.mdDoc ''
           ZNC network modules to load.
         '';
       };
@@ -54,7 +54,7 @@ let
         type = types.listOf types.str;
         default = [];
         example = [ "nixos" ];
-        description = ''
+        description = lib.mdDoc ''
           IRC channels to join.
         '';
       };
@@ -62,7 +62,7 @@ let
       hasBitlbeeControlChannel = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to add the special Bitlbee operations channel.
         '';
       };
@@ -79,9 +79,9 @@ let
           JoinDelay = 0
           Nick = johntron
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra config for the network. Consider using
-          <option>services.znc.config</option> instead.
+          {option}`services.znc.config` instead.
         '';
       };
     };
@@ -97,19 +97,18 @@ in
       useLegacyConfig = mkOption {
         default = true;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to propagate the legacy options under
-          <option>services.znc.confOptions.*</option> to the znc config. If this
+          {option}`services.znc.confOptions.*` to the znc config. If this
           is turned on, the znc config will contain a user with the default name
           "znc", global modules "webadmin" and "adminlog" will be enabled by
           default, and more, all controlled through the
-          <option>services.znc.confOptions.*</option> options.
-          You can use <command>nix-instantiate --eval --strict '&lt;nixpkgs/nixos&gt;' -A config.services.znc.config</command>
+          {option}`services.znc.confOptions.*` options.
+          You can use {command}`nix-instantiate --eval --strict '<nixpkgs/nixos>' -A config.services.znc.config`
           to view the current value of the config.
-          </para>
-          <para>
+
           In any case, if you need more flexibility,
-          <option>services.znc.config</option> can be used to override/add to
+          {option}`services.znc.config` can be used to override/add to
           all of the legacy options.
         '';
       };
@@ -119,7 +118,7 @@ in
           type = types.listOf types.str;
           default = [ "webadmin" "adminlog" ];
           example = [ "partyline" "webadmin" "adminlog" "log" ];
-          description = ''
+          description = lib.mdDoc ''
             A list of modules to include in the `znc.conf` file.
           '';
         };
@@ -128,7 +127,7 @@ in
           type = types.listOf types.str;
           default = [ "chansaver" "controlpanel" ];
           example = [ "chansaver" "controlpanel" "fish" "push" ];
-          description = ''
+          description = lib.mdDoc ''
             A list of user modules to include in the `znc.conf` file.
           '';
         };
@@ -137,7 +136,7 @@ in
           default = "znc";
           example = "johntron";
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             The user name used to log in to the ZNC web admin interface.
           '';
         };
@@ -145,7 +144,7 @@ in
         networks = mkOption {
           default = { };
           type = with types; attrsOf (submodule networkOpts);
-          description = ''
+          description = lib.mdDoc ''
             IRC networks to connect the user to.
           '';
           example = literalExpression ''
@@ -164,7 +163,7 @@ in
           default = "znc-user";
           example = "john";
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             The IRC nick.
           '';
         };
@@ -178,11 +177,11 @@ in
             &lt;/Pass&gt;
           '';
           type = types.str;
-          description = ''
-            Generate with `nix-shell -p znc --command "znc --makepass"`.
+          description = lib.mdDoc ''
+            Generate with {command}`nix-shell -p znc --command "znc --makepass"`.
             This is the password used to log in to the ZNC web admin interface.
             You can also set this through
-            <option>services.znc.config.User.&lt;username&gt;.Pass.Method</option>
+            {option}`services.znc.config.User.<username>.Pass.Method`
             and co.
           '';
         };
@@ -190,7 +189,7 @@ in
         port = mkOption {
           default = 5000;
           type = types.int;
-          description = ''
+          description = lib.mdDoc ''
             Specifies the port on which to listen.
           '';
         };
@@ -198,7 +197,7 @@ in
         useSSL = mkOption {
           default = true;
           type = types.bool;
-          description = ''
+          description = lib.mdDoc ''
             Indicates whether the ZNC server should use SSL when listening on
             the specified port. A self-signed certificate will be generated.
           '';
@@ -208,7 +207,7 @@ in
           type = types.nullOr types.str;
           default = null;
           example = "/znc/";
-          description = ''
+          description = lib.mdDoc ''
             An optional URI prefix for the ZNC web interface. Can be
             used to make ZNC available behind a reverse proxy.
           '';
@@ -217,7 +216,7 @@ in
         extraZncConf = mkOption {
           default = "";
           type = types.lines;
-          description = ''
+          description = lib.mdDoc ''
             Extra config to `znc.conf` file.
           '';
         };
diff --git a/nixos/modules/services/printing/cupsd.nix b/nixos/modules/services/printing/cupsd.nix
index 53091d8e2a0..ae59dcc226d 100644
--- a/nixos/modules/services/printing/cupsd.nix
+++ b/nixos/modules/services/printing/cupsd.nix
@@ -129,15 +129,24 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable printing support through the CUPS daemon.
         '';
       };
 
+      stateless = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          If set, all state directories relating to CUPS will be removed on
+          startup of the service.
+        '';
+      };
+
       startWhenNeeded = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           If set, CUPS is socket-activated; that is,
           instead of having it permanently running as a daemon,
           systemd will start it on the first incoming connection.
@@ -148,7 +157,7 @@ in
         type = types.listOf types.str;
         default = [ "localhost:631" ];
         example = [ "*:631" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of addresses and ports on which to listen.
         '';
       };
@@ -158,7 +167,7 @@ in
         default = [ "localhost" ];
         example = [ "all" ];
         apply = concatMapStringsSep "\n" (x: "Allow ${x}");
-        description = ''
+        description = lib.mdDoc ''
           From which hosts to allow unconditional access.
         '';
       };
@@ -167,7 +176,7 @@ in
         type = types.lines;
         internal = true;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Additional commands executed while creating the directory
           containing the CUPS server binaries.
         '';
@@ -176,7 +185,7 @@ in
       defaultShared = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether local printers are shared by default.
         '';
       };
@@ -184,7 +193,7 @@ in
       browsing = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether shared printers are advertised.
         '';
       };
@@ -192,7 +201,7 @@ in
       webInterface = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Specifies whether the web interface is enabled.
         '';
       };
@@ -201,7 +210,7 @@ in
         type = types.str;
         default = "info";
         example = "debug";
-        description = ''
+        description = lib.mdDoc ''
           Specifies the cupsd logging verbosity.
         '';
       };
@@ -209,9 +218,9 @@ in
       extraFilesConf = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra contents of the configuration file of the CUPS daemon
-          (<filename>cups-files.conf</filename>).
+          ({file}`cups-files.conf`).
         '';
       };
 
@@ -223,9 +232,9 @@ in
             BrowsePoll cups.example.com
             MaxCopies 42
           '';
-        description = ''
+        description = lib.mdDoc ''
           Extra contents of the configuration file of the CUPS daemon
-          (<filename>cupsd.conf</filename>).
+          ({file}`cupsd.conf`).
         '';
       };
 
@@ -237,9 +246,9 @@ in
             ServerName server.example.com
             Encryption Never
           '';
-        description = ''
+        description = lib.mdDoc ''
           The contents of the client configuration.
-          (<filename>client.conf</filename>)
+          ({file}`client.conf`)
         '';
       };
 
@@ -250,9 +259,9 @@ in
           ''
             BrowsePoll cups.example.com
           '';
-        description = ''
+        description = lib.mdDoc ''
           The contents of the configuration. file of the CUPS Browsed daemon
-          (<filename>cups-browsed.conf</filename>)
+          ({file}`cups-browsed.conf`)
         '';
       };
 
@@ -261,8 +270,8 @@ in
         default = ''
           Address @LOCAL
         '';
-        description = ''
-          The contents of <filename>/etc/cups/snmp.conf</filename>. See "man
+        description = lib.mdDoc ''
+          The contents of {file}`/etc/cups/snmp.conf`. See "man
           cups-snmp.conf" for a complete description.
         '';
       };
@@ -271,12 +280,12 @@ in
         type = types.listOf types.path;
         default = [];
         example = literalExpression "with pkgs; [ gutenprint hplip splix ]";
-        description = ''
+        description = lib.mdDoc ''
           CUPS drivers to use. Drivers provided by CUPS, cups-filters,
           Ghostscript and Samba are added unconditionally. If this list contains
           Gutenprint (i.e. a derivation with
-          <literal>meta.isGutenprint = true</literal>) the PPD files in
-          <filename>/var/lib/cups/ppd</filename> will be updated automatically
+          `meta.isGutenprint = true`) the PPD files in
+          {file}`/var/lib/cups/ppd` will be updated automatically
           to avoid errors due to incompatible versions.
         '';
       };
@@ -285,7 +294,7 @@ in
         type = types.path;
         default = "/tmp";
         example = "/tmp/cups";
-        description = ''
+        description = lib.mdDoc ''
           CUPSd temporary directory.
         '';
       };
@@ -343,8 +352,9 @@ in
 
         path = [ cups.out ];
 
-        preStart =
-          ''
+        preStart = lib.optionalString cfg.stateless ''
+          rm -rf /var/cache/cups /var/lib/cups /var/spool/cups
+        '' + ''
             mkdir -m 0700 -p /var/cache/cups
             mkdir -m 0700 -p /var/spool/cups
             mkdir -m 0755 -p ${cfg.tempDir}
diff --git a/nixos/modules/services/scheduling/atd.nix b/nixos/modules/services/scheduling/atd.nix
index 9bb0191ee46..235d4f348e5 100644
--- a/nixos/modules/services/scheduling/atd.nix
+++ b/nixos/modules/services/scheduling/atd.nix
@@ -19,19 +19,19 @@ in
     services.atd.enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
-        Whether to enable the <command>at</command> daemon, a command scheduler.
+      description = lib.mdDoc ''
+        Whether to enable the {command}`at` daemon, a command scheduler.
       '';
     };
 
     services.atd.allowEveryone = mkOption {
       type = types.bool;
       default = false;
-      description = ''
-        Whether to make <filename>/var/spool/at{jobs,spool}</filename>
+      description = lib.mdDoc ''
+        Whether to make {file}`/var/spool/at{jobs,spool}`
         writeable by everyone (and sticky).  This is normally not
-        needed since the <command>at</command> commands are
-        setuid/setgid <literal>atd</literal>.
+        needed since the {command}`at` commands are
+        setuid/setgid `atd`.
      '';
     };
 
diff --git a/nixos/modules/services/scheduling/cron.nix b/nixos/modules/services/scheduling/cron.nix
index 1fac54003cb..6e8fe5d9d03 100644
--- a/nixos/modules/services/scheduling/cron.nix
+++ b/nixos/modules/services/scheduling/cron.nix
@@ -40,13 +40,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the Vixie cron daemon.";
+        description = lib.mdDoc "Whether to enable the Vixie cron daemon.";
       };
 
       mailto = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "Email address to which job output will be mailed.";
+        description = lib.mdDoc "Email address to which job output will be mailed.";
       };
 
       systemCronJobs = mkOption {
@@ -57,11 +57,11 @@ in
             "* * * * *  eelco  echo Hello World > /home/eelco/cronout"
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           A list of Cron jobs to be appended to the system-wide
           crontab.  See the manual page for crontab for the expected
           format. If you want to get the results mailed you must setuid
-          sendmail. See <option>security.wrappers</option>
+          sendmail. See {option}`security.wrappers`
 
           If neither /var/cron/cron.deny nor /var/cron/cron.allow exist only root
           is allowed to have its own crontab file. The /var/cron/cron.deny file
@@ -76,7 +76,7 @@ in
       cronFiles = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of extra crontab files that will be read and appended to the main
           crontab file when the cron service starts.
         '';
diff --git a/nixos/modules/services/scheduling/fcron.nix b/nixos/modules/services/scheduling/fcron.nix
index acaa995f739..f1d2f462a75 100644
--- a/nixos/modules/services/scheduling/fcron.nix
+++ b/nixos/modules/services/scheduling/fcron.nix
@@ -40,40 +40,40 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the <command>fcron</command> daemon.";
+        description = lib.mdDoc "Whether to enable the {command}`fcron` daemon.";
       };
 
       allow = mkOption {
         type = types.listOf types.str;
         default = [ "all" ];
-        description = ''
+        description = lib.mdDoc ''
           Users allowed to use fcrontab and fcrondyn (one name per
-          line, <literal>all</literal> for everyone).
+          line, `all` for everyone).
         '';
       };
 
       deny = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Users forbidden from using fcron.";
+        description = lib.mdDoc "Users forbidden from using fcron.";
       };
 
       maxSerialJobs = mkOption {
         type = types.int;
         default = 1;
-        description = "Maximum number of serial jobs which can run simultaneously.";
+        description = lib.mdDoc "Maximum number of serial jobs which can run simultaneously.";
       };
 
       queuelen = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = "Number of jobs the serial queue and the lavg queue can contain.";
+        description = lib.mdDoc "Number of jobs the serial queue and the lavg queue can contain.";
       };
 
       systab = mkOption {
         type = types.lines;
         default = "";
-        description = ''The "system" crontab contents.'';
+        description = lib.mdDoc ''The "system" crontab contents.'';
       };
     };
 
diff --git a/nixos/modules/services/search/elasticsearch-curator.nix b/nixos/modules/services/search/elasticsearch-curator.nix
index bb2612322bb..f073ec7cf2b 100644
--- a/nixos/modules/services/search/elasticsearch-curator.nix
+++ b/nixos/modules/services/search/elasticsearch-curator.nix
@@ -37,24 +37,24 @@ in {
 
   options.services.elasticsearch-curator = {
 
-    enable = mkEnableOption "elasticsearch curator";
+    enable = mkEnableOption (lib.mdDoc "elasticsearch curator");
     interval = mkOption {
-      description = "The frequency to run curator, a systemd.time such as 'hourly'";
+      description = lib.mdDoc "The frequency to run curator, a systemd.time such as 'hourly'";
       default = "hourly";
       type = types.str;
     };
     hosts = mkOption {
-      description = "a list of elasticsearch hosts to connect to";
+      description = lib.mdDoc "a list of elasticsearch hosts to connect to";
       type = types.listOf types.str;
       default = ["localhost"];
     };
     port = mkOption {
-      description = "the port that elasticsearch is listening on";
+      description = lib.mdDoc "the port that elasticsearch is listening on";
       type = types.int;
       default = 9200;
     };
     actionYAML = mkOption {
-      description = "curator action.yaml file contents, alternatively use curator-cli which takes a simple action command";
+      description = lib.mdDoc "curator action.yaml file contents, alternatively use curator-cli which takes a simple action command";
       type = types.lines;
       example = ''
         ---
diff --git a/nixos/modules/services/search/elasticsearch.nix b/nixos/modules/services/search/elasticsearch.nix
index 041d0b3c43f..4a9dd50310e 100644
--- a/nixos/modules/services/search/elasticsearch.nix
+++ b/nixos/modules/services/search/elasticsearch.nix
@@ -45,50 +45,50 @@ in
 
   options.services.elasticsearch = {
     enable = mkOption {
-      description = "Whether to enable elasticsearch.";
+      description = lib.mdDoc "Whether to enable elasticsearch.";
       default = false;
       type = types.bool;
     };
 
     package = mkOption {
-      description = "Elasticsearch package to use.";
+      description = lib.mdDoc "Elasticsearch package to use.";
       default = pkgs.elasticsearch;
       defaultText = literalExpression "pkgs.elasticsearch";
       type = types.package;
     };
 
     listenAddress = mkOption {
-      description = "Elasticsearch listen address.";
+      description = lib.mdDoc "Elasticsearch listen address.";
       default = "127.0.0.1";
       type = types.str;
     };
 
     port = mkOption {
-      description = "Elasticsearch port to listen for HTTP traffic.";
+      description = lib.mdDoc "Elasticsearch port to listen for HTTP traffic.";
       default = 9200;
       type = types.int;
     };
 
     tcp_port = mkOption {
-      description = "Elasticsearch port for the node to node communication.";
+      description = lib.mdDoc "Elasticsearch port for the node to node communication.";
       default = 9300;
       type = types.int;
     };
 
     cluster_name = mkOption {
-      description = "Elasticsearch name that identifies your cluster for auto-discovery.";
+      description = lib.mdDoc "Elasticsearch name that identifies your cluster for auto-discovery.";
       default = "elasticsearch";
       type = types.str;
     };
 
     single_node = mkOption {
-      description = "Start a single-node cluster";
+      description = lib.mdDoc "Start a single-node cluster";
       default = true;
       type = types.bool;
     };
 
     extraConf = mkOption {
-      description = "Extra configuration for elasticsearch.";
+      description = lib.mdDoc "Extra configuration for elasticsearch.";
       default = "";
       type = types.str;
       example = ''
@@ -99,7 +99,7 @@ in
     };
 
     logging = mkOption {
-      description = "Elasticsearch logging configuration.";
+      description = lib.mdDoc "Elasticsearch logging configuration.";
       default = ''
         logger.action.name = org.elasticsearch.action
         logger.action.level = info
@@ -118,26 +118,26 @@ in
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/elasticsearch";
-      description = ''
+      description = lib.mdDoc ''
         Data directory for elasticsearch.
       '';
     };
 
     extraCmdLineOptions = mkOption {
-      description = "Extra command line options for the elasticsearch launcher.";
+      description = lib.mdDoc "Extra command line options for the elasticsearch launcher.";
       default = [ ];
       type = types.listOf types.str;
     };
 
     extraJavaOptions = mkOption {
-      description = "Extra command line options for Java.";
+      description = lib.mdDoc "Extra command line options for Java.";
       default = [ ];
       type = types.listOf types.str;
       example = [ "-Djava.net.preferIPv4Stack=true" ];
     };
 
     plugins = mkOption {
-      description = "Extra elasticsearch plugins";
+      description = lib.mdDoc "Extra elasticsearch plugins";
       default = [ ];
       type = types.listOf types.package;
       example = lib.literalExpression "[ pkgs.elasticsearchPlugins.discovery-ec2 ]";
@@ -145,7 +145,7 @@ in
 
     restartIfChanged  = mkOption {
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         Automatically restart the service on config change.
         This can be set to false to defer restarts on a server or cluster.
         Please consider the security implications of inadvertently running an older version,
diff --git a/nixos/modules/services/search/hound.nix b/nixos/modules/services/search/hound.nix
index ef62175b0a3..b41a2e2bae1 100644
--- a/nixos/modules/services/search/hound.nix
+++ b/nixos/modules/services/search/hound.nix
@@ -8,7 +8,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the hound code search daemon.
         '';
       };
@@ -16,7 +16,7 @@ in {
       user = mkOption {
         default = "hound";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           User the hound daemon should execute under.
         '';
       };
@@ -24,7 +24,7 @@ in {
       group = mkOption {
         default = "hound";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Group the hound daemon should execute under.
         '';
       };
@@ -33,7 +33,7 @@ in {
         type = types.listOf types.str;
         default = [ ];
         example = [ "dialout" ];
-        description = ''
+        description = lib.mdDoc ''
           List of extra groups that the "hound" user should be a part of.
         '';
       };
@@ -41,7 +41,7 @@ in {
       home = mkOption {
         default = "/var/lib/hound";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The path to use as hound's $HOME. If the default user
           "hound" is configured then this is the home of the "hound"
           user.
@@ -52,14 +52,14 @@ in {
         default = pkgs.hound;
         defaultText = literalExpression "pkgs.hound";
         type = types.package;
-        description = ''
+        description = lib.mdDoc ''
           Package for running hound.
         '';
       };
 
       config = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The full configuration of the Hound daemon. Note the dbpath
           should be an absolute path to a writable location on disk.
         '';
@@ -82,7 +82,7 @@ in {
         type = types.str;
         default = "0.0.0.0:6080";
         example = "127.0.0.1:6080 or just :6080";
-        description = ''
+        description = lib.mdDoc ''
           Listen on this IP:port / :port
         '';
       };
@@ -120,7 +120,6 @@ in {
                     " -conf ${pkgs.writeText "hound.json" cfg.config}";
 
       };
-      path = [ pkgs.git pkgs.mercurial pkgs.openssh ];
     };
   };
 
diff --git a/nixos/modules/services/search/kibana.nix b/nixos/modules/services/search/kibana.nix
index e4ab85be9ef..5eb2381d5d3 100644
--- a/nixos/modules/services/search/kibana.nix
+++ b/nixos/modules/services/search/kibana.nix
@@ -32,53 +32,53 @@ let
 
 in {
   options.services.kibana = {
-    enable = mkEnableOption "kibana service";
+    enable = mkEnableOption (lib.mdDoc "kibana service");
 
     listenAddress = mkOption {
-      description = "Kibana listening host";
+      description = lib.mdDoc "Kibana listening host";
       default = "127.0.0.1";
       type = types.str;
     };
 
     port = mkOption {
-      description = "Kibana listening port";
+      description = lib.mdDoc "Kibana listening port";
       default = 5601;
-      type = types.int;
+      type = types.port;
     };
 
     cert = mkOption {
-      description = "Kibana ssl certificate.";
+      description = lib.mdDoc "Kibana ssl certificate.";
       default = null;
       type = types.nullOr types.path;
     };
 
     key = mkOption {
-      description = "Kibana ssl key.";
+      description = lib.mdDoc "Kibana ssl key.";
       default = null;
       type = types.nullOr types.path;
     };
 
     index = mkOption {
-      description = "Elasticsearch index to use for saving kibana config.";
+      description = lib.mdDoc "Elasticsearch index to use for saving kibana config.";
       default = ".kibana";
       type = types.str;
     };
 
     defaultAppId = mkOption {
-      description = "Elasticsearch default application id.";
+      description = lib.mdDoc "Elasticsearch default application id.";
       default = "discover";
       type = types.str;
     };
 
     elasticsearch = {
       url = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Elasticsearch url.
 
-          Defaults to <literal>"http://localhost:9200"</literal>.
+          Defaults to `"http://localhost:9200"`.
 
           Don't set this when using Kibana >= 7.0.0 because it will result in a
-          configuration error. Use <option>services.kibana.elasticsearch.hosts</option>
+          configuration error. Use {option}`services.kibana.elasticsearch.hosts`
           instead.
         '';
         default = null;
@@ -86,11 +86,11 @@ in {
       };
 
       hosts = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           The URLs of the Elasticsearch instances to use for all your queries.
           All nodes listed here must be on the same cluster.
 
-          Defaults to <literal>[ "http://localhost:9200" ]</literal>.
+          Defaults to `[ "http://localhost:9200" ]`.
 
           This option is only valid when using kibana >= 6.6.
         '';
@@ -99,22 +99,22 @@ in {
       };
 
       username = mkOption {
-        description = "Username for elasticsearch basic auth.";
+        description = lib.mdDoc "Username for elasticsearch basic auth.";
         default = null;
         type = types.nullOr types.str;
       };
 
       password = mkOption {
-        description = "Password for elasticsearch basic auth.";
+        description = lib.mdDoc "Password for elasticsearch basic auth.";
         default = null;
         type = types.nullOr types.str;
       };
 
       ca = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           CA file to auth against elasticsearch.
 
-          It's recommended to use the <option>certificateAuthorities</option> option
+          It's recommended to use the {option}`certificateAuthorities` option
           when using kibana-5.4 or newer.
         '';
         default = null;
@@ -122,13 +122,13 @@ in {
       };
 
       certificateAuthorities = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           CA files to auth against elasticsearch.
 
-          Please use the <option>ca</option> option when using kibana &lt; 5.4
+          Please use the {option}`ca` option when using kibana \< 5.4
           because those old versions don't support setting multiple CA's.
 
-          This defaults to the singleton list [ca] when the <option>ca</option> option is defined.
+          This defaults to the singleton list [ca] when the {option}`ca` option is defined.
         '';
         default = if cfg.elasticsearch.ca == null then [] else [ca];
         defaultText = literalExpression ''
@@ -138,33 +138,33 @@ in {
       };
 
       cert = mkOption {
-        description = "Certificate file to auth against elasticsearch.";
+        description = lib.mdDoc "Certificate file to auth against elasticsearch.";
         default = null;
         type = types.nullOr types.path;
       };
 
       key = mkOption {
-        description = "Key file to auth against elasticsearch.";
+        description = lib.mdDoc "Key file to auth against elasticsearch.";
         default = null;
         type = types.nullOr types.path;
       };
     };
 
     package = mkOption {
-      description = "Kibana package to use";
+      description = lib.mdDoc "Kibana package to use";
       default = pkgs.kibana;
       defaultText = literalExpression "pkgs.kibana";
       type = types.package;
     };
 
     dataDir = mkOption {
-      description = "Kibana data directory";
+      description = lib.mdDoc "Kibana data directory";
       default = "/var/lib/kibana";
       type = types.path;
     };
 
     extraConf = mkOption {
-      description = "Kibana extra configuration";
+      description = lib.mdDoc "Kibana extra configuration";
       default = {};
       type = types.attrs;
     };
diff --git a/nixos/modules/services/search/meilisearch.nix b/nixos/modules/services/search/meilisearch.nix
index f6210f6f16e..9262b927cba 100644
--- a/nixos/modules/services/search/meilisearch.nix
+++ b/nixos/modules/services/search/meilisearch.nix
@@ -16,36 +16,36 @@ in
   ###### interface
 
   options.services.meilisearch = {
-    enable = mkEnableOption "MeiliSearch - a RESTful search API";
+    enable = mkEnableOption (lib.mdDoc "MeiliSearch - a RESTful search API");
 
     package = mkOption {
-      description = "The package to use for meilisearch. Use this if you require specific features to be enabled. The default package has no features.";
+      description = lib.mdDoc "The package to use for meilisearch. Use this if you require specific features to be enabled. The default package has no features.";
       default = pkgs.meilisearch;
       defaultText = "pkgs.meilisearch";
       type = types.package;
     };
 
     listenAddress = mkOption {
-      description = "MeiliSearch listen address.";
+      description = lib.mdDoc "MeiliSearch listen address.";
       default = "127.0.0.1";
       type = types.str;
     };
 
     listenPort = mkOption {
-      description = "MeiliSearch port to listen on.";
+      description = lib.mdDoc "MeiliSearch port to listen on.";
       default = 7700;
       type = types.port;
     };
 
     environment = mkOption {
-      description = "Defines the running environment of MeiliSearch.";
+      description = lib.mdDoc "Defines the running environment of MeiliSearch.";
       default = "development";
       type = types.enum [ "development" "production" ];
     };
 
     # TODO change this to LoadCredentials once possible
     masterKeyEnvironmentFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Path to file which contains the master key.
         By doing so, all routes will be protected and will require a key to be accessed.
         If no master key is provided, all routes can be accessed without requiring any key.
@@ -57,7 +57,7 @@ in
     };
 
     noAnalytics = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Deactivates analytics.
         Analytics allow MeiliSearch to know how many users are using MeiliSearch,
         which versions and which platforms are used.
@@ -68,7 +68,7 @@ in
     };
 
     logLevel = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Defines how much detail should be present in MeiliSearch's logs.
         MeiliSearch currently supports four log levels, listed in order of increasing verbosity:
         - 'ERROR': only log unexpected events indicating MeiliSearch is not functioning as expected
@@ -82,7 +82,7 @@ in
     };
 
     maxIndexSize = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Sets the maximum size of the index.
         Value must be given in bytes or explicitly stating a base unit.
         For example, the default value can be written as 107374182400, '107.7Gb', or '107374 Mb'.
@@ -93,7 +93,7 @@ in
     };
 
     payloadSizeLimit = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Sets the maximum size of accepted JSON payloads.
         Value must be given in bytes or explicitly stating a base unit.
         For example, the default value can be written as 107374182400, '107.7Gb', or '107374 Mb'.
diff --git a/nixos/modules/services/search/solr.nix b/nixos/modules/services/search/solr.nix
index ea76bfc9298..05592e9fa24 100644
--- a/nixos/modules/services/search/solr.nix
+++ b/nixos/modules/services/search/solr.nix
@@ -11,43 +11,43 @@ in
 {
   options = {
     services.solr = {
-      enable = mkEnableOption "Solr";
+      enable = mkEnableOption (lib.mdDoc "Solr");
 
       package = mkOption {
         type = types.package;
         default = pkgs.solr;
         defaultText = literalExpression "pkgs.solr";
-        description = "Which Solr package to use.";
+        description = lib.mdDoc "Which Solr package to use.";
       };
 
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8983;
-        description = "Port on which Solr is ran.";
+        description = lib.mdDoc "Port on which Solr is ran.";
       };
 
       stateDir = mkOption {
         type = types.path;
         default = "/var/lib/solr";
-        description = "The solr home directory containing config, data, and logging files.";
+        description = lib.mdDoc "The solr home directory containing config, data, and logging files.";
       };
 
       extraJavaOptions = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Extra command line options given to the java process running Solr.";
+        description = lib.mdDoc "Extra command line options given to the java process running Solr.";
       };
 
       user = mkOption {
         type = types.str;
         default = "solr";
-        description = "User under which Solr is ran.";
+        description = lib.mdDoc "User under which Solr is ran.";
       };
 
       group = mkOption {
         type = types.str;
         default = "solr";
-        description = "Group under which Solr is ran.";
+        description = lib.mdDoc "Group under which Solr is ran.";
       };
     };
   };
diff --git a/nixos/modules/services/security/aesmd.nix b/nixos/modules/services/security/aesmd.nix
index 8268b034a15..7b0a46d6d02 100644
--- a/nixos/modules/services/security/aesmd.nix
+++ b/nixos/modules/services/security/aesmd.nix
@@ -19,27 +19,27 @@ let
 in
 {
   options.services.aesmd = {
-    enable = mkEnableOption "Intel's Architectural Enclave Service Manager (AESM) for Intel SGX";
+    enable = mkEnableOption (lib.mdDoc "Intel's Architectural Enclave Service Manager (AESM) for Intel SGX");
     debug = mkOption {
       type = types.bool;
       default = false;
-      description = "Whether to build the PSW package in debug mode.";
+      description = lib.mdDoc "Whether to build the PSW package in debug mode.";
     };
     settings = mkOption {
-      description = "AESM configuration";
+      description = lib.mdDoc "AESM configuration";
       default = { };
       type = types.submodule {
         options.whitelistUrl = mkOption {
           type = with types; nullOr str;
           default = null;
           example = "http://whitelist.trustedservices.intel.com/SGX/LCWL/Linux/sgx_white_list_cert.bin";
-          description = "URL to retrieve authorized Intel SGX enclave signers.";
+          description = lib.mdDoc "URL to retrieve authorized Intel SGX enclave signers.";
         };
         options.proxy = mkOption {
           type = with types; nullOr str;
           default = null;
           example = "http://proxy_url:1234";
-          description = "HTTP network proxy.";
+          description = lib.mdDoc "HTTP network proxy.";
         };
         options.proxyType = mkOption {
           type = with types; nullOr (enum [ "default" "direct" "manual" ]);
@@ -48,18 +48,18 @@ in
             if (config.${opt.settings}.proxy != null) then "manual" else null
           '';
           example = "default";
-          description = ''
-            Type of proxy to use. The <literal>default</literal> uses the system's default proxy.
-            If <literal>direct</literal> is given, uses no proxy.
-            A value of <literal>manual</literal> uses the proxy from
-            <option>services.aesmd.settings.proxy</option>.
+          description = lib.mdDoc ''
+            Type of proxy to use. The `default` uses the system's default proxy.
+            If `direct` is given, uses no proxy.
+            A value of `manual` uses the proxy from
+            {option}`services.aesmd.settings.proxy`.
           '';
         };
         options.defaultQuotingType = mkOption {
           type = with types; nullOr (enum [ "ecdsa_256" "epid_linkable" "epid_unlinkable" ]);
           default = null;
           example = "ecdsa_256";
-          description = "Attestation quote type.";
+          description = lib.mdDoc "Attestation quote type.";
         };
       };
     };
diff --git a/nixos/modules/services/security/certmgr.nix b/nixos/modules/services/security/certmgr.nix
index d302a4e0002..ca4cf508472 100644
--- a/nixos/modules/services/security/certmgr.nix
+++ b/nixos/modules/services/security/certmgr.nix
@@ -35,43 +35,43 @@ let
 in
 {
   options.services.certmgr = {
-    enable = mkEnableOption "certmgr";
+    enable = mkEnableOption (lib.mdDoc "certmgr");
 
     package = mkOption {
       type = types.package;
       default = pkgs.certmgr;
       defaultText = literalExpression "pkgs.certmgr";
-      description = "Which certmgr package to use in the service.";
+      description = lib.mdDoc "Which certmgr package to use in the service.";
     };
 
     defaultRemote = mkOption {
       type = types.str;
       default = "127.0.0.1:8888";
-      description = "The default CA host:port to use.";
+      description = lib.mdDoc "The default CA host:port to use.";
     };
 
     validMin = mkOption {
       default = "72h";
       type = types.str;
-      description = "The interval before a certificate expires to start attempting to renew it.";
+      description = lib.mdDoc "The interval before a certificate expires to start attempting to renew it.";
     };
 
     renewInterval = mkOption {
       default = "30m";
       type = types.str;
-      description = "How often to check certificate expirations and how often to update the cert_next_expires metric.";
+      description = lib.mdDoc "How often to check certificate expirations and how often to update the cert_next_expires metric.";
     };
 
     metricsAddress = mkOption {
       default = "127.0.0.1";
       type = types.str;
-      description = "The address for the Prometheus HTTP endpoint.";
+      description = lib.mdDoc "The address for the Prometheus HTTP endpoint.";
     };
 
     metricsPort = mkOption {
       default = 9488;
       type = types.ints.u16;
-      description = "The port for the Prometheus HTTP endpoint.";
+      description = lib.mdDoc "The port for the Prometheus HTTP endpoint.";
     };
 
     specs = mkOption {
@@ -118,40 +118,40 @@ in
           service = mkOption {
             type = nullOr str;
             default = null;
-            description = "The service on which to perform &lt;action&gt; after fetching.";
+            description = lib.mdDoc "The service on which to perform \<action\> after fetching.";
           };
 
           action = mkOption {
             type = addCheck str (x: cfg.svcManager == "command" || elem x ["restart" "reload" "nop"]);
             default = "nop";
-            description = "The action to take after fetching.";
+            description = lib.mdDoc "The action to take after fetching.";
           };
 
           # These ought all to be specified according to certmgr spec def.
           authority = mkOption {
             type = attrs;
-            description = "certmgr spec authority object.";
+            description = lib.mdDoc "certmgr spec authority object.";
           };
 
           certificate = mkOption {
             type = nullOr attrs;
-            description = "certmgr spec certificate object.";
+            description = lib.mdDoc "certmgr spec certificate object.";
           };
 
           private_key = mkOption {
             type = nullOr attrs;
-            description = "certmgr spec private_key object.";
+            description = lib.mdDoc "certmgr spec private_key object.";
           };
 
           request = mkOption {
             type = nullOr attrs;
-            description = "certmgr spec request object.";
+            description = lib.mdDoc "certmgr spec request object.";
           };
         };
     }));
-      description = ''
+      description = lib.mdDoc ''
         Certificate specs as described by:
-        <link xlink:href="https://github.com/cloudflare/certmgr#certificate-specs" />
+        <https://github.com/cloudflare/certmgr#certificate-specs>
         These will be added to the Nix store, so they will be world readable.
       '';
     };
@@ -159,11 +159,11 @@ in
     svcManager = mkOption {
       default = "systemd";
       type = types.enum [ "circus" "command" "dummy" "openrc" "systemd" "sysv" ];
-      description = ''
+      description = lib.mdDoc ''
         This specifies the service manager to use for restarting or reloading services.
-        See: <link xlink:href="https://github.com/cloudflare/certmgr#certmgryaml" />.
+        See: <https://github.com/cloudflare/certmgr#certmgryaml>.
         For how to use the "command" service manager in particular,
-        see: <link xlink:href="https://github.com/cloudflare/certmgr#command-svcmgr-and-how-to-use-it" />.
+        see: <https://github.com/cloudflare/certmgr#command-svcmgr-and-how-to-use-it>.
       '';
     };
 
diff --git a/nixos/modules/services/security/cfssl.nix b/nixos/modules/services/security/cfssl.nix
index 6df2343b84d..202db98e222 100644
--- a/nixos/modules/services/security/cfssl.nix
+++ b/nixos/modules/services/security/cfssl.nix
@@ -6,69 +6,69 @@ let
   cfg = config.services.cfssl;
 in {
   options.services.cfssl = {
-    enable = mkEnableOption "the CFSSL CA api-server";
+    enable = mkEnableOption (lib.mdDoc "the CFSSL CA api-server");
 
     dataDir = mkOption {
       default = "/var/lib/cfssl";
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         The work directory for CFSSL.
 
-        <note><para>
-          If left as the default value this directory will automatically be
-          created before the CFSSL server starts, otherwise you are
-          responsible for ensuring the directory exists with appropriate
-          ownership and permissions.
-        </para></note>
+        ::: {.note}
+        If left as the default value this directory will automatically be
+        created before the CFSSL server starts, otherwise you are
+        responsible for ensuring the directory exists with appropriate
+        ownership and permissions.
+        :::
       '';
     };
 
     address = mkOption {
       default = "127.0.0.1";
       type = types.str;
-      description = "Address to bind.";
+      description = lib.mdDoc "Address to bind.";
     };
 
     port = mkOption {
       default = 8888;
       type = types.port;
-      description = "Port to bind.";
+      description = lib.mdDoc "Port to bind.";
     };
 
     ca = mkOption {
       defaultText = literalExpression ''"''${cfg.dataDir}/ca.pem"'';
       type = types.str;
-      description = "CA used to sign the new certificate -- accepts '[file:]fname' or 'env:varname'.";
+      description = lib.mdDoc "CA used to sign the new certificate -- accepts '[file:]fname' or 'env:varname'.";
     };
 
     caKey = mkOption {
       defaultText = literalExpression ''"file:''${cfg.dataDir}/ca-key.pem"'';
       type = types.str;
-      description = "CA private key -- accepts '[file:]fname' or 'env:varname'.";
+      description = lib.mdDoc "CA private key -- accepts '[file:]fname' or 'env:varname'.";
     };
 
     caBundle = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Path to root certificate store.";
+      description = lib.mdDoc "Path to root certificate store.";
     };
 
     intBundle = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Path to intermediate certificate store.";
+      description = lib.mdDoc "Path to intermediate certificate store.";
     };
 
     intDir = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Intermediates directory.";
+      description = lib.mdDoc "Intermediates directory.";
     };
 
     metadata = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = ''
+      description = lib.mdDoc ''
         Metadata file for root certificate presence.
         The content of the file is a json dictionary (k,v): each key k is
         a SHA-1 digest of a root certificate while value v is a list of key
@@ -79,79 +79,79 @@ in {
     remote = mkOption {
       default = null;
       type = types.nullOr types.str;
-      description = "Remote CFSSL server.";
+      description = lib.mdDoc "Remote CFSSL server.";
     };
 
     configFile = mkOption {
       default = null;
       type = types.nullOr types.str;
-      description = "Path to configuration file. Do not put this in nix-store as it might contain secrets.";
+      description = lib.mdDoc "Path to configuration file. Do not put this in nix-store as it might contain secrets.";
     };
 
     responder = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Certificate for OCSP responder.";
+      description = lib.mdDoc "Certificate for OCSP responder.";
     };
 
     responderKey = mkOption {
       default = null;
       type = types.nullOr types.str;
-      description = "Private key for OCSP responder certificate. Do not put this in nix-store.";
+      description = lib.mdDoc "Private key for OCSP responder certificate. Do not put this in nix-store.";
     };
 
     tlsKey = mkOption {
       default = null;
       type = types.nullOr types.str;
-      description = "Other endpoint's CA private key. Do not put this in nix-store.";
+      description = lib.mdDoc "Other endpoint's CA private key. Do not put this in nix-store.";
     };
 
     tlsCert = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Other endpoint's CA to set up TLS protocol.";
+      description = lib.mdDoc "Other endpoint's CA to set up TLS protocol.";
     };
 
     mutualTlsCa = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Mutual TLS - require clients be signed by this CA.";
+      description = lib.mdDoc "Mutual TLS - require clients be signed by this CA.";
     };
 
     mutualTlsCn = mkOption {
       default = null;
       type = types.nullOr types.str;
-      description = "Mutual TLS - regex for whitelist of allowed client CNs.";
+      description = lib.mdDoc "Mutual TLS - regex for whitelist of allowed client CNs.";
     };
 
     tlsRemoteCa = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "CAs to trust for remote TLS requests.";
+      description = lib.mdDoc "CAs to trust for remote TLS requests.";
     };
 
     mutualTlsClientCert = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Mutual TLS - client certificate to call remote instance requiring client certs.";
+      description = lib.mdDoc "Mutual TLS - client certificate to call remote instance requiring client certs.";
     };
 
     mutualTlsClientKey = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Mutual TLS - client key to call remote instance requiring client certs. Do not put this in nix-store.";
+      description = lib.mdDoc "Mutual TLS - client key to call remote instance requiring client certs. Do not put this in nix-store.";
     };
 
     dbConfig = mkOption {
       default = null;
       type = types.nullOr types.path;
-      description = "Certificate db configuration file. Path must be writeable.";
+      description = lib.mdDoc "Certificate db configuration file. Path must be writeable.";
     };
 
     logLevel = mkOption {
       default = 1;
       type = types.enum [ 0 1 2 3 4 5 ];
-      description = "Log level (0 = DEBUG, 5 = FATAL).";
+      description = lib.mdDoc "Log level (0 = DEBUG, 5 = FATAL).";
     };
   };
 
diff --git a/nixos/modules/services/security/clamav.nix b/nixos/modules/services/security/clamav.nix
index 95a0ad8770e..34897a9ac7d 100644
--- a/nixos/modules/services/security/clamav.nix
+++ b/nixos/modules/services/security/clamav.nix
@@ -26,24 +26,24 @@ in
   options = {
     services.clamav = {
       daemon = {
-        enable = mkEnableOption "ClamAV clamd daemon";
+        enable = mkEnableOption (lib.mdDoc "ClamAV clamd daemon");
 
         settings = mkOption {
           type = with types; attrsOf (oneOf [ bool int str (listOf str) ]);
           default = { };
-          description = ''
-            ClamAV configuration. Refer to <link xlink:href="https://linux.die.net/man/5/clamd.conf"/>,
+          description = lib.mdDoc ''
+            ClamAV configuration. Refer to <https://linux.die.net/man/5/clamd.conf>,
             for details on supported values.
           '';
         };
       };
       updater = {
-        enable = mkEnableOption "ClamAV freshclam updater";
+        enable = mkEnableOption (lib.mdDoc "ClamAV freshclam updater");
 
         frequency = mkOption {
           type = types.int;
           default = 12;
-          description = ''
+          description = lib.mdDoc ''
             Number of database checks per day.
           '';
         };
@@ -51,7 +51,7 @@ in
         interval = mkOption {
           type = types.str;
           default = "hourly";
-          description = ''
+          description = lib.mdDoc ''
             How often freshclam is invoked. See systemd.time(7) for more
             information about the format.
           '';
@@ -60,8 +60,8 @@ in
         settings = mkOption {
           type = with types; attrsOf (oneOf [ bool int str (listOf str) ]);
           default = { };
-          description = ''
-            freshclam configuration. Refer to <link xlink:href="https://linux.die.net/man/5/freshclam.conf"/>,
+          description = lib.mdDoc ''
+            freshclam configuration. Refer to <https://linux.die.net/man/5/freshclam.conf>,
             for details on supported values.
           '';
         };
diff --git a/nixos/modules/services/security/endlessh-go.nix b/nixos/modules/services/security/endlessh-go.nix
new file mode 100644
index 00000000000..6557ec953cd
--- /dev/null
+++ b/nixos/modules/services/security/endlessh-go.nix
@@ -0,0 +1,138 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.endlessh-go;
+in
+{
+  options.services.endlessh-go = {
+    enable = mkEnableOption (mdDoc "endlessh-go service");
+
+    listenAddress = mkOption {
+      type = types.str;
+      default = "0.0.0.0";
+      example = "[::]";
+      description = mdDoc ''
+        Interface address to bind the endlessh-go daemon to SSH connections.
+      '';
+    };
+
+    port = mkOption {
+      type = types.port;
+      default = 2222;
+      example = 22;
+      description = mdDoc ''
+        Specifies on which port the endlessh-go daemon listens for SSH
+        connections.
+
+        Setting this to `22` may conflict with {option}`services.openssh`.
+      '';
+    };
+
+    prometheus = {
+      enable = mkEnableOption (mdDoc "Prometheus integration");
+
+      listenAddress = mkOption {
+        type = types.str;
+        default = "0.0.0.0";
+        example = "[::]";
+        description = mdDoc ''
+          Interface address to bind the endlessh-go daemon to answer Prometheus
+          queries.
+        '';
+      };
+
+      port = mkOption {
+        type = types.port;
+        default = 2112;
+        example = 9119;
+        description = mdDoc ''
+          Specifies on which port the endlessh-go daemon listens for Prometheus
+          queries.
+        '';
+      };
+    };
+
+    extraOptions = mkOption {
+      type = with types; listOf str;
+      default = [ ];
+      example = [ "-conn_type=tcp4" "-max_clients=8192" ];
+      description = mdDoc ''
+        Additional command line options to pass to the endlessh-go daemon.
+      '';
+    };
+
+    openFirewall = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Whether to open a firewall port for the SSH listener.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.endlessh-go = {
+      description = "SSH tarpit";
+      requires = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig =
+        let
+          needsPrivileges = cfg.port < 1024 || cfg.prometheus.port < 1024;
+          capabilities = [ "" ] ++ optionals needsPrivileges [ "CAP_NET_BIND_SERVICE" ];
+          rootDirectory = "/run/endlessh-go";
+        in
+        {
+          Restart = "always";
+          ExecStart = with cfg; concatStringsSep " " ([
+            "${pkgs.endlessh-go}/bin/endlessh-go"
+            "-logtostderr"
+            "-host=${listenAddress}"
+            "-port=${toString port}"
+          ] ++ optionals prometheus.enable [
+            "-enable_prometheus"
+            "-prometheus_host=${prometheus.listenAddress}"
+            "-prometheus_port=${toString prometheus.port}"
+          ] ++ extraOptions);
+          DynamicUser = true;
+          RootDirectory = rootDirectory;
+          BindReadOnlyPaths = [ builtins.storeDir ];
+          InaccessiblePaths = [ "-+${rootDirectory}" ];
+          RuntimeDirectory = baseNameOf rootDirectory;
+          RuntimeDirectoryMode = "700";
+          AmbientCapabilities = capabilities;
+          CapabilityBoundingSet = capabilities;
+          UMask = "0077";
+          LockPersonality = true;
+          MemoryDenyWriteExecute = true;
+          NoNewPrivileges = true;
+          PrivateDevices = true;
+          PrivateTmp = true;
+          PrivateUsers = !needsPrivileges;
+          ProtectClock = true;
+          ProtectControlGroups = true;
+          ProtectHome = true;
+          ProtectHostname = true;
+          ProtectKernelLogs = true;
+          ProtectKernelModules = true;
+          ProtectKernelTunables = true;
+          ProtectSystem = "strict";
+          ProtectProc = "noaccess";
+          ProcSubset = "pid";
+          RemoveIPC = true;
+          RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+          RestrictNamespaces = true;
+          RestrictRealtime = true;
+          RestrictSUIDSGID = true;
+          SystemCallArchitectures = "native";
+          SystemCallFilter = [ "@system-service" "~@privileged" ];
+        };
+    };
+
+    networking.firewall.allowedTCPPorts = with cfg;
+      optionals openFirewall [ port prometheus.port ];
+  };
+
+  meta.maintainers = with maintainers; [ azahi ];
+}
diff --git a/nixos/modules/services/security/endlessh.nix b/nixos/modules/services/security/endlessh.nix
new file mode 100644
index 00000000000..e99b4dadcd5
--- /dev/null
+++ b/nixos/modules/services/security/endlessh.nix
@@ -0,0 +1,99 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.endlessh;
+in
+{
+  options.services.endlessh = {
+    enable = mkEnableOption (mdDoc "endlessh service");
+
+    port = mkOption {
+      type = types.port;
+      default = 2222;
+      example = 22;
+      description = mdDoc ''
+        Specifies on which port the endlessh daemon listens for SSH
+        connections.
+
+        Setting this to `22` may conflict with {option}`services.openssh`.
+      '';
+    };
+
+    extraOptions = mkOption {
+      type = with types; listOf str;
+      default = [ ];
+      example = [ "-6" "-d 9000" "-v" ];
+      description = mdDoc ''
+        Additional command line options to pass to the endlessh daemon.
+      '';
+    };
+
+    openFirewall = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Whether to open a firewall port for the SSH listener.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.endlessh = {
+      description = "SSH tarpit";
+      requires = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig =
+        let
+          needsPrivileges = cfg.port < 1024;
+          capabilities = [ "" ] ++ optionals needsPrivileges [ "CAP_NET_BIND_SERVICE" ];
+          rootDirectory = "/run/endlessh";
+        in
+        {
+          Restart = "always";
+          ExecStart = with cfg; concatStringsSep " " ([
+            "${pkgs.endlessh}/bin/endlessh"
+            "-p ${toString port}"
+          ] ++ extraOptions);
+          DynamicUser = true;
+          RootDirectory = rootDirectory;
+          BindReadOnlyPaths = [ builtins.storeDir ];
+          InaccessiblePaths = [ "-+${rootDirectory}" ];
+          RuntimeDirectory = baseNameOf rootDirectory;
+          RuntimeDirectoryMode = "700";
+          AmbientCapabilities = capabilities;
+          CapabilityBoundingSet = capabilities;
+          UMask = "0077";
+          LockPersonality = true;
+          MemoryDenyWriteExecute = true;
+          NoNewPrivileges = true;
+          PrivateDevices = true;
+          PrivateTmp = true;
+          PrivateUsers = !needsPrivileges;
+          ProtectClock = true;
+          ProtectControlGroups = true;
+          ProtectHome = true;
+          ProtectHostname = true;
+          ProtectKernelLogs = true;
+          ProtectKernelModules = true;
+          ProtectKernelTunables = true;
+          ProtectSystem = "strict";
+          ProtectProc = "noaccess";
+          ProcSubset = "pid";
+          RemoveIPC = true;
+          RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+          RestrictNamespaces = true;
+          RestrictRealtime = true;
+          RestrictSUIDSGID = true;
+          SystemCallArchitectures = "native";
+          SystemCallFilter = [ "@system-service" "~@resources" "~@privileged" ];
+        };
+    };
+
+    networking.firewall.allowedTCPPorts = with cfg;
+      optionals openFirewall [ port ];
+  };
+
+  meta.maintainers = with maintainers; [ azahi ];
+}
diff --git a/nixos/modules/services/security/fail2ban.nix b/nixos/modules/services/security/fail2ban.nix
index 67e1026dcef..e208eed008a 100644
--- a/nixos/modules/services/security/fail2ban.nix
+++ b/nixos/modules/services/security/fail2ban.nix
@@ -45,10 +45,10 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the fail2ban service.
 
-          See the documentation of <option>services.fail2ban.jails</option>
+          See the documentation of {option}`services.fail2ban.jails`
           for what jails are enabled by default.
         '';
       };
@@ -58,7 +58,7 @@ in
         defaultText = literalExpression "pkgs.fail2ban";
         type = types.package;
         example = literalExpression "pkgs.fail2ban_0_11";
-        description = "The fail2ban package to use for running the fail2ban service.";
+        description = lib.mdDoc "The fail2ban package to use for running the fail2ban service.";
       };
 
       packageFirewall = mkOption {
@@ -66,14 +66,14 @@ in
         defaultText = literalExpression "pkgs.iptables";
         type = types.package;
         example = literalExpression "pkgs.nftables";
-        description = "The firewall package used by fail2ban service.";
+        description = lib.mdDoc "The firewall package used by fail2ban service.";
       };
 
       extraPackages = mkOption {
         default = [];
         type = types.listOf types.package;
         example = lib.literalExpression "[ pkgs.ipset ]";
-        description = ''
+        description = lib.mdDoc ''
           Extra packages to be made available to the fail2ban service. The example contains
           the packages needed by the `iptables-ipset-proto6` action.
         '';
@@ -82,17 +82,18 @@ in
       maxretry = mkOption {
         default = 3;
         type = types.ints.unsigned;
-        description = "Number of failures before a host gets banned.";
+        description = lib.mdDoc "Number of failures before a host gets banned.";
       };
 
       banaction = mkOption {
         default = "iptables-multiport";
         type = types.str;
         example = "nftables-multiport";
-        description = ''
+        description = lib.mdDoc ''
           Default banning action (e.g. iptables, iptables-new, iptables-multiport,
-          shorewall, etc) It is used to define action_* variables. Can be overridden
-          globally or per section within jail.local file
+          iptables-ipset-proto6-allports, shorewall, etc) It is used to
+          define action_* variables. Can be overridden globally or per
+          section within jail.local file
         '';
       };
 
@@ -100,7 +101,7 @@ in
         default = "iptables-allport";
         type = types.str;
         example = "nftables-allport";
-        description = ''
+        description = lib.mdDoc ''
           Default banning action (e.g. iptables, iptables-new, iptables-multiport,
           shorewall, etc) It is used to define action_* variables. Can be overridden
           globally or per section within jail.local file
@@ -110,7 +111,7 @@ in
       bantime-increment.enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Allows to use database for searching of previously banned ip's to increase
           a default ban time using special formula, default it is banTime * 1, 2, 4, 8, 16, 32...
         '';
@@ -120,7 +121,7 @@ in
         default = "4m";
         type = types.str;
         example = "8m";
-        description = ''
+        description = lib.mdDoc ''
           "bantime-increment.rndtime" is the max number of seconds using for mixing with random time
           to prevent "clever" botnets calculate exact time IP can be unbanned again
         '';
@@ -130,7 +131,7 @@ in
         default = "10h";
         type = types.str;
         example = "48h";
-        description = ''
+        description = lib.mdDoc ''
           "bantime-increment.maxtime" is the max number of seconds using the ban time can reach (don't grows further)
         '';
       };
@@ -139,7 +140,7 @@ in
         default = "1";
         type = types.str;
         example = "4";
-        description = ''
+        description = lib.mdDoc ''
           "bantime-increment.factor" is a coefficient to calculate exponent growing of the formula or common multiplier,
           default value of factor is 1 and with default value of formula, the ban time grows by 1, 2, 4, 8, 16 ...
         '';
@@ -149,7 +150,7 @@ in
         default = "ban.Time * (1<<(ban.Count if ban.Count<20 else 20)) * banFactor";
         type = types.str;
         example = "ban.Time * math.exp(float(ban.Count+1)*banFactor)/math.exp(1*banFactor)";
-        description = ''
+        description = lib.mdDoc ''
           "bantime-increment.formula" used by default to calculate next value of ban time, default value bellow,
           the same ban time growing will be reached by multipliers 1, 2, 4, 8, 16, 32...
         '';
@@ -159,7 +160,7 @@ in
         default = "1 2 4 8 16 32 64";
         type = types.str;
         example = "2 4 16 128";
-        description = ''
+        description = lib.mdDoc ''
           "bantime-increment.multipliers" used to calculate next value of ban time instead of formula, coresponding
           previously ban count and given "bantime.factor" (for multipliers default is 1);
           following example grows ban time by 1, 2, 4, 8, 16 ... and if last ban count greater as multipliers count,
@@ -171,7 +172,7 @@ in
         default = false;
         type = types.bool;
         example = true;
-        description = ''
+        description = lib.mdDoc ''
           "bantime-increment.overalljails"  (if true) specifies the search of IP in the database will be executed
           cross over all jails, if false (dafault), only current jail of the ban IP will be searched
         '';
@@ -181,7 +182,7 @@ in
         default = [ ];
         type = types.listOf types.str;
         example = [ "192.168.0.0/16" "2001:DB8::42" ];
-        description = ''
+        description = lib.mdDoc ''
           "ignoreIP" can be a list of IP addresses, CIDR masks or DNS hosts. Fail2ban will not ban a host which
           matches an address in this list. Several addresses can be defined using space (and/or comma) separator.
         '';
@@ -196,7 +197,7 @@ in
           dbfile    = /var/lib/fail2ban/fail2ban.sqlite3
         '';
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           The contents of Fail2ban's main configuration file.  It's
           generally not necessary to change it.
        '';
@@ -212,29 +213,37 @@ in
               filter   = apache-nohome
               action   = iptables-multiport[name=HTTP, port="http,https"]
               logpath  = /var/log/httpd/error_log*
+              backend = auto
               findtime = 600
               bantime  = 600
               maxretry = 5
             ''';
+           dovecot = '''
+             # block IPs which failed to log-in
+             # aggressive mode add blocking for aborted connections
+             enabled = true
+             filter = dovecot[mode=aggressive]
+             maxretry = 3
+           ''';
           }
         '';
         type = types.attrsOf types.lines;
-        description = ''
+        description = lib.mdDoc ''
           The configuration of each Fail2ban “jail”.  A jail
           consists of an action (such as blocking a port using
-          <command>iptables</command>) that is triggered when a
+          {command}`iptables`) that is triggered when a
           filter applied to a log file triggers more than a certain
           number of times in a certain time period.  Actions are
-          defined in <filename>/etc/fail2ban/action.d</filename>,
+          defined in {file}`/etc/fail2ban/action.d`,
           while filters are defined in
-          <filename>/etc/fail2ban/filter.d</filename>.
+          {file}`/etc/fail2ban/filter.d`.
 
-          NixOS comes with a default <literal>sshd</literal> jail;
+          NixOS comes with a default `sshd` jail;
           for it to work well,
-          <option>services.openssh.logLevel</option> should be set to
-          <literal>"VERBOSE"</literal> or higher so that fail2ban
+          {option}`services.openssh.logLevel` should be set to
+          `"VERBOSE"` or higher so that fail2ban
           can observe failed login attempts.
-          This module sets it to <literal>"VERBOSE"</literal> if
+          This module sets it to `"VERBOSE"` if
           not set otherwise, so enabling fail2ban can make SSH logs
           more verbose.
         '';
diff --git a/nixos/modules/services/security/fprintd.nix b/nixos/modules/services/security/fprintd.nix
index 87c3f1f6f9e..28f9b5908b5 100644
--- a/nixos/modules/services/security/fprintd.nix
+++ b/nixos/modules/services/security/fprintd.nix
@@ -18,25 +18,25 @@ in
 
     services.fprintd = {
 
-      enable = mkEnableOption "fprintd daemon and PAM module for fingerprint readers handling";
+      enable = mkEnableOption (lib.mdDoc "fprintd daemon and PAM module for fingerprint readers handling");
 
       package = mkOption {
         type = types.package;
         default = fprintdPkg;
         defaultText = literalExpression "if config.services.fprintd.tod.enable then pkgs.fprintd-tod else pkgs.fprintd";
-        description = ''
+        description = lib.mdDoc ''
           fprintd package to use.
         '';
       };
 
       tod = {
 
-        enable = mkEnableOption "Touch OEM Drivers library support";
+        enable = mkEnableOption (lib.mdDoc "Touch OEM Drivers library support");
 
         driver = mkOption {
           type = types.package;
           example = literalExpression "pkgs.libfprint-2-tod1-goodix";
-          description = ''
+          description = lib.mdDoc ''
             Touch OEM Drivers (TOD) package to use.
           '';
         };
diff --git a/nixos/modules/services/security/haka.nix b/nixos/modules/services/security/haka.nix
index 2cfc05f3033..c93638f44d6 100644
--- a/nixos/modules/services/security/haka.nix
+++ b/nixos/modules/services/security/haka.nix
@@ -55,22 +55,22 @@ in
 
     services.haka = {
 
-      enable = mkEnableOption "Haka";
+      enable = mkEnableOption (lib.mdDoc "Haka");
 
       package = mkOption {
         default = pkgs.haka;
         defaultText = literalExpression "pkgs.haka";
         type = types.package;
-        description = "
+        description = lib.mdDoc ''
           Which Haka derivation to use.
-        ";
+        '';
       };
 
       configFile = mkOption {
         default = "empty.lua";
         example = "/srv/haka/myfilter.lua";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Specify which configuration file Haka uses.
           It can be absolute path or a path relative to the sample directory of
           the haka git repo.
@@ -81,7 +81,7 @@ in
         default = [ "eth0" ];
         example = [ "any" ];
         type = with types; listOf str;
-        description = ''
+        description = lib.mdDoc ''
           Specify which interface(s) Haka listens to.
           Use 'any' to listen to all interfaces.
         '';
@@ -91,7 +91,7 @@ in
         default = 0;
         example = 4;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
           The number of threads that will be used.
           All system threads are used by default.
         '';
@@ -100,24 +100,24 @@ in
       pcap = mkOption {
         default = true;
         type = types.bool;
-        description = "Whether to enable pcap";
+        description = lib.mdDoc "Whether to enable pcap";
       };
 
-      nfqueue = mkEnableOption "nfqueue";
+      nfqueue = mkEnableOption (lib.mdDoc "nfqueue");
 
-      dump.enable = mkEnableOption "dump";
+      dump.enable = mkEnableOption (lib.mdDoc "dump");
       dump.input  = mkOption {
         default = "/tmp/input.pcap";
         example = "/path/to/file.pcap";
         type = types.path;
-        description = "Path to file where incoming packets are dumped";
+        description = lib.mdDoc "Path to file where incoming packets are dumped";
       };
 
       dump.output  = mkOption {
         default = "/tmp/output.pcap";
         example = "/path/to/file.pcap";
         type = types.path;
-        description = "Path to file where outgoing packets are dumped";
+        description = lib.mdDoc "Path to file where outgoing packets are dumped";
       };
     };
   };
diff --git a/nixos/modules/services/security/haveged.nix b/nixos/modules/services/security/haveged.nix
index 57cef7e44d5..db12a28a7d0 100644
--- a/nixos/modules/services/security/haveged.nix
+++ b/nixos/modules/services/security/haveged.nix
@@ -15,16 +15,16 @@ in
 
     services.haveged = {
 
-      enable = mkEnableOption ''
+      enable = mkEnableOption (lib.mdDoc ''
         haveged entropy daemon, which refills /dev/random when low.
         NOTE: does nothing on kernels newer than 5.6.
-      '';
+      '');
       # source for the note https://github.com/jirka-h/haveged/issues/57
 
       refill_threshold = mkOption {
         type = types.int;
         default = 1024;
-        description = ''
+        description = lib.mdDoc ''
           The number of bits of available entropy beneath which
           haveged should refill the entropy pool.
         '';
diff --git a/nixos/modules/services/security/hockeypuck.nix b/nixos/modules/services/security/hockeypuck.nix
index d0e152934f5..127134bc5db 100644
--- a/nixos/modules/services/security/hockeypuck.nix
+++ b/nixos/modules/services/security/hockeypuck.nix
@@ -7,12 +7,12 @@ in {
   meta.maintainers = with lib.maintainers; [ etu ];
 
   options.services.hockeypuck = {
-    enable = lib.mkEnableOption "Hockeypuck OpenPGP Key Server";
+    enable = lib.mkEnableOption (lib.mdDoc "Hockeypuck OpenPGP Key Server");
 
     port = lib.mkOption {
       default = 11371;
       type = lib.types.port;
-      description = "HKP port to listen on.";
+      description = lib.mdDoc "HKP port to listen on.";
     };
 
     settings = lib.mkOption {
@@ -37,10 +37,10 @@ in {
           };
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Configuration file for hockeypuck, here you can override
-        certain settings (<literal>loglevel</literal> and
-        <literal>openpgp.db.dsn</literal>) by just setting those values.
+        certain settings (`loglevel` and
+        `openpgp.db.dsn`) by just setting those values.
 
         For other settings you need to use lib.mkForce to override them.
 
@@ -49,7 +49,7 @@ in {
         the database yourself.
 
         Example:
-        <literal>
+        ```
           services.postgresql = {
             enable = true;
             ensureDatabases = [ "hockeypuck" ];
@@ -58,7 +58,7 @@ in {
               ensurePermissions."DATABASE hockeypuck" = "ALL PRIVILEGES";
             }];
           };
-        </literal>
+        ```
       '';
     };
   };
diff --git a/nixos/modules/services/security/hologram-agent.nix b/nixos/modules/services/security/hologram-agent.nix
index e29267e5000..666d95b9b94 100644
--- a/nixos/modules/services/security/hologram-agent.nix
+++ b/nixos/modules/services/security/hologram-agent.nix
@@ -14,19 +14,19 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the Hologram agent for AWS instance credentials";
+        description = lib.mdDoc "Whether to enable the Hologram agent for AWS instance credentials";
       };
 
       dialAddress = mkOption {
         type        = types.str;
         default     = "localhost:3100";
-        description = "Hologram server and port.";
+        description = lib.mdDoc "Hologram server and port.";
       };
 
       httpPort = mkOption {
         type        = types.str;
         default     = "80";
-        description = "Port for metadata service to listen on.";
+        description = lib.mdDoc "Port for metadata service to listen on.";
       };
 
     };
diff --git a/nixos/modules/services/security/hologram-server.nix b/nixos/modules/services/security/hologram-server.nix
index 4acf6ae0e21..e995bc79b11 100644
--- a/nixos/modules/services/security/hologram-server.nix
+++ b/nixos/modules/services/security/hologram-server.nix
@@ -33,85 +33,85 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the Hologram server for AWS instance credentials";
+        description = lib.mdDoc "Whether to enable the Hologram server for AWS instance credentials";
       };
 
       listenAddress = mkOption {
         type        = types.str;
         default     = "0.0.0.0:3100";
-        description = "Address and port to listen on";
+        description = lib.mdDoc "Address and port to listen on";
       };
 
       ldapHost = mkOption {
         type        = types.str;
-        description = "Address of the LDAP server to use";
+        description = lib.mdDoc "Address of the LDAP server to use";
       };
 
       ldapInsecure = mkOption {
         type        = types.bool;
         default     = false;
-        description = "Whether to connect to LDAP over SSL or not";
+        description = lib.mdDoc "Whether to connect to LDAP over SSL or not";
       };
 
       ldapUserAttr = mkOption {
         type        = types.str;
         default     = "cn";
-        description = "The LDAP attribute for usernames";
+        description = lib.mdDoc "The LDAP attribute for usernames";
       };
 
       ldapBaseDN = mkOption {
         type        = types.str;
-        description = "The base DN for your Hologram users";
+        description = lib.mdDoc "The base DN for your Hologram users";
       };
 
       ldapBindDN = mkOption {
         type        = types.str;
-        description = "DN of account to use to query the LDAP server";
+        description = lib.mdDoc "DN of account to use to query the LDAP server";
       };
 
       ldapBindPassword = mkOption {
         type        = types.str;
-        description = "Password of account to use to query the LDAP server";
+        description = lib.mdDoc "Password of account to use to query the LDAP server";
       };
 
       enableLdapRoles = mkOption {
         type        = types.bool;
         default     = false;
-        description = "Whether to assign user roles based on the user's LDAP group memberships";
+        description = lib.mdDoc "Whether to assign user roles based on the user's LDAP group memberships";
       };
 
       groupClassAttr = mkOption {
         type = types.str;
         default = "groupOfNames";
-        description = "The objectclass attribute to search for groups when enableLdapRoles is true";
+        description = lib.mdDoc "The objectclass attribute to search for groups when enableLdapRoles is true";
       };
 
       roleAttr = mkOption {
         type        = types.str;
         default     = "businessCategory";
-        description = "Which LDAP group attribute to search for authorized role ARNs";
+        description = lib.mdDoc "Which LDAP group attribute to search for authorized role ARNs";
       };
 
       awsAccount = mkOption {
         type        = types.str;
-        description = "AWS account number";
+        description = lib.mdDoc "AWS account number";
       };
 
       awsDefaultRole = mkOption {
         type        = types.str;
-        description = "AWS default role";
+        description = lib.mdDoc "AWS default role";
       };
 
       statsAddress = mkOption {
         type        = types.str;
         default     = "";
-        description = "Address of statsd server";
+        description = lib.mdDoc "Address of statsd server";
       };
 
       cacheTimeoutSeconds = mkOption {
         type        = types.int;
         default     = 3600;
-        description = "How often (in seconds) to refresh the LDAP cache";
+        description = lib.mdDoc "How often (in seconds) to refresh the LDAP cache";
       };
     };
   };
diff --git a/nixos/modules/services/security/infnoise.nix b/nixos/modules/services/security/infnoise.nix
new file mode 100644
index 00000000000..739a0a84d90
--- /dev/null
+++ b/nixos/modules/services/security/infnoise.nix
@@ -0,0 +1,60 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.infnoise;
+in {
+  options = {
+    services.infnoise = {
+      enable = mkEnableOption (lib.mdDoc "the Infinite Noise TRNG driver");
+
+      fillDevRandom = mkOption {
+        description = lib.mdDoc ''
+          Whether to run the infnoise driver as a daemon to refill /dev/random.
+
+          If disabled, you can use the `infnoise` command-line tool to
+          manually obtain randomness.
+        '';
+        type = types.bool;
+        default = true;
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    environment.systemPackages = [ pkgs.infnoise ];
+
+    services.udev.extraRules = ''
+      SUBSYSTEM=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6015", SYMLINK+="infnoise", TAG+="systemd", GROUP="dialout", MODE="0664", ENV{SYSTEMD_WANTS}="infnoise.service"
+    '';
+
+    systemd.services.infnoise = mkIf cfg.fillDevRandom {
+      description = "Infinite Noise TRNG driver";
+
+      bindsTo = [ "dev-infnoise.device" ];
+      after = [ "dev-infnoise.device" ];
+
+      serviceConfig = {
+        ExecStart = "${pkgs.infnoise}/bin/infnoise --dev-random --debug";
+        Restart = "always";
+        User = "infnoise";
+        DynamicUser = true;
+        SupplementaryGroups = [ "dialout" ];
+        DeviceAllow = [ "/dev/infnoise" ];
+        DevicePolicy = "closed";
+        PrivateNetwork = true;
+        ProtectSystem = "strict";
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true; # only reads entropy pool size and watermark
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        LockPersonality = true;
+        MemoryDenyWriteExecute = true;
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/security/kanidm.nix b/nixos/modules/services/security/kanidm.nix
new file mode 100644
index 00000000000..55120799c99
--- /dev/null
+++ b/nixos/modules/services/security/kanidm.nix
@@ -0,0 +1,355 @@
+{ config, lib, options, pkgs, ... }:
+let
+  cfg = config.services.kanidm;
+  settingsFormat = pkgs.formats.toml { };
+  # Remove null values, so we can document optional values that don't end up in the generated TOML file.
+  filterConfig = lib.converge (lib.filterAttrsRecursive (_: v: v != null));
+  serverConfigFile = settingsFormat.generate "server.toml" (filterConfig cfg.serverSettings);
+  clientConfigFile = settingsFormat.generate "kanidm-config.toml" (filterConfig cfg.clientSettings);
+  unixConfigFile = settingsFormat.generate "kanidm-unixd.toml" (filterConfig cfg.unixSettings);
+
+  defaultServiceConfig = {
+    BindReadOnlyPaths = [
+      "/nix/store"
+      "-/etc/resolv.conf"
+      "-/etc/nsswitch.conf"
+      "-/etc/hosts"
+      "-/etc/localtime"
+    ];
+    CapabilityBoundingSet = "";
+    # ProtectClock= adds DeviceAllow=char-rtc r
+    DeviceAllow = "";
+    # Implies ProtectSystem=strict, which re-mounts all paths
+    # DynamicUser = true;
+    LockPersonality = true;
+    MemoryDenyWriteExecute = true;
+    NoNewPrivileges = true;
+    PrivateDevices = true;
+    PrivateMounts = true;
+    PrivateNetwork = true;
+    PrivateTmp = true;
+    PrivateUsers = true;
+    ProcSubset = "pid";
+    ProtectClock = true;
+    ProtectHome = true;
+    ProtectHostname = true;
+    # Would re-mount paths ignored by temporary root
+    #ProtectSystem = "strict";
+    ProtectControlGroups = true;
+    ProtectKernelLogs = true;
+    ProtectKernelModules = true;
+    ProtectKernelTunables = true;
+    ProtectProc = "invisible";
+    RestrictAddressFamilies = [ ];
+    RestrictNamespaces = true;
+    RestrictRealtime = true;
+    RestrictSUIDSGID = true;
+    SystemCallArchitectures = "native";
+    SystemCallFilter = [ "@system-service" "~@privileged @resources @setuid @keyring" ];
+    # Does not work well with the temporary root
+    #UMask = "0066";
+  };
+
+in
+{
+  options.services.kanidm = {
+    enableClient = lib.mkEnableOption (lib.mdDoc "the Kanidm client");
+    enableServer = lib.mkEnableOption (lib.mdDoc "the Kanidm server");
+    enablePam = lib.mkEnableOption (lib.mdDoc "the Kanidm PAM and NSS integration.");
+
+    serverSettings = lib.mkOption {
+      type = lib.types.submodule {
+        freeformType = settingsFormat.type;
+
+        options = {
+          bindaddress = lib.mkOption {
+            description = lib.mdDoc "Address/port combination the webserver binds to.";
+            example = "[::1]:8443";
+            type = lib.types.str;
+          };
+          # Should be optional but toml does not accept null
+          ldapbindaddress = lib.mkOption {
+            description = lib.mdDoc ''
+              Address and port the LDAP server is bound to. Setting this to `null` disables the LDAP interface.
+            '';
+            example = "[::1]:636";
+            default = null;
+            type = lib.types.nullOr lib.types.str;
+          };
+          origin = lib.mkOption {
+            description = lib.mdDoc "The origin of your Kanidm instance. Must have https as protocol.";
+            example = "https://idm.example.org";
+            type = lib.types.strMatching "^https://.*";
+          };
+          domain = lib.mkOption {
+            description = lib.mdDoc ''
+              The `domain` that Kanidm manages. Must be below or equal to the domain
+              specified in `serverSettings.origin`.
+              This can be left at `null`, only if your instance has the role `ReadOnlyReplica`.
+              While it is possible to change the domain later on, it requires extra steps!
+              Please consider the warnings and execute the steps described
+              [in the documentation](https://kanidm.github.io/kanidm/stable/administrivia.html#rename-the-domain).
+            '';
+            example = "example.org";
+            default = null;
+            type = lib.types.nullOr lib.types.str;
+          };
+          db_path = lib.mkOption {
+            description = lib.mdDoc "Path to Kanidm database.";
+            default = "/var/lib/kanidm/kanidm.db";
+            readOnly = true;
+            type = lib.types.path;
+          };
+          tls_chain = lib.mkOption {
+            description = lib.mdDoc "TLS chain in pem format.";
+            type = lib.types.path;
+          };
+          tls_key = lib.mkOption {
+            description = lib.mdDoc "TLS key in pem format.";
+            type = lib.types.path;
+          };
+          log_level = lib.mkOption {
+            description = lib.mdDoc "Log level of the server.";
+            default = "default";
+            type = lib.types.enum [ "default" "verbose" "perfbasic" "perffull" ];
+          };
+          role = lib.mkOption {
+            description = lib.mdDoc "The role of this server. This affects the replication relationship and thereby available features.";
+            default = "WriteReplica";
+            type = lib.types.enum [ "WriteReplica" "WriteReplicaNoUI" "ReadOnlyReplica" ];
+          };
+        };
+      };
+      default = { };
+      description = lib.mdDoc ''
+        Settings for Kanidm, see
+        [the documentation](https://github.com/kanidm/kanidm/blob/master/kanidm_book/src/server_configuration.md)
+        and [example configuration](https://github.com/kanidm/kanidm/blob/master/examples/server.toml)
+        for possible values.
+      '';
+    };
+
+    clientSettings = lib.mkOption {
+      type = lib.types.submodule {
+        freeformType = settingsFormat.type;
+
+        options.uri = lib.mkOption {
+          description = lib.mdDoc "Address of the Kanidm server.";
+          example = "http://127.0.0.1:8080";
+          type = lib.types.str;
+        };
+      };
+      description = lib.mdDoc ''
+        Configure Kanidm clients, needed for the PAM daemon. See
+        [the documentation](https://github.com/kanidm/kanidm/blob/master/kanidm_book/src/client_tools.md#kanidm-configuration)
+        and [example configuration](https://github.com/kanidm/kanidm/blob/master/examples/config)
+        for possible values.
+      '';
+    };
+
+    unixSettings = lib.mkOption {
+      type = lib.types.submodule {
+        freeformType = settingsFormat.type;
+
+        options.pam_allowed_login_groups = lib.mkOption {
+          description = lib.mdDoc "Kanidm groups that are allowed to login using PAM.";
+          example = "my_pam_group";
+          type = lib.types.listOf lib.types.str;
+        };
+      };
+      description = lib.mdDoc ''
+        Configure Kanidm unix daemon.
+        See [the documentation](https://github.com/kanidm/kanidm/blob/master/kanidm_book/src/pam_and_nsswitch.md#the-unix-daemon)
+        and [example configuration](https://github.com/kanidm/kanidm/blob/master/examples/unixd)
+        for possible values.
+      '';
+    };
+  };
+
+  config = lib.mkIf (cfg.enableClient || cfg.enableServer || cfg.enablePam) {
+    assertions =
+      [
+        {
+          assertion = !cfg.enableServer || ((cfg.serverSettings.tls_chain or null) == null) || (!lib.isStorePath cfg.serverSettings.tls_chain);
+          message = ''
+            <option>services.kanidm.serverSettings.tls_chain</option> points to
+            a file in the Nix store. You should use a quoted absolute path to
+            prevent this.
+          '';
+        }
+        {
+          assertion = !cfg.enableServer || ((cfg.serverSettings.tls_key or null) == null) || (!lib.isStorePath cfg.serverSettings.tls_key);
+          message = ''
+            <option>services.kanidm.serverSettings.tls_key</option> points to
+            a file in the Nix store. You should use a quoted absolute path to
+            prevent this.
+          '';
+        }
+        {
+          assertion = !cfg.enableClient || options.services.kanidm.clientSettings.isDefined;
+          message = ''
+            <option>services.kanidm.clientSettings</option> needs to be configured
+            if the client is enabled.
+          '';
+        }
+        {
+          assertion = !cfg.enablePam || options.services.kanidm.clientSettings.isDefined;
+          message = ''
+            <option>services.kanidm.clientSettings</option> needs to be configured
+            for the PAM daemon to connect to the Kanidm server.
+          '';
+        }
+        {
+          assertion = !cfg.enableServer || (cfg.serverSettings.domain == null
+            -> cfg.serverSettings.role == "WriteReplica" || cfg.serverSettings.role == "WriteReplicaNoUI");
+          message = ''
+            <option>services.kanidm.serverSettings.domain</option> can only be set if this instance
+            is not a ReadOnlyReplica. Otherwise the db would inherit it from
+            the instance it follows.
+          '';
+        }
+      ];
+
+    environment.systemPackages = lib.mkIf cfg.enableClient [ pkgs.kanidm ];
+
+    systemd.services.kanidm = lib.mkIf cfg.enableServer {
+      description = "kanidm identity management daemon";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+      serviceConfig = defaultServiceConfig // {
+        StateDirectory = "kanidm";
+        StateDirectoryMode = "0700";
+        ExecStart = "${pkgs.kanidm}/bin/kanidmd server -c ${serverConfigFile}";
+        User = "kanidm";
+        Group = "kanidm";
+
+        AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
+        CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
+        # This would otherwise override the CAP_NET_BIND_SERVICE capability.
+        PrivateUsers = false;
+        # Port needs to be exposed to the host network
+        PrivateNetwork = false;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+        TemporaryFileSystem = "/:ro";
+      };
+      environment.RUST_LOG = "info";
+    };
+
+    systemd.services.kanidm-unixd = lib.mkIf cfg.enablePam {
+      description = "Kanidm PAM daemon";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" ];
+      restartTriggers = [ unixConfigFile clientConfigFile ];
+      serviceConfig = defaultServiceConfig // {
+        CacheDirectory = "kanidm-unixd";
+        CacheDirectoryMode = "0700";
+        RuntimeDirectory = "kanidm-unixd";
+        ExecStart = "${pkgs.kanidm}/bin/kanidm_unixd";
+        User = "kanidm-unixd";
+        Group = "kanidm-unixd";
+
+        BindReadOnlyPaths = [
+          "/nix/store"
+          "-/etc/resolv.conf"
+          "-/etc/nsswitch.conf"
+          "-/etc/hosts"
+          "-/etc/localtime"
+          "-/etc/kanidm"
+          "-/etc/static/kanidm"
+          "-/etc/ssl"
+          "-/etc/static/ssl"
+        ];
+        BindPaths = [
+          # To create the socket
+          "/run/kanidm-unixd:/var/run/kanidm-unixd"
+        ];
+        # Needs to connect to kanidmd
+        PrivateNetwork = false;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
+        TemporaryFileSystem = "/:ro";
+      };
+      environment.RUST_LOG = "info";
+    };
+
+    systemd.services.kanidm-unixd-tasks = lib.mkIf cfg.enablePam {
+      description = "Kanidm PAM home management daemon";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" "kanidm-unixd.service" ];
+      partOf = [ "kanidm-unixd.service" ];
+      restartTriggers = [ unixConfigFile clientConfigFile ];
+      serviceConfig = {
+        ExecStart = "${pkgs.kanidm}/bin/kanidm_unixd_tasks";
+
+        BindReadOnlyPaths = [
+          "/nix/store"
+          "-/etc/resolv.conf"
+          "-/etc/nsswitch.conf"
+          "-/etc/hosts"
+          "-/etc/localtime"
+          "-/etc/kanidm"
+          "-/etc/static/kanidm"
+        ];
+        BindPaths = [
+          # To manage home directories
+          "/home"
+          # To connect to kanidm-unixd
+          "/run/kanidm-unixd:/var/run/kanidm-unixd"
+        ];
+        # CAP_DAC_OVERRIDE is needed to ignore ownership of unixd socket
+        CapabilityBoundingSet = [ "CAP_CHOWN" "CAP_FOWNER" "CAP_DAC_OVERRIDE" "CAP_DAC_READ_SEARCH" ];
+        IPAddressDeny = "any";
+        # Need access to users
+        PrivateUsers = false;
+        # Need access to home directories
+        ProtectHome = false;
+        RestrictAddressFamilies = [ "AF_UNIX" ];
+        TemporaryFileSystem = "/:ro";
+      };
+      environment.RUST_LOG = "info";
+    };
+
+    # These paths are hardcoded
+    environment.etc = lib.mkMerge [
+      (lib.mkIf options.services.kanidm.clientSettings.isDefined {
+        "kanidm/config".source = clientConfigFile;
+      })
+      (lib.mkIf cfg.enablePam {
+        "kanidm/unixd".source = unixConfigFile;
+      })
+    ];
+
+    system.nssModules = lib.mkIf cfg.enablePam [ pkgs.kanidm ];
+
+    system.nssDatabases.group = lib.optional cfg.enablePam "kanidm";
+    system.nssDatabases.passwd = lib.optional cfg.enablePam "kanidm";
+
+    users.groups = lib.mkMerge [
+      (lib.mkIf cfg.enableServer {
+        kanidm = { };
+      })
+      (lib.mkIf cfg.enablePam {
+        kanidm-unixd = { };
+      })
+    ];
+    users.users = lib.mkMerge [
+      (lib.mkIf cfg.enableServer {
+        kanidm = {
+          description = "Kanidm server";
+          isSystemUser = true;
+          group = "kanidm";
+          packages = with pkgs; [ kanidm ];
+        };
+      })
+      (lib.mkIf cfg.enablePam {
+        kanidm-unixd = {
+          description = "Kanidm PAM daemon";
+          isSystemUser = true;
+          group = "kanidm-unixd";
+        };
+      })
+    ];
+  };
+
+  meta.maintainers = with lib.maintainers; [ erictapen Flakebi ];
+  meta.buildDocsInSandbox = false;
+}
diff --git a/nixos/modules/services/security/munge.nix b/nixos/modules/services/security/munge.nix
index 89178886471..4d6fe33f697 100644
--- a/nixos/modules/services/security/munge.nix
+++ b/nixos/modules/services/security/munge.nix
@@ -15,12 +15,12 @@ in
   options = {
 
     services.munge = {
-      enable = mkEnableOption "munge service";
+      enable = mkEnableOption (lib.mdDoc "munge service");
 
       password = mkOption {
         default = "/etc/munge/munge.key";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The path to a daemon's secret key.
         '';
       };
diff --git a/nixos/modules/services/security/nginx-sso.nix b/nixos/modules/services/security/nginx-sso.nix
index b4de1d36edd..971f22ed347 100644
--- a/nixos/modules/services/security/nginx-sso.nix
+++ b/nixos/modules/services/security/nginx-sso.nix
@@ -8,13 +8,13 @@ let
   configYml = pkgs.writeText "nginx-sso.yml" (builtins.toJSON cfg.configuration);
 in {
   options.services.nginx.sso = {
-    enable = mkEnableOption "nginx-sso service";
+    enable = mkEnableOption (lib.mdDoc "nginx-sso service");
 
     package = mkOption {
       type = types.package;
       default = pkgs.nginx-sso;
       defaultText = literalExpression "pkgs.nginx-sso";
-      description = ''
+      description = lib.mdDoc ''
         The nginx-sso package that should be used.
       '';
     };
@@ -40,9 +40,9 @@ in {
           };
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         nginx-sso configuration
-        (<link xlink:href="https://github.com/Luzifer/nginx-sso/wiki/Main-Configuration">documentation</link>)
+        ([documentation](https://github.com/Luzifer/nginx-sso/wiki/Main-Configuration))
         as a Nix attribute set.
       '';
     };
diff --git a/nixos/modules/services/security/oauth2_proxy.nix b/nixos/modules/services/security/oauth2_proxy.nix
index ce295bd4ba3..e3f8e75ca24 100644
--- a/nixos/modules/services/security/oauth2_proxy.nix
+++ b/nixos/modules/services/security/oauth2_proxy.nix
@@ -86,13 +86,13 @@ let
 in
 {
   options.services.oauth2_proxy = {
-    enable = mkEnableOption "oauth2_proxy";
+    enable = mkEnableOption (lib.mdDoc "oauth2_proxy");
 
     package = mkOption {
       type = types.package;
       default = pkgs.oauth2-proxy;
       defaultText = literalExpression "pkgs.oauth2-proxy";
-      description = ''
+      description = lib.mdDoc ''
         The package that provides oauth2-proxy.
       '';
     };
@@ -118,7 +118,7 @@ in
         "oidc"
       ];
       default = "google";
-      description = ''
+      description = lib.mdDoc ''
         OAuth provider.
       '';
     };
@@ -126,14 +126,14 @@ in
     approvalPrompt = mkOption {
       type = types.enum ["force" "auto"];
       default = "force";
-      description = ''
+      description = lib.mdDoc ''
         OAuth approval_prompt.
       '';
     };
 
     clientID = mkOption {
       type = types.nullOr types.str;
-      description = ''
+      description = lib.mdDoc ''
         The OAuth Client ID.
       '';
       example = "123456.apps.googleusercontent.com";
@@ -141,7 +141,7 @@ in
 
     clientSecret = mkOption {
       type = types.nullOr types.str;
-      description = ''
+      description = lib.mdDoc ''
         The OAuth Client Secret.
       '';
     };
@@ -149,7 +149,7 @@ in
     skipAuthRegexes = mkOption {
      type = types.listOf types.str;
      default = [];
-     description = ''
+     description = lib.mdDoc ''
        Skip authentication for requests matching any of these regular
        expressions.
      '';
@@ -160,16 +160,16 @@ in
       domains = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Authenticate emails with the specified domains. Use
-          <literal>*</literal> to authenticate any email.
+          `*` to authenticate any email.
         '';
       };
 
       addresses = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Line-separated email addresses that are allowed to authenticate.
         '';
       };
@@ -178,7 +178,7 @@ in
     loginURL = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Authentication endpoint.
 
         You only need to set this if you are using a self-hosted provider (e.g.
@@ -191,7 +191,7 @@ in
     redeemURL = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Token redemption endpoint.
 
         You only need to set this if you are using a self-hosted provider (e.g.
@@ -204,7 +204,7 @@ in
     validateURL = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Access token validation endpoint.
 
         You only need to set this if you are using a self-hosted provider (e.g.
@@ -219,7 +219,7 @@ in
       # doesn't require it so making it optional.
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The OAuth2 redirect URL.
       '';
       example = "https://internalapp.yourcompany.com/oauth2/callback";
@@ -229,14 +229,14 @@ in
       tenant = mkOption {
         type = types.str;
         default = "common";
-        description = ''
+        description = lib.mdDoc ''
           Go to a tenant-specific or common (tenant-independent) endpoint.
         '';
       };
 
       resource = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The resource that is protected.
         '';
       };
@@ -245,28 +245,28 @@ in
     google = {
       adminEmail = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The Google Admin to impersonate for API calls.
 
           Only users with access to the Admin APIs can access the Admin SDK
           Directory API, thus the service account needs to impersonate one of
           those users to access the Admin SDK Directory API.
 
-          See <link xlink:href="https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account" />.
+          See <https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account>.
         '';
       };
 
       groups = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Restrict logins to members of these Google groups.
         '';
       };
 
       serviceAccountJSON = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           The path to the service account JSON credentials.
         '';
       };
@@ -276,7 +276,7 @@ in
       org = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Restrict logins to members of this organisation.
         '';
       };
@@ -284,7 +284,7 @@ in
       team = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Restrict logins to members of this team.
         '';
       };
@@ -296,8 +296,8 @@ in
     upstream = mkOption {
       type = with types; coercedTo str (x: [x]) (listOf str);
       default = [];
-      description = ''
-        The http url(s) of the upstream endpoint or <literal>file://</literal>
+      description = lib.mdDoc ''
+        The http url(s) of the upstream endpoint or `file://`
         paths for static files. Routing is based on the path.
       '';
     };
@@ -305,7 +305,7 @@ in
     passAccessToken = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Pass OAuth access_token to upstream via X-Forwarded-Access-Token header.
       '';
     };
@@ -313,7 +313,7 @@ in
     passBasicAuth = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream.
       '';
     };
@@ -321,7 +321,7 @@ in
     basicAuthPassword = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The password to set when passing the HTTP Basic Auth header.
       '';
     };
@@ -329,7 +329,7 @@ in
     passHostHeader = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Pass the request Host Header to upstream.
       '';
     };
@@ -337,7 +337,7 @@ in
     signatureKey = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         GAP-Signature request signature key.
       '';
       example = "sha1:secret0";
@@ -347,7 +347,7 @@ in
       domain = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Optional cookie domains to force cookies to (ie: `.yourcompany.com`).
           The longest domain matching the request's host will be used (or the shortest
           cookie domain if there is no match).
@@ -358,7 +358,7 @@ in
       expire = mkOption {
         type = types.str;
         default = "168h0m0s";
-        description = ''
+        description = lib.mdDoc ''
           Expire timeframe for cookie.
         '';
       };
@@ -366,7 +366,7 @@ in
       httpOnly = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Set HttpOnly cookie flag.
         '';
       };
@@ -374,7 +374,7 @@ in
       name = mkOption {
         type = types.str;
         default = "_oauth2_proxy";
-        description = ''
+        description = lib.mdDoc ''
           The name of the cookie that the oauth_proxy creates.
         '';
       };
@@ -383,7 +383,7 @@ in
         # XXX: Unclear what the behavior is when this is not specified.
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Refresh the cookie after this duration; 0 to disable.
         '';
         example = "168h0m0s";
@@ -391,7 +391,7 @@ in
 
       secret = mkOption {
         type = types.nullOr types.str;
-        description = ''
+        description = lib.mdDoc ''
           The seed string for secure cookies.
         '';
       };
@@ -399,7 +399,7 @@ in
       secure = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Set secure (HTTPS) cookie flag.
         '';
       };
@@ -411,10 +411,10 @@ in
     httpAddress = mkOption {
       type = types.str;
       default = "http://127.0.0.1:4180";
-      description = ''
+      description = lib.mdDoc ''
         HTTPS listening address.  This module does not expose the port by
         default. If you want this URL to be accessible to other machines, please
-        add the port to <literal>networking.firewall.allowedTCPPorts</literal>.
+        add the port to `networking.firewall.allowedTCPPorts`.
       '';
     };
 
@@ -422,16 +422,16 @@ in
       file = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Additionally authenticate against a htpasswd file. Entries must be
-          created with <literal>htpasswd -s</literal> for SHA encryption.
+          created with `htpasswd -s` for SHA encryption.
         '';
       };
 
       displayForm = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Display username / password login form if an htpasswd file is provided.
         '';
       };
@@ -440,7 +440,7 @@ in
     customTemplatesDir = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Path to custom HTML templates.
       '';
     };
@@ -448,9 +448,9 @@ in
     reverseProxy = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         In case when running behind a reverse proxy, controls whether headers
-        like <literal>X-Real-Ip</literal> are accepted. Usage behind a reverse
+        like `X-Real-Ip` are accepted. Usage behind a reverse
         proxy will require this flag to be set to avoid logging the reverse
         proxy IP address.
       '';
@@ -459,7 +459,7 @@ in
     proxyPrefix = mkOption {
       type = types.str;
       default = "/oauth2";
-      description = ''
+      description = lib.mdDoc ''
         The url root path that this proxy should be nested under.
       '';
     };
@@ -468,21 +468,21 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to serve over TLS.
         '';
       };
 
       certificate = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to certificate file.
         '';
       };
 
       key = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to private key file.
         '';
       };
@@ -490,11 +490,11 @@ in
       httpsAddress = mkOption {
         type = types.str;
         default = ":443";
-        description = ''
-          <literal>addr:port</literal> to listen on for HTTPS clients.
+        description = lib.mdDoc ''
+          `addr:port` to listen on for HTTPS clients.
 
-          Remember to add <literal>port</literal> to
-          <literal>allowedTCPPorts</literal> if you want other machines to be
+          Remember to add `port` to
+          `allowedTCPPorts` if you want other machines to be
           able to connect to it.
         '';
       };
@@ -503,7 +503,7 @@ in
     requestLogging = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Log requests to stdout.
       '';
     };
@@ -517,7 +517,7 @@ in
       # doesn't require it so making it optional.
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         OAuth scope specification.
       '';
     };
@@ -525,7 +525,7 @@ in
     profileURL = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Profile access endpoint.
       '';
     };
@@ -533,7 +533,7 @@ in
     setXauthrequest = mkOption {
       type = types.nullOr types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Set X-Auth-Request-User and X-Auth-Request-Email response headers (useful in Nginx auth_request mode). Setting this to 'null' means using the upstream default (false).
       '';
     };
@@ -541,7 +541,7 @@ in
     extraConfig = mkOption {
       default = {};
       type = types.attrsOf types.anything;
-      description = ''
+      description = lib.mdDoc ''
         Extra config to pass to oauth2-proxy.
       '';
     };
@@ -549,7 +549,7 @@ in
     keyFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         oauth2-proxy allows passing sensitive configuration via environment variables.
         Make a file that contains lines like
         OAUTH2_PROXY_CLIENT_SECRET=asdfasdfasdf.apps.googleuserscontent.com
@@ -571,8 +571,11 @@ in
     users.users.oauth2_proxy = {
       description = "OAuth2 Proxy";
       isSystemUser = true;
+      group = "oauth2_proxy";
     };
 
+    users.groups.oauth2_proxy = {};
+
     systemd.services.oauth2_proxy = {
       description = "OAuth2 Proxy";
       path = [ cfg.package ];
diff --git a/nixos/modules/services/security/oauth2_proxy_nginx.nix b/nixos/modules/services/security/oauth2_proxy_nginx.nix
index 5853c5a123c..b8e45f67cf7 100644
--- a/nixos/modules/services/security/oauth2_proxy_nginx.nix
+++ b/nixos/modules/services/security/oauth2_proxy_nginx.nix
@@ -9,14 +9,14 @@ in
       type = types.str;
       default = config.services.oauth2_proxy.httpAddress;
       defaultText = literalExpression "config.services.oauth2_proxy.httpAddress";
-      description = ''
+      description = lib.mdDoc ''
         The address of the reverse proxy endpoint for oauth2_proxy
       '';
     };
     virtualHosts = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         A list of nginx virtual hosts to put behind the oauth2 proxy
       '';
     };
diff --git a/nixos/modules/services/security/opensnitch.nix b/nixos/modules/services/security/opensnitch.nix
index f9b4985e199..8f1407b555f 100644
--- a/nixos/modules/services/security/opensnitch.nix
+++ b/nixos/modules/services/security/opensnitch.nix
@@ -5,10 +5,47 @@ with lib;
 let
   cfg = config.services.opensnitch;
   format = pkgs.formats.json {};
+
+  predefinedRules = flip mapAttrs cfg.rules (name: cfg: {
+    file = pkgs.writeText "rule" (builtins.toJSON cfg);
+  });
+
 in {
   options = {
     services.opensnitch = {
-      enable = mkEnableOption "Opensnitch application firewall";
+      enable = mkEnableOption (mdDoc "Opensnitch application firewall");
+
+      rules = mkOption {
+        default = {};
+        example = literalExpression ''
+          {
+            "tor" = {
+              "name" = "tor";
+              "enabled" = true;
+              "action" = "allow";
+              "duration" = "always";
+              "operator" = {
+                "type" ="simple";
+                "sensitive" = false;
+                "operand" = "process.path";
+                "data" = "''${lib.getBin pkgs.tor}/bin/tor";
+              };
+            };
+          };
+        '';
+
+        description = mdDoc ''
+          Declarative configuration of firewall rules.
+          All rules will be stored in `/var/lib/opensnitch/rules`.
+          See [upstream documentation](https://github.com/evilsocket/opensnitch/wiki/Rules)
+          for available options.
+        '';
+
+        type = types.submodule {
+          freeformType = format.type;
+        };
+      };
+
       settings = mkOption {
         type = types.submodule {
           freeformType = format.type;
@@ -18,7 +55,7 @@ in {
 
               Address = mkOption {
                 type = types.str;
-                description = ''
+                description = mdDoc ''
                   Unix socket path (unix:///tmp/osui.sock, the "unix:///" part is
                   mandatory) or TCP socket (192.168.1.100:50051).
                 '';
@@ -26,7 +63,7 @@ in {
 
               LogFile = mkOption {
                 type = types.path;
-                description = ''
+                description = mdDoc ''
                   File to write logs to (use /dev/stdout to write logs to standard
                   output).
                 '';
@@ -36,7 +73,7 @@ in {
 
             DefaultAction = mkOption {
               type = types.enum [ "allow" "deny" ];
-              description = ''
+              description = mdDoc ''
                 Default action whether to block or allow application internet
                 access.
               '';
@@ -46,28 +83,28 @@ in {
               type = types.enum [
                 "once" "always" "until restart" "30s" "5m" "15m" "30m" "1h"
               ];
-              description = ''
+              description = mdDoc ''
                 Default duration of firewall rule.
               '';
             };
 
             InterceptUnknown = mkOption {
               type = types.bool;
-              description = ''
+              description = mdDoc ''
                 Wheter to intercept spare connections.
               '';
             };
 
             ProcMonitorMethod = mkOption {
               type = types.enum [ "ebpf" "proc" "ftrace" "audit" ];
-              description = ''
+              description = mdDoc ''
                 Which process monitoring method to use.
               '';
             };
 
             LogLevel = mkOption {
               type = types.enum [ 0 1 2 3 4 ];
-              description = ''
+              description = mdDoc ''
                 Default log level from 0 to 4 (debug, info, important, warning,
                 error).
               '';
@@ -75,7 +112,7 @@ in {
 
             Firewall = mkOption {
               type = types.enum [ "iptables" "nftables" ];
-              description = ''
+              description = mdDoc ''
                 Which firewall backend to use.
               '';
             };
@@ -84,14 +121,14 @@ in {
 
               MaxEvents = mkOption {
                 type = types.int;
-                description = ''
+                description = mdDoc ''
                   Max events to send to the GUI.
                 '';
               };
 
               MaxStats = mkOption {
                 type = types.int;
-                description = ''
+                description = mdDoc ''
                   Max stats per item to keep in backlog.
                 '';
               };
@@ -99,9 +136,8 @@ in {
             };
           };
         };
-        description = ''
-          opensnitchd configuration. Refer to
-          <link xlink:href="https://github.com/evilsocket/opensnitch/wiki/Configurations"/>
+        description = mdDoc ''
+          opensnitchd configuration. Refer to [upstream documentation](https://github.com/evilsocket/opensnitch/wiki/Configurations)
           for details on supported values.
         '';
       };
@@ -118,6 +154,25 @@ in {
       services.opensnitchd.wantedBy = [ "multi-user.target" ];
     };
 
+    systemd.services.opensnitchd.preStart = mkIf (cfg.rules != {}) (let
+      rules = flip mapAttrsToList predefinedRules (file: content: {
+        inherit (content) file;
+        local = "/var/lib/opensnitch/rules/${file}.json";
+      });
+    in ''
+      # Remove all firewall rules from `/var/lib/opensnitch/rules` that are symlinks to a store-path,
+      # but aren't declared in `cfg.rules` (i.e. all networks that were "removed" from
+      # `cfg.rules`).
+      find /var/lib/opensnitch/rules -type l -lname '${builtins.storeDir}/*' ${optionalString (rules != {}) ''
+        -not \( ${concatMapStringsSep " -o " ({ local, ... }:
+          "-name '${baseNameOf local}*'")
+        rules} \) \
+      ''} -delete
+      ${concatMapStrings ({ file, local }: ''
+        ln -sf '${file}' "${local}"
+      '') rules}
+    '');
+
     environment.etc."opensnitchd/default-config.json".source = format.generate "default-config.json" cfg.settings;
 
   };
diff --git a/nixos/modules/services/security/pass-secret-service.nix b/nixos/modules/services/security/pass-secret-service.nix
new file mode 100644
index 00000000000..c3c70d97ff5
--- /dev/null
+++ b/nixos/modules/services/security/pass-secret-service.nix
@@ -0,0 +1,27 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.passSecretService;
+in
+{
+  options.services.passSecretService = {
+    enable = mkEnableOption (lib.mdDoc "pass secret service");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.pass-secret-service;
+      defaultText = literalExpression "pkgs.pass-secret-service";
+      description = lib.mdDoc "Which pass-secret-service package to use.";
+      example = literalExpression "pkgs.pass-secret-service.override { python3 = pkgs.python310 }";
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.packages = [ cfg.package ];
+    services.dbus.packages = [ cfg.package ];
+  };
+
+  meta.maintainers = with maintainers; [ aidalgol ];
+}
diff --git a/nixos/modules/services/security/physlock.nix b/nixos/modules/services/security/physlock.nix
index 760e80f147f..cd774765915 100644
--- a/nixos/modules/services/security/physlock.nix
+++ b/nixos/modules/services/security/physlock.nix
@@ -17,15 +17,15 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          Whether to enable the <command>physlock</command> screen locking mechanism.
+        description = lib.mdDoc ''
+          Whether to enable the {command}`physlock` screen locking mechanism.
 
-          Enable this and then run <command>systemctl start physlock</command>
+          Enable this and then run {command}`systemctl start physlock`
           to securely lock the screen.
 
           This will switch to a new virtual terminal, turn off console
           switching and disable SysRq mechanism (when
-          <option>services.physlock.disableSysRq</option> is set)
+          {option}`services.physlock.disableSysRq` is set)
           until the root or user password is given.
         '';
       };
@@ -33,7 +33,7 @@ in
       allowAnyUser = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to allow any user to lock the screen. This will install a
           setuid wrapper to allow any user to start physlock as root, which
           is a minor security risk. Call the physlock binary to use this instead
@@ -44,7 +44,7 @@ in
       disableSysRq = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to disable SysRq when locked with physlock.
         '';
       };
@@ -52,17 +52,25 @@ in
       lockMessage = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Message to show on physlock login terminal.
         '';
       };
 
+      muteKernelMessages = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Disable kernel messages on console while physlock is running.
+        '';
+      };
+
       lockOn = {
 
         suspend = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to lock screen with physlock just before suspend.
           '';
         };
@@ -70,7 +78,7 @@ in
         hibernate = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to lock screen with physlock just before hibernate.
           '';
         };
@@ -79,11 +87,11 @@ in
           type = types.listOf types.str;
           default = [];
           example = [ "display-manager.service" ];
-          description = ''
+          description = lib.mdDoc ''
             Other targets to lock the screen just before.
 
             Useful if you want to e.g. both autologin to X11 so that
-            your <filename>~/.xsession</filename> gets executed and
+            your {file}`~/.xsession` gets executed and
             still to have the screen locked so that the system can be
             booted relatively unattended.
           '';
@@ -116,7 +124,7 @@ in
                 ++ cfg.lockOn.extraTargets;
         serviceConfig = {
           Type = "forking";
-          ExecStart = "${pkgs.physlock}/bin/physlock -d${optionalString cfg.disableSysRq "s"}${optionalString (cfg.lockMessage != "") " -p \"${cfg.lockMessage}\""}";
+          ExecStart = "${pkgs.physlock}/bin/physlock -d${optionalString cfg.muteKernelMessages "m"}${optionalString cfg.disableSysRq "s"}${optionalString (cfg.lockMessage != "") " -p \"${cfg.lockMessage}\""}";
         };
       };
 
diff --git a/nixos/modules/services/security/privacyidea.nix b/nixos/modules/services/security/privacyidea.nix
index b8e2d9a8b0d..e446e606cad 100644
--- a/nixos/modules/services/security/privacyidea.nix
+++ b/nixos/modules/services/security/privacyidea.nix
@@ -6,7 +6,7 @@ let
   cfg = config.services.privacyidea;
   opt = options.services.privacyidea;
 
-  uwsgi = pkgs.uwsgi.override { plugins = [ "python3" ]; };
+  uwsgi = pkgs.uwsgi.override { plugins = [ "python3" ]; python3 = pkgs.python39; };
   python = uwsgi.python3;
   penv = python.withPackages (const [ pkgs.privacyidea ]);
   logCfg = pkgs.writeText "privacyidea-log.cfg" ''
@@ -51,37 +51,53 @@ let
     ${cfg.extraConfig}
   '';
 
+  renderValue = x:
+    if isList x then concatMapStringsSep "," (x: ''"${x}"'') x
+    else if isString x && hasInfix "," x then ''"${x}"''
+    else x;
+
+  ldapProxyConfig = pkgs.writeText "ldap-proxy.ini"
+    (generators.toINI {}
+      (flip mapAttrs cfg.ldap-proxy.settings
+        (const (mapAttrs (const renderValue)))));
+
+  privacyidea-token-janitor = pkgs.writeShellScriptBin "privacyidea-token-janitor" ''
+    exec -a privacyidea-token-janitor \
+      /run/wrappers/bin/sudo -u ${cfg.user} \
+      env PRIVACYIDEA_CONFIGFILE=${cfg.stateDir}/privacyidea.cfg \
+      ${penv}/bin/privacyidea-token-janitor $@
+  '';
 in
 
 {
   options = {
     services.privacyidea = {
-      enable = mkEnableOption "PrivacyIDEA";
+      enable = mkEnableOption (lib.mdDoc "PrivacyIDEA");
 
       environmentFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/root/privacyidea.env";
-        description = ''
+        description = lib.mdDoc ''
           File to load as environment file. Environment variables
           from this file will be interpolated into the config file
-          using <package>envsubst</package> which is helpful for specifying
+          using `envsubst` which is helpful for specifying
           secrets:
-          <programlisting>
-          { <xref linkend="opt-services.privacyidea.secretKey" /> = "$SECRET"; }
-          </programlisting>
+          ```
+          { services.privacyidea.secretKey = "$SECRET"; }
+          ```
 
           The environment-file can now specify the actual secret key:
-          <programlisting>
+          ```
           SECRET=veryverytopsecret
-          </programlisting>
+          ```
         '';
       };
 
       stateDir = mkOption {
         type = types.str;
         default = "/var/lib/privacyidea";
-        description = ''
+        description = lib.mdDoc ''
           Directory where all PrivacyIDEA files will be placed by default.
         '';
       };
@@ -89,7 +105,7 @@ in
       superuserRealm = mkOption {
         type = types.listOf types.str;
         default = [ "super" "administrators" ];
-        description = ''
+        description = lib.mdDoc ''
           The realm where users are allowed to login as administrators.
         '';
       };
@@ -97,7 +113,7 @@ in
       secretKey = mkOption {
         type = types.str;
         example = "t0p s3cr3t";
-        description = ''
+        description = lib.mdDoc ''
           This is used to encrypt the auth_token.
         '';
       };
@@ -105,7 +121,7 @@ in
       pepper = mkOption {
         type = types.str;
         example = "Never know...";
-        description = ''
+        description = lib.mdDoc ''
           This is used to encrypt the admin passwords.
         '';
       };
@@ -114,7 +130,7 @@ in
         type = types.str;
         default = "${cfg.stateDir}/enckey";
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/enckey"'';
-        description = ''
+        description = lib.mdDoc ''
           This is used to encrypt the token data and token passwords
         '';
       };
@@ -123,7 +139,7 @@ in
         type = types.str;
         default = "${cfg.stateDir}/private.pem";
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/private.pem"'';
-        description = ''
+        description = lib.mdDoc ''
           Private Key for signing the audit log.
         '';
       };
@@ -132,26 +148,26 @@ in
         type = types.str;
         default = "${cfg.stateDir}/public.pem";
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/public.pem"'';
-        description = ''
+        description = lib.mdDoc ''
           Public key for checking signatures of the audit log.
         '';
       };
 
       adminPasswordFile = mkOption {
         type = types.path;
-        description = "File containing password for the admin user";
+        description = lib.mdDoc "File containing password for the admin user";
       };
 
       adminEmail = mkOption {
         type = types.str;
         example = "admin@example.com";
-        description = "Mail address for the admin user";
+        description = lib.mdDoc "Mail address for the admin user";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration options for pi.cfg.
         '';
       };
@@ -159,21 +175,58 @@ in
       user = mkOption {
         type = types.str;
         default = "privacyidea";
-        description = "User account under which PrivacyIDEA runs.";
+        description = lib.mdDoc "User account under which PrivacyIDEA runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "privacyidea";
-        description = "Group account under which PrivacyIDEA runs.";
+        description = lib.mdDoc "Group account under which PrivacyIDEA runs.";
+      };
+
+      tokenjanitor = {
+        enable = mkEnableOption (lib.mdDoc "automatic runs of the token janitor");
+        interval = mkOption {
+          default = "quarterly";
+          type = types.str;
+          description = lib.mdDoc ''
+            Interval in which the cleanup program is supposed to run.
+            See {manpage}`systemd.time(7)` for further information.
+          '';
+        };
+        action = mkOption {
+          type = types.enum [ "delete" "mark" "disable" "unassign" ];
+          description = lib.mdDoc ''
+            Which action to take for matching tokens.
+          '';
+        };
+        unassigned = mkOption {
+          default = false;
+          type = types.bool;
+          description = lib.mdDoc ''
+            Whether to search for **unassigned** tokens
+            and apply [](#opt-services.privacyidea.tokenjanitor.action)
+            onto them.
+          '';
+        };
+        orphaned = mkOption {
+          default = true;
+          type = types.bool;
+          description = lib.mdDoc ''
+            Whether to search for **orphaned** tokens
+            and apply [](#opt-services.privacyidea.tokenjanitor.action)
+            onto them.
+          '';
+        };
       };
 
       ldap-proxy = {
-        enable = mkEnableOption "PrivacyIDEA LDAP Proxy";
+        enable = mkEnableOption (lib.mdDoc "PrivacyIDEA LDAP Proxy");
 
         configFile = mkOption {
-          type = types.path;
-          description = ''
+          type = types.nullOr types.path;
+          default = null;
+          description = lib.mdDoc ''
             Path to PrivacyIDEA LDAP Proxy configuration (proxy.ini).
           '';
         };
@@ -181,13 +234,33 @@ in
         user = mkOption {
           type = types.str;
           default = "pi-ldap-proxy";
-          description = "User account under which PrivacyIDEA LDAP proxy runs.";
+          description = lib.mdDoc "User account under which PrivacyIDEA LDAP proxy runs.";
         };
 
         group = mkOption {
           type = types.str;
           default = "pi-ldap-proxy";
-          description = "Group account under which PrivacyIDEA LDAP proxy runs.";
+          description = lib.mdDoc "Group account under which PrivacyIDEA LDAP proxy runs.";
+        };
+
+        settings = mkOption {
+          type = with types; attrsOf (attrsOf (oneOf [ str bool int (listOf str) ]));
+          default = {};
+          description = lib.mdDoc ''
+            Attribute-set containing the settings for `privacyidea-ldap-proxy`.
+            It's possible to pass secrets using env-vars as substitutes and
+            use the option [](#opt-services.privacyidea.ldap-proxy.environmentFile)
+            to inject them via `envsubst`.
+          '';
+        };
+
+        environmentFile = mkOption {
+          default = null;
+          type = types.nullOr types.str;
+          description = lib.mdDoc ''
+            Environment file containing secrets to be substituted into
+            [](#opt-services.privacyidea.ldap-proxy.settings).
+          '';
         };
       };
     };
@@ -197,10 +270,60 @@ in
 
     (mkIf cfg.enable {
 
-      environment.systemPackages = [ pkgs.privacyidea ];
+      assertions = [
+        {
+          assertion = cfg.tokenjanitor.enable -> (cfg.tokenjanitor.orphaned || cfg.tokenjanitor.unassigned);
+          message = ''
+            privacyidea-token-janitor has no effect if neither orphaned nor unassigned tokens
+            are to be searched.
+          '';
+        }
+      ];
+
+      environment.systemPackages = [ pkgs.privacyidea (hiPrio privacyidea-token-janitor) ];
 
       services.postgresql.enable = mkDefault true;
 
+      systemd.services.privacyidea-tokenjanitor = mkIf cfg.tokenjanitor.enable {
+        environment.PRIVACYIDEA_CONFIGFILE = "${cfg.stateDir}/privacyidea.cfg";
+        path = [ penv ];
+        serviceConfig = {
+          CapabilityBoundingSet = [ "" ];
+          ExecStart = "${pkgs.writeShellScript "pi-token-janitor" ''
+            ${optionalString cfg.tokenjanitor.orphaned ''
+              echo >&2 "Removing orphaned tokens..."
+              privacyidea-token-janitor find \
+                --orphaned true \
+                --action ${cfg.tokenjanitor.action}
+            ''}
+            ${optionalString cfg.tokenjanitor.unassigned ''
+              echo >&2 "Removing unassigned tokens..."
+              privacyidea-token-janitor find \
+                --assigned false \
+                --action ${cfg.tokenjanitor.action}
+            ''}
+          ''}";
+          Group = cfg.group;
+          LockPersonality = true;
+          MemoryDenyWriteExecute = true;
+          ProtectHome = true;
+          ProtectHostname = true;
+          ProtectKernelLogs = true;
+          ProtectKernelModules = true;
+          ProtectKernelTunables = true;
+          ProtectSystem = "strict";
+          ReadWritePaths = cfg.stateDir;
+          Type = "oneshot";
+          User = cfg.user;
+          WorkingDirectory = cfg.stateDir;
+        };
+      };
+      systemd.timers.privacyidea-tokenjanitor = mkIf cfg.tokenjanitor.enable {
+        wantedBy = [ "timers.target" ];
+        timerConfig.OnCalendar = cfg.tokenjanitor.interval;
+        timerConfig.Persistent = true;
+      };
+
       systemd.services.privacyidea = let
         piuwsgi = pkgs.writeText "uwsgi.json" (builtins.toJSON {
           uwsgi = {
@@ -276,6 +399,18 @@ in
 
     (mkIf cfg.ldap-proxy.enable {
 
+      assertions = [
+        { assertion = let
+            xor = a: b: a && !b || !a && b;
+          in xor (cfg.ldap-proxy.settings == {}) (cfg.ldap-proxy.configFile == null);
+          message = "configFile & settings are mutually exclusive for services.privacyidea.ldap-proxy!";
+        }
+      ];
+
+      warnings = mkIf (cfg.ldap-proxy.configFile != null) [
+        "Using services.privacyidea.ldap-proxy.configFile is deprecated! Use the RFC42-style settings option instead!"
+      ];
+
       systemd.services.privacyidea-ldap-proxy = let
         ldap-proxy-env = pkgs.python3.withPackages (ps: [ ps.privacyidea-ldap-proxy ]);
       in {
@@ -284,14 +419,28 @@ in
         serviceConfig = {
           User = cfg.ldap-proxy.user;
           Group = cfg.ldap-proxy.group;
-          ExecStart = ''
+          StateDirectory = "privacyidea-ldap-proxy";
+          EnvironmentFile = mkIf (cfg.ldap-proxy.environmentFile != null)
+            [ cfg.ldap-proxy.environmentFile ];
+          ExecStartPre =
+            "${pkgs.writeShellScript "substitute-secrets-ldap-proxy" ''
+              umask 0077
+              ${pkgs.envsubst}/bin/envsubst \
+                -i ${ldapProxyConfig} \
+                -o $STATE_DIRECTORY/ldap-proxy.ini
+            ''}";
+          ExecStart = let
+            configPath = if cfg.ldap-proxy.settings != {}
+              then "%S/privacyidea-ldap-proxy/ldap-proxy.ini"
+              else cfg.ldap-proxy.configFile;
+          in ''
             ${ldap-proxy-env}/bin/twistd \
               --nodaemon \
               --pidfile= \
               -u ${cfg.ldap-proxy.user} \
               -g ${cfg.ldap-proxy.group} \
               ldap-proxy \
-              -c ${cfg.ldap-proxy.configFile}
+              -c ${configPath}
           '';
           Restart = "always";
         };
diff --git a/nixos/modules/services/security/shibboleth-sp.nix b/nixos/modules/services/security/shibboleth-sp.nix
index fea2a855e20..6626ea21362 100644
--- a/nixos/modules/services/security/shibboleth-sp.nix
+++ b/nixos/modules/services/security/shibboleth-sp.nix
@@ -9,31 +9,31 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the shibboleth service";
+        description = lib.mdDoc "Whether to enable the shibboleth service";
       };
 
       configFile = mkOption {
         type = types.path;
         example = literalExpression ''"''${pkgs.shibboleth-sp}/etc/shibboleth/shibboleth2.xml"'';
-        description = "Path to shibboleth config file";
+        description = lib.mdDoc "Path to shibboleth config file";
       };
 
       fastcgi.enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to include the shibauthorizer and shibresponder FastCGI processes";
+        description = lib.mdDoc "Whether to include the shibauthorizer and shibresponder FastCGI processes";
       };
 
       fastcgi.shibAuthorizerPort = mkOption {
         type = types.int;
         default = 9100;
-        description = "Port for shibauthorizer FastCGI proccess to bind to";
+        description = lib.mdDoc "Port for shibauthorizer FastCGI proccess to bind to";
       };
 
       fastcgi.shibResponderPort = mkOption {
         type = types.int;
         default = 9101;
-        description = "Port for shibauthorizer FastCGI proccess to bind to";
+        description = lib.mdDoc "Port for shibauthorizer FastCGI proccess to bind to";
       };
     };
   };
diff --git a/nixos/modules/services/security/sks.nix b/nixos/modules/services/security/sks.nix
index f4911597564..550b61916a2 100644
--- a/nixos/modules/services/security/sks.nix
+++ b/nixos/modules/services/security/sks.nix
@@ -16,16 +16,16 @@ in {
 
     services.sks = {
 
-      enable = mkEnableOption ''
+      enable = mkEnableOption (lib.mdDoc ''
         SKS (synchronizing key server for OpenPGP) and start the database
         server. You need to create "''${dataDir}/dump/*.gpg" for the initial
-        import'';
+        import'');
 
       package = mkOption {
         default = pkgs.sks;
         defaultText = literalExpression "pkgs.sks";
         type = types.package;
-        description = "Which SKS derivation to use.";
+        description = lib.mdDoc "Which SKS derivation to use.";
       };
 
       dataDir = mkOption {
@@ -35,7 +35,7 @@ in {
         # TODO: The default might change to "/var/lib/sks" as this is more
         # common. There's also https://github.com/NixOS/nixpkgs/issues/26256
         # and "/var/db" is not FHS compliant (seems to come from BSD).
-        description = ''
+        description = lib.mdDoc ''
           Data directory (-basedir) for SKS, where the database and all
           configuration files are located (e.g. KDB, PTree, membership and
           sksconf).
@@ -45,7 +45,7 @@ in {
       extraDbConfig = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Set contents of the files "KDB/DB_CONFIG" and "PTree/DB_CONFIG" within
           the ''${dataDir} directory. This is used to configure options for the
           database for the sks key server.
@@ -59,7 +59,7 @@ in {
       hkpAddress = mkOption {
         default = [ "127.0.0.1" "::1" ];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Domain names, IPv4 and/or IPv6 addresses to listen on for HKP
           requests.
         '';
@@ -68,14 +68,14 @@ in {
       hkpPort = mkOption {
         default = 11371;
         type = types.ints.u16;
-        description = "HKP port to listen on.";
+        description = lib.mdDoc "HKP port to listen on.";
       };
 
       webroot = mkOption {
         type = types.nullOr types.path;
         default = "${sksPkg.webSamples}/OpenPKG";
         defaultText = literalExpression ''"''${package.webSamples}/OpenPKG"'';
-        description = ''
+        description = lib.mdDoc ''
           Source directory (will be symlinked, if not null) for the files the
           built-in webserver should serve. SKS (''${pkgs.sks.webSamples})
           provides the following examples: "HTML5", "OpenPKG", and "XHTML+ES".
diff --git a/nixos/modules/services/security/sshguard.nix b/nixos/modules/services/security/sshguard.nix
index 53bd9efa5ac..4e9d9571de5 100644
--- a/nixos/modules/services/security/sshguard.nix
+++ b/nixos/modules/services/security/sshguard.nix
@@ -17,7 +17,7 @@ let
       else "sshg-fw-ipset";
   in pkgs.writeText "sshguard.conf" ''
     BACKEND="${pkgs.sshguard}/libexec/${backend}"
-    LOGREADER="LANG=C ${pkgs.systemd}/bin/journalctl ${args}"
+    LOGREADER="LANG=C ${config.systemd.package}/bin/journalctl ${args}"
   '';
 
 in {
@@ -30,13 +30,13 @@ in {
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = "Whether to enable the sshguard service.";
+        description = lib.mdDoc "Whether to enable the sshguard service.";
       };
 
       attack_threshold = mkOption {
         default = 30;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
             Block attackers when their cumulative attack score exceeds threshold. Most attacks have a score of 10.
           '';
       };
@@ -45,7 +45,7 @@ in {
         default = null;
         example = 120;
         type = types.nullOr types.int;
-        description = ''
+        description = lib.mdDoc ''
             Blacklist an attacker when its score exceeds threshold. Blacklisted addresses are loaded from and added to blacklist-file.
           '';
       };
@@ -53,7 +53,7 @@ in {
       blacklist_file = mkOption {
         default = "/var/lib/sshguard/blacklist.db";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
             Blacklist an attacker when its score exceeds threshold. Blacklisted addresses are loaded from and added to blacklist-file.
           '';
       };
@@ -61,7 +61,7 @@ in {
       blocktime = mkOption {
         default = 120;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
             Block attackers for initially blocktime seconds after exceeding threshold. Subsequent blocks increase by a factor of 1.5.
 
             sshguard unblocks attacks at random intervals, so actual block times will be longer.
@@ -71,7 +71,7 @@ in {
       detection_time = mkOption {
         default = 1800;
         type = types.int;
-        description = ''
+        description = lib.mdDoc ''
             Remember potential attackers for up to detection_time seconds before resetting their score.
           '';
       };
@@ -80,7 +80,7 @@ in {
         default = [ ];
         example = [ "198.51.100.56" "198.51.100.2" ];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
             Whitelist a list of addresses, hostnames, or address blocks.
           '';
       };
@@ -89,7 +89,7 @@ in {
         default = [ "sshd" ];
         example = [ "sshd" "exim" ];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
             Systemd services sshguard should receive logs of.
           '';
       };
diff --git a/nixos/modules/services/security/sslmate-agent.nix b/nixos/modules/services/security/sslmate-agent.nix
new file mode 100644
index 00000000000..2d72406f0db
--- /dev/null
+++ b/nixos/modules/services/security/sslmate-agent.nix
@@ -0,0 +1,32 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.sslmate-agent;
+
+in {
+  meta.maintainers = with maintainers; [ wolfangaukang ];
+
+  options = {
+    services.sslmate-agent = {
+      enable = mkEnableOption (lib.mdDoc "sslmate-agent, a daemon for managing SSL/TLS certificates on a server");
+    };
+  };
+
+  config = mkIf cfg.enable {
+    environment.systemPackages = with pkgs; [ sslmate-agent ];
+
+    systemd = {
+      packages = [ pkgs.sslmate-agent ];
+      services.sslmate-agent = {
+        wantedBy = [ "multi-user.target" ];
+        serviceConfig = {
+          ConfigurationDirectory = "sslmate-agent";
+          LogsDirectory = "sslmate-agent";
+          StateDirectory = "sslmate-agent";
+        };
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/security/step-ca.nix b/nixos/modules/services/security/step-ca.nix
index 95183078d7b..433f162ecb8 100644
--- a/nixos/modules/services/security/step-ca.nix
+++ b/nixos/modules/services/security/step-ca.nix
@@ -8,68 +8,64 @@ in
 
   options = {
     services.step-ca = {
-      enable = lib.mkEnableOption "the smallstep certificate authority server";
-      openFirewall = lib.mkEnableOption "opening the certificate authority server port";
+      enable = lib.mkEnableOption (lib.mdDoc "the smallstep certificate authority server");
+      openFirewall = lib.mkEnableOption (lib.mdDoc "opening the certificate authority server port");
       package = lib.mkOption {
         type = lib.types.package;
         default = pkgs.step-ca;
         defaultText = lib.literalExpression "pkgs.step-ca";
-        description = "Which step-ca package to use.";
+        description = lib.mdDoc "Which step-ca package to use.";
       };
       address = lib.mkOption {
         type = lib.types.str;
         example = "127.0.0.1";
-        description = ''
+        description = lib.mdDoc ''
           The address (without port) the certificate authority should listen at.
-          This combined with <option>services.step-ca.port</option> overrides <option>services.step-ca.settings.address</option>.
+          This combined with {option}`services.step-ca.port` overrides {option}`services.step-ca.settings.address`.
         '';
       };
       port = lib.mkOption {
         type = lib.types.port;
         example = 8443;
-        description = ''
+        description = lib.mdDoc ''
           The port the certificate authority should listen on.
-          This combined with <option>services.step-ca.address</option> overrides <option>services.step-ca.settings.address</option>.
+          This combined with {option}`services.step-ca.address` overrides {option}`services.step-ca.settings.address`.
         '';
       };
       settings = lib.mkOption {
         type = with lib.types; attrsOf anything;
-        description = ''
-          Settings that go into <filename>ca.json</filename>. See
-          <link xlink:href="https://smallstep.com/docs/step-ca/configuration">
-          the step-ca manual</link> for more information. The easiest way to
-          configure this module would be to run <literal>step ca init</literal>
-          to generate <filename>ca.json</filename> and then import it using
-          <literal>builtins.fromJSON</literal>.
-          <link xlink:href="https://smallstep.com/docs/step-cli/basic-crypto-operations#run-an-offline-x509-certificate-authority">This article</link>
+        description = lib.mdDoc ''
+          Settings that go into {file}`ca.json`. See
+          [the step-ca manual](https://smallstep.com/docs/step-ca/configuration)
+          for more information. The easiest way to
+          configure this module would be to run `step ca init`
+          to generate {file}`ca.json` and then import it using
+          `builtins.fromJSON`.
+          [This article](https://smallstep.com/docs/step-cli/basic-crypto-operations#run-an-offline-x509-certificate-authority)
           may also be useful if you want to customize certain aspects of
           certificate generation for your CA.
-          You need to change the database storage path to <filename>/var/lib/step-ca/db</filename>.
+          You need to change the database storage path to {file}`/var/lib/step-ca/db`.
 
-          <warning>
-            <para>
-              The <option>services.step-ca.settings.address</option> option
-              will be ignored and overwritten by
-              <option>services.step-ca.address</option> and
-              <option>services.step-ca.port</option>.
-            </para>
-          </warning>
+          ::: {.warning}
+          The {option}`services.step-ca.settings.address` option
+          will be ignored and overwritten by
+          {option}`services.step-ca.address` and
+          {option}`services.step-ca.port`.
+          :::
         '';
       };
       intermediatePasswordFile = lib.mkOption {
         type = lib.types.path;
         example = "/run/keys/smallstep-password";
-        description = ''
+        description = lib.mdDoc ''
           Path to the file containing the password for the intermediate
           certificate private key.
 
-          <warning>
-            <para>
-              Make sure to use a quoted absolute path instead of a path literal
-              to prevent it from being copied to the globally readable Nix
-              store.
-            </para>
-          </warning>
+          ::: {.warning}
+          Make sure to use a quoted absolute path instead of a path literal
+          to prevent it from being copied to the globally readable Nix
+          store.
+          :::
         '';
       };
     };
diff --git a/nixos/modules/services/security/tor.nix b/nixos/modules/services/security/tor.nix
index a5822c02794..b85b78f269a 100644
--- a/nixos/modules/services/security/tor.nix
+++ b/nixos/modules/services/security/tor.nix
@@ -9,7 +9,7 @@ let
   stateDir = "/var/lib/tor";
   runDir = "/run/tor";
   descriptionGeneric = option: ''
-    See <link xlink:href="https://2019.www.torproject.org/docs/tor-manual.html.en#${option}">torrc manual</link>.
+    See [torrc manual](https://2019.www.torproject.org/docs/tor-manual.html.en#${option}).
   '';
   bindsPrivilegedPort =
     any (p0:
@@ -30,35 +30,35 @@ let
   optionBool = optionName: mkOption {
     type = with types; nullOr bool;
     default = null;
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
   optionInt = optionName: mkOption {
     type = with types; nullOr int;
     default = null;
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
   optionString = optionName: mkOption {
     type = with types; nullOr str;
     default = null;
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
   optionStrings = optionName: mkOption {
     type = with types; listOf str;
     default = [];
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
   optionAddress = mkOption {
     type = with types; nullOr str;
     default = null;
     example = "0.0.0.0";
-    description = ''
+    description = lib.mdDoc ''
       IPv4 or IPv6 (if between brackets) address.
     '';
   };
   optionUnix = mkOption {
     type = with types; nullOr path;
     default = null;
-    description = ''
+    description = lib.mdDoc ''
       Unix domain socket path to use.
     '';
   };
@@ -69,7 +69,7 @@ let
   optionPorts = optionName: mkOption {
     type = with types; listOf port;
     default = [];
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
   optionIsolablePort = with types; oneOf [
     port (enum ["auto"])
@@ -89,7 +89,7 @@ let
   optionIsolablePorts = optionName: mkOption {
     default = [];
     type = with types; either optionIsolablePort (listOf optionIsolablePort);
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
   isolateFlags = [
     "IsolateClientAddr"
@@ -144,17 +144,17 @@ let
         };
       }))
     ]))];
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
   optionBandwith = optionName: mkOption {
     type = with types; nullOr (either int str);
     default = null;
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
   optionPath = optionName: mkOption {
     type = with types; nullOr path;
     default = null;
-    description = descriptionGeneric optionName;
+    description = lib.mdDoc (descriptionGeneric optionName);
   };
 
   mkValueString = k: v:
@@ -224,45 +224,45 @@ in
 
   options = {
     services.tor = {
-      enable = mkEnableOption ''Tor daemon.
+      enable = mkEnableOption (lib.mdDoc ''Tor daemon.
         By default, the daemon is run without
-        relay, exit, bridge or client connectivity'';
+        relay, exit, bridge or client connectivity'');
 
-      openFirewall = mkEnableOption "opening of the relay port(s) in the firewall";
+      openFirewall = mkEnableOption (lib.mdDoc "opening of the relay port(s) in the firewall");
 
       package = mkOption {
         type = types.package;
         default = pkgs.tor;
         defaultText = literalExpression "pkgs.tor";
-        description = "Tor package to use.";
+        description = lib.mdDoc "Tor package to use.";
       };
 
-      enableGeoIP = mkEnableOption ''use of GeoIP databases.
+      enableGeoIP = mkEnableOption (lib.mdDoc ''use of GeoIP databases.
         Disabling this will disable by-country statistics for bridges and relays
-        and some client and third-party software functionality'' // { default = true; };
+        and some client and third-party software functionality'') // { default = true; };
 
-      controlSocket.enable = mkEnableOption ''control socket,
-        created in <literal>${runDir}/control</literal>'';
+      controlSocket.enable = mkEnableOption (lib.mdDoc ''control socket,
+        created in `${runDir}/control`'');
 
       client = {
-        enable = mkEnableOption ''the routing of application connections.
-          You might want to disable this if you plan running a dedicated Tor relay'';
+        enable = mkEnableOption (lib.mdDoc ''the routing of application connections.
+          You might want to disable this if you plan running a dedicated Tor relay'');
 
-        transparentProxy.enable = mkEnableOption "transparent proxy";
-        dns.enable = mkEnableOption "DNS resolver";
+        transparentProxy.enable = mkEnableOption (lib.mdDoc "transparent proxy");
+        dns.enable = mkEnableOption (lib.mdDoc "DNS resolver");
 
         socksListenAddress = mkOption {
           type = optionSOCKSPort false;
           default = {addr = "127.0.0.1"; port = 9050; IsolateDestAddr = true;};
           example = {addr = "192.168.0.1"; port = 9090; IsolateDestAddr = true;};
-          description = ''
+          description = lib.mdDoc ''
             Bind to this address to listen for connections from
             Socks-speaking applications.
           '';
         };
 
         onionServices = mkOption {
-          description = descriptionGeneric "HiddenServiceDir";
+          description = lib.mdDoc (descriptionGeneric "HiddenServiceDir");
           default = {};
           example = {
             "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" = {
@@ -271,11 +271,14 @@ in
           };
           type = types.attrsOf (types.submodule ({name, config, ...}: {
             options.clientAuthorizations = mkOption {
-              description = ''
+              description = lib.mdDoc ''
                 Clients' authorizations for a v3 onion service,
                 as a list of files containing each one private key, in the format:
-                <screen>descriptor:x25519:&lt;base32-private-key&gt;</screen>
-              '' + descriptionGeneric "_client_authorization";
+                ```
+                descriptor:x25519:<base32-private-key>
+                ```
+                ${descriptionGeneric "_client_authorization"}
+              '';
               type = with types; listOf path;
               default = [];
               example = ["/run/keys/tor/alice.prv.x25519"];
@@ -285,151 +288,109 @@ in
       };
 
       relay = {
-        enable = mkEnableOption ''relaying of Tor traffic for others.
+        enable = mkEnableOption (lib.mdDoc "tor relaying") // {
+          description = lib.mdDoc ''
+            Whether to enable relaying of Tor traffic for others.
 
-          See <link xlink:href="https://www.torproject.org/docs/tor-doc-relay" />
-          for details.
+            See <https://www.torproject.org/docs/tor-doc-relay>
+            for details.
 
-          Setting this to true requires setting
-          <option>services.tor.relay.role</option>
-          and
-          <option>services.tor.settings.ORPort</option>
-          options'';
+            Setting this to true requires setting
+            {option}`services.tor.relay.role`
+            and
+            {option}`services.tor.settings.ORPort`
+            options.
+          '';
+        };
 
         role = mkOption {
           type = types.enum [ "exit" "relay" "bridge" "private-bridge" ];
-          description = ''
+          description = lib.mdDoc ''
             Your role in Tor network. There're several options:
 
-            <variablelist>
-            <varlistentry>
-              <term><literal>exit</literal></term>
-              <listitem>
-                <para>
-                  An exit relay. This allows Tor users to access regular
-                  Internet services through your public IP.
-                </para>
+            - `exit`:
+              An exit relay. This allows Tor users to access regular
+              Internet services through your public IP.
 
-                <important><para>
-                  Running an exit relay may expose you to abuse
-                  complaints. See
-                  <link xlink:href="https://www.torproject.org/faq.html.en#ExitPolicies"/>
-                  for more info.
-                </para></important>
+              You can specify which services Tor users may access via
+              your exit relay using {option}`settings.ExitPolicy` option.
 
-                <para>
-                  You can specify which services Tor users may access via
-                  your exit relay using <option>settings.ExitPolicy</option> option.
-                </para>
-              </listitem>
-            </varlistentry>
+            - `relay`:
+              Regular relay. This allows Tor users to relay onion
+              traffic to other Tor nodes, but not to public
+              Internet.
 
-            <varlistentry>
-              <term><literal>relay</literal></term>
-              <listitem>
-                <para>
-                  Regular relay. This allows Tor users to relay onion
-                  traffic to other Tor nodes, but not to public
-                  Internet.
-                </para>
+              See
+              <https://www.torproject.org/docs/tor-doc-relay.html.en>
+              for more info.
 
-                <important><para>
-                  Note that some misconfigured and/or disrespectful
-                  towards privacy sites will block you even if your
-                  relay is not an exit relay. That is, just being listed
-                  in a public relay directory can have unwanted
-                  consequences.
+            - `bridge`:
+              Regular bridge. Works like a regular relay, but
+              doesn't list you in the public relay directory and
+              hides your Tor node behind obfs4proxy.
 
-                  Which means you might not want to use
-                  this role if you browse public Internet from the same
-                  network as your relay, unless you want to write
-                  e-mails to those sites (you should!).
-                </para></important>
+              Using this option will make Tor advertise your bridge
+              to users through various mechanisms like
+              <https://bridges.torproject.org/>, though.
 
-                <para>
-                  See
-                  <link xlink:href="https://www.torproject.org/docs/tor-doc-relay.html.en" />
-                  for more info.
-                </para>
-              </listitem>
-            </varlistentry>
+              See <https://www.torproject.org/docs/bridges.html.en>
+              for more info.
 
-            <varlistentry>
-              <term><literal>bridge</literal></term>
-              <listitem>
-                <para>
-                  Regular bridge. Works like a regular relay, but
-                  doesn't list you in the public relay directory and
-                  hides your Tor node behind obfs4proxy.
-                </para>
+            - `private-bridge`:
+              Private bridge. Works like regular bridge, but does
+              not advertise your node in any way.
 
-                <para>
-                  Using this option will make Tor advertise your bridge
-                  to users through various mechanisms like
-                  <link xlink:href="https://bridges.torproject.org/" />, though.
-                </para>
+              Using this role means that you won't contribute to Tor
+              network in any way unless you advertise your node
+              yourself in some way.
 
-                <important>
-                  <para>
-                    WARNING: THE FOLLOWING PARAGRAPH IS NOT LEGAL ADVICE.
-                    Consult with your lawyer when in doubt.
-                  </para>
+              Use this if you want to run a private bridge, for
+              example because you'll give out your bridge addr
+              manually to your friends.
 
-                  <para>
-                    This role should be safe to use in most situations
-                    (unless the act of forwarding traffic for others is
-                    a punishable offence under your local laws, which
-                    would be pretty insane as it would make ISP illegal).
-                  </para>
-                </important>
+              Switching to this role after measurable time in
+              "bridge" role is pretty useless as some Tor users
+              would have learned about your node already. In the
+              latter case you can still change
+              {option}`port` option.
 
-                <para>
-                  See <link xlink:href="https://www.torproject.org/docs/bridges.html.en" />
-                  for more info.
-                </para>
-              </listitem>
-            </varlistentry>
+              See <https://www.torproject.org/docs/bridges.html.en>
+              for more info.
 
-            <varlistentry>
-              <term><literal>private-bridge</literal></term>
-              <listitem>
-                <para>
-                  Private bridge. Works like regular bridge, but does
-                  not advertise your node in any way.
-                </para>
+            ::: {.important}
+            Running an exit relay may expose you to abuse
+            complaints. See
+            <https://www.torproject.org/faq.html.en#ExitPolicies>
+            for more info.
+            :::
 
-                <para>
-                  Using this role means that you won't contribute to Tor
-                  network in any way unless you advertise your node
-                  yourself in some way.
-                </para>
+            ::: {.important}
+            Note that some misconfigured and/or disrespectful
+            towards privacy sites will block you even if your
+            relay is not an exit relay. That is, just being listed
+            in a public relay directory can have unwanted
+            consequences.
 
-                <para>
-                  Use this if you want to run a private bridge, for
-                  example because you'll give out your bridge addr
-                  manually to your friends.
-                </para>
+            Which means you might not want to use
+            this role if you browse public Internet from the same
+            network as your relay, unless you want to write
+            e-mails to those sites (you should!).
+            :::
 
-                <para>
-                  Switching to this role after measurable time in
-                  "bridge" role is pretty useless as some Tor users
-                  would have learned about your node already. In the
-                  latter case you can still change
-                  <option>port</option> option.
-                </para>
+            ::: {.important}
+            WARNING: THE FOLLOWING PARAGRAPH IS NOT LEGAL ADVICE.
+            Consult with your lawyer when in doubt.
 
-                <para>
-                  See <link xlink:href="https://www.torproject.org/docs/bridges.html.en" />
-                  for more info.
-                </para>
-              </listitem>
-            </varlistentry>
-            </variablelist>
+            The `bridge` role should be safe to use in most situations
+            (unless the act of forwarding traffic for others is
+            a punishable offence under your local laws, which
+            would be pretty insane as it would make ISP illegal).
+            :::
           '';
         };
 
         onionServices = mkOption {
-          description = descriptionGeneric "HiddenServiceDir";
+          description = lib.mdDoc (descriptionGeneric "HiddenServiceDir");
           default = {};
           example = {
             "example.org/www" = {
@@ -442,62 +403,65 @@ in
           type = types.attrsOf (types.submodule ({name, config, ...}: {
             options.path = mkOption {
               type = types.path;
-              description = ''
+              description = lib.mdDoc ''
                 Path where to store the data files of the hidden service.
-                If the <option>secretKey</option> is null
-                this defaults to <literal>${stateDir}/onion/$onion</literal>,
-                otherwise to <literal>${runDir}/onion/$onion</literal>.
+                If the {option}`secretKey` is null
+                this defaults to `${stateDir}/onion/$onion`,
+                otherwise to `${runDir}/onion/$onion`.
               '';
             };
             options.secretKey = mkOption {
               type = with types; nullOr path;
               default = null;
               example = "/run/keys/tor/onion/expyuzz4wqqyqhjn/hs_ed25519_secret_key";
-              description = ''
+              description = lib.mdDoc ''
                 Secret key of the onion service.
-                If null, Tor reuses any preexisting secret key (in <option>path</option>)
+                If null, Tor reuses any preexisting secret key (in {option}`path`)
                 or generates a new one.
                 The associated public key and hostname are deterministically regenerated
                 from this file if they do not exist.
               '';
             };
             options.authorizeClient = mkOption {
-              description = descriptionGeneric "HiddenServiceAuthorizeClient";
+              description = lib.mdDoc (descriptionGeneric "HiddenServiceAuthorizeClient");
               default = null;
               type = types.nullOr (types.submodule ({...}: {
                 options = {
                   authType = mkOption {
                     type = types.enum [ "basic" "stealth" ];
-                    description = ''
-                      Either <literal>"basic"</literal> for a general-purpose authorization protocol
-                      or <literal>"stealth"</literal> for a less scalable protocol
+                    description = lib.mdDoc ''
+                      Either `"basic"` for a general-purpose authorization protocol
+                      or `"stealth"` for a less scalable protocol
                       that also hides service activity from unauthorized clients.
                     '';
                   };
                   clientNames = mkOption {
                     type = with types; nonEmptyListOf (strMatching "[A-Za-z0-9+-_]+");
-                    description = ''
+                    description = lib.mdDoc ''
                       Only clients that are listed here are authorized to access the hidden service.
-                      Generated authorization data can be found in <filename>${stateDir}/onion/$name/hostname</filename>.
+                      Generated authorization data can be found in {file}`${stateDir}/onion/$name/hostname`.
                       Clients need to put this authorization data in their configuration file using
-                      <xref linkend="opt-services.tor.settings.HidServAuth"/>.
+                      [](#opt-services.tor.settings.HidServAuth).
                     '';
                   };
                 };
               }));
             };
             options.authorizedClients = mkOption {
-              description = ''
+              description = lib.mdDoc ''
                 Authorized clients for a v3 onion service,
                 as a list of public key, in the format:
-                <screen>descriptor:x25519:&lt;base32-public-key&gt;</screen>
-              '' + descriptionGeneric "_client_authorization";
+                ```
+                descriptor:x25519:<base32-public-key>
+                ```
+                ${descriptionGeneric "_client_authorization"}
+              '';
               type = with types; listOf str;
               default = [];
               example = ["descriptor:x25519:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"];
             };
             options.map = mkOption {
-              description = descriptionGeneric "HiddenServicePort";
+              description = lib.mdDoc (descriptionGeneric "HiddenServicePort");
               type = with types; listOf (oneOf [
                 port (submodule ({...}: {
                   options = {
@@ -518,14 +482,15 @@ in
               apply = map (v: if isInt v then {port=v; target=null;} else v);
             };
             options.version = mkOption {
-              description = descriptionGeneric "HiddenServiceVersion";
+              description = lib.mdDoc (descriptionGeneric "HiddenServiceVersion");
               type = with types; nullOr (enum [2 3]);
               default = null;
             };
             options.settings = mkOption {
-              description = ''
+              description = lib.mdDoc ''
                 Settings of the onion service.
-              '' + descriptionGeneric "_hidden_service_options";
+                ${descriptionGeneric "_hidden_service_options"}
+              '';
               default = {};
               type = types.submodule {
                 freeformType = with types;
@@ -535,18 +500,18 @@ in
                 options.HiddenServiceAllowUnknownPorts = optionBool "HiddenServiceAllowUnknownPorts";
                 options.HiddenServiceDirGroupReadable = optionBool "HiddenServiceDirGroupReadable";
                 options.HiddenServiceExportCircuitID = mkOption {
-                  description = descriptionGeneric "HiddenServiceExportCircuitID";
+                  description = lib.mdDoc (descriptionGeneric "HiddenServiceExportCircuitID");
                   type = with types; nullOr (enum ["haproxy"]);
                   default = null;
                 };
                 options.HiddenServiceMaxStreams = mkOption {
-                  description = descriptionGeneric "HiddenServiceMaxStreams";
+                  description = lib.mdDoc (descriptionGeneric "HiddenServiceMaxStreams");
                   type = with types; nullOr (ints.between 0 65535);
                   default = null;
                 };
                 options.HiddenServiceMaxStreamsCloseCircuit = optionBool "HiddenServiceMaxStreamsCloseCircuit";
                 options.HiddenServiceNumIntroductionPoints = mkOption {
-                  description = descriptionGeneric "HiddenServiceNumIntroductionPoints";
+                  description = lib.mdDoc (descriptionGeneric "HiddenServiceNumIntroductionPoints");
                   type = with types; nullOr (ints.between 0 20);
                   default = null;
                 };
@@ -569,8 +534,8 @@ in
       };
 
       settings = mkOption {
-        description = ''
-          See <link xlink:href="https://2019.www.torproject.org/docs/tor-manual.html.en">torrc manual</link>
+        description = lib.mdDoc ''
+          See [torrc manual](https://2019.www.torproject.org/docs/tor-manual.html.en)
           for documentation.
         '';
         default = {};
@@ -605,7 +570,7 @@ in
           options.ClientAutoIPv6ORPort = optionBool "ClientAutoIPv6ORPort";
           options.ClientDNSRejectInternalAddresses = optionBool "ClientDNSRejectInternalAddresses";
           options.ClientOnionAuthDir = mkOption {
-            description = descriptionGeneric "ClientOnionAuthDir";
+            description = lib.mdDoc (descriptionGeneric "ClientOnionAuthDir");
             default = null;
             type = with types; nullOr path;
           };
@@ -618,7 +583,7 @@ in
           options.ConstrainedSockets = optionBool "ConstrainedSockets";
           options.ContactInfo = optionString "ContactInfo";
           options.ControlPort = mkOption rec {
-            description = descriptionGeneric "ControlPort";
+            description = lib.mdDoc (descriptionGeneric "ControlPort");
             default = [];
             example = [{port = 9051;}];
             type = with types; oneOf [port (enum ["auto"]) (listOf (oneOf [
@@ -653,7 +618,7 @@ in
           options.DormantTimeoutDisabledByIdleStreams = optionBool "DormantTimeoutDisabledByIdleStreams";
           options.DirCache = optionBool "DirCache";
           options.DirPolicy = mkOption {
-            description = descriptionGeneric "DirPolicy";
+            description = lib.mdDoc (descriptionGeneric "DirPolicy");
             type = with types; listOf str;
             default = [];
             example = ["accept *:*"];
@@ -680,7 +645,7 @@ in
           options.ExitPortStatistics = optionBool "ExitPortStatistics";
           options.ExitRelay = optionBool "ExitRelay"; # default is null and like "auto"
           options.ExtORPort = mkOption {
-            description = descriptionGeneric "ExtORPort";
+            description = lib.mdDoc (descriptionGeneric "ExtORPort");
             default = null;
             type = with types; nullOr (oneOf [
               port (enum ["auto"]) (submodule ({...}: {
@@ -709,19 +674,19 @@ in
           options.GeoIPv6File = optionPath "GeoIPv6File";
           options.GuardfractionFile = optionPath "GuardfractionFile";
           options.HidServAuth = mkOption {
-            description = descriptionGeneric "HidServAuth";
+            description = lib.mdDoc (descriptionGeneric "HidServAuth");
             default = [];
             type = with types; listOf (oneOf [
               (submodule {
                 options = {
                   onion = mkOption {
                     type = strMatching "[a-z2-7]{16}\\.onion";
-                    description = "Onion address.";
+                    description = lib.mdDoc "Onion address.";
                     example = "xxxxxxxxxxxxxxxx.onion";
                   };
                   auth = mkOption {
                     type = strMatching "[A-Za-z0-9+/]{22}";
-                    description = "Authentication cookie.";
+                    description = lib.mdDoc "Authentication cookie.";
                   };
                 };
               })
@@ -760,7 +725,7 @@ in
           options.ProtocolWarnings = optionBool "ProtocolWarnings";
           options.PublishHidServDescriptors = optionBool "PublishHidServDescriptors";
           options.PublishServerDescriptor = mkOption {
-            description = descriptionGeneric "PublishServerDescriptor";
+            description = lib.mdDoc (descriptionGeneric "PublishServerDescriptor");
             type = with types; nullOr (enum [false true 0 1 "0" "1" "v3" "bridge"]);
             default = null;
           };
@@ -778,18 +743,18 @@ in
           options.ServerDNSResolvConfFile = optionPath "ServerDNSResolvConfFile";
           options.ServerDNSSearchDomains = optionBool "ServerDNSSearchDomains";
           options.ServerTransportPlugin = mkOption {
-            description = descriptionGeneric "ServerTransportPlugin";
+            description = lib.mdDoc (descriptionGeneric "ServerTransportPlugin");
             default = null;
             type = with types; nullOr (submodule ({...}: {
               options = {
                 transports = mkOption {
-                  description = "List of pluggable transports.";
+                  description = lib.mdDoc "List of pluggable transports.";
                   type = listOf str;
                   example = ["obfs2" "obfs3" "obfs4" "scramblesuit"];
                 };
                 exec = mkOption {
                   type = types.str;
-                  description = "Command of pluggable transport.";
+                  description = lib.mdDoc "Command of pluggable transport.";
                 };
               };
             }));
@@ -797,13 +762,13 @@ in
           options.ShutdownWaitLength = mkOption {
             type = types.int;
             default = 30;
-            description = descriptionGeneric "ShutdownWaitLength";
+            description = lib.mdDoc (descriptionGeneric "ShutdownWaitLength");
           };
           options.SocksPolicy = optionStrings "SocksPolicy" // {
             example = ["accept *:*"];
           };
           options.SOCKSPort = mkOption {
-            description = descriptionGeneric "SOCKSPort";
+            description = lib.mdDoc (descriptionGeneric "SOCKSPort");
             default = if cfg.settings.HiddenServiceNonAnonymousMode == true then [{port = 0;}] else [];
             defaultText = literalExpression ''
               if config.${opt.settings}.HiddenServiceNonAnonymousMode == true
@@ -816,7 +781,7 @@ in
           options.TestingTorNetwork = optionBool "TestingTorNetwork";
           options.TransPort = optionIsolablePorts "TransPort";
           options.TransProxyType = mkOption {
-            description = descriptionGeneric "TransProxyType";
+            description = lib.mdDoc (descriptionGeneric "TransProxyType");
             type = with types; nullOr (enum ["default" "TPROXY" "ipfw" "pf-divert"]);
             default = null;
           };
@@ -851,13 +816,13 @@ in
         always create a container/VM with a separate Tor daemon instance.
       '' ++
       flatten (mapAttrsToList (n: o:
-        optional (o.settings.HiddenServiceVersion == 2) [
+        optionals (o.settings.HiddenServiceVersion == 2) [
           (optional (o.settings.HiddenServiceExportCircuitID != null) ''
             HiddenServiceExportCircuitID is used in the HiddenService: ${n}
             but this option is only for v3 hidden services.
           '')
         ] ++
-        optional (o.settings.HiddenServiceVersion != 2) [
+        optionals (o.settings.HiddenServiceVersion != 2) [
           (optional (o.settings.HiddenServiceAuthorizeClient != null) ''
             HiddenServiceAuthorizeClient is used in the HiddenService: ${n}
             but this option is only for v2 hidden services.
diff --git a/nixos/modules/services/security/torify.nix b/nixos/modules/services/security/torify.nix
index 39551190dd3..4d311adebca 100644
--- a/nixos/modules/services/security/torify.nix
+++ b/nixos/modules/services/security/torify.nix
@@ -27,16 +27,16 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to build tsocks wrapper script to relay application traffic via Tor.
 
-          <important>
-            <para>You shouldn't use this unless you know what you're
-            doing because your installation of Tor already comes with
-            its own superior (doesn't leak DNS queries)
-            <literal>torsocks</literal> wrapper which does pretty much
-            exactly the same thing as this.</para>
-          </important>
+          ::: {.important}
+          You shouldn't use this unless you know what you're
+          doing because your installation of Tor already comes with
+          its own superior (doesn't leak DNS queries)
+          `torsocks` wrapper which does pretty much
+          exactly the same thing as this.
+          :::
         '';
       };
 
@@ -44,7 +44,7 @@ in
         type = types.str;
         default = "localhost:9050";
         example = "192.168.0.20";
-        description = ''
+        description = lib.mdDoc ''
           IP address of TOR client to use.
         '';
       };
@@ -52,7 +52,7 @@ in
       config = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration. Contents will be added verbatim to TSocks
           configuration file.
         '';
diff --git a/nixos/modules/services/security/torsocks.nix b/nixos/modules/services/security/torsocks.nix
index fdd6ac32cc6..0647d7eb49b 100644
--- a/nixos/modules/services/security/torsocks.nix
+++ b/nixos/modules/services/security/torsocks.nix
@@ -38,8 +38,8 @@ in
         type        = types.bool;
         default     = config.services.tor.enable && config.services.tor.client.enable;
         defaultText = literalExpression "config.services.tor.enable && config.services.tor.client.enable";
-        description = ''
-          Whether to build <literal>/etc/tor/torsocks.conf</literal>
+        description = lib.mdDoc ''
+          Whether to build `/etc/tor/torsocks.conf`
           containing the specified global torsocks configuration.
         '';
       };
@@ -48,7 +48,7 @@ in
         type    = types.str;
         default = "127.0.0.1:9050";
         example = "192.168.0.20:1234";
-        description = ''
+        description = lib.mdDoc ''
           IP/Port of the Tor SOCKS server. Currently, hostnames are
           NOT supported by torsocks.
         '';
@@ -58,7 +58,7 @@ in
         type    = types.str;
         default = "127.0.0.1:9063";
         example = "192.168.0.20:1234";
-        description = ''
+        description = lib.mdDoc ''
           IP/Port of the Tor SOCKS server for torsocks-faster wrapper suitable for HTTP.
           Currently, hostnames are NOT supported by torsocks.
         '';
@@ -67,7 +67,7 @@ in
       onionAddrRange = mkOption {
         type    = types.str;
         default = "127.42.42.0/24";
-        description = ''
+        description = lib.mdDoc ''
           Tor hidden sites do not have real IP addresses. This
           specifies what range of IP addresses will be handed to the
           application as "cookies" for .onion names.  Of course, you
@@ -81,8 +81,8 @@ in
         type    = types.nullOr types.str;
         default = null;
         example = "bob";
-        description = ''
-          SOCKS5 username. The <literal>TORSOCKS_USERNAME</literal>
+        description = lib.mdDoc ''
+          SOCKS5 username. The `TORSOCKS_USERNAME`
           environment variable overrides this option if it is set.
         '';
       };
@@ -91,8 +91,8 @@ in
         type    = types.nullOr types.str;
         default = null;
         example = "sekret";
-        description = ''
-          SOCKS5 password. The <literal>TORSOCKS_PASSWORD</literal>
+        description = lib.mdDoc ''
+          SOCKS5 password. The `TORSOCKS_PASSWORD`
           environment variable overrides this option if it is set.
         '';
       };
@@ -100,9 +100,9 @@ in
       allowInbound = mkOption {
         type    = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Set Torsocks to accept inbound connections. If set to
-          <literal>true</literal>, listen() and accept() will be
+          `true`, listen() and accept() will be
           allowed to be used with non localhost address.
         '';
       };
diff --git a/nixos/modules/services/security/usbguard.nix b/nixos/modules/services/security/usbguard.nix
index 201b37f17ba..1b1fa84c4fa 100644
--- a/nixos/modules/services/security/usbguard.nix
+++ b/nixos/modules/services/security/usbguard.nix
@@ -39,15 +39,15 @@ in
 
   options = {
     services.usbguard = {
-      enable = mkEnableOption "USBGuard daemon";
+      enable = mkEnableOption (lib.mdDoc "USBGuard daemon");
 
       package = mkOption {
         type = types.package;
         default = pkgs.usbguard;
         defaultText = literalExpression "pkgs.usbguard";
-        description = ''
+        description = lib.mdDoc ''
           The usbguard package to use. If you do not need the Qt GUI, use
-          <literal>pkgs.usbguard-nox</literal> to save disk space.
+          `pkgs.usbguard-nox` to save disk space.
         '';
       };
 
@@ -57,28 +57,26 @@ in
         example = ''
           allow with-interface equals { 08:*:* }
         '';
-        description = ''
+        description = lib.mdDoc ''
           The USBGuard daemon will load this as the policy rule set.
           As these rules are NixOS managed they are immutable and can't
           be changed by the IPC interface.
 
           If you do not set this option, the USBGuard daemon will load
-          it's policy rule set from <literal>${defaultRuleFile}</literal>.
+          it's policy rule set from `${defaultRuleFile}`.
           This file can be changed manually or via the IPC interface.
 
-          Running <literal>usbguard generate-policy</literal> as root will
+          Running `usbguard generate-policy` as root will
           generate a config for your currently plugged in devices.
 
-          For more details see <citerefentry>
-          <refentrytitle>usbguard-rules.conf</refentrytitle>
-          <manvolnum>5</manvolnum></citerefentry>.
+          For more details see {manpage}`usbguard-rules.conf(5)`.
         '';
       };
 
       implictPolicyTarget = mkOption {
         type = policy;
         default = "block";
-        description = ''
+        description = lib.mdDoc ''
           How to treat USB devices that don't match any rule in the policy.
           Target should be one of allow, block or reject (logically remove the
           device node from the system).
@@ -88,7 +86,7 @@ in
       presentDevicePolicy = mkOption {
         type = policy;
         default = "apply-policy";
-        description = ''
+        description = lib.mdDoc ''
           How to treat USB devices that are already connected when the daemon
           starts. Policy should be one of allow, block, reject, keep (keep
           whatever state the device is currently in) or apply-policy (evaluate
@@ -99,7 +97,7 @@ in
       presentControllerPolicy = mkOption {
         type = policy;
         default = "keep";
-        description = ''
+        description = lib.mdDoc ''
           How to treat USB controller devices that are already connected when
           the daemon starts. One of allow, block, reject, keep or apply-policy.
         '';
@@ -108,7 +106,7 @@ in
       insertedDevicePolicy = mkOption {
         type = policy;
         default = "apply-policy";
-        description = ''
+        description = lib.mdDoc ''
           How to treat USB devices that are already connected after the daemon
           starts. One of block, reject, apply-policy.
         '';
@@ -117,7 +115,7 @@ in
       restoreControllerDeviceState = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           The  USBGuard  daemon  modifies  some attributes of controller
           devices like the default authorization state of new child device
           instances. Using this setting, you can controll whether the daemon
@@ -130,7 +128,7 @@ in
         type = types.listOf types.str;
         default = [ "root" ];
         example = [ "root" "yourusername" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of usernames that the daemon will accept IPC connections from.
         '';
       };
@@ -139,7 +137,7 @@ in
         type = types.listOf types.str;
         default = [ ];
         example = [ "wheel" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of groupnames that the daemon will accept IPC connections
           from.
         '';
@@ -148,7 +146,7 @@ in
       deviceRulesWithPort = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Generate device specific rules including the "via-port" attribute.
         '';
       };
diff --git a/nixos/modules/services/security/vault.nix b/nixos/modules/services/security/vault.nix
index d48bc472cb8..7b9e31a8d99 100644
--- a/nixos/modules/services/security/vault.nix
+++ b/nixos/modules/services/security/vault.nix
@@ -7,6 +7,8 @@ let
   opt = options.services.vault;
 
   configFile = pkgs.writeText "vault.hcl" ''
+    # vault in dev mode will refuse to start if its configuration sets listener
+    ${lib.optionalString (!cfg.dev) ''
     listener "tcp" {
       address = "${cfg.address}"
       ${if (cfg.tlsCertFile == null || cfg.tlsKeyFile == null) then ''
@@ -17,6 +19,7 @@ let
         ''}
       ${cfg.listenerExtraConfig}
     }
+    ''}
     storage "${cfg.storageBackend}" {
       ${optionalString (cfg.storagePath   != null) ''path = "${cfg.storagePath}"''}
       ${optionalString (cfg.storageConfig != null) cfg.storageConfig}
@@ -30,41 +33,59 @@ let
   '';
 
   allConfigPaths = [configFile] ++ cfg.extraSettingsPaths;
-
-  configOptions = escapeShellArgs (concatMap (p: ["-config" p]) allConfigPaths);
+  configOptions = escapeShellArgs
+    (lib.optional cfg.dev "-dev" ++
+     lib.optional (cfg.dev && cfg.devRootTokenID != null) "-dev-root-token-id=${cfg.devRootTokenID}"
+      ++ (concatMap (p: ["-config" p]) allConfigPaths));
 
 in
 
 {
   options = {
     services.vault = {
-      enable = mkEnableOption "Vault daemon";
+      enable = mkEnableOption (lib.mdDoc "Vault daemon");
 
       package = mkOption {
         type = types.package;
         default = pkgs.vault;
         defaultText = literalExpression "pkgs.vault";
-        description = "This option specifies the vault package to use.";
+        description = lib.mdDoc "This option specifies the vault package to use.";
+      };
+
+      dev = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          In this mode, Vault runs in-memory and starts unsealed. This option is not meant production but for development and testing i.e. for nixos tests.
+        '';
+      };
+
+      devRootTokenID = mkOption {
+        type = types.str;
+        default = false;
+        description = lib.mdDoc ''
+          Initial root token. This only applies when {option}`services.vault.dev` is true
+        '';
       };
 
       address = mkOption {
         type = types.str;
         default = "127.0.0.1:8200";
-        description = "The name of the ip interface to listen to";
+        description = lib.mdDoc "The name of the ip interface to listen to";
       };
 
       tlsCertFile = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "/path/to/your/cert.pem";
-        description = "TLS certificate file. TLS will be disabled unless this option is set";
+        description = lib.mdDoc "TLS certificate file. TLS will be disabled unless this option is set";
       };
 
       tlsKeyFile = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "/path/to/your/key.pem";
-        description = "TLS private key file. TLS will be disabled unless this option is set";
+        description = lib.mdDoc "TLS private key file. TLS will be disabled unless this option is set";
       };
 
       listenerExtraConfig = mkOption {
@@ -72,65 +93,65 @@ in
         default = ''
           tls_min_version = "tls12"
         '';
-        description = "Extra text appended to the listener section.";
+        description = lib.mdDoc "Extra text appended to the listener section.";
       };
 
       storageBackend = mkOption {
         type = types.enum [ "inmem" "file" "consul" "zookeeper" "s3" "azure" "dynamodb" "etcd" "mssql" "mysql" "postgresql" "swift" "gcs" "raft" ];
         default = "inmem";
-        description = "The name of the type of storage backend";
+        description = lib.mdDoc "The name of the type of storage backend";
       };
 
       storagePath = mkOption {
         type = types.nullOr types.path;
-        default = if cfg.storageBackend == "file" then "/var/lib/vault" else null;
+        default = if cfg.storageBackend == "file" || cfg.storageBackend == "raft" then "/var/lib/vault" else null;
         defaultText = literalExpression ''
-          if config.${opt.storageBackend} == "file"
+          if config.${opt.storageBackend} == "file" || cfg.storageBackend == "raft"
           then "/var/lib/vault"
           else null
         '';
-        description = "Data directory for file backend";
+        description = lib.mdDoc "Data directory for file backend";
       };
 
       storageConfig = mkOption {
         type = types.nullOr types.lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           HCL configuration to insert in the storageBackend section.
 
           Confidential values should not be specified here because this option's
           value is written to the Nix store, which is publicly readable.
           Provide credentials and such in a separate file using
-          <xref linkend="opt-services.vault.extraSettingsPaths"/>.
+          [](#opt-services.vault.extraSettingsPaths).
         '';
       };
 
       telemetryConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Telemetry configuration";
+        description = lib.mdDoc "Telemetry configuration";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Extra text appended to <filename>vault.hcl</filename>.";
+        description = lib.mdDoc "Extra text appended to {file}`vault.hcl`.";
       };
 
       extraSettingsPaths = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Configuration files to load besides the immutable one defined by the NixOS module.
           This can be used to avoid putting credentials in the Nix store, which can be read by any user.
 
           Each path can point to a JSON- or HCL-formatted file, or a directory
-          to be scanned for files with <literal>.hcl</literal> or
-          <literal>.json</literal> extensions.
+          to be scanned for files with `.hcl` or
+          `.json` extensions.
 
           To upload the confidential file with NixOps, use for example:
 
-          <programlisting><![CDATA[
+          ```
           # https://releases.nixos.org/nixops/latest/manual/manual.html#opt-deployment.keys
           deployment.keys."vault.hcl" = let db = import ./db-credentials.nix; in {
             text = ${"''"}
@@ -143,7 +164,7 @@ in
           services.vault.extraSettingsPaths = ["/run/keys/vault.hcl"];
           services.vault.storageBackend = "postgresql";
           users.users.vault.extraGroups = ["keys"];
-          ]]></programlisting>
+          ```
         '';
       };
     };
@@ -151,11 +172,16 @@ in
 
   config = mkIf cfg.enable {
     assertions = [
-      { assertion = cfg.storageBackend == "inmem" -> (cfg.storagePath == null && cfg.storageConfig == null);
+      {
+        assertion = cfg.storageBackend == "inmem" -> (cfg.storagePath == null && cfg.storageConfig == null);
         message = ''The "inmem" storage expects no services.vault.storagePath nor services.vault.storageConfig'';
       }
-      { assertion = (cfg.storageBackend == "file" -> (cfg.storagePath != null && cfg.storageConfig == null)) && (cfg.storagePath != null -> cfg.storageBackend == "file");
-        message = ''You must set services.vault.storagePath only when using the "file" backend'';
+      {
+        assertion = (
+          (cfg.storageBackend == "file" -> (cfg.storagePath != null && cfg.storageConfig == null)) &&
+          (cfg.storagePath != null -> (cfg.storageBackend == "file" || cfg.storageBackend == "raft"))
+        );
+        message = ''You must set services.vault.storagePath only when using the "file" or "raft" backend'';
       }
     ];
 
@@ -186,6 +212,9 @@ in
         Group = "vault";
         ExecStart = "${cfg.package}/bin/vault server ${configOptions}";
         ExecReload = "${pkgs.coreutils}/bin/kill -SIGHUP $MAINPID";
+        StateDirectory = "vault";
+        # In `dev` mode vault will put its token here
+        Environment = lib.optional (cfg.dev) "HOME=/var/lib/vault";
         PrivateDevices = true;
         PrivateTmp = true;
         ProtectSystem = "full";
diff --git a/nixos/modules/services/security/vaultwarden/default.nix b/nixos/modules/services/security/vaultwarden/default.nix
index 8277f493639..3ef0bfb090a 100644
--- a/nixos/modules/services/security/vaultwarden/default.nix
+++ b/nixos/modules/services/security/vaultwarden/default.nix
@@ -22,9 +22,9 @@ let
   # we can only check for values consistently after converting them to their corresponding environment variable name.
   configEnv =
     let
-      configEnv = listToAttrs (concatLists (mapAttrsToList (name: value:
-        if value != null then [ (nameValuePair (nameToEnvVar name) (if isBool value then boolToString value else toString value)) ] else []
-      ) cfg.config));
+      configEnv = concatMapAttrs (name: value: optionalAttrs (value != null) {
+        ${nameToEnvVar name} = if isBool value then boolToString value else toString value;
+      }) cfg.config;
     in { DATA_FOLDER = "/var/lib/bitwarden_rs"; } // optionalAttrs (!(configEnv ? WEB_VAULT_ENABLED) || configEnv.WEB_VAULT_ENABLED == "true") {
       WEB_VAULT_FOLDER = "${cfg.webVaultPackage}/share/vaultwarden/vault";
     } // configEnv;
@@ -39,12 +39,12 @@ in {
   ];
 
   options.services.vaultwarden = with types; {
-    enable = mkEnableOption "vaultwarden";
+    enable = mkEnableOption (lib.mdDoc "vaultwarden");
 
     dbBackend = mkOption {
       type = enum [ "sqlite" "mysql" "postgresql" ];
       default = "sqlite";
-      description = ''
+      description = lib.mdDoc ''
         Which database backend vaultwarden will be using.
       '';
     };
@@ -52,7 +52,7 @@ in {
     backupDir = mkOption {
       type = nullOr str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The directory under which vaultwarden will backup its persistent data.
       '';
     };
@@ -62,44 +62,94 @@ in {
       default = {};
       example = literalExpression ''
         {
-          domain = "https://bw.domain.tld:8443";
-          signupsAllowed = true;
-          rocketPort = 8222;
-          rocketLog = "critical";
+          DOMAIN = "https://bitwarden.example.com";
+          SIGNUPS_ALLOWED = false;
+
+          # Vaultwarden currently recommends running behind a reverse proxy
+          # (nginx or similar) for TLS termination, see
+          # https://github.com/dani-garcia/vaultwarden/wiki/Hardening-Guide#reverse-proxying
+          # > you should avoid enabling HTTPS via vaultwarden's built-in Rocket TLS support,
+          # > especially if your instance is publicly accessible.
+          #
+          # A suitable NixOS nginx reverse proxy example config might be:
+          #
+          #     services.nginx.virtualHosts."bitwarden.example.com" = {
+          #       enableACME = true;
+          #       forceSSL = true;
+          #       locations."/" = {
+          #         proxyPass = "http://127.0.0.1:''${toString config.services.vaultwarden.config.ROCKET_PORT}";
+          #       };
+          #     };
+          ROCKET_ADDRESS = "127.0.0.1";
+          ROCKET_PORT = 8222;
+
+          ROCKET_LOG = "critical";
+
+          # This example assumes a mailserver running on localhost,
+          # thus without transport encryption.
+          # If you use an external mail server, follow:
+          #   https://github.com/dani-garcia/vaultwarden/wiki/SMTP-configuration
+          SMTP_HOST = "127.0.0.1";
+          SMTP_PORT = 25;
+          SMTP_SSL = false;
+
+          SMTP_FROM = "admin@bitwarden.example.com";
+          SMTP_FROM_NAME = "example.com Bitwarden server";
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         The configuration of vaultwarden is done through environment variables,
-        therefore the names are converted from camel case (e.g. disable2FARemember)
-        to upper case snake case (e.g. DISABLE_2FA_REMEMBER).
+        therefore it is recommended to use upper snake case (e.g. {env}`DISABLE_2FA_REMEMBER`).
+
+        However, camel case (e.g. `disable2FARemember`) is also supported:
+        The NixOS module will convert it automatically to
+        upper case snake case (e.g. {env}`DISABLE_2FA_REMEMBER`).
         In this conversion digits (0-9) are handled just like upper case characters,
-        so foo2 would be converted to FOO_2.
-        Names already in this format remain unchanged, so FOO2 remains FOO2 if passed as such,
-        even though foo2 would have been converted to FOO_2.
+        so `foo2` would be converted to {env}`FOO_2`.
+        Names already in this format remain unchanged, so `FOO2` remains `FOO2` if passed as such,
+        even though `foo2` would have been converted to {env}`FOO_2`.
         This allows working around any potential future conflicting naming conventions.
 
         Based on the attributes passed to this config option an environment file will be generated
         that is passed to vaultwarden's systemd service.
 
         The available configuration options can be found in
-        <link xlink:href="https://github.com/dani-garcia/vaultwarden/blob/${vaultwarden.version}/.env.template">the environment template file</link>.
+        [the environment template file](https://github.com/dani-garcia/vaultwarden/blob/${vaultwarden.version}/.env.template).
+
+        See ()[#opt-services.vaultwarden.environmentFile) for how
+        to set up access to the Admin UI to invite initial users.
       '';
     };
 
     environmentFile = mkOption {
       type = with types; nullOr path;
       default = null;
-      example = "/root/vaultwarden.env";
-      description = ''
-        Additional environment file as defined in <citerefentry>
-        <refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum>
-        </citerefentry>.
+      example = "/var/lib/vaultwarden.env";
+      description = lib.mdDoc ''
+        Additional environment file as defined in {manpage}`systemd.exec(5)`.
 
-        Secrets like <envar>ADMIN_TOKEN</envar> and <envar>SMTP_PASSWORD</envar>
+        Secrets like {env}`ADMIN_TOKEN` and {env}`SMTP_PASSWORD`
         may be passed to the service without adding them to the world-readable Nix store.
 
         Note that this file needs to be available on the host on which
-        <literal>vaultwarden</literal> is running.
+        `vaultwarden` is running.
+
+        As a concrete example, to make the Admin UI available
+        (from which new users can be invited initially),
+        the secret {env}`ADMIN_TOKEN` needs to be defined as described
+        [here](https://github.com/dani-garcia/vaultwarden/wiki/Enabling-admin-page).
+        Setting `environmentFile` to `/var/lib/vaultwarden.env`
+        and ensuring permissions with e.g.
+        `chown vaultwarden:vaultwarden /var/lib/vaultwarden.env`
+        (the `vaultwarden` user will only exist after activating with
+        `enable = true;` before this), we can set the contents of the file to have
+        contents such as:
+
+        ```
+        # Admin secret token, see
+        # https://github.com/dani-garcia/vaultwarden/wiki/Enabling-admin-page
+        ADMIN_TOKEN=...copy-paste a unique generated secret token here...
+        ```
       '';
     };
 
@@ -107,14 +157,14 @@ in {
       type = package;
       default = pkgs.vaultwarden;
       defaultText = literalExpression "pkgs.vaultwarden";
-      description = "Vaultwarden package to use.";
+      description = lib.mdDoc "Vaultwarden package to use.";
     };
 
     webVaultPackage = mkOption {
       type = package;
       default = pkgs.vaultwarden-vault;
       defaultText = literalExpression "pkgs.vaultwarden-vault";
-      description = "Web vault package to use.";
+      description = lib.mdDoc "Web vault package to use.";
     };
   };
 
@@ -146,6 +196,8 @@ in {
         ProtectSystem = "strict";
         AmbientCapabilities = "CAP_NET_BIND_SERVICE";
         StateDirectory = "bitwarden_rs";
+        StateDirectoryMode = "0700";
+        Restart = "always";
       };
       wantedBy = [ "multi-user.target" ];
     };
@@ -158,6 +210,8 @@ in {
         BACKUP_FOLDER = cfg.backupDir;
       };
       path = with pkgs; [ sqlite ];
+      # if both services are started at the same time, vaultwarden fails with "database is locked"
+      before = [ "vaultwarden.service" ];
       serviceConfig = {
         SyslogIdentifier = "backup-vaultwarden";
         Type = "oneshot";
@@ -169,7 +223,7 @@ in {
     };
 
     systemd.timers.backup-vaultwarden = mkIf (cfg.backupDir != null) {
-      aliases = [ "backup-bitwarden_rs.service" ];
+      aliases = [ "backup-bitwarden_rs.timer" ];
       description = "Backup vaultwarden on time";
       timerConfig = {
         OnCalendar = mkDefault "23:00";
diff --git a/nixos/modules/services/security/yubikey-agent.nix b/nixos/modules/services/security/yubikey-agent.nix
index 8be2457e1e2..c91ff3e69a0 100644
--- a/nixos/modules/services/security/yubikey-agent.nix
+++ b/nixos/modules/services/security/yubikey-agent.nix
@@ -21,7 +21,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to start yubikey-agent when you log in.  Also sets
           SSH_AUTH_SOCK to point at yubikey-agent.
 
@@ -34,7 +34,7 @@ in
         type = types.package;
         default = pkgs.yubikey-agent;
         defaultText = literalExpression "pkgs.yubikey-agent";
-        description = ''
+        description = lib.mdDoc ''
           The package used for the yubikey-agent daemon.
         '';
       };
diff --git a/nixos/modules/services/system/automatic-timezoned.nix b/nixos/modules/services/system/automatic-timezoned.nix
new file mode 100644
index 00000000000..9bdd64dd33a
--- /dev/null
+++ b/nixos/modules/services/system/automatic-timezoned.nix
@@ -0,0 +1,92 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.automatic-timezoned;
+in
+{
+  options = {
+    services.automatic-timezoned = {
+      enable = mkOption {
+        type = types.bool;
+        default = false;
+        description = mdDoc ''
+          Enable `automatic-timezoned`, simple daemon for keeping the system
+          timezone up-to-date based on the current location. It uses geoclue2 to
+          determine the current location and systemd-timedated to actually set
+          the timezone.
+        '';
+      };
+      package = mkOption {
+        type = types.package;
+        default = pkgs.automatic-timezoned;
+        defaultText = literalExpression "pkgs.automatic-timezoned";
+        description = mdDoc ''
+          Which `automatic-timezoned` package to use.
+        '';
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    security.polkit.extraConfig = ''
+      polkit.addRule(function(action, subject) {
+        if (action.id == "org.freedesktop.timedate1.set-timezone"
+            && subject.user == "automatic-timezoned") {
+          return polkit.Result.YES;
+        }
+      });
+    '';
+
+    services.geoclue2 = {
+      enable = true;
+      appConfig.automatic-timezoned = {
+        isAllowed = true;
+        isSystem = true;
+        users = [ (toString config.ids.uids.automatic-timezoned) ];
+      };
+    };
+
+    systemd.services = {
+
+      automatic-timezoned = {
+        description = "Automatically update system timezone based on location";
+        requires = [ "automatic-timezoned-geoclue-agent.service" ];
+        after = [ "automatic-timezoned-geoclue-agent.service" ];
+        serviceConfig = {
+          Type = "exec";
+          User = "automatic-timezoned";
+          ExecStart = "${cfg.package}/bin/automatic-timezoned --zoneinfo-path=${pkgs.tzdata}/share/zoneinfo/zone1970.tab";
+        };
+        wantedBy = [ "default.target" ];
+      };
+
+      automatic-timezoned-geoclue-agent = {
+        description = "Geoclue agent for automatic-timezoned";
+        requires = [ "geoclue.service" ];
+        after = [ "geoclue.service" ];
+        serviceConfig = {
+          Type = "exec";
+          User = "automatic-timezoned";
+          ExecStart = "${pkgs.geoclue2-with-demo-agent}/libexec/geoclue-2.0/demos/agent";
+          Restart = "on-failure";
+          PrivateTmp = true;
+        };
+        wantedBy = [ "default.target" ];
+      };
+
+    };
+
+    users = {
+      users.automatic-timezoned = {
+        description = "automatic-timezoned";
+        uid = config.ids.uids.automatic-timezoned;
+        group = "automatic-timezoned";
+      };
+      groups.automatic-timezoned = {
+        gid = config.ids.gids.automatic-timezoned;
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/system/cachix-agent/default.nix b/nixos/modules/services/system/cachix-agent/default.nix
index 496e0b90355..aa3b2153422 100644
--- a/nixos/modules/services/system/cachix-agent/default.nix
+++ b/nixos/modules/services/system/cachix-agent/default.nix
@@ -8,32 +8,44 @@ in {
   meta.maintainers = [ lib.maintainers.domenkozar ];
 
   options.services.cachix-agent = {
-    enable = mkEnableOption "Cachix Deploy Agent: https://docs.cachix.org/deploy/";
+    enable = mkEnableOption (lib.mdDoc "Cachix Deploy Agent: https://docs.cachix.org/deploy/");
 
     name = mkOption {
       type = types.str;
-      description = "Agent name, usually same as the hostname";
+      description = lib.mdDoc "Agent name, usually same as the hostname";
       default = config.networking.hostName;
       defaultText = "config.networking.hostName";
     };
 
+    verbose = mkOption {
+      type = types.bool;
+      description = lib.mdDoc "Enable verbose output";
+      default = false;
+    };
+
     profile = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = "Profile name, defaults to 'system' (NixOS).";
+      description = lib.mdDoc "Profile name, defaults to 'system' (NixOS).";
+    };
+
+    host = mkOption {
+      type = types.nullOr types.str;
+      default = null;
+      description = lib.mdDoc "Cachix uri to use.";
     };
 
     package = mkOption {
       type = types.package;
       default = pkgs.cachix;
       defaultText = literalExpression "pkgs.cachix";
-      description = "Cachix Client package to use.";
+      description = lib.mdDoc "Cachix Client package to use.";
     };
 
     credentialsFile = mkOption {
       type = types.path;
       default = "/etc/cachix-agent.token";
-      description = ''
+      description = lib.mdDoc ''
         Required file that needs to contain CACHIX_AGENT_TOKEN=...
       '';
     };
@@ -45,12 +57,22 @@ in {
       after = ["network-online.target"];
       path = [ config.nix.package ];
       wantedBy = [ "multi-user.target" ];
-      # don't restart while changing
-      reloadIfChanged = true;
+
+      # Cachix requires $USER to be set
+      environment.USER = "root";
+
+      # don't stop the service if the unit disappears
+      unitConfig.X-StopOnRemoval = false;
+
       serviceConfig = {
+        # we don't want to kill children processes as those are deployments
+        KillMode = "process";
         Restart = "on-failure";
         EnvironmentFile = cfg.credentialsFile;
-        ExecStart = "${cfg.package}/bin/cachix deploy agent ${cfg.name} ${if cfg.profile != null then profile else ""}";
+        ExecStart = ''
+          ${cfg.package}/bin/cachix ${lib.optionalString cfg.verbose "--verbose"} ${lib.optionalString (cfg.host != null) "--host ${cfg.host}"} \
+            deploy agent ${cfg.name} ${if cfg.profile != null then cfg.profile else ""}
+        '';
       };
     };
   };
diff --git a/nixos/modules/services/system/cachix-watch-store.nix b/nixos/modules/services/system/cachix-watch-store.nix
new file mode 100644
index 00000000000..ec73c0bcdcf
--- /dev/null
+++ b/nixos/modules/services/system/cachix-watch-store.nix
@@ -0,0 +1,87 @@
+{ config, pkgs, lib, ... }:
+
+with lib;
+
+let
+  cfg = config.services.cachix-watch-store;
+in
+{
+  meta.maintainers = [ lib.maintainers.jfroche lib.maintainers.domenkozar ];
+
+  options.services.cachix-watch-store = {
+    enable = mkEnableOption (lib.mdDoc "Cachix Watch Store: https://docs.cachix.org");
+
+    cacheName = mkOption {
+      type = types.str;
+      description = lib.mdDoc "Cachix binary cache name";
+    };
+
+    cachixTokenFile = mkOption {
+      type = types.path;
+      description = lib.mdDoc ''
+        Required file that needs to contain the cachix auth token.
+      '';
+    };
+
+    compressionLevel = mkOption {
+      type = types.nullOr types.int;
+      description = lib.mdDoc "The compression level for XZ compression (between 0 and 9)";
+      default = null;
+    };
+
+    jobs = mkOption {
+      type = types.nullOr types.int;
+      description = lib.mdDoc "Number of threads used for pushing store paths";
+      default = null;
+    };
+
+    host = mkOption {
+      type = types.nullOr types.str;
+      default = null;
+      description = lib.mdDoc "Cachix host to connect to";
+    };
+
+    verbose = mkOption {
+      type = types.bool;
+      description = lib.mdDoc "Enable verbose output";
+      default = false;
+    };
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.cachix;
+      defaultText = literalExpression "pkgs.cachix";
+      description = lib.mdDoc "Cachix Client package to use.";
+    };
+
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.cachix-watch-store-agent = {
+      description = "Cachix watch store Agent";
+      after = [ "network-online.target" ];
+      path = [ config.nix.package ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        # we don't want to kill children processes as those are deployments
+        KillMode = "process";
+        Restart = "on-failure";
+        DynamicUser = true;
+        LoadCredential = [
+          "cachix-token:${toString cfg.cachixTokenFile}"
+        ];
+      };
+      script =
+        let
+          command = [ "${cfg.package}/bin/cachix" ]
+            ++ (lib.optional cfg.verbose "--verbose") ++ (lib.optionals (cfg.host != null) [ "--host" cfg.host ])
+            ++ [ "watch-store" ] ++ (lib.optionals (cfg.compressionLevel != null) [ "--compression-level" (toString cfg.compressionLevel) ])
+            ++ (lib.optionals (cfg.jobs != null) [ "--jobs" (toString cfg.jobs) ]) ++ [ cfg.cacheName ];
+        in
+        ''
+          export CACHIX_AUTH_TOKEN="$(<"$CREDENTIALS_DIRECTORY/cachix-token")"
+          ${lib.escapeShellArgs command}
+        '';
+    };
+  };
+}
diff --git a/nixos/modules/services/system/cloud-init.nix b/nixos/modules/services/system/cloud-init.nix
index 8c6a6e294eb..30b2ca568e1 100644
--- a/nixos/modules/services/system/cloud-init.nix
+++ b/nixos/modules/services/system/cloud-init.nix
@@ -20,7 +20,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the cloud-init service. This services reads
           configuration metadata in a cloud environment and configures
           the machine according to this metadata.
@@ -39,7 +39,7 @@ in
       btrfs.enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Allow the cloud-init service to operate `btrfs` filesystem.
         '';
       };
@@ -47,7 +47,7 @@ in
       ext4.enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Allow the cloud-init service to operate `ext4` filesystem.
         '';
       };
@@ -55,7 +55,7 @@ in
       network.enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Allow the cloud-init service to configure network interfaces
           through systemd-networkd.
         '';
@@ -81,7 +81,8 @@ in
            - write-files
            - growpart
            - resizefs
-           - update_etc_hosts
+           - update_hostname
+           - resolv_conf
            - ca-certs
            - rsyslog
            - users-groups
@@ -109,7 +110,7 @@ in
            - final-message
            - power-state-change
           '';
-        description = "cloud-init configuration.";
+        description = lib.mdDoc "cloud-init configuration.";
       };
 
     };
diff --git a/nixos/modules/services/system/dbus.nix b/nixos/modules/services/system/dbus.nix
index d4cacb85694..c677088101f 100644
--- a/nixos/modules/services/system/dbus.nix
+++ b/nixos/modules/services/system/dbus.nix
@@ -1,8 +1,6 @@
 # D-Bus configuration and system bus daemon.
 
-{ config, lib, options, pkgs, ... }:
-
-with lib;
+{ config, lib, pkgs, ... }:
 
 let
 
@@ -16,11 +14,11 @@ let
     serviceDirectories = cfg.packages;
   };
 
+  inherit (lib) mkOption mkIf mkMerge types;
+
 in
 
 {
-  ###### interface
-
   options = {
 
     services.dbus = {
@@ -29,111 +27,165 @@ in
         type = types.bool;
         default = false;
         internal = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to start the D-Bus message bus daemon, which is
           required by many other system services and applications.
         '';
       };
 
+      implementation = mkOption {
+        type = types.enum [ "dbus" "broker" ];
+        default = "dbus";
+        description = lib.mdDoc ''
+          The implementation to use for the message bus defined by the D-Bus specification.
+          Can be either the classic dbus daemon or dbus-broker, which aims to provide high
+          performance and reliability, while keeping compatibility to the D-Bus
+          reference implementation.
+        '';
+
+      };
+
       packages = mkOption {
         type = types.listOf types.path;
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           Packages whose D-Bus configuration files should be included in
           the configuration of the D-Bus system-wide or session-wide
           message bus.  Specifically, files in the following directories
           will be included into their respective DBus configuration paths:
-          <filename><replaceable>pkg</replaceable>/etc/dbus-1/system.d</filename>
-          <filename><replaceable>pkg</replaceable>/share/dbus-1/system.d</filename>
-          <filename><replaceable>pkg</replaceable>/share/dbus-1/system-services</filename>
-          <filename><replaceable>pkg</replaceable>/etc/dbus-1/session.d</filename>
-          <filename><replaceable>pkg</replaceable>/share/dbus-1/session.d</filename>
-          <filename><replaceable>pkg</replaceable>/share/dbus-1/services</filename>
+          {file}`«pkg»/etc/dbus-1/system.d`
+          {file}`«pkg»/share/dbus-1/system.d`
+          {file}`«pkg»/share/dbus-1/system-services`
+          {file}`«pkg»/etc/dbus-1/session.d`
+          {file}`«pkg»/share/dbus-1/session.d`
+          {file}`«pkg»/share/dbus-1/services`
         '';
       };
 
       apparmor = mkOption {
         type = types.enum [ "enabled" "disabled" "required" ];
-        description = ''
+        description = lib.mdDoc ''
           AppArmor mode for dbus.
 
-          <literal>enabled</literal> enables mediation when it's
-          supported in the kernel, <literal>disabled</literal>
+          `enabled` enables mediation when it's
+          supported in the kernel, `disabled`
           always disables AppArmor even with kernel support, and
-          <literal>required</literal> fails when AppArmor was not found
+          `required` fails when AppArmor was not found
           in the kernel.
         '';
         default = "disabled";
       };
-
-      socketActivated = mkOption {
-        type = types.nullOr types.bool;
-        default = null;
-        visible = false;
-        description = ''
-          Removed option, do not use.
-        '';
-      };
     };
   };
 
-  ###### implementation
+  config = mkIf cfg.enable (mkMerge [
+    {
+      environment.etc."dbus-1".source = configDir;
 
-  config = mkIf cfg.enable {
-    warnings = optional (cfg.socketActivated != null) (
-      let
-        files = showFiles options.services.dbus.socketActivated.files;
-      in
-        "The option 'services.dbus.socketActivated' in ${files} no longer has"
-        + " any effect and can be safely removed: the user D-Bus session is"
-        + " now always socket activated."
-    );
+      environment.pathsToLink = [
+        "/etc/dbus-1"
+        "/share/dbus-1"
+      ];
 
-    environment.systemPackages = [ pkgs.dbus.daemon pkgs.dbus ];
+      users.users.messagebus = {
+        uid = config.ids.uids.messagebus;
+        description = "D-Bus system message bus daemon user";
+        home = homeDir;
+        group = "messagebus";
+      };
 
-    environment.etc."dbus-1".source = configDir;
+      users.groups.messagebus.gid = config.ids.gids.messagebus;
+
+      # You still need the dbus reference implementation installed to use dbus-broker
+      systemd.packages = [
+        pkgs.dbus
+      ];
+
+      services.dbus.packages = [
+        pkgs.dbus
+        config.system.path
+      ];
+
+      systemd.user.sockets.dbus.wantedBy = [
+        "sockets.target"
+      ];
+    }
+
+    (mkIf (cfg.implementation == "dbus") {
+      environment.systemPackages = [
+        pkgs.dbus
+      ];
+
+      security.wrappers.dbus-daemon-launch-helper = {
+        source = "${pkgs.dbus}/libexec/dbus-daemon-launch-helper";
+        owner = "root";
+        group = "messagebus";
+        setuid = true;
+        setgid = false;
+        permissions = "u+rx,g+rx,o-rx";
+      };
 
-    users.users.messagebus = {
-      uid = config.ids.uids.messagebus;
-      description = "D-Bus system message bus daemon user";
-      home = homeDir;
-      group = "messagebus";
-    };
+      systemd.services.dbus = {
+        # Don't restart dbus-daemon. Bad things tend to happen if we do.
+        reloadIfChanged = true;
+        restartTriggers = [
+          configDir
+        ];
+        environment = {
+          LD_LIBRARY_PATH = config.system.nssModules.path;
+        };
+      };
 
-    users.groups.messagebus.gid = config.ids.gids.messagebus;
+      systemd.user.services.dbus = {
+        # Don't restart dbus-daemon. Bad things tend to happen if we do.
+        reloadIfChanged = true;
+        restartTriggers = [
+          configDir
+        ];
+      };
 
-    systemd.packages = [ pkgs.dbus.daemon ];
+    })
 
-    security.wrappers.dbus-daemon-launch-helper = {
-      source = "${pkgs.dbus.daemon}/libexec/dbus-daemon-launch-helper";
-      owner = "root";
-      group = "messagebus";
-      setuid = true;
-      setgid = false;
-      permissions = "u+rx,g+rx,o-rx";
-    };
+    (mkIf (cfg.implementation == "broker") {
+      environment.systemPackages = [
+        pkgs.dbus-broker
+      ];
 
-    services.dbus.packages = [
-      pkgs.dbus.out
-      config.system.path
-    ];
+      systemd.packages = [
+        pkgs.dbus-broker
+      ];
 
-    systemd.services.dbus = {
-      # Don't restart dbus-daemon. Bad things tend to happen if we do.
-      reloadIfChanged = true;
-      restartTriggers = [ configDir ];
-      environment = { LD_LIBRARY_PATH = config.system.nssModules.path; };
-    };
+      # Just to be sure we don't restart through the unit alias
+      systemd.services.dbus.reloadIfChanged = true;
+      systemd.user.services.dbus.reloadIfChanged = true;
 
-    systemd.user = {
-      services.dbus = {
-        # Don't restart dbus-daemon. Bad things tend to happen if we do.
+      # NixOS Systemd Module doesn't respect 'Install'
+      # https://github.com/NixOS/nixpkgs/issues/108643
+      systemd.services.dbus-broker = {
+        aliases = [
+          "dbus.service"
+        ];
+        # Don't restart dbus. Bad things tend to happen if we do.
         reloadIfChanged = true;
-        restartTriggers = [ configDir ];
+        restartTriggers = [
+          configDir
+        ];
+        environment = {
+          LD_LIBRARY_PATH = config.system.nssModules.path;
+        };
       };
-      sockets.dbus.wantedBy = [ "sockets.target" ];
-    };
 
-    environment.pathsToLink = [ "/etc/dbus-1" "/share/dbus-1" ];
-  };
+      systemd.user.services.dbus-broker = {
+        aliases = [
+          "dbus.service"
+        ];
+        # Don't restart dbus. Bad things tend to happen if we do.
+        reloadIfChanged = true;
+        restartTriggers = [
+          configDir
+        ];
+      };
+    })
+
+  ]);
 }
diff --git a/nixos/modules/services/system/earlyoom.nix b/nixos/modules/services/system/earlyoom.nix
index 62935855989..3f501d45346 100644
--- a/nixos/modules/services/system/earlyoom.nix
+++ b/nixos/modules/services/system/earlyoom.nix
@@ -11,60 +11,60 @@ let
 in
 {
   options.services.earlyoom = {
-    enable = mkEnableOption "Early out of memory killing";
+    enable = mkEnableOption (lib.mdDoc "Early out of memory killing");
 
     freeMemThreshold = mkOption {
       type = types.ints.between 1 100;
       default = 10;
-      description = ''
+      description = lib.mdDoc ''
         Minimum available memory (in percent).
 
         If the available memory falls below this threshold (and the analog is true for
-        <option>freeSwapThreshold</option>) the killing begins.
+        {option}`freeSwapThreshold`) the killing begins.
         SIGTERM is sent first to the process that uses the most memory; then, if the available
-        memory falls below <option>freeMemKillThreshold</option> (and the analog is true for
-        <option>freeSwapKillThreshold</option>), SIGKILL is sent.
+        memory falls below {option}`freeMemKillThreshold` (and the analog is true for
+        {option}`freeSwapKillThreshold`), SIGKILL is sent.
 
-        See <link xlink:href="https://github.com/rfjakob/earlyoom#command-line-options">README</link> for details.
+        See [README](https://github.com/rfjakob/earlyoom#command-line-options) for details.
       '';
     };
 
     freeMemKillThreshold = mkOption {
       type = types.nullOr (types.ints.between 1 100);
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Minimum available memory (in percent) before sending SIGKILL.
-        If unset, this defaults to half of <option>freeMemThreshold</option>.
+        If unset, this defaults to half of {option}`freeMemThreshold`.
 
-        See the description of <xref linkend="opt-services.earlyoom.freeMemThreshold"/>.
+        See the description of [](#opt-services.earlyoom.freeMemThreshold).
       '';
     };
 
     freeSwapThreshold = mkOption {
       type = types.ints.between 1 100;
       default = 10;
-      description = ''
+      description = lib.mdDoc ''
         Minimum free swap space (in percent) before sending SIGTERM.
 
-        See the description of <xref linkend="opt-services.earlyoom.freeMemThreshold"/>.
+        See the description of [](#opt-services.earlyoom.freeMemThreshold).
       '';
     };
 
     freeSwapKillThreshold = mkOption {
       type = types.nullOr (types.ints.between 1 100);
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Minimum free swap space (in percent) before sending SIGKILL.
-        If unset, this defaults to half of <option>freeSwapThreshold</option>.
+        If unset, this defaults to half of {option}`freeSwapThreshold`.
 
-        See the description of <xref linkend="opt-services.earlyoom.freeMemThreshold"/>.
+        See the description of [](#opt-services.earlyoom.freeMemThreshold).
       '';
     };
 
     enableDebugInfo = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable debugging messages.
       '';
     };
@@ -72,7 +72,7 @@ in
     enableNotifications = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Send notifications about killed processes via the system d-bus.
 
         WARNING: enabling this option (while convenient) should *not* be done on a
@@ -80,10 +80,10 @@ in
         local user to DoS your session by spamming notifications.
 
         To actually see the notifications in your GUI session, you need to have
-        <literal>systembus-notify</literal> running as your user, which this
-        option handles by enabling <option>services.systembus-notify</option>.
+        `systembus-notify` running as your user, which this
+        option handles by enabling {option}`services.systembus-notify`.
 
-        See <link xlink:href="https://github.com/rfjakob/earlyoom#notifications">README</link> for details.
+        See [README](https://github.com/rfjakob/earlyoom#notifications) for details.
       '';
     };
 
@@ -95,11 +95,11 @@ in
           echo "Process $EARLYOOM_NAME ($EARLYOOM_PID) was killed" >> /path/to/log
         '''
       '';
-      description = ''
+      description = lib.mdDoc ''
         An absolute path to an executable to be run for each process killed.
         Some environment variables are available, see
-        <link xlink:href="https://github.com/rfjakob/earlyoom#notifications">README</link> and
-        <link xlink:href="https://github.com/rfjakob/earlyoom/blob/master/MANPAGE.md#-n-pathtoscript">the man page</link>
+        [README](https://github.com/rfjakob/earlyoom#notifications) and
+        [the man page](https://github.com/rfjakob/earlyoom/blob/master/MANPAGE.md#-n-pathtoscript)
         for details.
       '';
     };
@@ -108,14 +108,14 @@ in
       type = types.int;
       default = 3600;
       example = 0;
-      description = "Interval (in seconds) at which a memory report is printed (set to 0 to disable).";
+      description = lib.mdDoc "Interval (in seconds) at which a memory report is printed (set to 0 to disable).";
     };
 
     extraArgs = mkOption {
       type = types.listOf types.str;
       default = [];
       example = [ "-g" "--prefer '(^|/)(java|chromium)$'" ];
-      description = "Extra command-line arguments to be passed to earlyoom.";
+      description = lib.mdDoc "Extra command-line arguments to be passed to earlyoom.";
     };
   };
 
diff --git a/nixos/modules/services/system/kerberos/default.nix b/nixos/modules/services/system/kerberos/default.nix
index 9a1e6739901..0c9e44a45c1 100644
--- a/nixos/modules/services/system/kerberos/default.nix
+++ b/nixos/modules/services/system/kerberos/default.nix
@@ -9,19 +9,19 @@ let
     options = {
       principal = mkOption {
         type = types.str;
-        description = "Which principal the rule applies to";
+        description = lib.mdDoc "Which principal the rule applies to";
       };
       access = mkOption {
         type = types.either
           (types.listOf (types.enum ["add" "cpw" "delete" "get" "list" "modify"]))
           (types.enum ["all"]);
         default = "all";
-        description = "The changes the principal is allowed to make.";
+        description = lib.mdDoc "The changes the principal is allowed to make.";
       };
       target = mkOption {
         type = types.str;
         default = "*";
-        description = "The principals that 'access' applies to.";
+        description = lib.mdDoc "The principals that 'access' applies to.";
       };
     };
   };
@@ -34,7 +34,7 @@ let
           { principal = "*/admin"; access = "all"; }
           { principal = "admin"; access = "all"; }
         ];
-        description = ''
+        description = lib.mdDoc ''
           The privileges granted to a user.
         '';
       };
@@ -51,11 +51,11 @@ in
   ###### interface
   options = {
     services.kerberos_server = {
-      enable = lib.mkEnableOption "the kerberos authentification server";
+      enable = lib.mkEnableOption (lib.mdDoc "the kerberos authentification server");
 
       realms = mkOption {
         type = types.attrsOf (types.submodule realm);
-        description = ''
+        description = lib.mdDoc ''
           The realm(s) to serve keys for.
         '';
       };
diff --git a/nixos/modules/services/system/localtime.nix b/nixos/modules/services/system/localtime.nix
deleted file mode 100644
index 8f23454af9d..00000000000
--- a/nixos/modules/services/system/localtime.nix
+++ /dev/null
@@ -1,49 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-let
-  cfg = config.services.localtime;
-in {
-  options = {
-    services.localtime = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Enable <literal>localtime</literal>, simple daemon for keeping the system
-          timezone up-to-date based on the current location. It uses geoclue2 to
-          determine the current location and systemd-timedated to actually set
-          the timezone.
-        '';
-      };
-    };
-  };
-
-  config = mkIf cfg.enable {
-    services.geoclue2 = {
-      enable = true;
-      appConfig.localtime = {
-        isAllowed = true;
-        isSystem = true;
-      };
-    };
-
-    # Install the polkit rules.
-    environment.systemPackages = [ pkgs.localtime ];
-    # Install the systemd unit.
-    systemd.packages = [ pkgs.localtime ];
-
-    users.users.localtimed = {
-      description = "localtime daemon";
-      isSystemUser = true;
-      group = "localtimed";
-    };
-    users.groups.localtimed = {};
-
-    systemd.services.localtime = {
-      wantedBy = [ "multi-user.target" ];
-      serviceConfig.Restart = "on-failure";
-    };
-  };
-}
diff --git a/nixos/modules/services/system/localtimed.nix b/nixos/modules/services/system/localtimed.nix
new file mode 100644
index 00000000000..345bdbd8dda
--- /dev/null
+++ b/nixos/modules/services/system/localtimed.nix
@@ -0,0 +1,66 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.localtimed;
+in {
+  imports = [ (lib.mkRenamedOptionModule [ "services" "localtime" ] [ "services" "localtimed" ]) ];
+
+  options = {
+    services.localtimed = {
+      enable = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Enable `localtimed`, a simple daemon for keeping the
+          system timezone up-to-date based on the current location. It uses
+          geoclue2 to determine the current location.
+        '';
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    services.geoclue2.appConfig.localtimed = {
+      isAllowed = true;
+      isSystem = true;
+      users = [ (toString config.ids.uids.localtimed) ];
+    };
+
+    # Install the polkit rules.
+    environment.systemPackages = [ pkgs.localtime ];
+
+    systemd.services.localtimed = {
+      wantedBy = [ "multi-user.target" ];
+      partOf = [ "localtimed-geoclue-agent.service" ];
+      after = [ "localtimed-geoclue-agent.service" ];
+      serviceConfig = {
+        ExecStart = "${pkgs.localtime}/bin/localtimed";
+        Restart = "on-failure";
+        Type = "exec";
+        User = "localtimed";
+      };
+    };
+
+    systemd.services.localtimed-geoclue-agent = {
+      wantedBy = [ "multi-user.target" ];
+      partOf = [ "geoclue.service" ];
+      after = [ "geoclue.service" ];
+      serviceConfig = {
+        ExecStart = "${pkgs.geoclue2-with-demo-agent}/libexec/geoclue-2.0/demos/agent";
+        Restart = "on-failure";
+        Type = "exec";
+        User = "localtimed";
+      };
+    };
+
+    users = {
+      users.localtimed = {
+        uid = config.ids.uids.localtimed;
+        group = "localtimed";
+      };
+      groups.localtimed.gid = config.ids.gids.localtimed;
+    };
+  };
+}
diff --git a/nixos/modules/services/system/nscd.nix b/nixos/modules/services/system/nscd.nix
index 00a87e788dc..fdc5190d084 100644
--- a/nixos/modules/services/system/nscd.nix
+++ b/nixos/modules/services/system/nscd.nix
@@ -7,10 +7,6 @@ let
   nssModulesPath = config.system.nssModules.path;
   cfg = config.services.nscd;
 
-  nscd = if pkgs.stdenv.hostPlatform.libc == "glibc"
-         then pkgs.stdenv.cc.libc.bin
-         else pkgs.glibc.bin;
-
 in
 
 {
@@ -24,17 +20,59 @@ in
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Name Service Cache Daemon.
           Disabling this is strongly discouraged, as this effectively disables NSS Lookups
           from all non-glibc NSS modules, including the ones provided by systemd.
         '';
       };
 
+      enableNsncd = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to use nsncd instead of nscd.
+          This is a nscd-compatible daemon, that proxies lookups, without any caching.
+        '';
+      };
+
+      user = mkOption {
+        type = types.str;
+        default = "nscd";
+        description = lib.mdDoc ''
+          User account under which nscd runs.
+        '';
+      };
+
+      group = mkOption {
+        type = types.str;
+        default = "nscd";
+        description = lib.mdDoc ''
+          User group under which nscd runs.
+        '';
+      };
+
       config = mkOption {
         type = types.lines;
         default = builtins.readFile ./nscd.conf;
-        description = "Configuration to use for Name Service Cache Daemon.";
+        description = lib.mdDoc "Configuration to use for Name Service Cache Daemon.";
+      };
+
+      package = mkOption {
+        type = types.package;
+        default =
+          if pkgs.stdenv.hostPlatform.libc == "glibc"
+          then pkgs.stdenv.cc.libc.bin
+          else pkgs.glibc.bin;
+        defaultText = lib.literalExpression ''
+          if pkgs.stdenv.hostPlatform.libc == "glibc"
+            then pkgs.stdenv.cc.libc.bin
+            else pkgs.glibc.bin;
+        '';
+        description = lib.mdDoc ''
+          package containing the nscd binary to be used by the service.
+          Ignored when enableNsncd is set to true.
+        '';
       };
 
     };
@@ -47,41 +85,65 @@ in
   config = mkIf cfg.enable {
     environment.etc."nscd.conf".text = cfg.config;
 
+    users.users.${cfg.user} = {
+      isSystemUser = true;
+      group = cfg.group;
+    };
+
+    users.groups.${cfg.group} = { };
+
     systemd.services.nscd =
-      { description = "Name Service Cache Daemon";
+      {
+        description = "Name Service Cache Daemon"
+          + lib.optionalString cfg.enableNsncd " (nsncd)";
 
         before = [ "nss-lookup.target" "nss-user-lookup.target" ];
         wants = [ "nss-lookup.target" "nss-user-lookup.target" ];
         wantedBy = [ "multi-user.target" ];
+        requiredBy = [ "nss-lookup.target" "nss-user-lookup.target" ];
 
         environment = { LD_LIBRARY_PATH = nssModulesPath; };
 
-        restartTriggers = [
+        restartTriggers = lib.optionals (!cfg.enableNsncd) ([
           config.environment.etc.hosts.source
           config.environment.etc."nsswitch.conf".source
           config.environment.etc."nscd.conf".source
-        ];
-
-        # We use DynamicUser because in default configurations nscd doesn't
-        # create any files that need to survive restarts. However, in some
-        # configurations, nscd needs to be started as root; it will drop
-        # privileges after all the NSS modules have read their configuration
-        # files. So prefix the ExecStart command with "!" to prevent systemd
-        # from dropping privileges early. See ExecStart in systemd.service(5).
+        ] ++ optionals config.users.mysql.enable [
+          config.environment.etc."libnss-mysql.cfg".source
+          config.environment.etc."libnss-mysql-root.cfg".source
+        ]);
+
+        # In some configurations, nscd needs to be started as root; it will
+        # drop privileges after all the NSS modules have read their
+        # configuration files. So prefix the ExecStart command with "!" to
+        # prevent systemd from dropping privileges early. See ExecStart in
+        # systemd.service(5). We use a static user, because some NSS modules
+        # sill want to read their configuration files after the privilege drop
+        # and so users can set the owner of those files to the nscd user.
         serviceConfig =
-          { ExecStart = "!@${nscd}/sbin/nscd nscd";
-            Type = "forking";
-            DynamicUser = true;
+          {
+            ExecStart =
+              if cfg.enableNsncd then "${pkgs.nsncd}/bin/nsncd"
+              else "!@${cfg.package}/bin/nscd nscd";
+            Type = if cfg.enableNsncd then "notify" else "forking";
+            User = cfg.user;
+            Group = cfg.group;
+            RemoveIPC = true;
+            PrivateTmp = true;
+            NoNewPrivileges = true;
+            RestrictSUIDSGID = true;
+            ProtectSystem = "strict";
+            ProtectHome = "read-only";
             RuntimeDirectory = "nscd";
             PIDFile = "/run/nscd/nscd.pid";
             Restart = "always";
             ExecReload =
-              [ "${nscd}/sbin/nscd --invalidate passwd"
-                "${nscd}/sbin/nscd --invalidate group"
-                "${nscd}/sbin/nscd --invalidate hosts"
+              lib.optionals (!cfg.enableNsncd) [
+                "${cfg.package}/bin/nscd --invalidate passwd"
+                "${cfg.package}/bin/nscd --invalidate group"
+                "${cfg.package}/bin/nscd --invalidate hosts"
               ];
           };
       };
-
   };
 }
diff --git a/nixos/modules/services/system/saslauthd.nix b/nixos/modules/services/system/saslauthd.nix
index 466b0ca60a7..09720146aaa 100644
--- a/nixos/modules/services/system/saslauthd.nix
+++ b/nixos/modules/services/system/saslauthd.nix
@@ -16,25 +16,25 @@ in
 
     services.saslauthd = {
 
-      enable = mkEnableOption "saslauthd, the Cyrus SASL authentication daemon";
+      enable = mkEnableOption (lib.mdDoc "saslauthd, the Cyrus SASL authentication daemon");
 
       package = mkOption {
         default = pkgs.cyrus_sasl.bin;
         defaultText = literalExpression "pkgs.cyrus_sasl.bin";
         type = types.package;
-        description = "Cyrus SASL package to use.";
+        description = lib.mdDoc "Cyrus SASL package to use.";
       };
 
       mechanism = mkOption {
         type = types.str;
         default = "pam";
-        description = "Auth mechanism to use";
+        description = lib.mdDoc "Auth mechanism to use";
       };
 
       config = mkOption {
         type = types.lines;
         default = "";
-        description = "Configuration to use for Cyrus SASL authentication daemon.";
+        description = lib.mdDoc "Configuration to use for Cyrus SASL authentication daemon.";
       };
 
     };
diff --git a/nixos/modules/services/system/self-deploy.nix b/nixos/modules/services/system/self-deploy.nix
index d7130a13c73..9b1ebfd3752 100644
--- a/nixos/modules/services/system/self-deploy.nix
+++ b/nixos/modules/services/system/self-deploy.nix
@@ -23,14 +23,14 @@ let
 in
 {
   options.services.self-deploy = {
-    enable = lib.mkEnableOption "self-deploy";
+    enable = lib.mkEnableOption (lib.mdDoc "self-deploy");
 
     nixFile = lib.mkOption {
       type = lib.types.path;
 
       default = "/default.nix";
 
-      description = ''
+      description = lib.mdDoc ''
         Path to nix file in repository. Leading '/' refers to root of
         git repository.
       '';
@@ -41,7 +41,7 @@ in
 
       default = null;
 
-      description = ''
+      description = lib.mdDoc ''
         Attribute of `nixFile` that builds the current system.
       '';
     };
@@ -51,7 +51,7 @@ in
 
       default = { };
 
-      description = ''
+      description = lib.mdDoc ''
         Arguments to `nix-build` passed as `--argstr` or `--arg` depending on
         the type.
       '';
@@ -62,7 +62,7 @@ in
 
       default = "switch";
 
-      description = ''
+      description = lib.mdDoc ''
         The `switch-to-configuration` subcommand used.
       '';
     };
@@ -70,7 +70,7 @@ in
     repository = lib.mkOption {
       type = with lib.types; oneOf [ path str ];
 
-      description = ''
+      description = lib.mdDoc ''
         The repository to fetch from. Must be properly formatted for git.
 
         If this value is set to a path (must begin with `/`) then it's
@@ -88,7 +88,7 @@ in
 
       default = null;
 
-      description = ''
+      description = lib.mdDoc ''
         Path to SSH private key used to fetch private repositories over
         SSH.
       '';
@@ -99,7 +99,7 @@ in
 
       default = "master";
 
-      description = ''
+      description = lib.mdDoc ''
         Branch to track
 
         Technically speaking any ref can be specified here, as this is
@@ -113,7 +113,7 @@ in
 
       default = "hourly";
 
-      description = ''
+      description = lib.mdDoc ''
         The schedule on which to run the `self-deploy` service. Format
         specified by `systemd.time 7`.
 
@@ -139,6 +139,8 @@ in
 
       path = with pkgs; [
         git
+        gnutar
+        gzip
         nix
       ] ++ lib.optionals (cfg.switchCommand == "boot") [ systemd ];
 
diff --git a/nixos/modules/services/system/systembus-notify.nix b/nixos/modules/services/system/systembus-notify.nix
index e918bc552ec..269197b3997 100644
--- a/nixos/modules/services/system/systembus-notify.nix
+++ b/nixos/modules/services/system/systembus-notify.nix
@@ -8,13 +8,13 @@ let
 in
 {
   options.services.systembus-notify = {
-    enable = mkEnableOption ''
+    enable = mkEnableOption (lib.mdDoc ''
       System bus notification support
 
       WARNING: enabling this option (while convenient) should *not* be done on a
       machine where you do not trust the other users as it allows any other
       local user to DoS your session by spamming notifications.
-    '';
+    '');
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/system/uptimed.nix b/nixos/modules/services/system/uptimed.nix
index 67a03876e19..df08c0f26e9 100644
--- a/nixos/modules/services/system/uptimed.nix
+++ b/nixos/modules/services/system/uptimed.nix
@@ -12,8 +12,8 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          Enable <literal>uptimed</literal>, allowing you to track
+        description = lib.mdDoc ''
+          Enable `uptimed`, allowing you to track
           your highest uptimes.
         '';
       };
diff --git a/nixos/modules/services/torrent/deluge.nix b/nixos/modules/services/torrent/deluge.nix
index cb0da9e83b4..70fad4d7d76 100644
--- a/nixos/modules/services/torrent/deluge.nix
+++ b/nixos/modules/services/torrent/deluge.nix
@@ -37,12 +37,12 @@ in {
   options = {
     services = {
       deluge = {
-        enable = mkEnableOption "Deluge daemon";
+        enable = mkEnableOption (lib.mdDoc "Deluge daemon");
 
         openFilesLimit = mkOption {
           default = openFilesLimit;
           type = types.either types.int types.str;
-          description = ''
+          description = lib.mdDoc ''
             Number of files to allow deluged to open.
           '';
         };
@@ -60,12 +60,12 @@ in {
               listen_ports = [ ${toString listenPortsDefault} ];
             }
           '';
-          description = ''
+          description = lib.mdDoc ''
             Deluge core configuration for the core.conf file. Only has an effect
-            when <option>services.deluge.declarative</option> is set to
-            <literal>true</literal>. String values must be quoted, integer and
+            when {option}`services.deluge.declarative` is set to
+            `true`. String values must be quoted, integer and
             boolean values must not. See
-            <link xlink:href="https://git.deluge-torrent.org/deluge/tree/deluge/core/preferencesmanager.py#n41"/>
+            <https://git.deluge-torrent.org/deluge/tree/deluge/core/preferencesmanager.py#n41>
             for the availaible options.
           '';
         };
@@ -73,12 +73,12 @@ in {
         declarative = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether to use a declarative deluge configuration.
-            Only if set to <literal>true</literal>, the options
-            <option>services.deluge.config</option>,
-            <option>services.deluge.openFirewall</option> and
-            <option>services.deluge.authFile</option> will be
+            Only if set to `true`, the options
+            {option}`services.deluge.config`,
+            {option}`services.deluge.openFirewall` and
+            {option}`services.deluge.authFile` will be
             applied.
           '';
         };
@@ -86,15 +86,15 @@ in {
         openFirewall = mkOption {
           default = false;
           type = types.bool;
-          description = ''
+          description = lib.mdDoc ''
             Whether to open the firewall for the ports in
-            <option>services.deluge.config.listen_ports</option>. It only takes effet if
-            <option>services.deluge.declarative</option> is set to
-            <literal>true</literal>.
+            {option}`services.deluge.config.listen_ports`. It only takes effet if
+            {option}`services.deluge.declarative` is set to
+            `true`.
 
             It does NOT apply to the daemon port nor the web UI port. To access those
             ports secuerly check the documentation
-            <link xlink:href="https://dev.deluge-torrent.org/wiki/UserGuide/ThinClient#CreateSSHTunnel"/>
+            <https://dev.deluge-torrent.org/wiki/UserGuide/ThinClient#CreateSSHTunnel>
             or use a VPN or configure certificates for deluge.
           '';
         };
@@ -102,7 +102,7 @@ in {
         dataDir = mkOption {
           type = types.path;
           default = "/var/lib/deluge";
-          description = ''
+          description = lib.mdDoc ''
             The directory where deluge will create files.
           '';
         };
@@ -110,13 +110,13 @@ in {
         authFile = mkOption {
           type = types.path;
           example = "/run/keys/deluge-auth";
-          description = ''
+          description = lib.mdDoc ''
             The file managing the authentication for deluge, the format of this
             file is straightforward, each line contains a
             username:password:level tuple in plaintext. It only has an effect
-            when <option>services.deluge.declarative</option> is set to
-            <literal>true</literal>.
-            See <link xlink:href="https://dev.deluge-torrent.org/wiki/UserGuide/Authentication"/> for
+            when {option}`services.deluge.declarative` is set to
+            `true`.
+            See <https://dev.deluge-torrent.org/wiki/UserGuide/Authentication> for
             more informations.
           '';
         };
@@ -124,7 +124,7 @@ in {
         user = mkOption {
           type = types.str;
           default = "deluge";
-          description = ''
+          description = lib.mdDoc ''
             User account under which deluge runs.
           '';
         };
@@ -132,7 +132,7 @@ in {
         group = mkOption {
           type = types.str;
           default = "deluge";
-          description = ''
+          description = lib.mdDoc ''
             Group under which deluge runs.
           '';
         };
@@ -140,7 +140,7 @@ in {
         extraPackages = mkOption {
           type = types.listOf types.package;
           default = [];
-          description = ''
+          description = lib.mdDoc ''
             Extra packages available at runtime to enable Deluge's plugins. For example,
             extraction utilities are required for the built-in "Extractor" plugin.
             This always contains unzip, gnutar, xz and bzip2.
@@ -150,19 +150,19 @@ in {
         package = mkOption {
           type = types.package;
           example = literalExpression "pkgs.deluge-2_x";
-          description = ''
+          description = lib.mdDoc ''
             Deluge package to use.
           '';
         };
       };
 
       deluge.web = {
-        enable = mkEnableOption "Deluge Web daemon";
+        enable = mkEnableOption (lib.mdDoc "Deluge Web daemon");
 
         port = mkOption {
           type = types.port;
           default = 8112;
-          description = ''
+          description = lib.mdDoc ''
             Deluge web UI port.
           '';
         };
@@ -170,7 +170,7 @@ in {
         openFirewall = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Open ports in the firewall for deluge web daemon
           '';
         };
diff --git a/nixos/modules/services/torrent/flexget.nix b/nixos/modules/services/torrent/flexget.nix
index e500e02d861..2a9ffac18d9 100644
--- a/nixos/modules/services/torrent/flexget.nix
+++ b/nixos/modules/services/torrent/flexget.nix
@@ -14,40 +14,40 @@ let
 in {
   options = {
     services.flexget = {
-      enable = mkEnableOption "Run FlexGet Daemon";
+      enable = mkEnableOption (lib.mdDoc "Run FlexGet Daemon");
 
       user = mkOption {
         default = "deluge";
         example = "some_user";
         type = types.str;
-        description = "The user under which to run flexget.";
+        description = lib.mdDoc "The user under which to run flexget.";
       };
 
       homeDir = mkOption {
         default = "/var/lib/deluge";
         example = "/home/flexget";
         type = types.path;
-        description = "Where files live.";
+        description = lib.mdDoc "Where files live.";
       };
 
       interval = mkOption {
         default = "10m";
         example = "1h";
         type = types.str;
-        description = "When to perform a <command>flexget</command> run. See <command>man 7 systemd.time</command> for the format.";
+        description = lib.mdDoc "When to perform a {command}`flexget` run. See {command}`man 7 systemd.time` for the format.";
       };
 
       systemScheduler = mkOption {
         default = true;
         example = false;
         type = types.bool;
-        description = "When true, execute the runs via the flexget-runner.timer. If false, you have to specify the settings yourself in the YML file.";
+        description = lib.mdDoc "When true, execute the runs via the flexget-runner.timer. If false, you have to specify the settings yourself in the YML file.";
       };
 
       config = mkOption {
         default = "";
         type = types.lines;
-        description = "The YAML configuration for FlexGet.";
+        description = lib.mdDoc "The YAML configuration for FlexGet.";
       };
     };
   };
diff --git a/nixos/modules/services/torrent/magnetico.nix b/nixos/modules/services/torrent/magnetico.nix
index 3dd7b1ece76..b681c58dfe2 100644
--- a/nixos/modules/services/torrent/magnetico.nix
+++ b/nixos/modules/services/torrent/magnetico.nix
@@ -43,13 +43,13 @@ in {
   ###### interface
 
   options.services.magnetico = {
-    enable = mkEnableOption "Magnetico, Bittorrent DHT crawler";
+    enable = mkEnableOption (lib.mdDoc "Magnetico, Bittorrent DHT crawler");
 
     crawler.address = mkOption {
       type = types.str;
       default = "0.0.0.0";
       example = "1.2.3.4";
-      description = ''
+      description = lib.mdDoc ''
         Address to be used for indexing DHT nodes.
       '';
     };
@@ -57,17 +57,17 @@ in {
     crawler.port = mkOption {
       type = types.port;
       default = 0;
-      description = ''
+      description = lib.mdDoc ''
         Port to be used for indexing DHT nodes.
         This port should be added to
-        <option>networking.firewall.allowedTCPPorts</option>.
+        {option}`networking.firewall.allowedTCPPorts`.
       '';
     };
 
     crawler.maxNeighbors = mkOption {
       type = types.ints.positive;
       default = 1000;
-      description = ''
+      description = lib.mdDoc ''
         Maximum number of simultaneous neighbors of an indexer.
         Be careful changing this number: high values can very
         easily cause your network to be congested or even crash
@@ -78,7 +78,7 @@ in {
     crawler.maxLeeches = mkOption {
       type = types.ints.positive;
       default = 200;
-      description = ''
+      description = lib.mdDoc ''
         Maximum number of simultaneous leeches.
       '';
     };
@@ -86,7 +86,7 @@ in {
     crawler.extraOptions = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Extra command line arguments to pass to magneticod.
       '';
     };
@@ -95,7 +95,7 @@ in {
       type = types.str;
       default = "localhost";
       example = "1.2.3.4";
-      description = ''
+      description = lib.mdDoc ''
         Address the web interface will listen to.
       '';
     };
@@ -103,7 +103,7 @@ in {
     web.port = mkOption {
       type = types.port;
       default = 8080;
-      description = ''
+      description = lib.mdDoc ''
         Port the web interface will listen to.
       '';
     };
@@ -116,50 +116,48 @@ in {
           myuser = "$2y$12$YE01LZ8jrbQbx6c0s2hdZO71dSjn2p/O9XsYJpz.5968yCysUgiaG";
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         The credentials to access the web interface, in case authentication is
-        enabled, in the format <literal>username:hash</literal>. If unset no
+        enabled, in the format `username:hash`. If unset no
         authentication will be required.
 
         Usernames must start with a lowercase ([a-z]) ASCII character, might
         contain non-consecutive underscores except at the end, and consists of
         small-case a-z characters and digits 0-9.  The
-        <command>htpasswd</command> tool from the <package>apacheHttpd
-        </package> package may be used to generate the hash: <command>htpasswd
-        -bnBC 12 username password</command>
-
-        <warning>
-        <para>
-          The hashes will be stored world-readable in the nix store.
-          Consider using the <literal>credentialsFile</literal> option if you
-          don't want this.
-        </para>
-        </warning>
+        {command}`htpasswd` tool from the `apacheHttpd`
+        package may be used to generate the hash:
+        {command}`htpasswd -bnBC 12 username password`
+
+        ::: {.warning}
+        The hashes will be stored world-readable in the nix store.
+        Consider using the `credentialsFile` option if you
+        don't want this.
+        :::
       '';
     };
 
     web.credentialsFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The path to the file holding the credentials to access the web
         interface. If unset no authentication will be required.
 
         The file must constain user names and password hashes in the format
-        <literal>username:hash </literal>, one for each line.  Usernames must
+        `username:hash `, one for each line.  Usernames must
         start with a lowecase ([a-z]) ASCII character, might contain
         non-consecutive underscores except at the end, and consists of
         small-case a-z characters and digits 0-9.
-        The <command>htpasswd</command> tool from the <package>apacheHttpd
-        </package> package may be used to generate the hash:
-        <command>htpasswd -bnBC 12 username password</command>
+        The {command}`htpasswd` tool from the `apacheHttpd`
+        package may be used to generate the hash:
+        {command}`htpasswd -bnBC 12 username password`
       '';
     };
 
     web.extraOptions = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Extra command line arguments to pass to magneticow.
       '';
     };
diff --git a/nixos/modules/services/torrent/opentracker.nix b/nixos/modules/services/torrent/opentracker.nix
index d76d61dfe85..7d67491c119 100644
--- a/nixos/modules/services/torrent/opentracker.nix
+++ b/nixos/modules/services/torrent/opentracker.nix
@@ -5,11 +5,11 @@ let
   cfg = config.services.opentracker;
 in {
   options.services.opentracker = {
-    enable = mkEnableOption "opentracker";
+    enable = mkEnableOption (lib.mdDoc "opentracker");
 
     package = mkOption {
       type = types.package;
-      description = ''
+      description = lib.mdDoc ''
         opentracker package to use
       '';
       default = pkgs.opentracker;
@@ -18,7 +18,7 @@ in {
 
     extraOptions = mkOption {
       type = types.separatedString " ";
-      description = ''
+      description = lib.mdDoc ''
         Configuration Arguments for opentracker
         See https://erdgeist.org/arts/software/opentracker/ for all params
       '';
diff --git a/nixos/modules/services/torrent/peerflix.nix b/nixos/modules/services/torrent/peerflix.nix
index 821c829f6b4..ea74d0f8b9c 100644
--- a/nixos/modules/services/torrent/peerflix.nix
+++ b/nixos/modules/services/torrent/peerflix.nix
@@ -19,19 +19,19 @@ in {
 
   options.services.peerflix = {
     enable = mkOption {
-      description = "Whether to enable peerflix service.";
+      description = lib.mdDoc "Whether to enable peerflix service.";
       default = false;
       type = types.bool;
     };
 
     stateDir = mkOption {
-      description = "Peerflix state directory.";
+      description = lib.mdDoc "Peerflix state directory.";
       default = "/var/lib/peerflix";
       type = types.path;
     };
 
     downloadDir = mkOption {
-      description = "Peerflix temporary download directory.";
+      description = lib.mdDoc "Peerflix temporary download directory.";
       default = "${cfg.stateDir}/torrents";
       defaultText = literalExpression ''"''${config.${opt.stateDir}}/torrents"'';
       type = types.path;
diff --git a/nixos/modules/services/torrent/rtorrent.nix b/nixos/modules/services/torrent/rtorrent.nix
index 759dcfe2e6c..935c11e3eb0 100644
--- a/nixos/modules/services/torrent/rtorrent.nix
+++ b/nixos/modules/services/torrent/rtorrent.nix
@@ -9,12 +9,12 @@ let
 
 in {
   options.services.rtorrent = {
-    enable = mkEnableOption "rtorrent";
+    enable = mkEnableOption (lib.mdDoc "rtorrent");
 
     dataDir = mkOption {
       type = types.str;
       default = "/var/lib/rtorrent";
-      description = ''
+      description = lib.mdDoc ''
         The directory where rtorrent stores its data files.
       '';
     };
@@ -23,7 +23,7 @@ in {
       type = types.str;
       default = "${cfg.dataDir}/download";
       defaultText = literalExpression ''"''${config.${opt.dataDir}}/download"'';
-      description = ''
+      description = lib.mdDoc ''
         Where to put downloaded files.
       '';
     };
@@ -31,7 +31,7 @@ in {
     user = mkOption {
       type = types.str;
       default = "rtorrent";
-      description = ''
+      description = lib.mdDoc ''
         User account under which rtorrent runs.
       '';
     };
@@ -39,7 +39,7 @@ in {
     group = mkOption {
       type = types.str;
       default = "rtorrent";
-      description = ''
+      description = lib.mdDoc ''
         Group under which rtorrent runs.
       '';
     };
@@ -48,7 +48,7 @@ in {
       type = types.package;
       default = pkgs.rtorrent;
       defaultText = literalExpression "pkgs.rtorrent";
-      description = ''
+      description = lib.mdDoc ''
         The rtorrent package to use.
       '';
     };
@@ -56,7 +56,7 @@ in {
     port = mkOption {
       type = types.port;
       default = 50000;
-      description = ''
+      description = lib.mdDoc ''
         The rtorrent port.
       '';
     };
@@ -64,8 +64,8 @@ in {
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = ''
-        Whether to open the firewall for the port in <option>services.rtorrent.port</option>.
+      description = lib.mdDoc ''
+        Whether to open the firewall for the port in {option}`services.rtorrent.port`.
       '';
     };
 
@@ -73,7 +73,7 @@ in {
       type = types.str;
       readOnly = true;
       default = "/run/rtorrent/rpc.sock";
-      description = ''
+      description = lib.mdDoc ''
         RPC socket path.
       '';
     };
@@ -81,8 +81,8 @@ in {
     configText = mkOption {
       type = types.lines;
       default = "";
-      description = ''
-        The content of <filename>rtorrent.rc</filename>. The <link xlink:href="https://rtorrent-docs.readthedocs.io/en/latest/cookbook.html#modernized-configuration-template">modernized configuration template</link> with the values specified in this module will be prepended using mkBefore. You can use mkForce to overwrite the config completly.
+      description = lib.mdDoc ''
+        The content of {file}`rtorrent.rc`. The [modernized configuration template](https://rtorrent-docs.readthedocs.io/en/latest/cookbook.html#modernized-configuration-template) with the values specified in this module will be prepended using mkBefore. You can use mkForce to overwrite the config completly.
       '';
     };
   };
diff --git a/nixos/modules/services/torrent/transmission.nix b/nixos/modules/services/torrent/transmission.nix
index d12d8aa2398..9b53f5de143 100644
--- a/nixos/modules/services/torrent/transmission.nix
+++ b/nixos/modules/services/torrent/transmission.nix
@@ -24,22 +24,26 @@ in
   ];
   options = {
     services.transmission = {
-      enable = mkEnableOption ''the headless Transmission BitTorrent daemon.
+      enable = mkEnableOption (lib.mdDoc "transmission") // {
+        description = lib.mdDoc ''
+          Whether to enable the headless Transmission BitTorrent daemon.
 
-        Transmission daemon can be controlled via the RPC interface using
-        transmission-remote, the WebUI (http://127.0.0.1:9091/ by default),
-        or other clients like stig or tremc.
+          Transmission daemon can be controlled via the RPC interface using
+          transmission-remote, the WebUI (http://127.0.0.1:9091/ by default),
+          or other clients like stig or tremc.
 
-        Torrents are downloaded to <xref linkend="opt-services.transmission.home"/>/${downloadsDir} by default and are
-        accessible to users in the "transmission" group'';
+          Torrents are downloaded to [](#opt-services.transmission.home)/${downloadsDir} by default and are
+          accessible to users in the "transmission" group.
+        '';
+      };
 
       settings = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Settings whose options overwrite fields in
-          <literal>.config/transmission-daemon/settings.json</literal>
+          `.config/transmission-daemon/settings.json`
           (each time the service starts).
 
-          See <link xlink:href="https://github.com/transmission/transmission/wiki/Editing-Configuration-Files">Transmission's Wiki</link>
+          See [Transmission's Wiki](https://github.com/transmission/transmission/wiki/Editing-Configuration-Files)
           for documentation of settings not explicitely covered by this module.
         '';
         default = {};
@@ -49,89 +53,89 @@ in
             type = types.path;
             default = "${cfg.home}/${downloadsDir}";
             defaultText = literalExpression ''"''${config.${opt.home}}/${downloadsDir}"'';
-            description = "Directory where to download torrents.";
+            description = lib.mdDoc "Directory where to download torrents.";
           };
           options.incomplete-dir = mkOption {
             type = types.path;
             default = "${cfg.home}/${incompleteDir}";
             defaultText = literalExpression ''"''${config.${opt.home}}/${incompleteDir}"'';
-            description = ''
+            description = lib.mdDoc ''
               When enabled with
               services.transmission.home
-              <xref linkend="opt-services.transmission.settings.incomplete-dir-enabled"/>,
+              [](#opt-services.transmission.settings.incomplete-dir-enabled),
               new torrents will download the files to this directory.
               When complete, the files will be moved to download-dir
-              <xref linkend="opt-services.transmission.settings.download-dir"/>.
+              [](#opt-services.transmission.settings.download-dir).
             '';
           };
           options.incomplete-dir-enabled = mkOption {
             type = types.bool;
             default = true;
-            description = "";
+            description = lib.mdDoc "";
           };
           options.message-level = mkOption {
             type = types.ints.between 0 3;
             default = 2;
-            description = "Set verbosity of transmission messages.";
+            description = lib.mdDoc "Set verbosity of transmission messages.";
           };
           options.peer-port = mkOption {
             type = types.port;
             default = 51413;
-            description = "The peer port to listen for incoming connections.";
+            description = lib.mdDoc "The peer port to listen for incoming connections.";
           };
           options.peer-port-random-high = mkOption {
             type = types.port;
             default = 65535;
-            description = ''
+            description = lib.mdDoc ''
               The maximum peer port to listen to for incoming connections
-              when <xref linkend="opt-services.transmission.settings.peer-port-random-on-start"/> is enabled.
+              when [](#opt-services.transmission.settings.peer-port-random-on-start) is enabled.
             '';
           };
           options.peer-port-random-low = mkOption {
             type = types.port;
             default = 65535;
-            description = ''
+            description = lib.mdDoc ''
               The minimal peer port to listen to for incoming connections
-              when <xref linkend="opt-services.transmission.settings.peer-port-random-on-start"/> is enabled.
+              when [](#opt-services.transmission.settings.peer-port-random-on-start) is enabled.
             '';
           };
           options.peer-port-random-on-start = mkOption {
             type = types.bool;
             default = false;
-            description = "Randomize the peer port.";
+            description = lib.mdDoc "Randomize the peer port.";
           };
           options.rpc-bind-address = mkOption {
             type = types.str;
             default = "127.0.0.1";
             example = "0.0.0.0";
-            description = ''
+            description = lib.mdDoc ''
               Where to listen for RPC connections.
-              Use \"0.0.0.0\" to listen on all interfaces.
+              Use `0.0.0.0` to listen on all interfaces.
             '';
           };
           options.rpc-port = mkOption {
             type = types.port;
             default = 9091;
-            description = "The RPC port to listen to.";
+            description = lib.mdDoc "The RPC port to listen to.";
           };
           options.script-torrent-done-enabled = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Whether to run
-              <xref linkend="opt-services.transmission.settings.script-torrent-done-filename"/>
+              [](#opt-services.transmission.settings.script-torrent-done-filename)
               at torrent completion.
             '';
           };
           options.script-torrent-done-filename = mkOption {
             type = types.nullOr types.path;
             default = null;
-            description = "Executable to be run at torrent completion.";
+            description = lib.mdDoc "Executable to be run at torrent completion.";
           };
           options.umask = mkOption {
             type = types.int;
             default = 2;
-            description = ''
+            description = lib.mdDoc ''
               Sets transmission's file mode creation mask.
               See the umask(2) manpage for more information.
               Users who want their saved torrents to be world-writable
@@ -143,28 +147,28 @@ in
           options.utp-enabled = mkOption {
             type = types.bool;
             default = true;
-            description = ''
-              Whether to enable <link xlink:href="http://en.wikipedia.org/wiki/Micro_Transport_Protocol">Micro Transport Protocol (µTP)</link>.
+            description = lib.mdDoc ''
+              Whether to enable [Micro Transport Protocol (µTP)](http://en.wikipedia.org/wiki/Micro_Transport_Protocol).
             '';
           };
           options.watch-dir = mkOption {
             type = types.path;
             default = "${cfg.home}/${watchDir}";
             defaultText = literalExpression ''"''${config.${opt.home}}/${watchDir}"'';
-            description = "Watch a directory for torrent files and add them to transmission.";
+            description = lib.mdDoc "Watch a directory for torrent files and add them to transmission.";
           };
           options.watch-dir-enabled = mkOption {
             type = types.bool;
             default = false;
-            description = ''Whether to enable the
-              <xref linkend="opt-services.transmission.settings.watch-dir"/>.
+            description = lib.mdDoc ''Whether to enable the
+              [](#opt-services.transmission.settings.watch-dir).
             '';
           };
           options.trash-original-torrent-files = mkOption {
             type = types.bool;
             default = false;
-            description = ''Whether to delete torrents added from the
-              <xref linkend="opt-services.transmission.settings.watch-dir"/>.
+            description = lib.mdDoc ''Whether to delete torrents added from the
+              [](#opt-services.transmission.settings.watch-dir).
             '';
           };
         };
@@ -174,47 +178,47 @@ in
         type = with types; nullOr str;
         default = null;
         example = "770";
-        description = ''
-          If not <code>null</code>, is used as the permissions
-          set by <literal>systemd.activationScripts.transmission-daemon</literal>
-          on the directories <xref linkend="opt-services.transmission.settings.download-dir"/>,
-          <xref linkend="opt-services.transmission.settings.incomplete-dir"/>.
-          and <xref linkend="opt-services.transmission.settings.watch-dir"/>.
+        description = lib.mdDoc ''
+          If not `null`, is used as the permissions
+          set by `systemd.activationScripts.transmission-daemon`
+          on the directories [](#opt-services.transmission.settings.download-dir),
+          [](#opt-services.transmission.settings.incomplete-dir).
+          and [](#opt-services.transmission.settings.watch-dir).
           Note that you may also want to change
-          <xref linkend="opt-services.transmission.settings.umask"/>.
+          [](#opt-services.transmission.settings.umask).
         '';
       };
 
       home = mkOption {
         type = types.path;
         default = "/var/lib/transmission";
-        description = ''
-          The directory where Transmission will create <literal>${settingsDir}</literal>.
-          as well as <literal>${downloadsDir}/</literal> unless
-          <xref linkend="opt-services.transmission.settings.download-dir"/> is changed,
-          and <literal>${incompleteDir}/</literal> unless
-          <xref linkend="opt-services.transmission.settings.incomplete-dir"/> is changed.
+        description = lib.mdDoc ''
+          The directory where Transmission will create `${settingsDir}`.
+          as well as `${downloadsDir}/` unless
+          [](#opt-services.transmission.settings.download-dir) is changed,
+          and `${incompleteDir}/` unless
+          [](#opt-services.transmission.settings.incomplete-dir) is changed.
         '';
       };
 
       user = mkOption {
         type = types.str;
         default = "transmission";
-        description = "User account under which Transmission runs.";
+        description = lib.mdDoc "User account under which Transmission runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "transmission";
-        description = "Group account under which Transmission runs.";
+        description = lib.mdDoc "Group account under which Transmission runs.";
       };
 
       credentialsFile = mkOption {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to a JSON file to be merged with the settings.
           Useful to merge a file which is better kept out of the Nix store
-          to set secret config parameters like <code>rpc-password</code>.
+          to set secret config parameters like `rpc-password`.
         '';
         default = "/dev/null";
         example = "/var/lib/secrets/transmission/settings.json";
@@ -224,23 +228,27 @@ in
         type = types.listOf types.str;
         default = [];
         example = [ "--log-debug" ];
-        description = ''
+        description = lib.mdDoc ''
           Extra flags passed to the transmission command in the service definition.
         '';
       };
 
-      openPeerPorts = mkEnableOption "opening of the peer port(s) in the firewall";
+      openPeerPorts = mkEnableOption (lib.mdDoc "opening of the peer port(s) in the firewall");
 
-      openRPCPort = mkEnableOption "opening of the RPC port in the firewall";
+      openRPCPort = mkEnableOption (lib.mdDoc "opening of the RPC port in the firewall");
 
-      performanceNetParameters = mkEnableOption ''tweaking of kernel parameters
-        to open many more connections at the same time.
+      performanceNetParameters = mkEnableOption (lib.mdDoc "performance tweaks") // {
+        description = lib.mdDoc ''
+          Whether to enable tweaking of kernel parameters
+          to open many more connections at the same time.
 
-        Note that you may also want to increase
-        <code>peer-limit-global"</code>.
-        And be aware that these settings are quite aggressive
-        and might not suite your regular desktop use.
-        For instance, SSH sessions may time out more easily'';
+          Note that you may also want to increase
+          `peer-limit-global`.
+          And be aware that these settings are quite aggressive
+          and might not suite your regular desktop use.
+          For instance, SSH sessions may time out more easily.
+        '';
+      };
     };
   };
 
@@ -423,7 +431,7 @@ in
       # https://trac.transmissionbt.com/browser/trunk/libtransmission/tr-udp.c?rev=11956.
       # at least up to the values hardcoded here:
       (mkIf cfg.settings.utp-enabled {
-        "net.core.rmem_max" = mkDefault "4194304"; # 4MB
+        "net.core.rmem_max" = mkDefault 4194304; # 4MB
         "net.core.wmem_max" = mkDefault "1048576"; # 1MB
       })
       (mkIf cfg.performanceNetParameters {
diff --git a/nixos/modules/services/tracing/tempo.nix b/nixos/modules/services/tracing/tempo.nix
new file mode 100644
index 00000000000..4a098c31eff
--- /dev/null
+++ b/nixos/modules/services/tracing/tempo.nix
@@ -0,0 +1,68 @@
+{ config, lib, pkgs, ... }:
+
+let
+  inherit (lib) mkEnableOption mkIf mkOption types;
+
+  cfg = config.services.tempo;
+
+  settingsFormat = pkgs.formats.yaml {};
+in {
+  options.services.tempo = {
+    enable = mkEnableOption (lib.mdDoc "Grafana Tempo");
+
+    settings = mkOption {
+      type = settingsFormat.type;
+      default = {};
+      description = lib.mdDoc ''
+        Specify the configuration for Tempo in Nix.
+
+        See https://grafana.com/docs/tempo/latest/configuration/ for available options.
+      '';
+    };
+
+    configFile = mkOption {
+      type = types.nullOr types.path;
+      default = null;
+      description = lib.mdDoc ''
+        Specify a path to a configuration file that Tempo should use.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    # for tempo-cli and friends
+    environment.systemPackages = [ pkgs.tempo ];
+
+    assertions = [{
+      assertion = (
+        (cfg.settings == {}) != (cfg.configFile == null)
+      );
+      message  = ''
+        Please specify a configuration for Tempo with either
+        'services.tempo.settings' or
+        'services.tempo.configFile'.
+      '';
+    }];
+
+    systemd.services.tempo = {
+      description = "Grafana Tempo Service Daemon";
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = let
+        conf = if cfg.configFile == null
+               then settingsFormat.generate "config.yaml" cfg.settings
+               else cfg.configFile;
+      in
+      {
+        ExecStart = "${pkgs.tempo}/bin/tempo --config.file=${conf}";
+        DynamicUser = true;
+        Restart = "always";
+        ProtectSystem = "full";
+        DevicePolicy = "closed";
+        NoNewPrivileges = true;
+        WorkingDirectory = "/var/lib/tempo";
+        StateDirectory = "tempo";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/ttys/getty.nix b/nixos/modules/services/ttys/getty.nix
index 7021a2c80f8..22ae9c27e5b 100644
--- a/nixos/modules/services/ttys/getty.nix
+++ b/nixos/modules/services/ttys/getty.nix
@@ -34,7 +34,7 @@ in
       autologinUser = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Username of the account that will be automatically logged in at the console.
           If unspecified, a login prompt is shown as usual.
         '';
@@ -44,7 +44,7 @@ in
         type = types.path;
         default = "${pkgs.shadow}/bin/login";
         defaultText = literalExpression ''"''${pkgs.shadow}/bin/login"'';
-        description = ''
+        description = lib.mdDoc ''
           Path to the login binary executed by agetty.
         '';
       };
@@ -52,15 +52,13 @@ in
       loginOptions = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Template for arguments to be passed to
-          <citerefentry><refentrytitle>login</refentrytitle>
-          <manvolnum>1</manvolnum></citerefentry>.
+          {manpage}`login(1)`.
 
-          See <citerefentry><refentrytitle>agetty</refentrytitle>
-          <manvolnum>1</manvolnum></citerefentry> for details,
+          See {manpage}`agetty(1)` for details,
           including security considerations.  If unspecified, agetty
-          will not be invoked with a <option>--login-options</option>
+          will not be invoked with a {option}`--login-options`
           option.
         '';
         example = "-h darkstar -- \\u";
@@ -69,7 +67,7 @@ in
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [ ];
-        description = ''
+        description = lib.mdDoc ''
           Additional arguments passed to agetty.
         '';
         example = [ "--nohostname" ];
@@ -77,7 +75,7 @@ in
 
       greetingLine = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Welcome line printed by agetty.
           The default shows current NixOS version label, machine type and tty.
         '';
@@ -86,7 +84,7 @@ in
       helpLine = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Help line printed by agetty below the welcome line.
           Used by the installation CD to give some hints on
           how to proceed.
@@ -104,6 +102,7 @@ in
     # Note: this is set here rather than up there so that changing
     # nixos.label would not rebuild manual pages
     services.getty.greetingLine = mkDefault ''<<< Welcome to NixOS ${config.system.nixos.label} (\m) - \l >>>'';
+    services.getty.helpLine = mkIf (config.documentation.nixos.enable && config.documentation.doc.enable) "\nRun 'nixos-help' for the NixOS manual.";
 
     systemd.services."getty@" =
       { serviceConfig.ExecStart = [
@@ -147,7 +146,7 @@ in
         enable = mkDefault config.boot.isContainer;
       };
 
-    environment.etc.issue =
+    environment.etc.issue = mkDefault
       { # Friendly greeting on the virtual consoles.
         source = pkgs.writeText "issue" ''
 
diff --git a/nixos/modules/services/ttys/gpm.nix b/nixos/modules/services/ttys/gpm.nix
index 308a6d3643a..378f6b17732 100644
--- a/nixos/modules/services/ttys/gpm.nix
+++ b/nixos/modules/services/ttys/gpm.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable GPM, the General Purpose Mouse daemon,
           which enables mouse support in virtual consoles.
         '';
@@ -28,7 +28,7 @@ in
       protocol = mkOption {
         type = types.str;
         default = "ps/2";
-        description = "Mouse protocol to use.";
+        description = lib.mdDoc "Mouse protocol to use.";
       };
 
     };
diff --git a/nixos/modules/services/ttys/kmscon.nix b/nixos/modules/services/ttys/kmscon.nix
index 4fe720bf044..f5a8d8b104d 100644
--- a/nixos/modules/services/ttys/kmscon.nix
+++ b/nixos/modules/services/ttys/kmscon.nix
@@ -1,6 +1,6 @@
 { config, pkgs, lib, ... }:
 let
-  inherit (lib) mkOption types mkIf;
+  inherit (lib) mapAttrs mkIf mkOption optional optionals types;
 
   cfg = config.services.kmscon;
 
@@ -11,7 +11,7 @@ in {
   options = {
     services.kmscon = {
       enable = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Use kmscon as the virtual console instead of gettys.
           kmscon is a kms/dri-based userspace virtual terminal implementation.
           It supports a richer feature set than the standard linux console VT,
@@ -23,20 +23,33 @@ in {
       };
 
       hwRender = mkOption {
-        description = "Whether to use 3D hardware acceleration to render the console.";
+        description = lib.mdDoc "Whether to use 3D hardware acceleration to render the console.";
         type = types.bool;
         default = false;
       };
 
+      fonts = mkOption {
+        description = lib.mdDoc "Fonts used by kmscon, in order of priority.";
+        default = null;
+        example = lib.literalExpression ''[ { name = "Source Code Pro"; package = pkgs.source-code-pro; } ]'';
+        type = with types;
+          let fontType = submodule {
+                options = {
+                  name = mkOption { type = str; description = lib.mdDoc "Font name, as used by fontconfig."; };
+                  package = mkOption { type = package; description = lib.mdDoc "Package providing the font."; };
+                };
+          }; in nullOr (nonEmptyListOf fontType);
+      };
+
       extraConfig = mkOption {
-        description = "Extra contents of the kmscon.conf file.";
+        description = lib.mdDoc "Extra contents of the kmscon.conf file.";
         type = types.lines;
         default = "";
         example = "font-size=14";
       };
 
       extraOptions = mkOption {
-        description = "Extra flags to pass to kmscon.";
+        description = lib.mdDoc "Extra flags to pass to kmscon.";
         type = types.separatedString " ";
         default = "";
         example = "--term xterm-256color";
@@ -45,7 +58,7 @@ in {
       autologinUser = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Username of the account that will be automatically logged in at the console.
           If unspecified, a login prompt is shown as usual.
         '';
@@ -87,11 +100,17 @@ in {
 
     systemd.services.systemd-vconsole-setup.enable = false;
 
-    services.kmscon.extraConfig = mkIf cfg.hwRender ''
-      drm
-      hwaccel
-    '';
+    services.kmscon.extraConfig =
+      let
+        render = optionals cfg.hwRender [ "drm" "hwaccel" ];
+        fonts = optional (cfg.fonts != null) "font-name=${lib.concatMapStringsSep ", " (f: f.name) cfg.fonts}";
+      in lib.concatStringsSep "\n" (render ++ fonts);
 
     hardware.opengl.enable = mkIf cfg.hwRender true;
+
+    fonts = mkIf (cfg.fonts != null) {
+      fontconfig.enable = true;
+      fonts = map (f: f.package) cfg.fonts;
+    };
   };
 }
diff --git a/nixos/modules/services/video/epgstation/default.nix b/nixos/modules/services/video/epgstation/default.nix
index 191f6eb52e5..3d1d7a27c21 100644
--- a/nixos/modules/services/video/epgstation/default.nix
+++ b/nixos/modules/services/video/epgstation/default.nix
@@ -78,39 +78,37 @@ in
   ];
 
   options.services.epgstation = {
-    enable = lib.mkEnableOption description;
+    enable = lib.mkEnableOption (lib.mdDoc description);
 
     package = lib.mkOption {
       default = pkgs.epgstation;
       type = lib.types.package;
       defaultText = lib.literalExpression "pkgs.epgstation";
-      description = "epgstation package to use";
+      description = lib.mdDoc "epgstation package to use";
     };
 
     usePreconfiguredStreaming = lib.mkOption {
       type = lib.types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Use preconfigured default streaming options.
 
         Upstream defaults:
-        <link xlink:href="https://github.com/l3tnun/EPGStation/blob/master/config/config.yml.template"/>
+        <https://github.com/l3tnun/EPGStation/blob/master/config/config.yml.template>
       '';
     };
 
     openFirewall = lib.mkOption {
       type = lib.types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Open ports in the firewall for the EPGStation web interface.
 
-        <warning>
-          <para>
-            Exposing EPGStation to the open internet is generally advised
-            against. Only use it inside a trusted local network, or consider
-            putting it behind a VPN if you want remote access.
-          </para>
-        </warning>
+        ::: {.warning}
+        Exposing EPGStation to the open internet is generally advised
+        against. Only use it inside a trusted local network, or consider
+        putting it behind a VPN if you want remote access.
+        :::
       '';
     };
 
@@ -118,7 +116,7 @@ in
       name = lib.mkOption {
         type = lib.types.str;
         default = "epgstation";
-        description = ''
+        description = lib.mdDoc ''
           Name of the MySQL database that holds EPGStation's data.
         '';
       };
@@ -126,9 +124,9 @@ in
       passwordFile = lib.mkOption {
         type = lib.types.path;
         example = "/run/keys/epgstation-db-password";
-        description = ''
+        description = lib.mdDoc ''
           A file containing the password for the database named
-          <option>database.name</option>.
+          {option}`database.name`.
         '';
       };
     };
@@ -144,11 +142,11 @@ in
     # configure them according to their needs. In these cases, the value in the
     # upstream template configuration should serve as a "good enough" default.
     settings = lib.mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Options to add to config.yml.
 
         Documentation:
-        <link xlink:href="https://github.com/l3tnun/EPGStation/blob/master/doc/conf-manual.md"/>
+        <https://github.com/l3tnun/EPGStation/blob/master/doc/conf-manual.md>
       '';
 
       default = { };
@@ -163,7 +161,7 @@ in
         options.port = lib.mkOption {
           type = lib.types.port;
           default = 20772;
-          description = ''
+          description = lib.mdDoc ''
             HTTP port for EPGStation to listen on.
           '';
         };
@@ -172,9 +170,9 @@ in
           type = lib.types.port;
           default = cfg.settings.port + 1;
           defaultText = lib.literalExpression "config.${opt.settings}.port + 1";
-          description = ''
+          description = lib.mdDoc ''
             Socket.io port for EPGStation to listen on. It is valid to share
-            ports with <option>${opt.settings}.port</option>.
+            ports with {option}`${opt.settings}.port`.
           '';
         };
 
@@ -182,9 +180,9 @@ in
           type = lib.types.port;
           default = cfg.settings.socketioPort;
           defaultText = lib.literalExpression "config.${opt.settings}.socketioPort";
-          description = ''
+          description = lib.mdDoc ''
             Socket.io port that the web client is going to connect to. This may
-            be different from <option>${opt.settings}.socketioPort</option> if
+            be different from {option}`${opt.settings}.socketioPort` if
             EPGStation is hidden behind a reverse proxy.
           '';
         };
@@ -196,13 +194,13 @@ in
             "http+unix://''${lib.replaceStrings ["/"] ["%2F"] config.${option}}"
           '';
           example = "http://localhost:40772";
-          description = "URL to connect to Mirakurun.";
+          description = lib.mdDoc "URL to connect to Mirakurun.";
         };
 
         options.encodeProcessNum = lib.mkOption {
           type = lib.types.ints.positive;
           default = 4;
-          description = ''
+          description = lib.mdDoc ''
             The maximum number of processes that EPGStation would allow to run
             at the same time for encoding or streaming videos.
           '';
@@ -211,7 +209,7 @@ in
         options.concurrentEncodeNum = lib.mkOption {
           type = lib.types.ints.positive;
           default = 1;
-          description = ''
+          description = lib.mdDoc ''
             The maximum number of encoding jobs that EPGStation would run at the
             same time.
           '';
@@ -219,7 +217,7 @@ in
 
         options.encode = lib.mkOption {
           type = with lib.types; listOf attrs;
-          description = "Encoding presets for recorded videos.";
+          description = lib.mdDoc "Encoding presets for recorded videos.";
           default = [
             {
               name = "H.264";
diff --git a/nixos/modules/services/video/mirakurun.nix b/nixos/modules/services/video/mirakurun.nix
index 35303b2332c..5484515e7cb 100644
--- a/nixos/modules/services/video/mirakurun.nix
+++ b/nixos/modules/services/video/mirakurun.nix
@@ -24,13 +24,13 @@ in
   {
     options = {
       services.mirakurun = {
-        enable = mkEnableOption "the Mirakurun DVR Tuner Server";
+        enable = mkEnableOption (lib.mdDoc "the Mirakurun DVR Tuner Server");
 
         port = mkOption {
           type = with types; nullOr port;
           default = 40772;
-          description = ''
-            Port to listen on. If <literal>null</literal>, it won't listen on
+          description = lib.mdDoc ''
+            Port to listen on. If `null`, it won't listen on
             any port.
           '';
         };
@@ -38,24 +38,22 @@ in
         openFirewall = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Open ports in the firewall for Mirakurun.
 
-            <warning>
-              <para>
-                Exposing Mirakurun to the open internet is generally advised
-                against. Only use it inside a trusted local network, or
-                consider putting it behind a VPN if you want remote access.
-              </para>
-            </warning>
+            ::: {.warning}
+            Exposing Mirakurun to the open internet is generally advised
+            against. Only use it inside a trusted local network, or
+            consider putting it behind a VPN if you want remote access.
+            :::
           '';
         };
 
         unixSocket = mkOption {
           type = with types; nullOr path;
           default = "/var/run/mirakurun/mirakurun.sock";
-          description = ''
-            Path to unix socket to listen on. If <literal>null</literal>, it
+          description = lib.mdDoc ''
+            Path to unix socket to listen on. If `null`, it
             won't listen on any unix sockets.
           '';
         };
@@ -63,7 +61,7 @@ in
         allowSmartCardAccess = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Install polkit rules to allow Mirakurun to access smart card readers
             which is commonly used along with tuner devices.
           '';
@@ -78,11 +76,11 @@ in
               overflowTimeLimit = 30000;
             };
           '';
-          description = ''
+          description = lib.mdDoc ''
             Options for server.yml.
 
             Documentation:
-            <link xlink:href="https://github.com/Chinachu/Mirakurun/blob/master/doc/Configuration.md"/>
+            <https://github.com/Chinachu/Mirakurun/blob/master/doc/Configuration.md>
           '';
         };
 
@@ -98,12 +96,12 @@ in
               }
             ];
           '';
-          description = ''
+          description = lib.mdDoc ''
             Options which are added to tuners.yml. If none is specified, it will
             automatically be generated at runtime.
 
             Documentation:
-            <link xlink:href="https://github.com/Chinachu/Mirakurun/blob/master/doc/Configuration.md"/>
+            <https://github.com/Chinachu/Mirakurun/blob/master/doc/Configuration.md>
           '';
         };
 
@@ -119,12 +117,12 @@ in
               }
             ];
           '';
-          description = ''
+          description = lib.mdDoc ''
             Options which are added to channels.yml. If none is specified, it
             will automatically be generated at runtime.
 
             Documentation:
-            <link xlink:href="https://github.com/Chinachu/Mirakurun/blob/master/doc/Configuration.md"/>
+            <https://github.com/Chinachu/Mirakurun/blob/master/doc/Configuration.md>
           '';
         };
       };
@@ -189,6 +187,7 @@ in
           CHANNELS_CONFIG_PATH = "/etc/mirakurun/channels.yml";
           SERVICES_DB_PATH = "/var/lib/mirakurun/services.json";
           PROGRAMS_DB_PATH = "/var/lib/mirakurun/programs.json";
+          LOGO_DATA_DIR_PATH = "/var/lib/mirakurun/logos";
           NODE_ENV = "production";
         };
 
diff --git a/nixos/modules/services/video/replay-sorcery.nix b/nixos/modules/services/video/replay-sorcery.nix
index abe7202a4a8..1be02f4d6da 100644
--- a/nixos/modules/services/video/replay-sorcery.nix
+++ b/nixos/modules/services/video/replay-sorcery.nix
@@ -9,23 +9,23 @@ in
 {
   options = with types; {
     services.replay-sorcery = {
-      enable = mkEnableOption "the ReplaySorcery service for instant-replays";
+      enable = mkEnableOption (lib.mdDoc "the ReplaySorcery service for instant-replays");
 
-      enableSysAdminCapability = mkEnableOption ''
+      enableSysAdminCapability = mkEnableOption (lib.mdDoc ''
         the system admin capability to support hardware accelerated
         video capture. This is equivalent to running ReplaySorcery as
-        root, so use with caution'';
+        root, so use with caution'');
 
       autoStart = mkOption {
         type = bool;
         default = false;
-        description = "Automatically start ReplaySorcery when graphical-session.target starts.";
+        description = lib.mdDoc "Automatically start ReplaySorcery when graphical-session.target starts.";
       };
 
       settings = mkOption {
         type = attrsOf (oneOf [ str int ]);
         default = {};
-        description = "System-wide configuration for ReplaySorcery (/etc/replay-sorcery.conf).";
+        description = lib.mdDoc "System-wide configuration for ReplaySorcery (/etc/replay-sorcery.conf).";
         example = literalExpression ''
           {
             videoInput = "hwaccel"; # requires `services.replay-sorcery.enableSysAdminCapability = true`
diff --git a/nixos/modules/services/video/rtsp-simple-server.nix b/nixos/modules/services/video/rtsp-simple-server.nix
index 644b1945a1e..2dd62edab78 100644
--- a/nixos/modules/services/video/rtsp-simple-server.nix
+++ b/nixos/modules/services/video/rtsp-simple-server.nix
@@ -10,12 +10,12 @@ in
 {
   options = {
     services.rtsp-simple-server = {
-      enable = mkEnableOption "RTSP Simple Server";
+      enable = mkEnableOption (lib.mdDoc "RTSP Simple Server");
 
       settings = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Settings for rtsp-simple-server.
-          Read more at <link xlink:href="https://github.com/aler9/rtsp-simple-server/blob/main/rtsp-simple-server.yml"/>
+          Read more at <https://github.com/aler9/rtsp-simple-server/blob/main/rtsp-simple-server.yml>
         '';
         type = format.type;
 
@@ -40,7 +40,7 @@ in
 
       env = mkOption {
         type = with types; attrsOf anything;
-        description = "Extra environment variables for RTSP Simple Server";
+        description = lib.mdDoc "Extra environment variables for RTSP Simple Server";
         default = {};
         example = {
           RTSP_CONFKEY = "mykey";
diff --git a/nixos/modules/services/video/unifi-video.nix b/nixos/modules/services/video/unifi-video.nix
index 43208a9fe4c..fcc3cb02a1b 100644
--- a/nixos/modules/services/video/unifi-video.nix
+++ b/nixos/modules/services/video/unifi-video.nix
@@ -16,7 +16,7 @@ let
     -pidfile ${cfg.pidFile} \
     -procname unifi-video \
     -Djava.security.egd=file:/dev/./urandom \
-    -Xmx${cfg.maximumJavaHeapSize}M \
+    -Xmx${toString cfg.maximumJavaHeapSize}M \
     -Xss512K \
     -XX:+UseG1GC \
     -XX:+UseStringDeduplication \
@@ -91,98 +91,102 @@ let
   stateDir = "/var/lib/unifi-video";
 
 in
-  {
-
-    options.services.unifi-video = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Whether or not to enable the unifi-video service.
-        '';
-      };
+{
 
-      jrePackage = mkOption {
-        type = types.package;
-        default = pkgs.jre8;
-        defaultText = literalExpression "pkgs.jre8";
-        description = ''
-          The JRE package to use. Check the release notes to ensure it is supported.
-        '';
-      };
+  options.services.unifi-video = {
 
-      unifiVideoPackage = mkOption {
-        type = types.package;
-        default = pkgs.unifi-video;
-        defaultText = literalExpression "pkgs.unifi-video";
-        description = ''
-          The unifi-video package to use.
-        '';
-      };
+    enable = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Whether or not to enable the unifi-video service.
+      '';
+    };
 
-      mongodbPackage = mkOption {
-        type = types.package;
-        default = pkgs.mongodb-4_0;
-        defaultText = literalExpression "pkgs.mongodb";
-        description = ''
-          The mongodb package to use.
-        '';
-      };
+    jrePackage = mkOption {
+      type = types.package;
+      default = pkgs.jre8;
+      defaultText = literalExpression "pkgs.jre8";
+      description = lib.mdDoc ''
+        The JRE package to use. Check the release notes to ensure it is supported.
+      '';
+    };
 
-      logDir = mkOption {
-        type = types.str;
-        default = "${stateDir}/logs";
-        description = ''
-          Where to store the logs.
-        '';
-      };
+    unifiVideoPackage = mkOption {
+      type = types.package;
+      default = pkgs.unifi-video;
+      defaultText = literalExpression "pkgs.unifi-video";
+      description = lib.mdDoc ''
+        The unifi-video package to use.
+      '';
+    };
 
-      dataDir = mkOption {
-        type = types.str;
-        default = "${stateDir}/data";
-        description = ''
-          Where to store the database and other data.
-        '';
-      };
+    mongodbPackage = mkOption {
+      type = types.package;
+      default = pkgs.mongodb-4_0;
+      defaultText = literalExpression "pkgs.mongodb";
+      description = lib.mdDoc ''
+        The mongodb package to use.
+      '';
+    };
 
-      openPorts = mkOption {
-        type = types.bool;
-        default = true;
-        description = ''
-          Whether or not to open the required ports on the firewall.
-        '';
-      };
+    logDir = mkOption {
+      type = types.str;
+      default = "${stateDir}/logs";
+      description = lib.mdDoc ''
+        Where to store the logs.
+      '';
+    };
 
-      maximumJavaHeapSize = mkOption {
-        type = types.nullOr types.int;
-        default = 1024;
-        example = 4096;
-        description = ''
-          Set the maximimum heap size for the JVM in MB.
-        '';
-      };
+    dataDir = mkOption {
+      type = types.str;
+      default = "${stateDir}/data";
+      description = lib.mdDoc ''
+        Where to store the database and other data.
+      '';
+    };
 
-      pidFile = mkOption {
-        type = types.path;
-        default = "${cfg.dataDir}/unifi-video.pid";
-        defaultText = literalExpression ''"''${config.${opt.dataDir}}/unifi-video.pid"'';
-        description = "Location of unifi-video pid file.";
-      };
+    openFirewall = mkOption {
+      type = types.bool;
+      default = true;
+      description = lib.mdDoc ''
+        Whether or not to open the required ports on the firewall.
+      '';
+    };
+
+    maximumJavaHeapSize = mkOption {
+      type = types.nullOr types.int;
+      default = 1024;
+      example = 4096;
+      description = lib.mdDoc ''
+        Set the maximimum heap size for the JVM in MB.
+      '';
+    };
+
+    pidFile = mkOption {
+      type = types.path;
+      default = "${cfg.dataDir}/unifi-video.pid";
+      defaultText = literalExpression ''"''${config.${opt.dataDir}}/unifi-video.pid"'';
+      description = lib.mdDoc "Location of unifi-video pid file.";
+    };
+
+  };
+
+  config = mkIf cfg.enable {
 
-};
+    warnings = optional
+      (options.services.unifi-video.openFirewall.highestPrio >= (mkOptionDefault null).priority)
+      "The current services.unifi-video.openFirewall = true default is deprecated and will change to false in 22.11. Set it explicitly to silence this warning.";
 
-config = mkIf cfg.enable {
-  users = {
-    users.unifi-video = {
+    users.users.unifi-video = {
       description = "UniFi Video controller daemon user";
       home = stateDir;
       group = "unifi-video";
       isSystemUser = true;
     };
-    groups.unifi-video = {};
-  };
+    users.groups.unifi-video = {};
 
-  networking.firewall = mkIf cfg.openPorts {
+    networking.firewall = mkIf cfg.openFirewall {
       # https://help.ui.com/hc/en-us/articles/217875218-UniFi-Video-Ports-Used
       allowedTCPPorts = [
         7080 # HTTP portal
@@ -237,7 +241,6 @@ config = mkIf cfg.enable {
       "L+ '${stateDir}/conf/server.xml' 0700 unifi-video unifi-video - ${pkgs.unifi-video}/lib/unifi-video/conf/server.xml"
       "L+ '${stateDir}/conf/tomcat-users.xml' 0700 unifi-video unifi-video - ${pkgs.unifi-video}/lib/unifi-video/conf/tomcat-users.xml"
       "L+ '${stateDir}/conf/web.xml' 0700 unifi-video unifi-video - ${pkgs.unifi-video}/lib/unifi-video/conf/web.xml"
-
     ];
 
     systemd.services.unifi-video = {
@@ -258,10 +261,11 @@ config = mkIf cfg.enable {
         WorkingDirectory = "${stateDir}";
       };
     };
-
   };
 
-  meta = {
-    maintainers = with lib.maintainers; [ rsynnest ];
-  };
+  imports = [
+    (mkRenamedOptionModule [ "services" "unifi-video" "openPorts" ] [ "services" "unifi-video" "openFirewall" ])
+  ];
+
+  meta.maintainers = with lib.maintainers; [ rsynnest ];
 }
diff --git a/nixos/modules/services/wayland/cage.nix b/nixos/modules/services/wayland/cage.nix
index a32b81a916f..330dce1d0c0 100644
--- a/nixos/modules/services/wayland/cage.nix
+++ b/nixos/modules/services/wayland/cage.nix
@@ -5,12 +5,12 @@ with lib;
 let
   cfg = config.services.cage;
 in {
-  options.services.cage.enable = mkEnableOption "cage kiosk service";
+  options.services.cage.enable = mkEnableOption (lib.mdDoc "cage kiosk service");
 
   options.services.cage.user = mkOption {
     type = types.str;
     default = "demo";
-    description = ''
+    description = lib.mdDoc ''
       User to log-in as.
     '';
   };
@@ -19,7 +19,7 @@ in {
     type = types.listOf types.str;
     default = [];
     defaultText = literalExpression "[]";
-    description = "Additional command line arguments to pass to Cage.";
+    description = lib.mdDoc "Additional command line arguments to pass to Cage.";
     example = ["-d"];
   };
 
@@ -27,7 +27,7 @@ in {
     type = types.path;
     default = "${pkgs.xterm}/bin/xterm";
     defaultText = literalExpression ''"''${pkgs.xterm}/bin/xterm"'';
-    description = ''
+    description = lib.mdDoc ''
       Program to run in cage.
     '';
   };
@@ -88,7 +88,7 @@ in {
       account required pam_unix.so
       session required pam_unix.so
       session required pam_env.so conffile=/etc/pam/environment readenv=0
-      session required ${pkgs.systemd}/lib/security/pam_systemd.so
+      session required ${config.systemd.package}/lib/security/pam_systemd.so
     '';
 
     hardware.opengl.enable = mkDefault true;
diff --git a/nixos/modules/services/web-apps/alps.nix b/nixos/modules/services/web-apps/alps.nix
new file mode 100644
index 00000000000..1a58df2da1d
--- /dev/null
+++ b/nixos/modules/services/web-apps/alps.nix
@@ -0,0 +1,132 @@
+{ lib, pkgs, config, ... }:
+
+with lib;
+
+let
+  cfg = config.services.alps;
+in {
+  options.services.alps = {
+    enable = mkEnableOption (lib.mdDoc "alps");
+
+    port = mkOption {
+      type = types.port;
+      default = 1323;
+      description = lib.mdDoc ''
+        TCP port the service should listen on.
+      '';
+    };
+
+    bindIP = mkOption {
+      default = "[::]";
+      type = types.str;
+      description = lib.mdDoc ''
+        The IP the service should listen on.
+      '';
+    };
+
+    theme = mkOption {
+      type = types.enum [ "alps" "sourcehut" ];
+      default = "sourcehut";
+      description = lib.mdDoc ''
+        The frontend's theme to use.
+      '';
+    };
+
+    imaps = {
+      port = mkOption {
+        type = types.port;
+        default = 993;
+        description = lib.mdDoc ''
+          The IMAPS server port.
+        '';
+      };
+
+      host = mkOption {
+        type = types.str;
+        default = "[::1]";
+        example = "mail.example.org";
+        description = lib.mdDoc ''
+          The IMAPS server address.
+        '';
+      };
+    };
+
+    smtps = {
+      port = mkOption {
+        type = types.port;
+        default = 465;
+        description = lib.mdDoc ''
+          The SMTPS server port.
+        '';
+      };
+
+      host = mkOption {
+        type = types.str;
+        default = cfg.imaps.host;
+        defaultText = "services.alps.imaps.host";
+        example = "mail.example.org";
+        description = lib.mdDoc ''
+          The SMTPS server address.
+        '';
+      };
+    };
+
+    package = mkOption {
+      internal = true;
+      type = types.package;
+      default = pkgs.alps;
+    };
+
+    args = mkOption {
+      internal = true;
+      type = types.listOf types.str;
+      default = [
+        "-addr" "${cfg.bindIP}:${toString cfg.port}"
+        "-theme" "${cfg.theme}"
+        "imaps://${cfg.imaps.host}:${toString cfg.imaps.port}"
+        "smpts://${cfg.smtps.host}:${toString cfg.smtps.port}"
+      ];
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.alps = {
+      description = "alps is a simple and extensible webmail.";
+      documentation = [ "https://git.sr.ht/~migadu/alps" ];
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" "network-online.target" ];
+
+      serviceConfig = {
+        ExecStart = "${cfg.package}/bin/alps ${escapeShellArgs cfg.args}";
+        AmbientCapabilities = "";
+        CapabilityBoundingSet = "";
+        DynamicUser = true;
+        LockPersonality = true;
+        MemoryDenyWriteExecute = true;
+        NoNewPrivileges = true;
+        PrivateDevices = true;
+        PrivateIPC = true;
+        PrivateTmp = true;
+        PrivateUsers = true;
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectProc = "invisible";
+        ProtectSystem = "strict";
+        RemoveIPC = true;
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        RestrictSUIDSGID = true;
+        SocketBindAllow = cfg.port;
+        SocketBindDeny = "any";
+        SystemCallArchitectures = "native";
+        SystemCallFilter = [ "@system-service" "~@privileged @obsolete" ];
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/web-apps/atlassian/confluence.nix b/nixos/modules/services/web-apps/atlassian/confluence.nix
index 2d809c17ff0..fe98c1777ea 100644
--- a/nixos/modules/services/web-apps/atlassian/confluence.nix
+++ b/nixos/modules/services/web-apps/atlassian/confluence.nix
@@ -8,114 +8,122 @@ let
 
   pkg = cfg.package.override (optionalAttrs cfg.sso.enable {
     enableSSO = cfg.sso.enable;
-    crowdProperties = ''
-      application.name                        ${cfg.sso.applicationName}
-      application.password                    ${cfg.sso.applicationPassword}
-      application.login.url                   ${cfg.sso.crowd}/console/
-
-      crowd.server.url                        ${cfg.sso.crowd}/services/
-      crowd.base.url                          ${cfg.sso.crowd}/
-
-      session.isauthenticated                 session.isauthenticated
-      session.tokenkey                        session.tokenkey
-      session.validationinterval              ${toString cfg.sso.validationInterval}
-      session.lastvalidation                  session.lastvalidation
-    '';
   });
 
+  crowdProperties = pkgs.writeText "crowd.properties" ''
+    application.name                        ${cfg.sso.applicationName}
+    application.password                    ${if cfg.sso.applicationPassword != null then cfg.sso.applicationPassword else "@NIXOS_CONFLUENCE_CROWD_SSO_PWD@"}
+    application.login.url                   ${cfg.sso.crowd}/console/
+
+    crowd.server.url                        ${cfg.sso.crowd}/services/
+    crowd.base.url                          ${cfg.sso.crowd}/
+
+    session.isauthenticated                 session.isauthenticated
+    session.tokenkey                        session.tokenkey
+    session.validationinterval              ${toString cfg.sso.validationInterval}
+    session.lastvalidation                  session.lastvalidation
+  '';
+
 in
 
 {
   options = {
     services.confluence = {
-      enable = mkEnableOption "Atlassian Confluence service";
+      enable = mkEnableOption (lib.mdDoc "Atlassian Confluence service");
 
       user = mkOption {
         type = types.str;
         default = "confluence";
-        description = "User which runs confluence.";
+        description = lib.mdDoc "User which runs confluence.";
       };
 
       group = mkOption {
         type = types.str;
         default = "confluence";
-        description = "Group which runs confluence.";
+        description = lib.mdDoc "Group which runs confluence.";
       };
 
       home = mkOption {
         type = types.str;
         default = "/var/lib/confluence";
-        description = "Home directory of the confluence instance.";
+        description = lib.mdDoc "Home directory of the confluence instance.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "Address to listen on.";
+        description = lib.mdDoc "Address to listen on.";
       };
 
       listenPort = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8090;
-        description = "Port to listen on.";
+        description = lib.mdDoc "Port to listen on.";
       };
 
       catalinaOptions = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "-Xms1024m" "-Xmx2048m" "-Dconfluence.disable.peopledirectory.all=true" ];
-        description = "Java options to pass to catalina/tomcat.";
+        description = lib.mdDoc "Java options to pass to catalina/tomcat.";
       };
 
       proxy = {
-        enable = mkEnableOption "proxy support";
+        enable = mkEnableOption (lib.mdDoc "proxy support");
 
         name = mkOption {
           type = types.str;
           example = "confluence.example.com";
-          description = "Virtual hostname at the proxy";
+          description = lib.mdDoc "Virtual hostname at the proxy";
         };
 
         port = mkOption {
-          type = types.int;
+          type = types.port;
           default = 443;
           example = 80;
-          description = "Port used at the proxy";
+          description = lib.mdDoc "Port used at the proxy";
         };
 
         scheme = mkOption {
           type = types.str;
           default = "https";
           example = "http";
-          description = "Protocol used at the proxy.";
+          description = lib.mdDoc "Protocol used at the proxy.";
         };
       };
 
       sso = {
-        enable = mkEnableOption "SSO with Atlassian Crowd";
+        enable = mkEnableOption (lib.mdDoc "SSO with Atlassian Crowd");
 
         crowd = mkOption {
           type = types.str;
           example = "http://localhost:8095/crowd";
-          description = "Crowd Base URL without trailing slash";
+          description = lib.mdDoc "Crowd Base URL without trailing slash";
         };
 
         applicationName = mkOption {
           type = types.str;
           example = "jira";
-          description = "Exact name of this Confluence instance in Crowd";
+          description = lib.mdDoc "Exact name of this Confluence instance in Crowd";
         };
 
         applicationPassword = mkOption {
-          type = types.str;
-          description = "Application password of this Confluence instance in Crowd";
+          type = types.nullOr types.str;
+          default = null;
+          description = lib.mdDoc "Application password of this Confluence instance in Crowd";
+        };
+
+        applicationPasswordFile = mkOption {
+          type = types.nullOr types.str;
+          default = null;
+          description = lib.mdDoc "Path to the application password for Crowd of Confluence.";
         };
 
         validationInterval = mkOption {
           type = types.int;
           default = 2;
           example = 0;
-          description = ''
+          description = lib.mdDoc ''
             Set to 0, if you want authentication checks to occur on each
             request. Otherwise set to the number of minutes between request
             to validate if the user is logged in or out of the Crowd SSO
@@ -129,14 +137,14 @@ in
         type = types.package;
         default = pkgs.atlassian-confluence;
         defaultText = literalExpression "pkgs.atlassian-confluence";
-        description = "Atlassian Confluence package to use.";
+        description = lib.mdDoc "Atlassian Confluence package to use.";
       };
 
       jrePackage = mkOption {
         type = types.package;
         default = pkgs.oraclejre8;
         defaultText = literalExpression "pkgs.oraclejre8";
-        description = "Note that Atlassian only support the Oracle JRE (JRASERVER-46152).";
+        description = lib.mdDoc "Note that Atlassian only support the Oracle JRE (JRASERVER-46152).";
       };
     };
   };
@@ -147,6 +155,16 @@ in
       group = cfg.group;
     };
 
+    assertions = [
+      { assertion = cfg.sso.enable -> ((cfg.sso.applicationPassword == null) != (cfg.sso.applicationPasswordFile));
+        message = "Please set either applicationPassword or applicationPasswordFile";
+      }
+    ];
+
+    warnings = mkIf (cfg.sso.enable && cfg.sso.applicationPassword != null) [
+      "Using `services.confluence.sso.applicationPassword` is deprecated! Use `applicationPasswordFile` instead!"
+    ];
+
     users.groups.${cfg.group} = {};
 
     systemd.tmpfiles.rules = [
@@ -173,6 +191,7 @@ in
         CONF_USER = cfg.user;
         JAVA_HOME = "${cfg.jrePackage}";
         CATALINA_OPTS = concatStringsSep " " cfg.catalinaOptions;
+        JAVA_OPTS = mkIf cfg.sso.enable "-Dcrowd.properties=${cfg.home}/crowd.properties";
       };
 
       preStart = ''
@@ -183,12 +202,24 @@ in
           -e 's,protocol="org.apache.coyote.http11.Http11NioProtocol",protocol="org.apache.coyote.http11.Http11NioProtocol" proxyName="${cfg.proxy.name}" proxyPort="${toString cfg.proxy.port}" scheme="${cfg.proxy.scheme}",' \
         '') + ''
           ${pkg}/conf/server.xml.dist > ${cfg.home}/server.xml
+
+        ${optionalString cfg.sso.enable ''
+          install -m660 ${crowdProperties} ${cfg.home}/crowd.properties
+          ${optionalString (cfg.sso.applicationPasswordFile != null) ''
+            ${pkgs.replace-secret}/bin/replace-secret \
+              '@NIXOS_CONFLUENCE_CROWD_SSO_PWD@' \
+              ${cfg.sso.applicationPasswordFile} \
+              ${cfg.home}/crowd.properties
+          ''}
+        ''}
       '';
 
       serviceConfig = {
         User = cfg.user;
         Group = cfg.group;
         PrivateTmp = true;
+        Restart = "on-failure";
+        RestartSec = "10";
         ExecStart = "${pkg}/bin/start-confluence.sh -fg";
         ExecStop = "${pkg}/bin/stop-confluence.sh";
       };
diff --git a/nixos/modules/services/web-apps/atlassian/crowd.nix b/nixos/modules/services/web-apps/atlassian/crowd.nix
index a8b2482d5a9..c8d1eaef31d 100644
--- a/nixos/modules/services/web-apps/atlassian/crowd.nix
+++ b/nixos/modules/services/web-apps/atlassian/crowd.nix
@@ -14,82 +14,104 @@ let
     proxyUrl = "${cfg.proxy.scheme}://${cfg.proxy.name}:${toString cfg.proxy.port}";
   });
 
+  crowdPropertiesFile = pkgs.writeText "crowd.properties" ''
+    application.name                        crowd-openid-server
+    application.password @NIXOS_CROWD_OPENID_PW@
+    application.base.url                    http://localhost:${toString cfg.listenPort}/openidserver
+    application.login.url                   http://localhost:${toString cfg.listenPort}/openidserver
+    application.login.url.template          http://localhost:${toString cfg.listenPort}/openidserver?returnToUrl=''${RETURN_TO_URL}
+
+    crowd.server.url                        http://localhost:${toString cfg.listenPort}/crowd/services/
+
+    session.isauthenticated                 session.isauthenticated
+    session.tokenkey                        session.tokenkey
+    session.validationinterval              0
+    session.lastvalidation                  session.lastvalidation
+  '';
+
 in
 
 {
   options = {
     services.crowd = {
-      enable = mkEnableOption "Atlassian Crowd service";
+      enable = mkEnableOption (lib.mdDoc "Atlassian Crowd service");
 
       user = mkOption {
         type = types.str;
         default = "crowd";
-        description = "User which runs Crowd.";
+        description = lib.mdDoc "User which runs Crowd.";
       };
 
       group = mkOption {
         type = types.str;
         default = "crowd";
-        description = "Group which runs Crowd.";
+        description = lib.mdDoc "Group which runs Crowd.";
       };
 
       home = mkOption {
         type = types.str;
         default = "/var/lib/crowd";
-        description = "Home directory of the Crowd instance.";
+        description = lib.mdDoc "Home directory of the Crowd instance.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "Address to listen on.";
+        description = lib.mdDoc "Address to listen on.";
       };
 
       listenPort = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8092;
-        description = "Port to listen on.";
+        description = lib.mdDoc "Port to listen on.";
       };
 
       openidPassword = mkOption {
         type = types.str;
-        description = "Application password for OpenID server.";
+        default = "WILL_NEVER_BE_SET";
+        description = lib.mdDoc "Application password for OpenID server.";
+      };
+
+      openidPasswordFile = mkOption {
+        type = types.nullOr types.str;
+        default = null;
+        description = lib.mdDoc "Path to the file containing the application password for OpenID server.";
       };
 
       catalinaOptions = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "-Xms1024m" "-Xmx2048m" ];
-        description = "Java options to pass to catalina/tomcat.";
+        description = lib.mdDoc "Java options to pass to catalina/tomcat.";
       };
 
       proxy = {
-        enable = mkEnableOption "reverse proxy support";
+        enable = mkEnableOption (lib.mdDoc "reverse proxy support");
 
         name = mkOption {
           type = types.str;
           example = "crowd.example.com";
-          description = "Virtual hostname at the proxy";
+          description = lib.mdDoc "Virtual hostname at the proxy";
         };
 
         port = mkOption {
-          type = types.int;
+          type = types.port;
           default = 443;
           example = 80;
-          description = "Port used at the proxy";
+          description = lib.mdDoc "Port used at the proxy";
         };
 
         scheme = mkOption {
           type = types.str;
           default = "https";
           example = "http";
-          description = "Protocol used at the proxy.";
+          description = lib.mdDoc "Protocol used at the proxy.";
         };
 
         secure = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether the connections to the proxy should be considered secure.";
+          description = lib.mdDoc "Whether the connections to the proxy should be considered secure.";
         };
       };
 
@@ -97,14 +119,14 @@ in
         type = types.package;
         default = pkgs.atlassian-crowd;
         defaultText = literalExpression "pkgs.atlassian-crowd";
-        description = "Atlassian Crowd package to use.";
+        description = lib.mdDoc "Atlassian Crowd package to use.";
       };
 
       jrePackage = mkOption {
         type = types.package;
         default = pkgs.oraclejre8;
         defaultText = literalExpression "pkgs.oraclejre8";
-        description = "Note that Atlassian only support the Oracle JRE (JRASERVER-46152).";
+        description = lib.mdDoc "Note that Atlassian only support the Oracle JRE (JRASERVER-46152).";
       };
     };
   };
@@ -140,6 +162,7 @@ in
         JAVA_HOME = "${cfg.jrePackage}";
         CATALINA_OPTS = concatStringsSep " " cfg.catalinaOptions;
         CATALINA_TMPDIR = "/tmp";
+        JAVA_OPTS = mkIf (cfg.openidPasswordFile != null) "-Dcrowd.properties=${cfg.home}/crowd.properties";
       };
 
       preStart = ''
@@ -151,12 +174,22 @@ in
           -e 's,compression="on",compression="off" protocol="HTTP/1.1" proxyName="${cfg.proxy.name}" proxyPort="${toString cfg.proxy.port}" scheme="${cfg.proxy.scheme}" secure="${boolToString cfg.proxy.secure}",' \
         '') + ''
           ${pkg}/apache-tomcat/conf/server.xml.dist > ${cfg.home}/server.xml
+
+        ${optionalString (cfg.openidPasswordFile != null) ''
+          install -m660 ${crowdPropertiesFile} ${cfg.home}/crowd.properties
+          ${pkgs.replace-secret}/bin/replace-secret \
+            '@NIXOS_CROWD_OPENID_PW@' \
+            ${cfg.openidPasswordFile} \
+            ${cfg.home}/crowd.properties
+        ''}
       '';
 
       serviceConfig = {
         User = cfg.user;
         Group = cfg.group;
         PrivateTmp = true;
+        Restart = "on-failure";
+        RestartSec = "10";
         ExecStart = "${pkg}/start_crowd.sh -fg";
       };
     };
diff --git a/nixos/modules/services/web-apps/atlassian/jira.nix b/nixos/modules/services/web-apps/atlassian/jira.nix
index d7a26838d6f..4cc85821694 100644
--- a/nixos/modules/services/web-apps/atlassian/jira.nix
+++ b/nixos/modules/services/web-apps/atlassian/jira.nix
@@ -8,120 +8,121 @@ let
 
   pkg = cfg.package.override (optionalAttrs cfg.sso.enable {
     enableSSO = cfg.sso.enable;
-    crowdProperties = ''
-      application.name                        ${cfg.sso.applicationName}
-      application.password                    ${cfg.sso.applicationPassword}
-      application.login.url                   ${cfg.sso.crowd}/console/
-
-      crowd.server.url                        ${cfg.sso.crowd}/services/
-      crowd.base.url                          ${cfg.sso.crowd}/
-
-      session.isauthenticated                 session.isauthenticated
-      session.tokenkey                        session.tokenkey
-      session.validationinterval              ${toString cfg.sso.validationInterval}
-      session.lastvalidation                  session.lastvalidation
-    '';
   });
 
+  crowdProperties = pkgs.writeText "crowd.properties" ''
+    application.name                        ${cfg.sso.applicationName}
+    application.password                    @NIXOS_JIRA_CROWD_SSO_PWD@
+    application.login.url                   ${cfg.sso.crowd}/console/
+
+    crowd.server.url                        ${cfg.sso.crowd}/services/
+    crowd.base.url                          ${cfg.sso.crowd}/
+
+    session.isauthenticated                 session.isauthenticated
+    session.tokenkey                        session.tokenkey
+    session.validationinterval              ${toString cfg.sso.validationInterval}
+    session.lastvalidation                  session.lastvalidation
+  '';
+
 in
 
 {
   options = {
     services.jira = {
-      enable = mkEnableOption "Atlassian JIRA service";
+      enable = mkEnableOption (lib.mdDoc "Atlassian JIRA service");
 
       user = mkOption {
         type = types.str;
         default = "jira";
-        description = "User which runs JIRA.";
+        description = lib.mdDoc "User which runs JIRA.";
       };
 
       group = mkOption {
         type = types.str;
         default = "jira";
-        description = "Group which runs JIRA.";
+        description = lib.mdDoc "Group which runs JIRA.";
       };
 
       home = mkOption {
         type = types.str;
         default = "/var/lib/jira";
-        description = "Home directory of the JIRA instance.";
+        description = lib.mdDoc "Home directory of the JIRA instance.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "Address to listen on.";
+        description = lib.mdDoc "Address to listen on.";
       };
 
       listenPort = mkOption {
-        type = types.int;
+        type = types.port;
         default = 8091;
-        description = "Port to listen on.";
+        description = lib.mdDoc "Port to listen on.";
       };
 
       catalinaOptions = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "-Xms1024m" "-Xmx2048m" ];
-        description = "Java options to pass to catalina/tomcat.";
+        description = lib.mdDoc "Java options to pass to catalina/tomcat.";
       };
 
       proxy = {
-        enable = mkEnableOption "reverse proxy support";
+        enable = mkEnableOption (lib.mdDoc "reverse proxy support");
 
         name = mkOption {
           type = types.str;
           example = "jira.example.com";
-          description = "Virtual hostname at the proxy";
+          description = lib.mdDoc "Virtual hostname at the proxy";
         };
 
         port = mkOption {
-          type = types.int;
+          type = types.port;
           default = 443;
           example = 80;
-          description = "Port used at the proxy";
+          description = lib.mdDoc "Port used at the proxy";
         };
 
         scheme = mkOption {
           type = types.str;
           default = "https";
           example = "http";
-          description = "Protocol used at the proxy.";
+          description = lib.mdDoc "Protocol used at the proxy.";
         };
 
         secure = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether the connections to the proxy should be considered secure.";
+          description = lib.mdDoc "Whether the connections to the proxy should be considered secure.";
         };
       };
 
       sso = {
-        enable = mkEnableOption "SSO with Atlassian Crowd";
+        enable = mkEnableOption (lib.mdDoc "SSO with Atlassian Crowd");
 
         crowd = mkOption {
           type = types.str;
           example = "http://localhost:8095/crowd";
-          description = "Crowd Base URL without trailing slash";
+          description = lib.mdDoc "Crowd Base URL without trailing slash";
         };
 
         applicationName = mkOption {
           type = types.str;
           example = "jira";
-          description = "Exact name of this JIRA instance in Crowd";
+          description = lib.mdDoc "Exact name of this JIRA instance in Crowd";
         };
 
-        applicationPassword = mkOption {
+        applicationPasswordFile = mkOption {
           type = types.str;
-          description = "Application password of this JIRA instance in Crowd";
+          description = lib.mdDoc "Path to the file containing the application password of this JIRA instance in Crowd";
         };
 
         validationInterval = mkOption {
           type = types.int;
           default = 2;
           example = 0;
-          description = ''
+          description = lib.mdDoc ''
             Set to 0, if you want authentication checks to occur on each
             request. Otherwise set to the number of minutes between request
             to validate if the user is logged in or out of the Crowd SSO
@@ -135,14 +136,14 @@ in
         type = types.package;
         default = pkgs.atlassian-jira;
         defaultText = literalExpression "pkgs.atlassian-jira";
-        description = "Atlassian JIRA package to use.";
+        description = lib.mdDoc "Atlassian JIRA package to use.";
       };
 
       jrePackage = mkOption {
         type = types.package;
         default = pkgs.oraclejre8;
         defaultText = literalExpression "pkgs.oraclejre8";
-        description = "Note that Atlassian only support the Oracle JRE (JRASERVER-46152).";
+        description = lib.mdDoc "Note that Atlassian only support the Oracle JRE (JRASERVER-46152).";
       };
     };
   };
@@ -151,6 +152,7 @@ in
     users.users.${cfg.user} = {
       isSystemUser = true;
       group = cfg.group;
+      home = cfg.home;
     };
 
     users.groups.${cfg.group} = {};
@@ -180,6 +182,7 @@ in
         JIRA_HOME = cfg.home;
         JAVA_HOME = "${cfg.jrePackage}";
         CATALINA_OPTS = concatStringsSep " " cfg.catalinaOptions;
+        JAVA_OPTS = mkIf cfg.sso.enable "-Dcrowd.properties=${cfg.home}/crowd.properties";
       };
 
       preStart = ''
@@ -190,15 +193,31 @@ in
           -e 's,protocol="HTTP/1.1",protocol="HTTP/1.1" proxyName="${cfg.proxy.name}" proxyPort="${toString cfg.proxy.port}" scheme="${cfg.proxy.scheme}" secure="${toString cfg.proxy.secure}",' \
         '') + ''
           ${pkg}/conf/server.xml.dist > ${cfg.home}/server.xml
+
+        ${optionalString cfg.sso.enable ''
+          install -m660 ${crowdProperties} ${cfg.home}/crowd.properties
+          ${pkgs.replace-secret}/bin/replace-secret \
+            '@NIXOS_JIRA_CROWD_SSO_PWD@' \
+            ${cfg.sso.applicationPasswordFile} \
+            ${cfg.home}/crowd.properties
+        ''}
       '';
 
       serviceConfig = {
         User = cfg.user;
         Group = cfg.group;
         PrivateTmp = true;
+        Restart = "on-failure";
+        RestartSec = "10";
         ExecStart = "${pkg}/bin/start-jira.sh -fg";
         ExecStop = "${pkg}/bin/stop-jira.sh";
       };
     };
   };
+
+  imports = [
+    (mkRemovedOptionModule [ "services" "jira" "sso" "applicationPassword" ] ''
+      Use `applicationPasswordFile` instead!
+    '')
+  ];
 }
diff --git a/nixos/modules/services/web-apps/baget.nix b/nixos/modules/services/web-apps/baget.nix
index 3007dd4fbb2..e4d5a1faddb 100644
--- a/nixos/modules/services/web-apps/baget.nix
+++ b/nixos/modules/services/web-apps/baget.nix
@@ -53,12 +53,12 @@ let
 in
 {
   options.services.baget = {
-    enable = mkEnableOption "BaGet NuGet-compatible server";
+    enable = mkEnableOption (lib.mdDoc "BaGet NuGet-compatible server");
 
     apiKeyFile = mkOption {
       type = types.path;
       example = "/root/baget.key";
-      description = ''
+      description = lib.mdDoc ''
         Private API key for BaGet.
       '';
     };
@@ -112,8 +112,8 @@ in
           };
         }
       '';
-      description = ''
-        Extra configuration options for BaGet. Refer to <link xlink:href="https://loic-sharma.github.io/BaGet/configuration/"/> for details.
+      description = lib.mdDoc ''
+        Extra configuration options for BaGet. Refer to <https://loic-sharma.github.io/BaGet/configuration/> for details.
         Default value is merged with values from here.
       '';
     };
diff --git a/nixos/modules/services/web-apps/bookstack.nix b/nixos/modules/services/web-apps/bookstack.nix
index 64a2767fab6..40bb377e2c8 100644
--- a/nixos/modules/services/web-apps/bookstack.nix
+++ b/nixos/modules/services/web-apps/bookstack.nix
@@ -34,25 +34,25 @@ in {
 
   options.services.bookstack = {
 
-    enable = mkEnableOption "BookStack";
+    enable = mkEnableOption (lib.mdDoc "BookStack");
 
     user = mkOption {
       default = "bookstack";
-      description = "User bookstack runs as.";
+      description = lib.mdDoc "User bookstack runs as.";
       type = types.str;
     };
 
     group = mkOption {
       default = "bookstack";
-      description = "Group bookstack runs as.";
+      description = lib.mdDoc "Group bookstack runs as.";
       type = types.str;
     };
 
     appKeyFile = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         A file containing the Laravel APP_KEY - a 32 character long,
         base64 encoded key used for encryption where needed. Can be
-        generated with <code>head -c 32 /dev/urandom | base64</code>.
+        generated with `head -c 32 /dev/urandom | base64`.
       '';
       example = "/run/keys/bookstack-appkey";
       type = types.path;
@@ -60,21 +60,18 @@ in {
 
     hostname = lib.mkOption {
       type = lib.types.str;
-      default = if config.networking.domain != null then
-                  config.networking.fqdn
-                else
-                  config.networking.hostName;
-      defaultText = lib.literalExpression "config.networking.fqdn";
+      default = config.networking.fqdnOrHostName;
+      defaultText = lib.literalExpression "config.networking.fqdnOrHostName";
       example = "bookstack.example.com";
-      description = ''
+      description = lib.mdDoc ''
         The hostname to serve BookStack on.
       '';
     };
 
     appURL = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The root URL that you want to host BookStack on. All URLs in BookStack will be generated using this value.
-        If you change this in the future you may need to run a command to update stored URLs in the database. Command example: <code>php artisan bookstack:update-url https://old.example.com https://new.example.com</code>
+        If you change this in the future you may need to run a command to update stored URLs in the database. Command example: `php artisan bookstack:update-url https://old.example.com https://new.example.com`
       '';
       default = "http${lib.optionalString tlsEnabled "s"}://${cfg.hostname}";
       defaultText = ''http''${lib.optionalString tlsEnabled "s"}://''${cfg.hostname}'';
@@ -83,7 +80,7 @@ in {
     };
 
     dataDir = mkOption {
-      description = "BookStack data directory";
+      description = lib.mdDoc "BookStack data directory";
       default = "/var/lib/bookstack";
       type = types.path;
     };
@@ -92,37 +89,37 @@ in {
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Database host address.";
+        description = lib.mdDoc "Database host address.";
       };
       port = mkOption {
         type = types.port;
         default = 3306;
-        description = "Database host port.";
+        description = lib.mdDoc "Database host port.";
       };
       name = mkOption {
         type = types.str;
         default = "bookstack";
-        description = "Database name.";
+        description = lib.mdDoc "Database name.";
       };
       user = mkOption {
         type = types.str;
         default = user;
         defaultText = literalExpression "user";
-        description = "Database username.";
+        description = lib.mdDoc "Database username.";
       };
       passwordFile = mkOption {
         type = with types; nullOr path;
         default = null;
         example = "/run/keys/bookstack-dbpassword";
-        description = ''
+        description = lib.mdDoc ''
           A file containing the password corresponding to
-          <option>database.user</option>.
+          {option}`database.user`.
         '';
       };
       createLocally = mkOption {
         type = types.bool;
         default = false;
-        description = "Create the database and database user locally.";
+        description = lib.mdDoc "Create the database and database user locally.";
       };
     };
 
@@ -130,47 +127,47 @@ in {
       driver = mkOption {
         type = types.enum [ "smtp" "sendmail" ];
         default = "smtp";
-        description = "Mail driver to use.";
+        description = lib.mdDoc "Mail driver to use.";
       };
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Mail host address.";
+        description = lib.mdDoc "Mail host address.";
       };
       port = mkOption {
         type = types.port;
         default = 1025;
-        description = "Mail host port.";
+        description = lib.mdDoc "Mail host port.";
       };
       fromName = mkOption {
         type = types.str;
         default = "BookStack";
-        description = "Mail \"from\" name.";
+        description = lib.mdDoc "Mail \"from\" name.";
       };
       from = mkOption {
         type = types.str;
         default = "mail@bookstackapp.com";
-        description = "Mail \"from\" email.";
+        description = lib.mdDoc "Mail \"from\" email.";
       };
       user = mkOption {
         type = with types; nullOr str;
         default = null;
         example = "bookstack";
-        description = "Mail username.";
+        description = lib.mdDoc "Mail username.";
       };
       passwordFile = mkOption {
         type = with types; nullOr path;
         default = null;
         example = "/run/keys/bookstack-mailpassword";
-        description = ''
+        description = lib.mdDoc ''
           A file containing the password corresponding to
-          <option>mail.user</option>.
+          {option}`mail.user`.
         '';
       };
       encryption = mkOption {
         type = with types; nullOr (enum [ "tls" ]);
         default = null;
-        description = "SMTP encryption mechanism to use.";
+        description = lib.mdDoc "SMTP encryption mechanism to use.";
       };
     };
 
@@ -178,7 +175,7 @@ in {
       type = types.str;
       default = "18M";
       example = "1G";
-      description = "The maximum size for uploads (e.g. images).";
+      description = lib.mdDoc "The maximum size for uploads (e.g. images).";
     };
 
     poolConfig = mkOption {
@@ -191,8 +188,8 @@ in {
         "pm.max_spare_servers" = 4;
         "pm.max_requests" = 500;
       };
-      description = ''
-        Options for the bookstack PHP pool. See the documentation on <literal>php-fpm.conf</literal>
+      description = lib.mdDoc ''
+        Options for the bookstack PHP pool. See the documentation on `php-fpm.conf`
         for details on configuration directives.
       '';
     };
@@ -213,7 +210,7 @@ in {
           enableACME = true;
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         With this option, you can customize the nginx virtualHost settings.
       '';
     };
@@ -234,7 +231,7 @@ in {
                 options = {
                   _secret = mkOption {
                     type = nullOr str;
-                    description = ''
+                    description = lib.mdDoc ''
                       The path to a file containing the value the
                       option should be set to in the final
                       configuration file.
@@ -256,20 +253,20 @@ in {
           OIDC_ISSUER_DISCOVER = true;
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         BookStack configuration options to set in the
-        <filename>.env</filename> file.
+        {file}`.env` file.
 
-        Refer to <link xlink:href="https://www.bookstackapp.com/docs/"/>
+        Refer to <https://www.bookstackapp.com/docs/>
         for details on supported values.
 
         Settings containing secret data should be set to an attribute
-        set containing the attribute <literal>_secret</literal> - a
+        set containing the attribute `_secret` - a
         string pointing to a file containing the value the option
         should be set to. See the example to get a better picture of
-        this: in the resulting <filename>.env</filename> file, the
-        <literal>OIDC_CLIENT_SECRET</literal> key will be set to the
-        contents of the <filename>/run/keys/oidc_secret</filename>
+        this: in the resulting {file}`.env` file, the
+        `OIDC_CLIENT_SECRET` key will be set to the
+        contents of the {file}`/run/keys/oidc_secret`
         file.
       '';
     };
@@ -372,7 +369,7 @@ in {
         User = user;
         WorkingDirectory = "${bookstack}";
         RuntimeDirectory = "bookstack/cache";
-        RuntimeDirectoryMode = 0700;
+        RuntimeDirectoryMode = "0700";
       };
       path = [ pkgs.replace-secret ];
       script =
diff --git a/nixos/modules/services/web-apps/calibre-web.nix b/nixos/modules/services/web-apps/calibre-web.nix
index 704cd2cfa8a..143decfc091 100644
--- a/nixos/modules/services/web-apps/calibre-web.nix
+++ b/nixos/modules/services/web-apps/calibre-web.nix
@@ -8,13 +8,13 @@ in
 {
   options = {
     services.calibre-web = {
-      enable = mkEnableOption "Calibre-Web";
+      enable = mkEnableOption (lib.mdDoc "Calibre-Web");
 
       listen = {
         ip = mkOption {
           type = types.str;
           default = "::1";
-          description = ''
+          description = lib.mdDoc ''
             IP address that Calibre-Web should listen on.
           '';
         };
@@ -22,7 +22,7 @@ in
         port = mkOption {
           type = types.port;
           default = 8083;
-          description = ''
+          description = lib.mdDoc ''
             Listen port for Calibre-Web.
           '';
         };
@@ -31,27 +31,27 @@ in
       dataDir = mkOption {
         type = types.str;
         default = "calibre-web";
-        description = ''
-          The directory below <filename>/var/lib</filename> where Calibre-Web stores its data.
+        description = lib.mdDoc ''
+          The directory below {file}`/var/lib` where Calibre-Web stores its data.
         '';
       };
 
       user = mkOption {
         type = types.str;
         default = "calibre-web";
-        description = "User account under which Calibre-Web runs.";
+        description = lib.mdDoc "User account under which Calibre-Web runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "calibre-web";
-        description = "Group account under which Calibre-Web runs.";
+        description = lib.mdDoc "Group account under which Calibre-Web runs.";
       };
 
       openFirewall = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Open ports in the firewall for the server.
         '';
       };
@@ -60,7 +60,7 @@ in
         calibreLibrary = mkOption {
           type = types.nullOr types.path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Path to Calibre library.
           '';
         };
@@ -68,7 +68,7 @@ in
         enableBookConversion = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Configure path to the Calibre's ebook-convert in the DB.
           '';
         };
@@ -76,7 +76,7 @@ in
         enableBookUploading = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Allow books to be uploaded via Calibre-Web UI.
           '';
         };
@@ -85,7 +85,7 @@ in
           enable = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Enable authorization using auth proxy.
             '';
           };
@@ -93,7 +93,7 @@ in
           header = mkOption {
             type = types.str;
             default = "";
-            description = ''
+            description = lib.mdDoc ''
               Auth proxy header name.
             '';
           };
@@ -136,7 +136,7 @@ in
 
               ${pkgs.sqlite}/bin/sqlite3 ${appDb} "update settings set ${settings}"
             '' + optionalString (cfg.options.calibreLibrary != null) ''
-              test -f ${cfg.options.calibreLibrary}/metadata.db || { echo "Invalid Calibre library"; exit 1; }
+              test -f "${cfg.options.calibreLibrary}/metadata.db" || { echo "Invalid Calibre library"; exit 1; }
             ''
           );
 
diff --git a/nixos/modules/services/web-apps/changedetection-io.nix b/nixos/modules/services/web-apps/changedetection-io.nix
new file mode 100644
index 00000000000..fc00aee4351
--- /dev/null
+++ b/nixos/modules/services/web-apps/changedetection-io.nix
@@ -0,0 +1,220 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.changedetection-io;
+in
+{
+  options.services.changedetection-io = {
+    enable = mkEnableOption (lib.mdDoc "changedetection-io");
+
+    user = mkOption {
+      default = "changedetection-io";
+      type = types.str;
+      description = lib.mdDoc ''
+        User account under which changedetection-io runs.
+      '';
+    };
+
+    group = mkOption {
+      default = "changedetection-io";
+      type = types.str;
+      description = lib.mdDoc ''
+        Group account under which changedetection-io runs.
+      '';
+    };
+
+    listenAddress = mkOption {
+      type = types.str;
+      default = "localhost";
+      description = lib.mdDoc "Address the server will listen on.";
+    };
+
+    port = mkOption {
+      type = types.port;
+      default = 5000;
+      description = lib.mdDoc "Port the server will listen on.";
+    };
+
+    datastorePath = mkOption {
+      type = types.str;
+      default = "/var/lib/changedetection-io";
+      description = lib.mdDoc ''
+        The directory used to store all data for changedetection-io.
+      '';
+    };
+
+    baseURL = mkOption {
+      type = types.nullOr types.str;
+      default = null;
+      example = "https://changedetection-io.example";
+      description = lib.mdDoc ''
+        The base url used in notifications and `{base_url}` token.
+      '';
+    };
+
+    behindProxy = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Enable this option when changedetection-io runs behind a reverse proxy, so that it trusts X-* headers.
+        It is recommend to run changedetection-io behind a TLS reverse proxy.
+      '';
+    };
+
+    environmentFile = mkOption {
+      type = types.nullOr types.path;
+      default = null;
+      example = "/run/secrets/changedetection-io.env";
+      description = lib.mdDoc ''
+        Securely pass environment variabels to changedetection-io.
+
+        This can be used to set for example a frontend password reproducible via `SALTED_PASS`
+        which convinetly also deactivates nags about the hosted version.
+        `SALTED_PASS` should be 64 characters long while the first 32 are the salt and the second the frontend password.
+        It can easily be retrieved from the settings file when first set via the frontend with the following command:
+        ``jq -r .settings.application.password /var/lib/changedetection-io/url-watches.json``
+      '';
+    };
+
+    webDriverSupport = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Enable support for fetching web pages using WebDriver and Chromium.
+        This starts a headless chromium controlled by puppeteer in an oci container.
+
+        ::: {.note}
+        Playwright can currently leak memory.
+        See https://github.com/dgtlmoon/changedetection.io/wiki/Playwright-content-fetcher#playwright-memory-leak
+        :::
+      '';
+    };
+
+    playwrightSupport = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Enable support for fetching web pages using playwright and Chromium.
+        This starts a headless Chromium controlled by puppeteer in an oci container.
+
+        ::: {.note}
+        Playwright can currently leak memory.
+        See https://github.com/dgtlmoon/changedetection.io/wiki/Playwright-content-fetcher#playwright-memory-leak
+        :::
+      '';
+    };
+
+    chromePort = mkOption {
+      type = types.port;
+      default = 4444;
+      description = lib.mdDoc ''
+        A free port on which webDriverSupport or playwrightSupport listen on localhost.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    assertions = [
+      {
+        assertion = !((cfg.webDriverSupport == true) && (cfg.playwrightSupport == true));
+        message = "'services.changedetection-io.webDriverSupport' and 'services.changedetection-io.playwrightSupport' cannot be used together.";
+      }
+    ];
+
+    systemd = let
+      defaultStateDir = cfg.datastorePath == "/var/lib/changedetection-io";
+    in {
+      services.changedetection-io = {
+        wantedBy = [ "multi-user.target" ];
+        after = [ "network.target" ];
+        preStart = ''
+          mkdir -p ${cfg.datastorePath}
+        '';
+        serviceConfig = {
+          User = cfg.user;
+          Group = cfg.group;
+          StateDirectory = mkIf defaultStateDir "changedetection-io";
+          StateDirectoryMode = mkIf defaultStateDir "0750";
+          WorkingDirectory = cfg.datastorePath;
+          Environment = [ "HIDE_REFERER=true" ]
+            ++ lib.optional (cfg.baseURL != null) "BASE_URL=${cfg.baseURL}"
+            ++ lib.optional cfg.behindProxy "USE_X_SETTINGS=1"
+            ++ lib.optional cfg.webDriverSupport "WEBDRIVER_URL=http://127.0.0.1:${toString cfg.chromePort}/wd/hub"
+            ++ lib.optional cfg.playwrightSupport "PLAYWRIGHT_DRIVER_URL=ws://127.0.0.1:${toString cfg.chromePort}/?stealth=1&--disable-web-security=true";
+          EnvironmentFile = mkIf (cfg.environmentFile != null) cfg.environmentFile;
+          ExecStart = ''
+            ${pkgs.changedetection-io}/bin/changedetection.py \
+              -h ${cfg.listenAddress} -p ${toString cfg.port} -d ${cfg.datastorePath}
+          '';
+          ProtectHome = true;
+          ProtectSystem = true;
+          Restart = "on-failure";
+        };
+      };
+      tmpfiles.rules = mkIf defaultStateDir [
+        "d ${cfg.datastorePath} 0750 ${cfg.user} ${cfg.group} - -"
+      ];
+    };
+
+    users = {
+      users = optionalAttrs (cfg.user == "changedetection-io") {
+        "changedetection-io" = {
+          isSystemUser = true;
+          group = "changedetection-io";
+        };
+      };
+
+      groups = optionalAttrs (cfg.group == "changedetection-io") {
+        "changedetection-io" = { };
+      };
+    };
+
+    virtualisation = {
+      oci-containers.containers = lib.mkMerge [
+        (mkIf cfg.webDriverSupport {
+          changedetection-io-webdriver = {
+            image = "selenium/standalone-chrome";
+            environment = {
+              VNC_NO_PASSWORD = "1";
+              SCREEN_WIDTH = "1920";
+              SCREEN_HEIGHT = "1080";
+              SCREEN_DEPTH = "24";
+            };
+            ports = [
+              "127.0.0.1:${toString cfg.chromePort}:4444"
+            ];
+            volumes = [
+              "/dev/shm:/dev/shm"
+            ];
+            extraOptions = [ "--network=bridge" ];
+          };
+        })
+
+        (mkIf cfg.playwrightSupport {
+          changedetection-io-playwright = {
+            image = "browserless/chrome";
+            environment = {
+              SCREEN_WIDTH = "1920";
+              SCREEN_HEIGHT = "1024";
+              SCREEN_DEPTH = "16";
+              ENABLE_DEBUGGER = "false";
+              PREBOOT_CHROME = "true";
+              CONNECTION_TIMEOUT = "300000";
+              MAX_CONCURRENT_SESSIONS = "10";
+              CHROME_REFRESH_TIME = "600000";
+              DEFAULT_BLOCK_ADS = "true";
+              DEFAULT_STEALTH = "true";
+            };
+            ports = [
+              "127.0.0.1:${toString cfg.chromePort}:3000"
+            ];
+            extraOptions = [ "--network=bridge" ];
+          };
+        })
+      ];
+      podman.defaultNetwork.dnsname.enable = true;
+    };
+  };
+}
diff --git a/nixos/modules/services/web-apps/code-server.nix b/nixos/modules/services/web-apps/code-server.nix
index 474e9140ae8..0d6b6c529b6 100644
--- a/nixos/modules/services/web-apps/code-server.nix
+++ b/nixos/modules/services/web-apps/code-server.nix
@@ -11,18 +11,18 @@ in {
   ###### interface
   options = {
     services.code-server = {
-      enable = mkEnableOption "code-server";
+      enable = mkEnableOption (lib.mdDoc "code-server");
 
       package = mkOption {
         default = pkgs.code-server;
         defaultText = "pkgs.code-server";
-        description = "Which code-server derivation to use.";
+        description = lib.mdDoc "Which code-server derivation to use.";
         type = types.package;
       };
 
       extraPackages = mkOption {
         default = [ ];
-        description = "Packages that are available in the PATH of code-server.";
+        description = lib.mdDoc "Packages that are available in the PATH of code-server.";
         example = "[ pkgs.go ]";
         type = types.listOf types.package;
       };
@@ -30,49 +30,49 @@ in {
       extraEnvironment = mkOption {
         type = types.attrsOf types.str;
         description =
-          "Additional environment variables to passed to code-server.";
+          lib.mdDoc "Additional environment variables to passed to code-server.";
         default = { };
         example = { PKG_CONFIG_PATH = "/run/current-system/sw/lib/pkgconfig"; };
       };
 
       extraArguments = mkOption {
         default = [ "--disable-telemetry" ];
-        description = "Additional arguments that passed to code-server";
+        description = lib.mdDoc "Additional arguments that passed to code-server";
         example = ''[ "--verbose" ]'';
         type = types.listOf types.str;
       };
 
       host = mkOption {
         default = "127.0.0.1";
-        description = "The host-ip to bind to.";
+        description = lib.mdDoc "The host-ip to bind to.";
         type = types.str;
       };
 
       port = mkOption {
         default = 4444;
-        description = "The port where code-server runs.";
+        description = lib.mdDoc "The port where code-server runs.";
         type = types.port;
       };
 
       auth = mkOption {
         default = "password";
-        description = "The type of authentication to use.";
+        description = lib.mdDoc "The type of authentication to use.";
         type = types.enum [ "none" "password" ];
       };
 
       hashedPassword = mkOption {
         default = "";
         description =
-          "Create the password with: 'echo -n 'thisismypassword' | npx argon2-cli -e'.";
+          lib.mdDoc "Create the password with: `echo -n 'thisismypassword' | npx argon2-cli -e`.";
         type = types.str;
       };
 
       user = mkOption {
         default = defaultUser;
         example = "yourUser";
-        description = ''
+        description = lib.mdDoc ''
           The user to run code-server as.
-          By default, a user named <literal>${defaultUser}</literal> will be created.
+          By default, a user named `${defaultUser}` will be created.
         '';
         type = types.str;
       };
@@ -80,9 +80,9 @@ in {
       group = mkOption {
         default = defaultGroup;
         example = "yourGroup";
-        description = ''
+        description = lib.mdDoc ''
           The group to run code-server under.
-          By default, a group named <literal>${defaultGroup}</literal> will be created.
+          By default, a group named `${defaultGroup}` will be created.
         '';
         type = types.str;
       };
@@ -90,7 +90,7 @@ in {
       extraGroups = mkOption {
         default = [ ];
         description =
-          "An array of additional groups for the <literal>${defaultUser}</literal> user.";
+          lib.mdDoc "An array of additional groups for the `${defaultUser}` user.";
         example = [ "docker" ];
         type = types.listOf types.str;
       };
@@ -109,7 +109,7 @@ in {
         HASHED_PASSWORD = cfg.hashedPassword;
       } // cfg.extraEnvironment;
       serviceConfig = {
-        ExecStart = "${cfg.package}/bin/code-server --bind-addr ${cfg.host}:${toString cfg.port} --auth ${cfg.auth} " + builtins.concatStringsSep " " cfg.extraArguments;
+        ExecStart = "${cfg.package}/bin/code-server --bind-addr ${cfg.host}:${toString cfg.port} --auth ${cfg.auth} " + lib.escapeShellArgs cfg.extraArguments;
         ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
         RuntimeDirectory = cfg.user;
         User = cfg.user;
diff --git a/nixos/modules/services/web-apps/convos.nix b/nixos/modules/services/web-apps/convos.nix
index 8be11eec9f3..cd9f9d885d6 100644
--- a/nixos/modules/services/web-apps/convos.nix
+++ b/nixos/modules/services/web-apps/convos.nix
@@ -7,26 +7,26 @@ let
 in
 {
   options.services.convos = {
-    enable = mkEnableOption "Convos";
+    enable = mkEnableOption (lib.mdDoc "Convos");
     listenPort = mkOption {
       type = types.port;
       default = 3000;
       example = 8080;
-      description = "Port the web interface should listen on";
+      description = lib.mdDoc "Port the web interface should listen on";
     };
     listenAddress = mkOption {
       type = types.str;
       default = "*";
       example = "127.0.0.1";
-      description = "Address or host the web interface should listen on";
+      description = lib.mdDoc "Address or host the web interface should listen on";
     };
     reverseProxy = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enables reverse proxy support. This will allow Convos to automatically
-        pick up the <literal>X-Forwarded-For</literal> and
-        <literal>X-Request-Base</literal> HTTP headers set in your reverse proxy
+        pick up the `X-Forwarded-For` and
+        `X-Request-Base` HTTP headers set in your reverse proxy
         web server. Note that enabling this option without a reverse proxy in
         front will be a security issue.
       '';
diff --git a/nixos/modules/services/web-apps/cryptpad.nix b/nixos/modules/services/web-apps/cryptpad.nix
deleted file mode 100644
index e6772de768e..00000000000
--- a/nixos/modules/services/web-apps/cryptpad.nix
+++ /dev/null
@@ -1,54 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-let
-  cfg = config.services.cryptpad;
-in
-{
-  options.services.cryptpad = {
-    enable = mkEnableOption "the Cryptpad service";
-
-    package = mkOption {
-      default = pkgs.cryptpad;
-      defaultText = literalExpression "pkgs.cryptpad";
-      type = types.package;
-      description = "
-        Cryptpad package to use.
-      ";
-    };
-
-    configFile = mkOption {
-      type = types.path;
-      default = "${cfg.package}/lib/node_modules/cryptpad/config/config.example.js";
-      defaultText = literalExpression ''"''${package}/lib/node_modules/cryptpad/config/config.example.js"'';
-      description = ''
-        Path to the JavaScript configuration file.
-
-        See <link
-        xlink:href="https://github.com/xwiki-labs/cryptpad/blob/master/config/config.example.js"/>
-        for a configuration example.
-      '';
-    };
-  };
-
-  config = mkIf cfg.enable {
-    systemd.services.cryptpad = {
-      description = "Cryptpad Service";
-      wantedBy = [ "multi-user.target" ];
-      after = [ "networking.target" ];
-      serviceConfig = {
-        DynamicUser = true;
-        Environment = [
-          "CRYPTPAD_CONFIG=${cfg.configFile}"
-          "HOME=%S/cryptpad"
-        ];
-        ExecStart = "${cfg.package}/bin/cryptpad";
-        PrivateTmp = true;
-        Restart = "always";
-        StateDirectory = "cryptpad";
-        WorkingDirectory = "%S/cryptpad";
-      };
-    };
-  };
-}
diff --git a/nixos/modules/services/web-apps/dex.nix b/nixos/modules/services/web-apps/dex.nix
index 4d4689a4cf2..1dcc6f7a7c5 100644
--- a/nixos/modules/services/web-apps/dex.nix
+++ b/nixos/modules/services/web-apps/dex.nix
@@ -11,14 +11,25 @@ let
   settingsFormat = pkgs.formats.yaml {};
   configFile = settingsFormat.generate "config.yaml" filteredSettings;
 
-  startPreScript = pkgs.writeShellScript "dex-start-pre" (''
-  '' + (concatStringsSep "\n" (builtins.map (file: ''
-    ${pkgs.replace-secret}/bin/replace-secret '${file}' '${file}' /run/dex/config.yaml
-  '') secretFiles)));
+  startPreScript = pkgs.writeShellScript "dex-start-pre"
+    (concatStringsSep "\n" (map (file: ''
+      replace-secret '${file}' '${file}' /run/dex/config.yaml
+    '')
+    secretFiles));
 in
 {
   options.services.dex = {
-    enable = mkEnableOption "the OpenID Connect and OAuth2 identity provider";
+    enable = mkEnableOption (lib.mdDoc "the OpenID Connect and OAuth2 identity provider");
+
+    environmentFile = mkOption {
+      type = types.nullOr types.path;
+      default = null;
+      description = lib.mdDoc ''
+        Environment file (see `systemd.exec(5)`
+        "EnvironmentFile=" section for the syntax) to define variables for dex.
+        This option can be used to safely include secret keys into the dex configuration.
+      '';
+    };
 
     settings = mkOption {
       type = settingsFormat.type;
@@ -45,9 +56,12 @@ in
           ];
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         The available options can be found in
-        <link xlink:href="https://github.com/dexidp/dex/blob/v${pkgs.dex.version}/config.yaml.dist">the example configuration</link>.
+        [the example configuration](https://github.com/dexidp/dex/blob/v${pkgs.dex-oidc.version}/config.yaml.dist).
+
+        It's also possible to refer to environment variables (defined in [services.dex.environmentFile](#opt-services.dex.environmentFile))
+        using the syntax `$VARIABLE_NAME`.
       '';
     };
   };
@@ -57,15 +71,15 @@ in
       description = "dex identity provider";
       wantedBy = [ "multi-user.target" ];
       after = [ "networking.target" ] ++ (optional (cfg.settings.storage.type == "postgres") "postgresql.service");
-
+      path = with pkgs; [ replace-secret ];
       serviceConfig = {
         ExecStart = "${pkgs.dex-oidc}/bin/dex serve /run/dex/config.yaml";
         ExecStartPre = [
           "${pkgs.coreutils}/bin/install -m 600 ${configFile} /run/dex/config.yaml"
           "+${startPreScript}"
         ];
-        RuntimeDirectory = "dex";
 
+        RuntimeDirectory = "dex";
         AmbientCapabilities = "CAP_NET_BIND_SERVICE";
         BindReadOnlyPaths = [
           "/nix/store"
@@ -105,10 +119,12 @@ in
         RestrictRealtime = true;
         RestrictSUIDSGID = true;
         SystemCallArchitectures = "native";
-        SystemCallFilter = [ "@system-service" "~@privileged @resources @setuid @keyring" ];
+        SystemCallFilter = [ "@system-service" "~@privileged @setuid @keyring" ];
         TemporaryFileSystem = "/:ro";
         # Does not work well with the temporary root
         #UMask = "0066";
+      } // optionalAttrs (cfg.environmentFile != null) {
+        EnvironmentFile = cfg.environmentFile;
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/discourse.nix b/nixos/modules/services/web-apps/discourse.nix
index 2c2911aada3..1ab0e679a54 100644
--- a/nixos/modules/services/web-apps/discourse.nix
+++ b/nixos/modules/services/web-apps/discourse.nix
@@ -6,7 +6,7 @@ let
   cfg = config.services.discourse;
   opt = options.services.discourse;
 
-  # Keep in sync with https://github.com/discourse/discourse_docker/blob/master/image/base/Dockerfile#L5
+  # Keep in sync with https://github.com/discourse/discourse_docker/blob/main/image/base/slim.Dockerfile#L5
   upstreamPostgresqlVersion = lib.getVersion pkgs.postgresql_13;
 
   postgresqlPackage = if config.services.postgresql.enable then
@@ -19,14 +19,14 @@ let
   # We only want to create a database if we're actually going to connect to it.
   databaseActuallyCreateLocally = cfg.database.createLocally && cfg.database.host == null;
 
-  tlsEnabled = (cfg.enableACME
+  tlsEnabled = cfg.enableACME
                 || cfg.sslCertificate != null
-                || cfg.sslCertificateKey != null);
+                || cfg.sslCertificateKey != null;
 in
 {
   options = {
     services.discourse = {
-      enable = lib.mkEnableOption "Discourse, an open source discussion platform";
+      enable = lib.mkEnableOption (lib.mdDoc "Discourse, an open source discussion platform");
 
       package = lib.mkOption {
         type = lib.types.package;
@@ -35,20 +35,17 @@ in
           plugins = lib.unique (p.enabledPlugins ++ cfg.plugins);
         };
         defaultText = lib.literalExpression "pkgs.discourse";
-        description = ''
+        description = lib.mdDoc ''
           The discourse package to use.
         '';
       };
 
       hostname = lib.mkOption {
         type = lib.types.str;
-        default = if config.networking.domain != null then
-                    config.networking.fqdn
-                  else
-                    config.networking.hostName;
-        defaultText = lib.literalExpression "config.networking.fqdn";
+        default = config.networking.fqdnOrHostName;
+        defaultText = lib.literalExpression "config.networking.fqdnOrHostName";
         example = "discourse.example.com";
-        description = ''
+        description = lib.mdDoc ''
           The hostname to serve Discourse on.
         '';
       };
@@ -57,20 +54,20 @@ in
         type = with lib.types; nullOr path;
         default = null;
         example = "/run/keys/secret_key_base";
-        description = ''
+        description = lib.mdDoc ''
           The path to a file containing the
-          <literal>secret_key_base</literal> secret.
+          `secret_key_base` secret.
 
-          Discourse uses <literal>secret_key_base</literal> to encrypt
+          Discourse uses `secret_key_base` to encrypt
           the cookie store, which contains session data, and to digest
           user auth tokens.
 
           Needs to be a 64 byte long string of hexadecimal
           characters. You can generate one by running
 
-          <screen>
-          <prompt>$ </prompt>openssl rand -hex 64 >/path/to/secret_key_base_file
-          </screen>
+          ```
+          openssl rand -hex 64 >/path/to/secret_key_base_file
+          ```
 
           This should be a string, not a nix path, since nix paths are
           copied into the world-readable nix store.
@@ -81,7 +78,7 @@ in
         type = with lib.types; nullOr path;
         default = null;
         example = "/run/keys/ssl.cert";
-        description = ''
+        description = lib.mdDoc ''
           The path to the server SSL certificate. Set this to enable
           SSL.
         '';
@@ -91,7 +88,7 @@ in
         type = with lib.types; nullOr path;
         default = null;
         example = "/run/keys/ssl.key";
-        description = ''
+        description = lib.mdDoc ''
           The path to the server SSL certificate key. Set this to
           enable SSL.
         '';
@@ -100,11 +97,11 @@ in
       enableACME = lib.mkOption {
         type = lib.types.bool;
         default = cfg.sslCertificate == null && cfg.sslCertificateKey == null;
-        defaultText = lib.literalDocBook ''
-          <literal>true</literal>, unless <option>services.discourse.sslCertificate</option>
-          and <option>services.discourse.sslCertificateKey</option> are set.
+        defaultText = lib.literalMD ''
+          `true`, unless {option}`services.discourse.sslCertificate`
+          and {option}`services.discourse.sslCertificateKey` are set.
         '';
-        description = ''
+        description = lib.mdDoc ''
           Whether an ACME certificate should be used to secure
           connections to the server.
         '';
@@ -121,17 +118,16 @@ in
             max_reqs_per_ip_mode = "warn+block";
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Additional settings to put in the
-          <filename>discourse.conf</filename> file.
+          {file}`discourse.conf` file.
 
           Look in the
-          <link xlink:href="https://github.com/discourse/discourse/blob/master/config/discourse_defaults.conf">discourse_defaults.conf</link>
+          [discourse_defaults.conf](https://github.com/discourse/discourse/blob/master/config/discourse_defaults.conf)
           file in the upstream distribution to find available options.
 
-          Setting an option to <literal>null</literal> means
-          <quote>define variable, but leave right-hand side
-          empty</quote>.
+          Setting an option to `null` means
+          “define variable, but leave right-hand side empty”.
         '';
       };
 
@@ -151,26 +147,26 @@ in
             };
           };
         '';
-        description = ''
+        description = lib.mdDoc ''
           Discourse site settings. These are the settings that can be
           changed from the UI. This only defines their default values:
           they can still be overridden from the UI.
 
           Available settings can be found by looking in the
-          <link xlink:href="https://github.com/discourse/discourse/blob/master/config/site_settings.yml">site_settings.yml</link>
+          [site_settings.yml](https://github.com/discourse/discourse/blob/master/config/site_settings.yml)
           file of the upstream distribution. To find a setting's path,
           you only need to care about the first two levels; i.e. its
           category and name. See the example.
 
           Settings containing secret data should be set to an
           attribute set containing the attribute
-          <literal>_secret</literal> - a string pointing to a file
+          `_secret` - a string pointing to a file
           containing the value the option should be set to. See the
           example to get a better picture of this: in the resulting
-          <filename>config/nixos_site_settings.json</filename> file,
-          the <literal>login.github_client_secret</literal> key will
+          {file}`config/nixos_site_settings.json` file,
+          the `login.github_client_secret` key will
           be set to the contents of the
-          <filename>/run/keys/discourse_github_client_secret</filename>
+          {file}`/run/keys/discourse_github_client_secret`
           file.
         '';
       };
@@ -179,7 +175,7 @@ in
         skipCreate = lib.mkOption {
           type = lib.types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Do not create the admin account, instead rely on other
             existing admin accounts.
           '';
@@ -188,7 +184,7 @@ in
         email = lib.mkOption {
           type = lib.types.str;
           example = "admin@example.com";
-          description = ''
+          description = lib.mdDoc ''
             The admin user email address.
           '';
         };
@@ -196,21 +192,21 @@ in
         username = lib.mkOption {
           type = lib.types.str;
           example = "admin";
-          description = ''
+          description = lib.mdDoc ''
             The admin user username.
           '';
         };
 
         fullName = lib.mkOption {
           type = lib.types.str;
-          description = ''
+          description = lib.mdDoc ''
             The admin user's full name.
           '';
         };
 
         passwordFile = lib.mkOption {
           type = lib.types.path;
-          description = ''
+          description = lib.mdDoc ''
             A path to a file containing the admin user's password.
 
             This should be a string, not a nix path, since nix paths are
@@ -222,8 +218,8 @@ in
       nginx.enable = lib.mkOption {
         type = lib.types.bool;
         default = true;
-        description = ''
-          Whether an <literal>nginx</literal> virtual host should be
+        description = lib.mdDoc ''
+          Whether an `nginx` virtual host should be
           set up to serve Discourse. Only disable if you're planning
           to use a different web server, which is not recommended.
         '';
@@ -233,7 +229,7 @@ in
         pool = lib.mkOption {
           type = lib.types.int;
           default = 8;
-          description = ''
+          description = lib.mdDoc ''
             Database connection pool size.
           '';
         };
@@ -241,16 +237,16 @@ in
         host = lib.mkOption {
           type = with lib.types; nullOr str;
           default = null;
-          description = ''
-            Discourse database hostname. <literal>null</literal> means <quote>prefer
-            local unix socket connection</quote>.
+          description = lib.mdDoc ''
+            Discourse database hostname. `null` means
+            “prefer local unix socket connection”.
           '';
         };
 
         passwordFile = lib.mkOption {
           type = with lib.types; nullOr path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             File containing the Discourse database user password.
 
             This should be a string, not a nix path, since nix paths are
@@ -261,18 +257,18 @@ in
         createLocally = lib.mkOption {
           type = lib.types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether a database should be automatically created on the
-            local host. Set this to <literal>false</literal> if you plan
+            local host. Set this to `false` if you plan
             on provisioning a local database yourself. This has no effect
-            if <option>services.discourse.database.host</option> is customized.
+            if {option}`services.discourse.database.host` is customized.
           '';
         };
 
         name = lib.mkOption {
           type = lib.types.str;
           default = "discourse";
-          description = ''
+          description = lib.mdDoc ''
             Discourse database name.
           '';
         };
@@ -280,7 +276,7 @@ in
         username = lib.mkOption {
           type = lib.types.str;
           default = "discourse";
-          description = ''
+          description = lib.mdDoc ''
             Discourse database user.
           '';
         };
@@ -288,10 +284,10 @@ in
         ignorePostgresqlVersion = lib.mkOption {
           type = lib.types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether to allow other versions of PostgreSQL than the
             recommended one. Only effective when
-            <option>services.discourse.database.createLocally</option>
+            {option}`services.discourse.database.createLocally`
             is enabled.
           '';
         };
@@ -301,7 +297,7 @@ in
         host = lib.mkOption {
           type = lib.types.str;
           default = "localhost";
-          description = ''
+          description = lib.mdDoc ''
             Redis server hostname.
           '';
         };
@@ -309,7 +305,7 @@ in
         passwordFile = lib.mkOption {
           type = with lib.types; nullOr path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             File containing the Redis password.
 
             This should be a string, not a nix path, since nix paths are
@@ -320,7 +316,7 @@ in
         dbNumber = lib.mkOption {
           type = lib.types.int;
           default = 0;
-          description = ''
+          description = lib.mdDoc ''
             Redis database number.
           '';
         };
@@ -329,7 +325,7 @@ in
           type = lib.types.bool;
           default = cfg.redis.host != "localhost";
           defaultText = lib.literalExpression ''config.${opt.redis.host} != "localhost"'';
-          description = ''
+          description = lib.mdDoc ''
             Connect to Redis with SSL.
           '';
         };
@@ -342,8 +338,8 @@ in
           defaultText = lib.literalExpression ''
             "''${if config.services.discourse.mail.incoming.enable then "notifications" else "noreply"}@''${config.services.discourse.hostname}"
           '';
-          description = ''
-            The <literal>from:</literal> email address used when
+          description = lib.mdDoc ''
+            The `from:` email address used when
             sending all essential system emails. The domain specified
             here must have SPF, DKIM and reverse PTR records set
             correctly for email to arrive.
@@ -353,10 +349,10 @@ in
         contactEmailAddress = lib.mkOption {
           type = lib.types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Email address of key contact responsible for this
             site. Used for critical notifications, as well as on the
-            <literal>/about</literal> contact form for urgent matters.
+            `/about` contact form for urgent matters.
           '';
         };
 
@@ -364,7 +360,7 @@ in
           serverAddress = lib.mkOption {
             type = lib.types.str;
             default = "localhost";
-            description = ''
+            description = lib.mdDoc ''
               The address of the SMTP server Discourse should use to
               send email.
             '';
@@ -373,7 +369,7 @@ in
           port = lib.mkOption {
             type = lib.types.port;
             default = 25;
-            description = ''
+            description = lib.mdDoc ''
               The port of the SMTP server Discourse should use to
               send email.
             '';
@@ -382,7 +378,7 @@ in
           username = lib.mkOption {
             type = with lib.types; nullOr str;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               The username of the SMTP server.
             '';
           };
@@ -390,7 +386,7 @@ in
           passwordFile = lib.mkOption {
             type = lib.types.nullOr lib.types.path;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               A file containing the password of the SMTP server account.
 
               This should be a string, not a nix path, since nix paths
@@ -402,7 +398,7 @@ in
             type = lib.types.str;
             default = cfg.hostname;
             defaultText = lib.literalExpression "config.${opt.hostname}";
-            description = ''
+            description = lib.mdDoc ''
               HELO domain to use for outgoing mail.
             '';
           };
@@ -410,7 +406,7 @@ in
           authentication = lib.mkOption {
             type = with lib.types; nullOr (enum ["plain" "login" "cram_md5"]);
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Authentication type to use, see http://api.rubyonrails.org/classes/ActionMailer/Base.html
             '';
           };
@@ -418,7 +414,7 @@ in
           enableStartTLSAuto = lib.mkOption {
             type = lib.types.bool;
             default = true;
-            description = ''
+            description = lib.mdDoc ''
               Whether to try to use StartTLS.
             '';
           };
@@ -426,7 +422,7 @@ in
           opensslVerifyMode = lib.mkOption {
             type = lib.types.str;
             default = "peer";
-            description = ''
+            description = lib.mdDoc ''
               How OpenSSL checks the certificate, see http://api.rubyonrails.org/classes/ActionMailer/Base.html
             '';
           };
@@ -434,7 +430,7 @@ in
           forceTLS = lib.mkOption {
             type = lib.types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Force implicit TLS as per RFC 8314 3.3.
             '';
           };
@@ -444,7 +440,7 @@ in
           enable = lib.mkOption {
             type = lib.types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Whether to set up Postfix to receive incoming mail.
             '';
           };
@@ -453,7 +449,7 @@ in
             type = lib.types.str;
             default = "%{reply_key}@${cfg.hostname}";
             defaultText = lib.literalExpression ''"%{reply_key}@''${config.services.discourse.hostname}"'';
-            description = ''
+            description = lib.mdDoc ''
               Template for reply by email incoming email address, for
               example: %{reply_key}@reply.example.com or
               replies+%{reply_key}@example.com
@@ -464,7 +460,7 @@ in
             type = lib.types.package;
             default = pkgs.discourse-mail-receiver;
             defaultText = lib.literalExpression "pkgs.discourse-mail-receiver";
-            description = ''
+            description = lib.mdDoc ''
               The discourse-mail-receiver package to use.
             '';
           };
@@ -472,10 +468,10 @@ in
           apiKeyFile = lib.mkOption {
             type = lib.types.nullOr lib.types.path;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               A file containing the Discourse API key used to add
               posts and messages from mail. If left at its default
-              value <literal>null</literal>, one will be automatically
+              value `null`, one will be automatically
               generated.
 
               This should be a string, not a nix path, since nix paths
@@ -494,17 +490,15 @@ in
             discourse-github
           ];
         '';
-        description = ''
-          Plugins to install as part of
-          <productname>Discourse</productname>, expressed as a list of
-          derivations.
+        description = lib.mdDoc ''
+          Plugins to install as part of Discourse, expressed as a list of derivations.
         '';
       };
 
       sidekiqProcesses = lib.mkOption {
         type = lib.types.int;
         default = 1;
-        description = ''
+        description = lib.mdDoc ''
           How many Sidekiq processes should be spawned.
         '';
       };
@@ -512,7 +506,7 @@ in
       unicornTimeout = lib.mkOption {
         type = lib.types.int;
         default = 30;
-        description = ''
+        description = lib.mdDoc ''
           Time in seconds before a request to Unicorn times out.
 
           This can be raised if the system Discourse is running on is
@@ -604,11 +598,11 @@ in
       cors_origin = "";
       serve_static_assets = false;
       sidekiq_workers = 5;
-      rtl_css = false;
       connection_reaper_age = 30;
       connection_reaper_interval = 30;
       relative_url_root = null;
       message_bus_max_backlog_size = 100;
+      message_bus_clear_every = 50;
       secret_key_base = cfg.secretKeyBaseFile;
       fallback_assets_path = null;
 
@@ -655,7 +649,12 @@ in
       long_polling_interval = null;
     };
 
-    services.redis.enable = lib.mkDefault (cfg.redis.host == "localhost");
+    services.redis.servers.discourse =
+      lib.mkIf (lib.elem cfg.redis.host [ "localhost" "127.0.0.1" ]) {
+        enable = true;
+        bind = cfg.redis.host;
+        port = cfg.backendSettings.redis_port;
+      };
 
     services.postgresql = lib.mkIf databaseActuallyCreateLocally {
       enable = true;
@@ -696,12 +695,12 @@ in
     systemd.services.discourse = {
       wantedBy = [ "multi-user.target" ];
       after = [
-        "redis.service"
+        "redis-discourse.service"
         "postgresql.service"
         "discourse-postgresql.service"
       ];
       bindsTo = [
-        "redis.service"
+        "redis-discourse.service"
       ] ++ lib.optionals (cfg.database.host == null) [
         "postgresql.service"
         "discourse-postgresql.service"
@@ -796,13 +795,13 @@ in
           "public"
           "sockets"
         ];
-        RuntimeDirectoryMode = 0750;
+        RuntimeDirectoryMode = "0750";
         StateDirectory = map (p: "discourse/" + p) [
           "uploads"
           "backups"
           "tmp"
         ];
-        StateDirectoryMode = 0750;
+        StateDirectoryMode = "0750";
         LogsDirectory = "discourse";
         TimeoutSec = "infinity";
         Restart = "on-failure";
@@ -934,7 +933,6 @@ in
                   proxy_cache discourse;
                   proxy_cache_key "$scheme,$host,$request_uri";
                   proxy_cache_valid 200 301 302 7d;
-                  proxy_cache_valid any 1m;
                 '';
               };
               "/message-bus/" = proxy {
diff --git a/nixos/modules/services/web-apps/documize.nix b/nixos/modules/services/web-apps/documize.nix
index 7f2ed82ee33..f70da0829f4 100644
--- a/nixos/modules/services/web-apps/documize.nix
+++ b/nixos/modules/services/web-apps/documize.nix
@@ -12,13 +12,13 @@ let
 
 in {
   options.services.documize = {
-    enable = mkEnableOption "Documize Wiki";
+    enable = mkEnableOption (lib.mdDoc "Documize Wiki");
 
     stateDirectoryName = mkOption {
       type = types.str;
       default = "documize";
-      description = ''
-        The name of the directory below <filename>/var/lib/private</filename>
+      description = lib.mdDoc ''
+        The name of the directory below {file}`/var/lib/private`
         where documize runs in and stores, for example, backups.
       '';
     };
@@ -27,7 +27,7 @@ in {
       type = types.package;
       default = pkgs.documize-community;
       defaultText = literalExpression "pkgs.documize-community";
-      description = ''
+      description = lib.mdDoc ''
         Which package to use for documize.
       '';
     };
@@ -36,7 +36,7 @@ in {
       type = types.nullOr types.str;
       default = null;
       example = "3edIYV6c8B28b19fh";
-      description = ''
+      description = lib.mdDoc ''
         The salt string used to encode JWT tokens, if not set a random value will be generated.
       '';
     };
@@ -44,23 +44,23 @@ in {
     cert = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
-        The <filename>cert.pem</filename> file used for https.
+      description = lib.mdDoc ''
+        The {file}`cert.pem` file used for https.
       '';
     };
 
     key = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
-        The <filename>key.pem</filename> file used for https.
+      description = lib.mdDoc ''
+        The {file}`key.pem` file used for https.
       '';
     };
 
     port = mkOption {
       type = types.port;
       default = 5001;
-      description = ''
+      description = lib.mdDoc ''
         The http/https port number.
       '';
     };
@@ -68,7 +68,7 @@ in {
     forcesslport = mkOption {
       type = types.nullOr types.port;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Redirect given http port number to TLS.
       '';
     };
@@ -76,8 +76,8 @@ in {
     offline = mkOption {
       type = types.bool;
       default = false;
-      description = ''
-        Set <literal>true</literal> for offline mode.
+      description = lib.mdDoc ''
+        Set `true` for offline mode.
       '';
       apply = v: if true == v then 1 else 0;
     };
@@ -85,44 +85,31 @@ in {
     dbtype = mkOption {
       type = types.enum [ "mysql" "percona" "mariadb" "postgresql" "sqlserver" ];
       default = "postgresql";
-      description = ''
-        Specify the database provider:
-        <simplelist type='inline'>
-          <member><literal>mysql</literal></member>
-          <member><literal>percona</literal></member>
-          <member><literal>mariadb</literal></member>
-          <member><literal>postgresql</literal></member>
-          <member><literal>sqlserver</literal></member>
-        </simplelist>
+      description = lib.mdDoc ''
+        Specify the database provider: `mysql`, `percona`, `mariadb`, `postgresql`, `sqlserver`
       '';
     };
 
     db = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Database specific connection string for example:
-        <itemizedlist>
-        <listitem><para>MySQL/Percona/MariaDB:
-          <literal>user:password@tcp(host:3306)/documize</literal>
-        </para></listitem>
-        <listitem><para>MySQLv8+:
-          <literal>user:password@tcp(host:3306)/documize?allowNativePasswords=true</literal>
-        </para></listitem>
-        <listitem><para>PostgreSQL:
-          <literal>host=localhost port=5432 dbname=documize user=admin password=secret sslmode=disable</literal>
-        </para></listitem>
-        <listitem><para>MSSQL:
-          <literal>sqlserver://username:password@localhost:1433?database=Documize</literal> or
-          <literal>sqlserver://sa@localhost/SQLExpress?database=Documize</literal>
-        </para></listitem>
-        </itemizedlist>
+        - MySQL/Percona/MariaDB:
+          `user:password@tcp(host:3306)/documize`
+        - MySQLv8+:
+          `user:password@tcp(host:3306)/documize?allowNativePasswords=true`
+        - PostgreSQL:
+          `host=localhost port=5432 dbname=documize user=admin password=secret sslmode=disable`
+        - MSSQL:
+          `sqlserver://username:password@localhost:1433?database=Documize` or
+          `sqlserver://sa@localhost/SQLExpress?database=Documize`
       '';
     };
 
     location = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         reserved
       '';
     };
diff --git a/nixos/modules/services/web-apps/dokuwiki.nix b/nixos/modules/services/web-apps/dokuwiki.nix
index 1f8ca742db9..f0b3c7b2bcf 100644
--- a/nixos/modules/services/web-apps/dokuwiki.nix
+++ b/nixos/modules/services/web-apps/dokuwiki.nix
@@ -7,7 +7,6 @@ let
   eachSite = cfg.sites;
   user = "dokuwiki";
   webserver = config.services.${cfg.webserver};
-  stateDir = hostName: "/var/lib/dokuwiki/${hostName}/data";
 
   dokuwikiAclAuthConfig = hostName: cfg: pkgs.writeText "acl.auth-${hostName}.php" ''
     # acl.auth.php
@@ -60,27 +59,27 @@ let
   siteOpts = { config, lib, name, ... }:
     {
       options = {
-        enable = mkEnableOption "DokuWiki web application.";
+        enable = mkEnableOption (lib.mdDoc "DokuWiki web application.");
 
         package = mkOption {
           type = types.package;
           default = pkgs.dokuwiki;
           defaultText = literalExpression "pkgs.dokuwiki";
-          description = "Which DokuWiki package to use.";
+          description = lib.mdDoc "Which DokuWiki package to use.";
         };
 
         stateDir = mkOption {
           type = types.path;
           default = "/var/lib/dokuwiki/${name}/data";
-          description = "Location of the DokuWiki state directory.";
+          description = lib.mdDoc "Location of the DokuWiki state directory.";
         };
 
         acl = mkOption {
           type = types.nullOr types.lines;
           default = null;
           example = "*               @ALL               8";
-          description = ''
-            Access Control Lists: see <link xlink:href="https://www.dokuwiki.org/acl"/>
+          description = lib.mdDoc ''
+            Access Control Lists: see <https://www.dokuwiki.org/acl>
             Mutually exclusive with services.dokuwiki.aclFile
             Set this to a value other than null to take precedence over aclFile option.
 
@@ -92,11 +91,11 @@ let
         aclFile = mkOption {
           type = with types; nullOr str;
           default = if (config.aclUse && config.acl == null) then "/var/lib/dokuwiki/${name}/acl.auth.php" else null;
-          description = ''
+          description = lib.mdDoc ''
             Location of the dokuwiki acl rules. Mutually exclusive with services.dokuwiki.acl
             Mutually exclusive with services.dokuwiki.acl which is preferred.
-            Consult documentation <link xlink:href="https://www.dokuwiki.org/acl"/> for further instructions.
-            Example: <link xlink:href="https://github.com/splitbrain/dokuwiki/blob/master/conf/acl.auth.php.dist"/>
+            Consult documentation <https://www.dokuwiki.org/acl> for further instructions.
+            Example: <https://github.com/splitbrain/dokuwiki/blob/master/conf/acl.auth.php.dist>
           '';
           example = "/var/lib/dokuwiki/${name}/acl.auth.php";
         };
@@ -104,7 +103,7 @@ let
         aclUse = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Necessary for users to log in into the system.
             Also limits anonymous users. When disabled,
             everyone is able to create and edit content.
@@ -119,7 +118,7 @@ let
             $plugins['authmysql'] = 0;
             $plugins['authpgsql'] = 0;
           '';
-          description = ''
+          description = lib.mdDoc ''
             List of the dokuwiki (un)loaded plugins.
           '';
         };
@@ -127,21 +126,26 @@ let
         superUser = mkOption {
           type = types.nullOr types.str;
           default = "@admin";
-          description = ''
+          description = lib.mdDoc ''
             You can set either a username, a list of usernames (“admin1,admin2”),
             or the name of a group by prepending an @ char to the groupname
-            Consult documentation <link xlink:href="https://www.dokuwiki.org/config:superuser"/> for further instructions.
+            Consult documentation <https://www.dokuwiki.org/config:superuser> for further instructions.
           '';
         };
 
         usersFile = mkOption {
           type = with types; nullOr str;
           default = if config.aclUse then "/var/lib/dokuwiki/${name}/users.auth.php" else null;
-          description = ''
+          description = lib.mdDoc ''
             Location of the dokuwiki users file. List of users. Format:
-            login:passwordhash:Real Name:email:groups,comma,separated
-            Create passwordHash easily by using:$ mkpasswd -5 password `pwgen 8 1`
-            Example: <link xlink:href="https://github.com/splitbrain/dokuwiki/blob/master/conf/users.auth.php.dist"/>
+
+                login:passwordhash:Real Name:email:groups,comma,separated
+
+            Create passwordHash easily by using:
+
+                mkpasswd -5 password `pwgen 8 1`
+
+            Example: <https://github.com/splitbrain/dokuwiki/blob/master/conf/users.auth.php.dist>
             '';
           example = "/var/lib/dokuwiki/${name}/users.auth.php";
         };
@@ -150,9 +154,9 @@ let
           type = types.nullOr types.str;
           default = "";
           example = "search,register";
-          description = ''
+          description = lib.mdDoc ''
             Disable individual action modes. Refer to
-            <link xlink:href="https://www.dokuwiki.org/config:action_modes"/>
+            <https://www.dokuwiki.org/config:action_modes>
             for details on supported values.
           '';
         };
@@ -160,9 +164,12 @@ let
         plugins = mkOption {
           type = types.listOf types.path;
           default = [];
-          description = ''
+          description = lib.mdDoc ''
                 List of path(s) to respective plugin(s) which are copied from the 'plugin' directory.
-                <note><para>These plugins need to be packaged before use, see example.</para></note>
+
+                ::: {.note}
+                These plugins need to be packaged before use, see example.
+                :::
           '';
           example = literalExpression ''
                 let
@@ -188,9 +195,12 @@ let
         templates = mkOption {
           type = types.listOf types.path;
           default = [];
-          description = ''
+          description = lib.mdDoc ''
                 List of path(s) to respective template(s) which are copied from the 'tpl' directory.
-                <note><para>These templates need to be packaged before use, see example.</para></note>
+
+                ::: {.note}
+                These templates need to be packaged before use, see example.
+                :::
           '';
           example = literalExpression ''
                 let
@@ -222,8 +232,8 @@ let
             "pm.max_spare_servers" = 4;
             "pm.max_requests" = 500;
           };
-          description = ''
-            Options for the DokuWiki PHP pool. See the documentation on <literal>php-fpm.conf</literal>
+          description = lib.mdDoc ''
+            Options for the DokuWiki PHP pool. See the documentation on `php-fpm.conf`
             for details on configuration directives.
           '';
         };
@@ -235,9 +245,9 @@ let
             $conf['title'] = 'My Wiki';
             $conf['userewrite'] = 1;
           '';
-          description = ''
+          description = lib.mdDoc ''
             DokuWiki configuration. Refer to
-            <link xlink:href="https://www.dokuwiki.org/config"/>
+            <https://www.dokuwiki.org/config>
             for details on supported values.
           '';
         };
@@ -254,20 +264,20 @@ in
       sites = mkOption {
         type = types.attrsOf (types.submodule siteOpts);
         default = {};
-        description = "Specification of one or more DokuWiki sites to serve";
+        description = lib.mdDoc "Specification of one or more DokuWiki sites to serve";
       };
 
       webserver = mkOption {
         type = types.enum [ "nginx" "caddy" ];
         default = "nginx";
-        description = ''
+        description = lib.mdDoc ''
           Whether to use nginx or caddy for virtual host management.
 
-          Further nginx configuration can be done by adapting <literal>services.nginx.virtualHosts.&lt;name&gt;</literal>.
-          See <xref linkend="opt-services.nginx.virtualHosts"/> for further information.
+          Further nginx configuration can be done by adapting `services.nginx.virtualHosts.<name>`.
+          See [](#opt-services.nginx.virtualHosts) for further information.
 
-          Further apache2 configuration can be done by adapting <literal>services.httpd.virtualHosts.&lt;name&gt;</literal>.
-          See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
+          Further apache2 configuration can be done by adapting `services.httpd.virtualHosts.<name>`.
+          See [](#opt-services.httpd.virtualHosts) for further information.
         '';
       };
 
@@ -293,9 +303,7 @@ in
         inherit user;
         group = webserver.group;
 
-        # Not yet compatible with php 8 https://www.dokuwiki.org/requirements
-        # https://github.com/splitbrain/dokuwiki/issues/3545
-        phpPackage = pkgs.php74;
+        phpPackage = pkgs.php81;
         phpEnv = {
           DOKUWIKI_LOCAL_CONFIG = "${dokuwikiLocalConfig hostName cfg}";
           DOKUWIKI_PLUGINS_LOCAL_CONFIG = "${dokuwikiPluginsLocalConfig hostName cfg}";
@@ -316,16 +324,17 @@ in
 
   {
     systemd.tmpfiles.rules = flatten (mapAttrsToList (hostName: cfg: [
-      "d ${stateDir hostName}/attic 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/cache 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/index 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/locks 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/media 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/media_attic 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/media_meta 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/meta 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/pages 0750 ${user} ${webserver.group} - -"
-      "d ${stateDir hostName}/tmp 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/attic 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/cache 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/index 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/locks 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/log 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/media 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/media_attic 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/media_meta 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/meta 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/pages 0750 ${user} ${webserver.group} - -"
+      "d ${cfg.stateDir}/tmp 0750 ${user} ${webserver.group} - -"
     ] ++ lib.optional (cfg.aclFile != null) "C ${cfg.aclFile} 0640 ${user} ${webserver.group} - ${pkg hostName cfg}/share/dokuwiki/conf/acl.auth.php.dist"
     ++ lib.optional (cfg.usersFile != null) "C ${cfg.usersFile} 0640 ${user} ${webserver.group} - ${pkg hostName cfg}/share/dokuwiki/conf/users.auth.php.dist"
     ) eachSite);
@@ -349,7 +358,7 @@ in
           };
 
           "~ ^/data/" = {
-            root = "${stateDir hostName}";
+            root = "${cfg.stateDir}";
             extraConfig = "internal;";
           };
 
diff --git a/nixos/modules/services/web-apps/dolibarr.nix b/nixos/modules/services/web-apps/dolibarr.nix
new file mode 100644
index 00000000000..5335c439329
--- /dev/null
+++ b/nixos/modules/services/web-apps/dolibarr.nix
@@ -0,0 +1,320 @@
+{ config, pkgs, lib, ... }:
+let
+  inherit (lib) any boolToString concatStringsSep isBool isString literalExpression mapAttrsToList mkDefault mkEnableOption mkIf mkOption optionalAttrs types;
+
+  package = pkgs.dolibarr.override { inherit (cfg) stateDir; };
+
+  cfg = config.services.dolibarr;
+  vhostCfg = config.services.nginx.virtualHosts."${cfg.domain}";
+
+  mkConfigFile = filename: settings:
+    let
+      # hack in special logic for secrets so we read them from a separate file avoiding the nix store
+      secretKeys = [ "force_install_databasepass" "dolibarr_main_db_pass" "dolibarr_main_instance_unique_id" ];
+
+      toStr = k: v:
+        if (any (str: k == str) secretKeys) then v
+        else if isString v then "'${v}'"
+        else if isBool v then boolToString v
+        else if isNull v then "null"
+        else toString v
+      ;
+    in
+      pkgs.writeText filename ''
+        <?php
+        ${concatStringsSep "\n" (mapAttrsToList (k: v: "\$${k} = ${toStr k v};") settings)}
+      '';
+
+  # see https://github.com/Dolibarr/dolibarr/blob/develop/htdocs/install/install.forced.sample.php for all possible values
+  install = {
+    force_install_noedit = 2;
+    force_install_main_data_root = "${cfg.stateDir}/documents";
+    force_install_nophpinfo = true;
+    force_install_lockinstall = "444";
+    force_install_distrib = "nixos";
+    force_install_type = "mysqli";
+    force_install_dbserver = cfg.database.host;
+    force_install_port = toString cfg.database.port;
+    force_install_database = cfg.database.name;
+    force_install_databaselogin = cfg.database.user;
+
+    force_install_mainforcehttps = vhostCfg.forceSSL;
+    force_install_createuser = false;
+    force_install_dolibarrlogin = null;
+  } // optionalAttrs (cfg.database.passwordFile != null) {
+    force_install_databasepass = ''file_get_contents("${cfg.database.passwordFile}")'';
+  };
+in
+{
+  # interface
+  options.services.dolibarr = {
+    enable = mkEnableOption (lib.mdDoc "dolibarr");
+
+    domain = mkOption {
+      type = types.str;
+      default = "localhost";
+      description = lib.mdDoc ''
+        Domain name of your server.
+      '';
+    };
+
+    user = mkOption {
+      type = types.str;
+      default = "dolibarr";
+      description = lib.mdDoc ''
+        User account under which dolibarr runs.
+
+        ::: {.note}
+        If left as the default value this user will automatically be created
+        on system activation, otherwise you are responsible for
+        ensuring the user exists before the dolibarr application starts.
+        :::
+      '';
+    };
+
+    group = mkOption {
+      type = types.str;
+      default = "dolibarr";
+      description = lib.mdDoc ''
+        Group account under which dolibarr runs.
+
+        ::: {.note}
+        If left as the default value this group will automatically be created
+        on system activation, otherwise you are responsible for
+        ensuring the group exists before the dolibarr application starts.
+        :::
+      '';
+    };
+
+    stateDir = mkOption {
+      type = types.str;
+      default = "/var/lib/dolibarr";
+      description = lib.mdDoc ''
+        State and configuration directory dolibarr will use.
+      '';
+    };
+
+    database = {
+      host = mkOption {
+        type = types.str;
+        default = "localhost";
+        description = lib.mdDoc "Database host address.";
+      };
+      port = mkOption {
+        type = types.port;
+        default = 3306;
+        description = lib.mdDoc "Database host port.";
+      };
+      name = mkOption {
+        type = types.str;
+        default = "dolibarr";
+        description = lib.mdDoc "Database name.";
+      };
+      user = mkOption {
+        type = types.str;
+        default = "dolibarr";
+        description = lib.mdDoc "Database username.";
+      };
+      passwordFile = mkOption {
+        type = with types; nullOr path;
+        default = null;
+        example = "/run/keys/dolibarr-dbpassword";
+        description = lib.mdDoc "Database password file.";
+      };
+      createLocally = mkOption {
+        type = types.bool;
+        default = true;
+        description = lib.mdDoc "Create the database and database user locally.";
+      };
+    };
+
+    settings = mkOption {
+      type = with types; (attrsOf (oneOf [ bool int str ]));
+      default = { };
+      description = lib.mdDoc "Dolibarr settings, see <https://github.com/Dolibarr/dolibarr/blob/develop/htdocs/conf/conf.php.example> for details.";
+    };
+
+    nginx = mkOption {
+      type = types.nullOr (types.submodule (
+        lib.recursiveUpdate
+          (import ../web-servers/nginx/vhost-options.nix { inherit config lib; })
+          {
+            # enable encryption by default,
+            # as sensitive login and Dolibarr (ERP) data should not be transmitted in clear text.
+            options.forceSSL.default = true;
+            options.enableACME.default = true;
+          }
+      ));
+      default = null;
+      example = lib.literalExpression ''
+        {
+          serverAliases = [
+            "dolibarr.''${config.networking.domain}"
+            "erp.''${config.networking.domain}"
+          ];
+          enableACME = false;
+        }
+      '';
+      description = lib.mdDoc ''
+          With this option, you can customize an nginx virtual host which already has sensible defaults for Dolibarr.
+          Set to {} if you do not need any customization to the virtual host.
+          If enabled, then by default, the {option}`serverName` is
+          `''${domain}`,
+          SSL is active, and certificates are acquired via ACME.
+          If this is set to null (the default), no nginx virtualHost will be configured.
+      '';
+    };
+
+    poolConfig = mkOption {
+      type = with types; attrsOf (oneOf [ str int bool ]);
+      default = {
+        "pm" = "dynamic";
+        "pm.max_children" = 32;
+        "pm.start_servers" = 2;
+        "pm.min_spare_servers" = 2;
+        "pm.max_spare_servers" = 4;
+        "pm.max_requests" = 500;
+      };
+      description = lib.mdDoc ''
+        Options for the Dolibarr PHP pool. See the documentation on [`php-fpm.conf`](https://www.php.net/manual/en/install.fpm.configuration.php)
+        for details on configuration directives.
+      '';
+    };
+  };
+
+  # implementation
+  config = mkIf cfg.enable {
+
+    assertions = [
+      { assertion = cfg.database.createLocally -> cfg.database.user == cfg.user;
+        message = "services.dolibarr.database.user must match services.dolibarr.user if the database is to be automatically provisioned";
+      }
+    ];
+
+    services.dolibarr.settings = {
+      dolibarr_main_url_root = "https://${cfg.domain}";
+      dolibarr_main_document_root = "${package}/htdocs";
+      dolibarr_main_url_root_alt = "/custom";
+      dolibarr_main_data_root = "${cfg.stateDir}/documents";
+
+      dolibarr_main_db_host = cfg.database.host;
+      dolibarr_main_db_port = toString cfg.database.port;
+      dolibarr_main_db_name = cfg.database.name;
+      dolibarr_main_db_prefix = "llx_";
+      dolibarr_main_db_user = cfg.database.user;
+      dolibarr_main_db_pass = mkIf (cfg.database.passwordFile != null) ''
+        file_get_contents("${cfg.database.passwordFile}")
+      '';
+      dolibarr_main_db_type = "mysqli";
+      dolibarr_main_db_character_set = mkDefault "utf8";
+      dolibarr_main_db_collation = mkDefault "utf8_unicode_ci";
+
+      # Authentication settings
+      dolibarr_main_authentication = mkDefault "dolibarr";
+
+      # Security settings
+      dolibarr_main_prod = true;
+      dolibarr_main_force_https = vhostCfg.forceSSL;
+      dolibarr_main_restrict_os_commands = "${pkgs.mariadb}/bin/mysqldump, ${pkgs.mariadb}/bin/mysql";
+      dolibarr_nocsrfcheck = false;
+      dolibarr_main_instance_unique_id = ''
+        file_get_contents("${cfg.stateDir}/dolibarr_main_instance_unique_id")
+      '';
+      dolibarr_mailing_limit_sendbyweb = false;
+    };
+
+    systemd.tmpfiles.rules = [
+      "d '${cfg.stateDir}' 0750 ${cfg.user} ${cfg.group}"
+      "d '${cfg.stateDir}/documents' 0750 ${cfg.user} ${cfg.group}"
+      "f '${cfg.stateDir}/conf.php' 0660 ${cfg.user} ${cfg.group}"
+      "L '${cfg.stateDir}/install.forced.php' - ${cfg.user} ${cfg.group} - ${mkConfigFile "install.forced.php" install}"
+    ];
+
+    services.mysql = mkIf cfg.database.createLocally {
+      enable = mkDefault true;
+      package = mkDefault pkgs.mariadb;
+      ensureDatabases = [ cfg.database.name ];
+      ensureUsers = [
+        { name = cfg.database.user;
+          ensurePermissions = { "${cfg.database.name}.*" = "ALL PRIVILEGES"; };
+        }
+      ];
+    };
+
+    services.nginx.enable = mkIf (cfg.nginx != null) true;
+    services.nginx.virtualHosts."${cfg.domain}" = mkIf (cfg.nginx != null) (lib.mkMerge [
+      cfg.nginx
+      ({
+        root = lib.mkForce "${package}/htdocs";
+        locations."/".index = "index.php";
+        locations."~ [^/]\\.php(/|$)" = {
+          extraConfig = ''
+            fastcgi_split_path_info ^(.+?\.php)(/.*)$;
+            fastcgi_pass unix:${config.services.phpfpm.pools.dolibarr.socket};
+          '';
+        };
+      })
+    ]);
+
+    systemd.services."phpfpm-dolibarr".after = mkIf cfg.database.createLocally [ "mysql.service" ];
+    services.phpfpm.pools.dolibarr = {
+      inherit (cfg) user group;
+      phpPackage = pkgs.php.buildEnv {
+        extensions = { enabled, all }: enabled ++ [ all.calendar ];
+        # recommended by dolibarr web application
+        extraConfig = ''
+          session.use_strict_mode = 1
+          session.cookie_samesite = "Lax"
+          ; open_basedir = "${package}/htdocs, ${cfg.stateDir}"
+          allow_url_fopen = 0
+          disable_functions = "pcntl_alarm, pcntl_fork, pcntl_waitpid, pcntl_wait, pcntl_wifexited, pcntl_wifstopped, pcntl_wifsignaled, pcntl_wifcontinued, pcntl_wexitstatus, pcntl_wtermsig, pcntl_wstopsig, pcntl_signal, pcntl_signal_get_handler, pcntl_signal_dispatch, pcntl_get_last_error, pcntl_strerror, pcntl_sigprocmask, pcntl_sigwaitinfo, pcntl_sigtimedwait, pcntl_exec, pcntl_getpriority, pcntl_setpriority, pcntl_async_signals"
+        '';
+      };
+
+      settings = {
+        "listen.mode" = "0660";
+        "listen.owner" = cfg.user;
+        "listen.group" = cfg.group;
+      } // cfg.poolConfig;
+    };
+
+    # there are several challenges with dolibarr and NixOS which we can address here
+    # - the dolibarr installer cannot be entirely automated, though it can partially be by including a file called install.forced.php
+    # - the dolibarr installer requires write access to its config file during installation, though not afterwards
+    # - the dolibarr config file generally holds secrets generated by the installer, though the config file is a php file so we can read and write these secrets from an external file
+    systemd.services.dolibarr-config = {
+      description = "dolibarr configuration file management via NixOS";
+      wantedBy = [ "multi-user.target" ];
+
+      script = ''
+        # extract the 'main instance unique id' secret that the dolibarr installer generated for us, store it in a file for use by our own NixOS generated configuration file
+        ${pkgs.php}/bin/php -r "include '${cfg.stateDir}/conf.php'; file_put_contents('${cfg.stateDir}/dolibarr_main_instance_unique_id', \$dolibarr_main_instance_unique_id);"
+
+        # replace configuration file generated by installer with the NixOS generated configuration file
+        install -m 644 ${mkConfigFile "conf.php" cfg.settings} '${cfg.stateDir}/conf.php'
+      '';
+
+      serviceConfig = {
+        Type = "oneshot";
+        User = cfg.user;
+        Group = cfg.group;
+        RemainAfterExit = "yes";
+      };
+
+      unitConfig = {
+        ConditionFileNotEmpty = "${cfg.stateDir}/conf.php";
+      };
+    };
+
+    users.users.dolibarr = mkIf (cfg.user == "dolibarr" ) {
+      isSystemUser = true;
+      group = cfg.group;
+    };
+
+    users.groups = optionalAttrs (cfg.group == "dolibarr") {
+      dolibarr = { };
+    };
+
+    users.users."${config.services.nginx.group}".extraGroups = [ cfg.group ];
+  };
+}
diff --git a/nixos/modules/services/web-apps/engelsystem.nix b/nixos/modules/services/web-apps/engelsystem.nix
index 06c3c6dfc3d..f1d71f17447 100644
--- a/nixos/modules/services/web-apps/engelsystem.nix
+++ b/nixos/modules/services/web-apps/engelsystem.nix
@@ -9,7 +9,7 @@ in {
       enable = mkOption {
         default = false;
         example = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable engelsystem, an online tool for coordinating volunteers
           and shifts on large events.
         '';
@@ -19,12 +19,12 @@ in {
       domain = mkOption {
         type = types.str;
         example = "engelsystem.example.com";
-        description = "Domain to serve on.";
+        description = lib.mdDoc "Domain to serve on.";
       };
 
       package = mkOption {
         type = types.package;
-        description = "Engelsystem package used for the service.";
+        description = lib.mdDoc "Engelsystem package used for the service.";
         default = pkgs.engelsystem;
         defaultText = literalExpression "pkgs.engelsystem";
       };
@@ -32,9 +32,9 @@ in {
       createDatabase = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to create a local database automatically.
-          This will override every database setting in <option>services.engelsystem.config</option>.
+          This will override every database setting in {option}`services.engelsystem.config`.
         '';
       };
     };
@@ -70,7 +70,7 @@ in {
         min_password_length = 6;
         default_locale = "de_DE";
       };
-      description = ''
+      description = lib.mdDoc ''
         Options to be added to config.php, as a nix attribute set. Options containing secret data
         should be set to an attribute set containing the attribute _secret - a string pointing to a
         file containing the value the option should be set to. See the example to get a better
diff --git a/nixos/modules/services/web-apps/ethercalc.nix b/nixos/modules/services/web-apps/ethercalc.nix
index d74def59c6c..a5be86a34aa 100644
--- a/nixos/modules/services/web-apps/ethercalc.nix
+++ b/nixos/modules/services/web-apps/ethercalc.nix
@@ -10,11 +10,11 @@ in {
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           ethercalc, an online collaborative spreadsheet server.
 
           Persistent state will be maintained under
-          <filename>/var/lib/ethercalc</filename>. Upstream supports using a
+          {file}`/var/lib/ethercalc`. Upstream supports using a
           redis server for storage and recommends the redis backend for
           intensive use; however, the Nix module doesn't currently support
           redis.
@@ -28,19 +28,19 @@ in {
         default = pkgs.ethercalc;
         defaultText = literalExpression "pkgs.ethercalc";
         type = types.package;
-        description = "Ethercalc package to use.";
+        description = lib.mdDoc "Ethercalc package to use.";
       };
 
       host = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = "Address to listen on (use 0.0.0.0 to allow access from any address).";
+        description = lib.mdDoc "Address to listen on (use 0.0.0.0 to allow access from any address).";
       };
 
       port = mkOption {
         type = types.port;
         default = 8000;
-        description = "Port to bind to.";
+        description = lib.mdDoc "Port to bind to.";
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/fluidd.nix b/nixos/modules/services/web-apps/fluidd.nix
index 6ac1acc9d03..d4b86b9dfb3 100644
--- a/nixos/modules/services/web-apps/fluidd.nix
+++ b/nixos/modules/services/web-apps/fluidd.nix
@@ -6,11 +6,11 @@ let
 in
 {
   options.services.fluidd = {
-    enable = mkEnableOption "Fluidd, a Klipper web interface for managing your 3d printer";
+    enable = mkEnableOption (lib.mdDoc "Fluidd, a Klipper web interface for managing your 3d printer");
 
     package = mkOption {
       type = types.package;
-      description = "Fluidd package to be used in the module";
+      description = lib.mdDoc "Fluidd package to be used in the module";
       default = pkgs.fluidd;
       defaultText = literalExpression "pkgs.fluidd";
     };
@@ -18,7 +18,7 @@ in
     hostName = mkOption {
       type = types.str;
       default = "localhost";
-      description = "Hostname to serve fluidd on";
+      description = lib.mdDoc "Hostname to serve fluidd on";
     };
 
     nginx = mkOption {
@@ -30,7 +30,7 @@ in
           serverAliases = [ "fluidd.''${config.networking.domain}" ];
         }
       '';
-      description = "Extra configuration for the nginx virtual host of fluidd.";
+      description = lib.mdDoc "Extra configuration for the nginx virtual host of fluidd.";
     };
   };
 
diff --git a/nixos/modules/services/web-apps/freshrss.nix b/nixos/modules/services/web-apps/freshrss.nix
new file mode 100644
index 00000000000..c05e7b2c4f7
--- /dev/null
+++ b/nixos/modules/services/web-apps/freshrss.nix
@@ -0,0 +1,282 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let
+  cfg = config.services.freshrss;
+
+  poolName = "freshrss";
+in
+{
+  meta.maintainers = with maintainers; [ etu stunkymonkey ];
+
+  options.services.freshrss = {
+    enable = mkEnableOption (mdDoc "FreshRSS feed reader");
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.freshrss;
+      defaultText = lib.literalExpression "pkgs.freshrss";
+      description = mdDoc "Which FreshRSS package to use.";
+    };
+
+    defaultUser = mkOption {
+      type = types.str;
+      default = "admin";
+      description = mdDoc "Default username for FreshRSS.";
+      example = "eva";
+    };
+
+    passwordFile = mkOption {
+      type = types.path;
+      description = mdDoc "Password for the defaultUser for FreshRSS.";
+      example = "/run/secrets/freshrss";
+    };
+
+    baseUrl = mkOption {
+      type = types.str;
+      description = mdDoc "Default URL for FreshRSS.";
+      example = "https://freshrss.example.com";
+    };
+
+    language = mkOption {
+      type = types.str;
+      default = "en";
+      description = mdDoc "Default language for FreshRSS.";
+      example = "de";
+    };
+
+    database = {
+      type = mkOption {
+        type = types.enum [ "sqlite" "pgsql" "mysql" ];
+        default = "sqlite";
+        description = mdDoc "Database type.";
+        example = "pgsql";
+      };
+
+      host = mkOption {
+        type = types.nullOr types.str;
+        default = "localhost";
+        description = mdDoc "Database host for FreshRSS.";
+      };
+
+      port = mkOption {
+        type = with types; nullOr port;
+        default = null;
+        description = mdDoc "Database port for FreshRSS.";
+        example = 3306;
+      };
+
+      user = mkOption {
+        type = types.nullOr types.str;
+        default = "freshrss";
+        description = mdDoc "Database user for FreshRSS.";
+      };
+
+      passFile = mkOption {
+        type = types.nullOr types.str;
+        default = null;
+        description = mdDoc "Database password file for FreshRSS.";
+        example = "/run/secrets/freshrss";
+      };
+
+      name = mkOption {
+        type = types.nullOr types.str;
+        default = "freshrss";
+        description = mdDoc "Database name for FreshRSS.";
+      };
+
+      tableprefix = mkOption {
+        type = types.nullOr types.str;
+        default = null;
+        description = mdDoc "Database table prefix for FreshRSS.";
+        example = "freshrss";
+      };
+    };
+
+    dataDir = mkOption {
+      type = types.str;
+      default = "/var/lib/freshrss";
+      description = mdDoc "Default data folder for FreshRSS.";
+      example = "/mnt/freshrss";
+    };
+
+    virtualHost = mkOption {
+      type = types.nullOr types.str;
+      default = "freshrss";
+      description = mdDoc ''
+        Name of the nginx virtualhost to use and setup. If null, do not setup any virtualhost.
+      '';
+    };
+
+    pool = mkOption {
+      type = types.str;
+      default = poolName;
+      description = mdDoc ''
+        Name of the phpfpm pool to use and setup. If not specified, a pool will be created
+        with default values.
+      '';
+    };
+  };
+
+
+  config =
+    let
+      systemd-hardening = {
+        CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
+        DeviceAllow = "";
+        LockPersonality = true;
+        NoNewPrivileges = true;
+        PrivateDevices = true;
+        PrivateTmp = true;
+        PrivateUsers = true;
+        ProcSubset = "pid";
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectProc = "invisible";
+        ProtectSystem = "strict";
+        RemoveIPC = true;
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        RestrictSUIDSGID = true;
+        SystemCallArchitectures = "native";
+        SystemCallFilter = [ "@system-service" "~@resources" "~@privileged" ];
+        UMask = "0007";
+      };
+    in
+    mkIf cfg.enable {
+      # Set up a Nginx virtual host.
+      services.nginx = mkIf (cfg.virtualHost != null) {
+        enable = true;
+        virtualHosts.${cfg.virtualHost} = {
+          root = "${cfg.package}/p";
+
+          # php files handling
+          # this regex is mandatory because of the API
+          locations."~ ^.+?\.php(/.*)?$".extraConfig = ''
+            fastcgi_pass unix:${config.services.phpfpm.pools.${cfg.pool}.socket};
+            fastcgi_split_path_info ^(.+\.php)(/.*)$;
+            # By default, the variable PATH_INFO is not set under PHP-FPM
+            # But FreshRSS API greader.php need it. If you have a “Bad Request” error, double check this var!
+            # NOTE: the separate $path_info variable is required. For more details, see:
+            # https://trac.nginx.org/nginx/ticket/321
+            set $path_info $fastcgi_path_info;
+            fastcgi_param PATH_INFO $path_info;
+            include ${pkgs.nginx}/conf/fastcgi_params;
+            include ${pkgs.nginx}/conf/fastcgi.conf;
+          '';
+
+          locations."/" = {
+            tryFiles = "$uri $uri/ index.php";
+            index = "index.php index.html index.htm";
+          };
+        };
+      };
+
+      # Set up phpfpm pool
+      services.phpfpm.pools = mkIf (cfg.pool == poolName) {
+        ${poolName} = {
+          user = "freshrss";
+          settings = {
+            "listen.owner" = "nginx";
+            "listen.group" = "nginx";
+            "listen.mode" = "0600";
+            "pm" = "dynamic";
+            "pm.max_children" = 32;
+            "pm.max_requests" = 500;
+            "pm.start_servers" = 2;
+            "pm.min_spare_servers" = 2;
+            "pm.max_spare_servers" = 5;
+            "catch_workers_output" = true;
+          };
+          phpEnv = {
+            FRESHRSS_DATA_PATH = "${cfg.dataDir}";
+          };
+        };
+      };
+
+      users.users.freshrss = {
+        description = "FreshRSS service user";
+        isSystemUser = true;
+        group = "freshrss";
+      };
+      users.groups.freshrss = { };
+
+      systemd.services.freshrss-config =
+        let
+          settingsFlags = concatStringsSep " \\\n    "
+            (mapAttrsToList (k: v: "${k} ${toString v}") {
+              "--default_user" = ''"${cfg.defaultUser}"'';
+              "--auth_type" = ''"form"'';
+              "--base_url" = ''"${cfg.baseUrl}"'';
+              "--language" = ''"${cfg.language}"'';
+              "--db-type" = ''"${cfg.database.type}"'';
+              # The following attributes are optional depending on the type of
+              # database.  Those that evaluate to null on the left hand side
+              # will be omitted.
+              ${if cfg.database.name != null then "--db-base" else null} = ''"${cfg.database.name}"'';
+              ${if cfg.database.passFile != null then "--db-password" else null} = ''"$(cat ${cfg.database.passFile})"'';
+              ${if cfg.database.user != null then "--db-user" else null} = ''"${cfg.database.user}"'';
+              ${if cfg.database.tableprefix != null then "--db-prefix" else null} = ''"${cfg.database.tableprefix}"'';
+              ${if cfg.database.host != null && cfg.database.port != null then "--db-host" else null} = ''"${cfg.database.host}:${toString cfg.database.port}"'';
+            });
+        in
+        {
+          description = "Set up the state directory for FreshRSS before use";
+          wantedBy = [ "multi-user.target" ];
+          serviceConfig = {
+            Type = "oneshot";
+            User = "freshrss";
+            Group = "freshrss";
+            StateDirectory = "freshrss";
+            WorkingDirectory = cfg.package;
+          } // systemd-hardening;
+          environment = {
+            FRESHRSS_DATA_PATH = cfg.dataDir;
+          };
+
+          script = ''
+            # create files with correct permissions
+            mkdir -m 755 -p ${cfg.dataDir}
+
+            # do installation or reconfigure
+            if test -f ${cfg.dataDir}/config.php; then
+              # reconfigure with settings
+              ./cli/reconfigure.php ${settingsFlags}
+              ./cli/update-user.php --user ${cfg.defaultUser} --password "$(cat ${cfg.passwordFile})"
+            else
+              # Copy the user data template directory
+              cp -r ./data ${cfg.dataDir}
+
+              # check correct folders in data folder
+              ./cli/prepare.php
+              # install with settings
+              ./cli/do-install.php ${settingsFlags}
+              ./cli/create-user.php --user ${cfg.defaultUser} --password "$(cat ${cfg.passwordFile})"
+            fi
+          '';
+        };
+
+      systemd.services.freshrss-updater = {
+        description = "FreshRSS feed updater";
+        after = [ "freshrss-config.service" ];
+        wantedBy = [ "multi-user.target" ];
+        startAt = "*:0/5";
+        environment = {
+          FRESHRSS_DATA_PATH = cfg.dataDir;
+        };
+        serviceConfig = {
+          Type = "oneshot";
+          User = "freshrss";
+          Group = "freshrss";
+          StateDirectory = "freshrss";
+          WorkingDirectory = cfg.package;
+          ExecStart = "${cfg.package}/app/actualize_script.php";
+        } // systemd-hardening;
+      };
+    };
+}
diff --git a/nixos/modules/services/web-apps/galene.nix b/nixos/modules/services/web-apps/galene.nix
index 1d0a620585b..15ef09aa0b8 100644
--- a/nixos/modules/services/web-apps/galene.nix
+++ b/nixos/modules/services/web-apps/galene.nix
@@ -12,12 +12,12 @@ in
 {
   options = {
     services.galene = {
-      enable = mkEnableOption "Galene Service.";
+      enable = mkEnableOption (lib.mdDoc "Galene Service.");
 
       stateDir = mkOption {
         default = defaultstateDir;
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The directory where Galene stores its internal state. If left as the default
           value this directory will automatically be created before the Galene server
           starts, otherwise the sysadmin is responsible for ensuring the directory
@@ -28,19 +28,19 @@ in
       user = mkOption {
         type = types.str;
         default = "galene";
-        description = "User account under which galene runs.";
+        description = lib.mdDoc "User account under which galene runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "galene";
-        description = "Group under which galene runs.";
+        description = lib.mdDoc "Group under which galene runs.";
       };
 
       insecure = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether Galene should listen in http or in https. If left as the default
           value (false), Galene needs to be fed a private key and a certificate.
         '';
@@ -50,7 +50,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "/path/to/your/cert.pem";
-        description = ''
+        description = lib.mdDoc ''
           Path to the server's certificate. The file is copied at runtime to
           Galene's data directory where it needs to reside.
         '';
@@ -60,7 +60,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "/path/to/your/key.pem";
-        description = ''
+        description = lib.mdDoc ''
           Path to the server's private key. The file is copied at runtime to
           Galene's data directory where it needs to reside.
         '';
@@ -69,13 +69,13 @@ in
       httpAddress = mkOption {
         type = types.str;
         default = "";
-        description = "HTTP listen address for galene.";
+        description = lib.mdDoc "HTTP listen address for galene.";
       };
 
       httpPort = mkOption {
         type = types.port;
         default = 8443;
-        description = "HTTP listen port.";
+        description = lib.mdDoc "HTTP listen port.";
       };
 
       staticDir = mkOption {
@@ -83,7 +83,7 @@ in
         default = "${cfg.package.static}/static";
         defaultText = literalExpression ''"''${package.static}/static"'';
         example = "/var/lib/galene/static";
-        description = "Web server directory.";
+        description = lib.mdDoc "Web server directory.";
       };
 
       recordingsDir = mkOption {
@@ -91,7 +91,7 @@ in
         default = defaultrecordingsDir;
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/recordings"'';
         example = "/var/lib/galene/recordings";
-        description = "Recordings directory.";
+        description = lib.mdDoc "Recordings directory.";
       };
 
       dataDir = mkOption {
@@ -99,7 +99,7 @@ in
         default = defaultdataDir;
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/data"'';
         example = "/var/lib/galene/data";
-        description = "Data directory.";
+        description = lib.mdDoc "Data directory.";
       };
 
       groupsDir = mkOption {
@@ -107,14 +107,14 @@ in
         default = defaultgroupsDir;
         defaultText = literalExpression ''"''${config.${opt.stateDir}}/groups"'';
         example = "/var/lib/galene/groups";
-        description = "Web server directory.";
+        description = lib.mdDoc "Web server directory.";
       };
 
       package = mkOption {
         default = pkgs.galene;
         defaultText = literalExpression "pkgs.galene";
         type = types.package;
-        description = ''
+        description = lib.mdDoc ''
           Package for running Galene.
         '';
       };
@@ -164,6 +164,35 @@ in
             optional (cfg.dataDir == defaultdataDir) "galene/data" ++
             optional (cfg.groupsDir == defaultgroupsDir) "galene/groups" ++
             optional (cfg.recordingsDir == defaultrecordingsDir) "galene/recordings";
+
+          # Hardening
+          CapabilityBoundingSet = [ "" ];
+          DeviceAllow = [ "" ];
+          LockPersonality = true;
+          MemoryDenyWriteExecute = true;
+          NoNewPrivileges = true;
+          PrivateDevices = true;
+          PrivateTmp = true;
+          PrivateUsers = true;
+          ProcSubset = "pid";
+          ProtectClock = true;
+          ProtectControlGroups = true;
+          ProtectHome = true;
+          ProtectHostname = true;
+          ProtectKernelLogs = true;
+          ProtectKernelModules = true;
+          ProtectKernelTunables = true;
+          ProtectProc = "invisible";
+          ProtectSystem = "strict";
+          ReadWritePaths = cfg.recordingsDir;
+          RemoveIPC = true;
+          RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+          RestrictNamespaces = true;
+          RestrictRealtime = true;
+          RestrictSUIDSGID = true;
+          SystemCallArchitectures = "native";
+          SystemCallFilter = [ "@system-service" "~@privileged" ];
+          UMask = "0077";
         }
       ];
     };
diff --git a/nixos/modules/services/web-apps/gerrit.nix b/nixos/modules/services/web-apps/gerrit.nix
index 6bfc67368dd..ab2eeea09bd 100644
--- a/nixos/modules/services/web-apps/gerrit.nix
+++ b/nixos/modules/services/web-apps/gerrit.nix
@@ -59,20 +59,20 @@ in
 {
   options = {
     services.gerrit = {
-      enable = mkEnableOption "Gerrit service";
+      enable = mkEnableOption (lib.mdDoc "Gerrit service");
 
       package = mkOption {
         type = types.package;
         default = pkgs.gerrit;
         defaultText = literalExpression "pkgs.gerrit";
-        description = "Gerrit package to use";
+        description = lib.mdDoc "Gerrit package to use";
       };
 
       jvmPackage = mkOption {
         type = types.package;
         default = pkgs.jre_headless;
         defaultText = literalExpression "pkgs.jre_headless";
-        description = "Java Runtime Environment package to use";
+        description = lib.mdDoc "Java Runtime Environment package to use";
       };
 
       jvmOpts = mkOption {
@@ -81,13 +81,13 @@ in
           "-Dflogger.backend_factory=com.google.common.flogger.backend.log4j.Log4jBackendFactory#getInstance"
           "-Dflogger.logging_context=com.google.gerrit.server.logging.LoggingContext#getInstance"
         ];
-        description = "A list of JVM options to start gerrit with.";
+        description = lib.mdDoc "A list of JVM options to start gerrit with.";
       };
 
       jvmHeapLimit = mkOption {
         type = types.str;
         default = "1024m";
-        description = ''
+        description = lib.mdDoc ''
           How much memory to allocate to the JVM heap
         '';
       };
@@ -95,8 +95,8 @@ in
       listenAddress = mkOption {
         type = types.str;
         default = "[::]:8080";
-        description = ''
-          <literal>hostname:port</literal> to listen for HTTP traffic.
+        description = lib.mdDoc ''
+          `hostname:port` to listen for HTTP traffic.
 
           This is bound using the systemd socket activation.
         '';
@@ -105,25 +105,25 @@ in
       settings = mkOption {
         type = gitIniType;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Gerrit configuration. This will be generated to the
-          <literal>etc/gerrit.config</literal> file.
+          `etc/gerrit.config` file.
         '';
       };
 
       replicationSettings = mkOption {
         type = gitIniType;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Replication configuration. This will be generated to the
-          <literal>etc/replication.config</literal> file.
+          `etc/replication.config` file.
         '';
       };
 
       plugins = mkOption {
         type = types.listOf types.package;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of plugins to add to Gerrit. Each derivation is a jar file
           itself where the name of the derivation is the name of plugin.
         '';
@@ -132,19 +132,19 @@ in
       builtinPlugins = mkOption {
         type = types.listOf (types.enum cfg.package.passthru.plugins);
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of builtins plugins to install. Those are shipped in the
-          <literal>gerrit.war</literal> file.
+          `gerrit.war` file.
         '';
       };
 
       serverId = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Set a UUID that uniquely identifies the server.
 
           This can be generated with
-          <literal>nix-shell -p util-linux --run uuidgen</literal>.
+          `nix-shell -p util-linux --run uuidgen`.
         '';
       };
     };
diff --git a/nixos/modules/services/web-apps/gotify-server.nix b/nixos/modules/services/web-apps/gotify-server.nix
index 03e01f46a94..8db3a8ef3e8 100644
--- a/nixos/modules/services/web-apps/gotify-server.nix
+++ b/nixos/modules/services/web-apps/gotify-server.nix
@@ -7,11 +7,11 @@ let
 in {
   options = {
     services.gotify = {
-      enable = mkEnableOption "Gotify webserver";
+      enable = mkEnableOption (lib.mdDoc "Gotify webserver");
 
       port = mkOption {
         type = types.port;
-        description = ''
+        description = lib.mdDoc ''
           Port the server listens to.
         '';
       };
@@ -19,8 +19,8 @@ in {
       stateDirectoryName = mkOption {
         type = types.str;
         default = "gotify-server";
-        description = ''
-          The name of the directory below <filename>/var/lib</filename> where
+        description = lib.mdDoc ''
+          The name of the directory below {file}`/var/lib` where
           gotify stores its runtime data.
         '';
       };
diff --git a/nixos/modules/services/web-apps/grocy.nix b/nixos/modules/services/web-apps/grocy.nix
index be2de638dd9..6efc2ccfd30 100644
--- a/nixos/modules/services/web-apps/grocy.nix
+++ b/nixos/modules/services/web-apps/grocy.nix
@@ -6,11 +6,11 @@ let
   cfg = config.services.grocy;
 in {
   options.services.grocy = {
-    enable = mkEnableOption "grocy";
+    enable = mkEnableOption (lib.mdDoc "grocy");
 
     hostName = mkOption {
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         FQDN for the grocy instance.
       '';
     };
@@ -18,7 +18,7 @@ in {
     nginx.enableSSL = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether or not to enable SSL (with ACME and let's encrypt)
         for the grocy vhost.
       '';
@@ -39,7 +39,7 @@ in {
         "pm.max_requests" = "500";
       };
 
-      description = ''
+      description = lib.mdDoc ''
         Options for grocy's PHPFPM pool.
       '';
     };
@@ -47,8 +47,8 @@ in {
     dataDir = mkOption {
       type = types.str;
       default = "/var/lib/grocy";
-      description = ''
-        Home directory of the <literal>grocy</literal> user which contains
+      description = lib.mdDoc ''
+        Home directory of the `grocy` user which contains
         the application's state.
       '';
     };
@@ -58,7 +58,7 @@ in {
         type = types.str;
         default = "USD";
         example = "EUR";
-        description = ''
+        description = lib.mdDoc ''
           ISO 4217 code for the currency to display.
         '';
       };
@@ -66,7 +66,7 @@ in {
       culture = mkOption {
         type = types.enum [ "de" "en" "da" "en_GB" "es" "fr" "hu" "it" "nl" "no" "pl" "pt_BR" "ru" "sk_SK" "sv_SE" "tr" ];
         default = "en";
-        description = ''
+        description = lib.mdDoc ''
           Display language of the frontend.
         '';
       };
@@ -75,14 +75,14 @@ in {
         showWeekNumber = mkOption {
           default = true;
           type = types.bool;
-          description = ''
+          description = lib.mdDoc ''
             Show the number of the weeks in the calendar views.
           '';
         };
         firstDayOfWeek = mkOption {
           default = null;
           type = types.nullOr (types.enum (range 0 6));
-          description = ''
+          description = lib.mdDoc ''
             Which day of the week (0=Sunday, 1=Monday etc.) should be the
             first day.
           '';
@@ -115,9 +115,9 @@ in {
       user = "grocy";
       group = "nginx";
 
-      # PHP 7.4 is the only version which is supported/tested by upstream:
-      # https://github.com/grocy/grocy/blob/v3.0.0/README.md#how-to-install
-      phpPackage = pkgs.php74;
+      # PHP 8.0 is the only version which is supported/tested by upstream:
+      # https://github.com/grocy/grocy/blob/v3.3.0/README.md#how-to-install
+      phpPackage = pkgs.php80;
 
       inherit (cfg.phpfpm) settings;
 
diff --git a/nixos/modules/services/web-apps/healthchecks.nix b/nixos/modules/services/web-apps/healthchecks.nix
new file mode 100644
index 00000000000..7da6dce1f95
--- /dev/null
+++ b/nixos/modules/services/web-apps/healthchecks.nix
@@ -0,0 +1,249 @@
+{ config, lib, pkgs, buildEnv, ... }:
+
+with lib;
+
+let
+  defaultUser = "healthchecks";
+  cfg = config.services.healthchecks;
+  pkg = cfg.package;
+  boolToPython = b: if b then "True" else "False";
+  environment = {
+    PYTHONPATH = pkg.pythonPath;
+    STATIC_ROOT = cfg.dataDir + "/static";
+    DB_NAME = "${cfg.dataDir}/healthchecks.sqlite";
+  } // cfg.settings;
+
+  environmentFile = pkgs.writeText "healthchecks-environment" (lib.generators.toKeyValue { } environment);
+
+  healthchecksManageScript = pkgs.writeShellScriptBin "healthchecks-manage" ''
+    sudo=exec
+    if [[ "$USER" != "${cfg.user}" ]]; then
+      sudo='exec /run/wrappers/bin/sudo -u ${cfg.user} --preserve-env --preserve-env=PYTHONPATH'
+    fi
+    export $(cat ${environmentFile} | xargs)
+    $sudo ${pkg}/opt/healthchecks/manage.py "$@"
+  '';
+in
+{
+  options.services.healthchecks = {
+    enable = mkEnableOption (lib.mdDoc "healthchecks") // {
+      description = lib.mdDoc ''
+        Enable healthchecks.
+        It is expected to be run behind a HTTP reverse proxy.
+      '';
+    };
+
+    package = mkOption {
+      default = pkgs.healthchecks;
+      defaultText = literalExpression "pkgs.healthchecks";
+      type = types.package;
+      description = lib.mdDoc "healthchecks package to use.";
+    };
+
+    user = mkOption {
+      default = defaultUser;
+      type = types.str;
+      description = lib.mdDoc ''
+        User account under which healthchecks runs.
+
+        ::: {.note}
+        If left as the default value this user will automatically be created
+        on system activation, otherwise you are responsible for
+        ensuring the user exists before the healthchecks service starts.
+        :::
+      '';
+    };
+
+    group = mkOption {
+      default = defaultUser;
+      type = types.str;
+      description = lib.mdDoc ''
+        Group account under which healthchecks runs.
+
+        ::: {.note}
+        If left as the default value this group will automatically be created
+        on system activation, otherwise you are responsible for
+        ensuring the group exists before the healthchecks service starts.
+        :::
+      '';
+    };
+
+    listenAddress = mkOption {
+      type = types.str;
+      default = "localhost";
+      description = lib.mdDoc "Address the server will listen on.";
+    };
+
+    port = mkOption {
+      type = types.port;
+      default = 8000;
+      description = lib.mdDoc "Port the server will listen on.";
+    };
+
+    dataDir = mkOption {
+      type = types.str;
+      default = "/var/lib/healthchecks";
+      description = lib.mdDoc ''
+        The directory used to store all data for healthchecks.
+
+        ::: {.note}
+        If left as the default value this directory will automatically be created before
+        the healthchecks server starts, otherwise you are responsible for ensuring the
+        directory exists with appropriate ownership and permissions.
+        :::
+      '';
+    };
+
+    settings = lib.mkOption {
+      description = lib.mdDoc ''
+        Environment variables which are read by healthchecks `(local)_settings.py`.
+
+        Settings which are explictly covered in options bewlow, are type-checked and/or transformed
+        before added to the environment, everything else is passed as a string.
+
+        See <https://healthchecks.io/docs/self_hosted_configuration/>
+        for a full documentation of settings.
+
+        We add two variables to this list inside the packages `local_settings.py.`
+        - STATIC_ROOT to set a state directory for dynamically generated static files.
+        - SECRET_KEY_FILE to read SECRET_KEY from a file at runtime and keep it out of /nix/store.
+      '';
+      type = types.submodule {
+        freeformType = types.attrsOf types.str;
+        options = {
+          ALLOWED_HOSTS = lib.mkOption {
+            type = types.listOf types.str;
+            default = [ "*" ];
+            description = lib.mdDoc "The host/domain names that this site can serve.";
+            apply = lib.concatStringsSep ",";
+          };
+
+          SECRET_KEY_FILE = mkOption {
+            type = types.path;
+            description = lib.mdDoc "Path to a file containing the secret key.";
+          };
+
+          DEBUG = mkOption {
+            type = types.bool;
+            default = false;
+            description = lib.mdDoc "Enable debug mode.";
+            apply = boolToPython;
+          };
+
+          REGISTRATION_OPEN = mkOption {
+            type = types.bool;
+            default = false;
+            description = lib.mdDoc ''
+              A boolean that controls whether site visitors can create new accounts.
+              Set it to false if you are setting up a private Healthchecks instance,
+              but it needs to be publicly accessible (so, for example, your cloud
+              services can send pings to it).
+              If you close new user registration, you can still selectively invite
+              users to your team account.
+            '';
+            apply = boolToPython;
+          };
+        };
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    environment.systemPackages = [ healthchecksManageScript ];
+
+    systemd.targets.healthchecks = {
+      description = "Target for all Healthchecks services";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" "network-online.target" ];
+    };
+
+    systemd.services =
+      let
+        commonConfig = {
+          WorkingDirectory = cfg.dataDir;
+          User = cfg.user;
+          Group = cfg.group;
+          EnvironmentFile = [ environmentFile ];
+          StateDirectory = mkIf (cfg.dataDir == "/var/lib/healthchecks") "healthchecks";
+          StateDirectoryMode = mkIf (cfg.dataDir == "/var/lib/healthchecks") "0750";
+        };
+      in
+        {
+        healthchecks-migration = {
+          description = "Healthchecks migrations";
+          wantedBy = [ "healthchecks.target" ];
+
+          serviceConfig = commonConfig // {
+            Restart = "on-failure";
+            Type = "oneshot";
+            ExecStart = ''
+              ${pkg}/opt/healthchecks/manage.py migrate
+            '';
+          };
+        };
+
+        healthchecks = {
+          description = "Healthchecks WSGI Service";
+          wantedBy = [ "healthchecks.target" ];
+          after = [ "healthchecks-migration.service" ];
+
+          preStart = ''
+            ${pkg}/opt/healthchecks/manage.py collectstatic --no-input
+            ${pkg}/opt/healthchecks/manage.py remove_stale_contenttypes --no-input
+            ${pkg}/opt/healthchecks/manage.py compress
+          '';
+
+          serviceConfig = commonConfig // {
+            Restart = "always";
+            ExecStart = ''
+              ${pkgs.python3Packages.gunicorn}/bin/gunicorn hc.wsgi \
+                --bind ${cfg.listenAddress}:${toString cfg.port} \
+                --pythonpath ${pkg}/opt/healthchecks
+            '';
+          };
+        };
+
+        healthchecks-sendalerts = {
+          description = "Healthchecks Alert Service";
+          wantedBy = [ "healthchecks.target" ];
+          after = [ "healthchecks.service" ];
+
+          serviceConfig = commonConfig // {
+            Restart = "always";
+            ExecStart = ''
+              ${pkg}/opt/healthchecks/manage.py sendalerts
+            '';
+          };
+        };
+
+        healthchecks-sendreports = {
+          description = "Healthchecks Reporting Service";
+          wantedBy = [ "healthchecks.target" ];
+          after = [ "healthchecks.service" ];
+
+          serviceConfig = commonConfig // {
+            Restart = "always";
+            ExecStart = ''
+              ${pkg}/opt/healthchecks/manage.py sendreports --loop
+            '';
+          };
+        };
+      };
+
+    users.users = optionalAttrs (cfg.user == defaultUser) {
+      ${defaultUser} =
+        {
+          description = "healthchecks service owner";
+          isSystemUser = true;
+          group = defaultUser;
+        };
+    };
+
+    users.groups = optionalAttrs (cfg.user == defaultUser) {
+      ${defaultUser} =
+        {
+          members = [ defaultUser ];
+        };
+    };
+  };
+}
diff --git a/nixos/modules/services/web-apps/hedgedoc.nix b/nixos/modules/services/web-apps/hedgedoc.nix
index 9eeabb9d566..ea27eb7ba39 100644
--- a/nixos/modules/services/web-apps/hedgedoc.nix
+++ b/nixos/modules/services/web-apps/hedgedoc.nix
@@ -13,26 +13,31 @@ let
     then "hedgedoc"
     else "codimd";
 
+  settingsFormat = pkgs.formats.json {};
+
   prettyJSON = conf:
     pkgs.runCommandLocal "hedgedoc-config.json" {
       nativeBuildInputs = [ pkgs.jq ];
     } ''
-      echo '${builtins.toJSON conf}' | jq \
-        '{production:del(.[]|nulls)|del(.[][]?|nulls)}' > $out
+      jq '{production:del(.[]|nulls)|del(.[][]?|nulls)}' \
+        < ${settingsFormat.generate "hedgedoc-ugly.json" cfg.settings} \
+        > $out
     '';
 in
 {
   imports = [
     (mkRenamedOptionModule [ "services" "codimd" ] [ "services" "hedgedoc" ])
+    (mkRenamedOptionModule
+      [ "services" "hedgedoc" "configuration" ] [ "services" "hedgedoc" "settings" ])
   ];
 
   options.services.hedgedoc = {
-    enable = mkEnableOption "the HedgeDoc Markdown Editor";
+    enable = mkEnableOption (lib.mdDoc "the HedgeDoc Markdown Editor");
 
     groups = mkOption {
       type = types.listOf types.str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Groups to which the service user should be added.
       '';
     };
@@ -40,18 +45,18 @@ in
     workDir = mkOption {
       type = types.path;
       default = "/var/lib/${name}";
-      description = ''
+      description = lib.mdDoc ''
         Working directory for the HedgeDoc service.
       '';
     };
 
-    configuration = {
-      debug = mkEnableOption "debug mode";
+    settings = let options = {
+      debug = mkEnableOption (lib.mdDoc "debug mode");
       domain = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "hedgedoc.org";
-        description = ''
+        description = lib.mdDoc ''
           Domain name for the HedgeDoc instance.
         '';
       };
@@ -59,22 +64,22 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "/url/path/to/hedgedoc";
-        description = ''
+        description = lib.mdDoc ''
           Path under which HedgeDoc is accessible.
         '';
       };
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           Address to listen on.
         '';
       };
       port = mkOption {
-        type = types.int;
+        type = types.port;
         default = 3000;
         example = 80;
-        description = ''
+        description = lib.mdDoc ''
           Port to listen on.
         '';
       };
@@ -82,7 +87,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "/run/hedgedoc.sock";
-        description = ''
+        description = lib.mdDoc ''
           Specify where a UNIX domain socket should be placed.
         '';
       };
@@ -90,44 +95,44 @@ in
         type = types.listOf types.str;
         default = [];
         example = [ "localhost" "hedgedoc.org" ];
-        description = ''
+        description = lib.mdDoc ''
           List of domains to whitelist.
         '';
       };
       useSSL = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable to use SSL server. This will also enable
-          <option>protocolUseSSL</option>.
+          {option}`protocolUseSSL`.
         '';
       };
       hsts = {
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to enable HSTS if HTTPS is also enabled.
           '';
         };
         maxAgeSeconds = mkOption {
           type = types.int;
           default = 31536000;
-          description = ''
+          description = lib.mdDoc ''
             Max duration for clients to keep the HSTS status.
           '';
         };
         includeSubdomains = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to include subdomains in HSTS.
           '';
         };
         preload = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether to allow preloading of the site's HSTS status.
           '';
         };
@@ -145,62 +150,68 @@ in
             addDefaults = true;
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Specify the Content Security Policy which is passed to Helmet.
-          For configuration details see <link xlink:href="https://helmetjs.github.io/docs/csp/"
-          >https://helmetjs.github.io/docs/csp/</link>.
+          For configuration details see <https://helmetjs.github.io/docs/csp/>.
         '';
       };
       protocolUseSSL = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable to use TLS for resource paths.
-          This only applies when <option>domain</option> is set.
+          This only applies when {option}`domain` is set.
         '';
       };
       urlAddPort = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable to add the port to callback URLs.
-          This only applies when <option>domain</option> is set
+          This only applies when {option}`domain` is set
           and only for ports other than 80 and 443.
         '';
       };
       useCDN = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use CDN resources or not.
         '';
       };
       allowAnonymous = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to allow anonymous usage.
         '';
       };
       allowAnonymousEdits = mkOption {
         type = types.bool;
         default = false;
-        description = ''
-          Whether to allow guests to edit existing notes with the `freely' permission,
-          when <option>allowAnonymous</option> is enabled.
+        description = lib.mdDoc ''
+          Whether to allow guests to edit existing notes with the `freely` permission,
+          when {option}`allowAnonymous` is enabled.
         '';
       };
       allowFreeURL = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to allow note creation by accessing a nonexistent note URL.
         '';
       };
+      requireFreeURLAuthentication = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to require authentication for FreeURL mode style note creation.
+        '';
+      };
       defaultPermission = mkOption {
         type = types.enum [ "freely" "editable" "limited" "locked" "private" ];
         default = "editable";
-        description = ''
+        description = lib.mdDoc ''
           Default permissions for notes.
           This only applies for signed-in users.
         '';
@@ -211,12 +222,12 @@ in
         example = ''
           postgres://user:pass@host:5432/dbname
         '';
-        description = ''
+        description = lib.mdDoc ''
           Specify which database to use.
           HedgeDoc supports mysql, postgres, sqlite and mssql.
-          See <link xlink:href="https://sequelize.readthedocs.io/en/v3/">
-          https://sequelize.readthedocs.io/en/v3/</link> for more information.
-          Note: This option overrides <option>db</option>.
+          See [
+          https://sequelize.readthedocs.io/en/v3/](https://sequelize.readthedocs.io/en/v3/) for more information.
+          Note: This option overrides {option}`db`.
         '';
       };
       db = mkOption {
@@ -228,52 +239,52 @@ in
             storage = "/var/lib/${name}/db.${name}.sqlite";
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Specify the configuration for sequelize.
           HedgeDoc supports mysql, postgres, sqlite and mssql.
-          See <link xlink:href="https://sequelize.readthedocs.io/en/v3/">
-          https://sequelize.readthedocs.io/en/v3/</link> for more information.
-          Note: This option overrides <option>db</option>.
+          See [
+          https://sequelize.readthedocs.io/en/v3/](https://sequelize.readthedocs.io/en/v3/) for more information.
+          Note: This option overrides {option}`db`.
         '';
       };
       sslKeyPath= mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "/var/lib/hedgedoc/hedgedoc.key";
-        description = ''
-          Path to the SSL key. Needed when <option>useSSL</option> is enabled.
+        description = lib.mdDoc ''
+          Path to the SSL key. Needed when {option}`useSSL` is enabled.
         '';
       };
       sslCertPath = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "/var/lib/hedgedoc/hedgedoc.crt";
-        description = ''
-          Path to the SSL cert. Needed when <option>useSSL</option> is enabled.
+        description = lib.mdDoc ''
+          Path to the SSL cert. Needed when {option}`useSSL` is enabled.
         '';
       };
       sslCAPath = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "/var/lib/hedgedoc/ca.crt" ];
-        description = ''
-          SSL ca chain. Needed when <option>useSSL</option> is enabled.
+        description = lib.mdDoc ''
+          SSL ca chain. Needed when {option}`useSSL` is enabled.
         '';
       };
       dhParamPath = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "/var/lib/hedgedoc/dhparam.pem";
-        description = ''
-          Path to the SSL dh params. Needed when <option>useSSL</option> is enabled.
+        description = lib.mdDoc ''
+          Path to the SSL dh params. Needed when {option}`useSSL` is enabled.
         '';
       };
       tmpPath = mkOption {
         type = types.str;
         default = "/tmp";
-        description = ''
+        description = lib.mdDoc ''
           Path to the temp directory HedgeDoc should use.
-          Note that <option>serviceConfig.PrivateTmp</option> is enabled for
+          Note that {option}`serviceConfig.PrivateTmp` is enabled for
           the HedgeDoc systemd service by default.
           (Non-canonical paths are relative to HedgeDoc's base directory)
         '';
@@ -281,7 +292,7 @@ in
       defaultNotePath = mkOption {
         type = types.nullOr types.str;
         default = "./public/default.md";
-        description = ''
+        description = lib.mdDoc ''
           Path to the default Note file.
           (Non-canonical paths are relative to HedgeDoc's base directory)
         '';
@@ -289,7 +300,7 @@ in
       docsPath = mkOption {
         type = types.nullOr types.str;
         default = "./public/docs";
-        description = ''
+        description = lib.mdDoc ''
           Path to the docs directory.
           (Non-canonical paths are relative to HedgeDoc's base directory)
         '';
@@ -297,7 +308,7 @@ in
       indexPath = mkOption {
         type = types.nullOr types.str;
         default = "./public/views/index.ejs";
-        description = ''
+        description = lib.mdDoc ''
           Path to the index template file.
           (Non-canonical paths are relative to HedgeDoc's base directory)
         '';
@@ -305,7 +316,7 @@ in
       hackmdPath = mkOption {
         type = types.nullOr types.str;
         default = "./public/views/hackmd.ejs";
-        description = ''
+        description = lib.mdDoc ''
           Path to the hackmd template file.
           (Non-canonical paths are relative to HedgeDoc's base directory)
         '';
@@ -314,7 +325,7 @@ in
         type = types.nullOr types.str;
         default = null;
         defaultText = literalExpression "./public/views/error.ejs";
-        description = ''
+        description = lib.mdDoc ''
           Path to the error template file.
           (Non-canonical paths are relative to HedgeDoc's base directory)
         '';
@@ -323,7 +334,7 @@ in
         type = types.nullOr types.str;
         default = null;
         defaultText = literalExpression "./public/views/pretty.ejs";
-        description = ''
+        description = lib.mdDoc ''
           Path to the pretty template file.
           (Non-canonical paths are relative to HedgeDoc's base directory)
         '';
@@ -332,7 +343,7 @@ in
         type = types.nullOr types.str;
         default = null;
         defaultText = literalExpression "./public/views/slide.hbs";
-        description = ''
+        description = lib.mdDoc ''
           Path to the slide template file.
           (Non-canonical paths are relative to HedgeDoc's base directory)
         '';
@@ -341,21 +352,21 @@ in
         type = types.str;
         default = "${cfg.workDir}/uploads";
         defaultText = literalExpression "/var/lib/${name}/uploads";
-        description = ''
+        description = lib.mdDoc ''
           Path under which uploaded files are saved.
         '';
       };
       sessionName = mkOption {
         type = types.str;
         default = "connect.sid";
-        description = ''
+        description = lib.mdDoc ''
           Specify the name of the session cookie.
         '';
       };
       sessionSecret = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Specify the secret used to sign the session cookie.
           If unset, one will be generated on startup.
         '';
@@ -363,56 +374,56 @@ in
       sessionLife = mkOption {
         type = types.int;
         default = 1209600000;
-        description = ''
+        description = lib.mdDoc ''
           Session life time in milliseconds.
         '';
       };
       heartbeatInterval = mkOption {
         type = types.int;
         default = 5000;
-        description = ''
+        description = lib.mdDoc ''
           Specify the socket.io heartbeat interval.
         '';
       };
       heartbeatTimeout = mkOption {
         type = types.int;
         default = 10000;
-        description = ''
+        description = lib.mdDoc ''
           Specify the socket.io heartbeat timeout.
         '';
       };
       documentMaxLength = mkOption {
         type = types.int;
         default = 100000;
-        description = ''
+        description = lib.mdDoc ''
           Specify the maximum document length.
         '';
       };
       email = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable email sign-in.
         '';
       };
       allowEmailRegister = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable email registration.
         '';
       };
       allowGravatar = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to use gravatar as profile picture source.
         '';
       };
       imageUploadType = mkOption {
         type = types.enum [ "imgur" "s3" "minio" "filesystem" ];
         default = "filesystem";
-        description = ''
+        description = lib.mdDoc ''
           Specify where to upload images.
         '';
       };
@@ -421,85 +432,85 @@ in
           options = {
             accessKey = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Minio access key.
               '';
             };
             secretKey = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Minio secret key.
               '';
             };
-            endpoint = mkOption {
+            endPoint = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Minio endpoint.
               '';
             };
             port = mkOption {
               type = types.int;
               default = 9000;
-              description = ''
+              description = lib.mdDoc ''
                 Minio listen port.
               '';
             };
             secure = mkOption {
               type = types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 Whether to use HTTPS for Minio.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the minio third-party integration.";
+        description = lib.mdDoc "Configure the minio third-party integration.";
       };
       s3 = mkOption {
         type = types.nullOr (types.submodule {
           options = {
             accessKeyId = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 AWS access key id.
               '';
             };
             secretAccessKey = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 AWS access key.
               '';
             };
             region = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 AWS S3 region.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the s3 third-party integration.";
+        description = lib.mdDoc "Configure the s3 third-party integration.";
       };
       s3bucket = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
-          Specify the bucket name for upload types <literal>s3</literal> and <literal>minio</literal>.
+        description = lib.mdDoc ''
+          Specify the bucket name for upload types `s3` and `minio`.
         '';
       };
       allowPDFExport = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable PDF exports.
         '';
       };
       imgur.clientId = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Imgur API client ID.
         '';
       };
@@ -508,13 +519,13 @@ in
           options = {
             connectionString = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Azure Blob Storage connection string.
               '';
             };
             container = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Azure Blob Storage container name.
                 It will be created if non-existent.
               '';
@@ -522,162 +533,162 @@ in
           };
         });
         default = null;
-        description = "Configure the azure third-party integration.";
+        description = lib.mdDoc "Configure the azure third-party integration.";
       };
       oauth2 = mkOption {
         type = types.nullOr (types.submodule {
           options = {
             authorizationURL = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the OAuth authorization URL.
               '';
             };
             tokenURL = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the OAuth token URL.
               '';
             };
             baseURL = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the OAuth base URL.
               '';
             };
             userProfileURL = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the OAuth userprofile URL.
               '';
             };
             userProfileUsernameAttr = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the name of the attribute for the username from the claim.
               '';
             };
             userProfileDisplayNameAttr = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the name of the attribute for the display name from the claim.
               '';
             };
             userProfileEmailAttr = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the name of the attribute for the email from the claim.
               '';
             };
             scope = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the OAuth scope.
               '';
             };
             providerName = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the name to be displayed for this strategy.
               '';
             };
             rolesClaim = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the role claim name.
               '';
             };
             accessRole = mkOption {
               type = with types; nullOr str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 Specify role which should be included in the ID token roles claim to grant access
               '';
             };
             clientID = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the OAuth client ID.
               '';
             };
             clientSecret = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Specify the OAuth client secret.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the OAuth integration.";
+        description = lib.mdDoc "Configure the OAuth integration.";
       };
       facebook = mkOption {
         type = types.nullOr (types.submodule {
           options = {
             clientID = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Facebook API client ID.
               '';
             };
             clientSecret = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Facebook API client secret.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the facebook third-party integration";
+        description = lib.mdDoc "Configure the facebook third-party integration";
       };
       twitter = mkOption {
         type = types.nullOr (types.submodule {
           options = {
             consumerKey = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Twitter API consumer key.
               '';
             };
             consumerSecret = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Twitter API consumer secret.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the Twitter third-party integration.";
+        description = lib.mdDoc "Configure the Twitter third-party integration.";
       };
       github = mkOption {
         type = types.nullOr (types.submodule {
           options = {
             clientID = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 GitHub API client ID.
               '';
             };
             clientSecret = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Github API client secret.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the GitHub third-party integration.";
+        description = lib.mdDoc "Configure the GitHub third-party integration.";
       };
       gitlab = mkOption {
         type = types.nullOr (types.submodule {
@@ -685,27 +696,27 @@ in
             baseURL = mkOption {
               type = types.str;
               default = "";
-              description = ''
+              description = lib.mdDoc ''
                 GitLab API authentication endpoint.
                 Only needed for other endpoints than gitlab.com.
               '';
             };
             clientID = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 GitLab API client ID.
               '';
             };
             clientSecret = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 GitLab API client secret.
               '';
             };
             scope = mkOption {
               type = types.enum [ "api" "read_user" ];
               default = "api";
-              description = ''
+              description = lib.mdDoc ''
                 GitLab API requested scope.
                 GitLab snippet import/export requires api scope.
               '';
@@ -713,79 +724,79 @@ in
           };
         });
         default = null;
-        description = "Configure the GitLab third-party integration.";
+        description = lib.mdDoc "Configure the GitLab third-party integration.";
       };
       mattermost = mkOption {
         type = types.nullOr (types.submodule {
           options = {
             baseURL = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Mattermost authentication endpoint.
               '';
             };
             clientID = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Mattermost API client ID.
               '';
             };
             clientSecret = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Mattermost API client secret.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the Mattermost third-party integration.";
+        description = lib.mdDoc "Configure the Mattermost third-party integration.";
       };
       dropbox = mkOption {
         type = types.nullOr (types.submodule {
           options = {
             clientID = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Dropbox API client ID.
               '';
             };
             clientSecret = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Dropbox API client secret.
               '';
             };
             appKey = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Dropbox app key.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the Dropbox third-party integration.";
+        description = lib.mdDoc "Configure the Dropbox third-party integration.";
       };
       google = mkOption {
         type = types.nullOr (types.submodule {
           options = {
             clientID = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Google API client ID.
               '';
             };
             clientSecret = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Google API client secret.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the Google third-party integration.";
+        description = lib.mdDoc "Configure the Google third-party integration.";
       };
       ldap = mkOption {
         type = types.nullOr (types.submodule {
@@ -793,76 +804,78 @@ in
             providerName = mkOption {
               type = types.str;
               default = "";
-              description = ''
+              description = lib.mdDoc ''
                 Optional name to be displayed at login form, indicating the LDAP provider.
               '';
             };
             url = mkOption {
               type = types.str;
               example = "ldap://localhost";
-              description = ''
+              description = lib.mdDoc ''
                 URL of LDAP server.
               '';
             };
             bindDn = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Bind DN for LDAP access.
               '';
             };
             bindCredentials = mkOption {
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Bind credentials for LDAP access.
               '';
             };
             searchBase = mkOption {
               type = types.str;
               example = "o=users,dc=example,dc=com";
-              description = ''
+              description = lib.mdDoc ''
                 LDAP directory to begin search from.
               '';
             };
             searchFilter = mkOption {
               type = types.str;
               example = "(uid={{username}})";
-              description = ''
+              description = lib.mdDoc ''
                 LDAP filter to search with.
               '';
             };
             searchAttributes = mkOption {
-              type = types.listOf types.str;
+              type = types.nullOr (types.listOf types.str);
+              default = null;
               example = [ "displayName" "mail" ];
-              description = ''
+              description = lib.mdDoc ''
                 LDAP attributes to search with.
               '';
             };
             userNameField = mkOption {
               type = types.str;
               default = "";
-              description = ''
+              description = lib.mdDoc ''
                 LDAP field which is used as the username on HedgeDoc.
-                By default <option>useridField</option> is used.
+                By default {option}`useridField` is used.
               '';
             };
             useridField = mkOption {
               type = types.str;
               example = "uid";
-              description = ''
+              description = lib.mdDoc ''
                 LDAP field which is a unique identifier for users on HedgeDoc.
               '';
             };
             tlsca = mkOption {
               type = types.str;
+              default = "/etc/ssl/certs/ca-certificates.crt";
               example = "server-cert.pem,root.pem";
-              description = ''
+              description = lib.mdDoc ''
                 Root CA for LDAP TLS in PEM format.
               '';
             };
           };
         });
         default = null;
-        description = "Configure the LDAP integration.";
+        description = lib.mdDoc "Configure the LDAP integration.";
       };
       saml = mkOption {
         type = types.nullOr (types.submodule {
@@ -870,21 +883,21 @@ in
             idpSsoUrl = mkOption {
               type = types.str;
               example = "https://idp.example.com/sso";
-              description = ''
+              description = lib.mdDoc ''
                 IdP authentication endpoint.
               '';
             };
             idpCert = mkOption {
               type = types.path;
               example = "/path/to/cert.pem";
-              description = ''
+              description = lib.mdDoc ''
                 Path to IdP certificate file in PEM format.
               '';
             };
             issuer = mkOption {
               type = types.str;
               default = "";
-              description = ''
+              description = lib.mdDoc ''
                 Optional identity of the service provider.
                 This defaults to the server URL.
               '';
@@ -892,7 +905,7 @@ in
             identifierFormat = mkOption {
               type = types.str;
               default = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
-              description = ''
+              description = lib.mdDoc ''
                 Optional name identifier format.
               '';
             };
@@ -900,7 +913,7 @@ in
               type = types.str;
               default = "";
               example = "memberOf";
-              description = ''
+              description = lib.mdDoc ''
                 Optional attribute name for group list.
               '';
             };
@@ -908,7 +921,7 @@ in
               type = types.listOf types.str;
               default = [];
               example = [ "Temporary-staff" "External-users" ];
-              description = ''
+              description = lib.mdDoc ''
                 Excluded group names.
               '';
             };
@@ -916,15 +929,23 @@ in
               type = types.listOf types.str;
               default = [];
               example = [ "Hedgedoc-Users" ];
-              description = ''
+              description = lib.mdDoc ''
                 Required group names.
               '';
             };
+            providerName = mkOption {
+              type = types.str;
+              default = "";
+              example = "My institution";
+              description = lib.mdDoc ''
+                Optional name to be displayed at login form indicating the SAML provider.
+              '';
+            };
             attribute = {
               id = mkOption {
                 type = types.str;
                 default = "";
-                description = ''
+                description = lib.mdDoc ''
                   Attribute map for `id'.
                   Defaults to `NameID' of SAML response.
                 '';
@@ -932,7 +953,7 @@ in
               username = mkOption {
                 type = types.str;
                 default = "";
-                description = ''
+                description = lib.mdDoc ''
                   Attribute map for `username'.
                   Defaults to `NameID' of SAML response.
                 '';
@@ -940,10 +961,10 @@ in
               email = mkOption {
                 type = types.str;
                 default = "";
-                description = ''
-                  Attribute map for `email'.
-                  Defaults to `NameID' of SAML response if
-                  <option>identifierFormat</option> has
+                description = lib.mdDoc ''
+                  Attribute map for `email`.
+                  Defaults to `NameID` of SAML response if
+                  {option}`identifierFormat` has
                   the default value.
                 '';
               };
@@ -951,37 +972,45 @@ in
           };
         });
         default = null;
-        description = "Configure the SAML integration.";
+        description = lib.mdDoc "Configure the SAML integration.";
+      };
+    }; in lib.mkOption {
+      type = lib.types.submodule {
+        freeformType = settingsFormat.type;
+        inherit options;
       };
+      description = lib.mdDoc ''
+        HedgeDoc configuration, see
+        <https://docs.hedgedoc.org/configuration/>
+        for documentation.
+      '';
     };
 
     environmentFile = mkOption {
       type = with types; nullOr path;
       default = null;
       example = "/var/lib/hedgedoc/hedgedoc.env";
-      description = ''
-        Environment file as defined in <citerefentry>
-        <refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum>
-        </citerefentry>.
+      description = lib.mdDoc ''
+        Environment file as defined in {manpage}`systemd.exec(5)`.
 
         Secrets may be passed to the service without adding them to the world-readable
         Nix store, by specifying placeholder variables as the option value in Nix and
         setting these variables accordingly in the environment file.
 
-        <programlisting>
+        ```
           # snippet of HedgeDoc-related config
-          services.hedgedoc.configuration.dbURL = "postgres://hedgedoc:\''${DB_PASSWORD}@db-host:5432/hedgedocdb";
-          services.hedgedoc.configuration.minio.secretKey = "$MINIO_SECRET_KEY";
-        </programlisting>
+          services.hedgedoc.settings.dbURL = "postgres://hedgedoc:\''${DB_PASSWORD}@db-host:5432/hedgedocdb";
+          services.hedgedoc.settings.minio.secretKey = "$MINIO_SECRET_KEY";
+        ```
 
-        <programlisting>
+        ```
           # content of the environment file
           DB_PASSWORD=verysecretdbpassword
           MINIO_SECRET_KEY=verysecretminiokey
-        </programlisting>
+        ```
 
         Note that this file needs to be available on the host on which
-        <literal>HedgeDoc</literal> is running.
+        `HedgeDoc` is running.
       '';
     };
 
@@ -989,16 +1018,17 @@ in
       type = types.package;
       default = pkgs.hedgedoc;
       defaultText = literalExpression "pkgs.hedgedoc";
-      description = ''
+      description = lib.mdDoc ''
         Package that provides HedgeDoc.
       '';
     };
+
   };
 
   config = mkIf cfg.enable {
     assertions = [
-      { assertion = cfg.configuration.db == {} -> (
-          cfg.configuration.dbURL != "" && cfg.configuration.dbURL != null
+      { assertion = cfg.settings.db == {} -> (
+          cfg.settings.dbURL != "" && cfg.settings.dbURL != null
         );
         message = "Database configuration for HedgeDoc missing."; }
     ];
@@ -1019,10 +1049,12 @@ in
       preStart = ''
         ${pkgs.envsubst}/bin/envsubst \
           -o ${cfg.workDir}/config.json \
-          -i ${prettyJSON cfg.configuration}
+          -i ${prettyJSON cfg.settings}
+        mkdir -p ${cfg.settings.uploadsPath}
       '';
       serviceConfig = {
         WorkingDirectory = cfg.workDir;
+        StateDirectory = [ cfg.workDir cfg.settings.uploadsPath ];
         ExecStart = "${cfg.package}/bin/hedgedoc";
         EnvironmentFile = mkIf (cfg.environmentFile != null) [ cfg.environmentFile ];
         Environment = [
diff --git a/nixos/modules/services/web-apps/hledger-web.nix b/nixos/modules/services/web-apps/hledger-web.nix
index 4f6a34e6d2f..86716a02649 100644
--- a/nixos/modules/services/web-apps/hledger-web.nix
+++ b/nixos/modules/services/web-apps/hledger-web.nix
@@ -5,14 +5,14 @@ let
 in {
   options.services.hledger-web = {
 
-    enable = mkEnableOption "hledger-web service";
+    enable = mkEnableOption (lib.mdDoc "hledger-web service");
 
-    serveApi = mkEnableOption "Serve only the JSON web API, without the web UI.";
+    serveApi = mkEnableOption (lib.mdDoc "Serve only the JSON web API, without the web UI.");
 
     host = mkOption {
       type = types.str;
       default = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         Address to listen on.
       '';
     };
@@ -21,7 +21,7 @@ in {
       type = types.port;
       default = 5000;
       example = 80;
-      description = ''
+      description = lib.mdDoc ''
         Port to listen on.
       '';
     };
@@ -30,21 +30,21 @@ in {
       view = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Enable the view capability.
         '';
       };
       add = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the add capability.
         '';
       };
       manage = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable the manage capability.
         '';
       };
@@ -53,7 +53,7 @@ in {
     stateDir = mkOption {
       type = types.path;
       default = "/var/lib/hledger-web";
-      description = ''
+      description = lib.mdDoc ''
         Path the service has access to. If left as the default value this
         directory will automatically be created before the hledger-web server
         starts, otherwise the sysadmin is responsible for ensuring the
@@ -64,8 +64,8 @@ in {
     journalFiles = mkOption {
       type = types.listOf types.str;
       default = [ ".hledger.journal" ];
-      description = ''
-        Paths to journal files relative to <option>services.hledger-web.stateDir</option>.
+      description = lib.mdDoc ''
+        Paths to journal files relative to {option}`services.hledger-web.stateDir`.
       '';
     };
 
@@ -73,7 +73,7 @@ in {
       type = with types; nullOr str;
       default = null;
       example = "https://example.org";
-      description = ''
+      description = lib.mdDoc ''
         Base URL, when sharing over a network.
       '';
     };
@@ -82,7 +82,7 @@ in {
       type = types.listOf types.str;
       default = [];
       example = [ "--forecast" ];
-      description = ''
+      description = lib.mdDoc ''
         Extra command line arguments to pass to hledger-web.
       '';
     };
diff --git a/nixos/modules/services/web-apps/icingaweb2/icingaweb2.nix b/nixos/modules/services/web-apps/icingaweb2/icingaweb2.nix
index b9761061aaa..67d235ab447 100644
--- a/nixos/modules/services/web-apps/icingaweb2/icingaweb2.nix
+++ b/nixos/modules/services/web-apps/icingaweb2/icingaweb2.nix
@@ -12,12 +12,12 @@ in {
   meta.maintainers = with maintainers; [ das_j ];
 
   options.services.icingaweb2 = with types; {
-    enable = mkEnableOption "the icingaweb2 web interface";
+    enable = mkEnableOption (lib.mdDoc "the icingaweb2 web interface");
 
     pool = mkOption {
       type = str;
       default = poolName;
-      description = ''
+      description = lib.mdDoc ''
          Name of existing PHP-FPM pool that is used to run Icingaweb2.
          If not specified, a pool will automatically created with default values.
       '';
@@ -26,7 +26,7 @@ in {
     libraryPaths = mkOption {
       type = attrsOf package;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Libraries to add to the Icingaweb2 library path.
         The name of the attribute is the name of the library, the value
         is the package to add.
@@ -36,7 +36,7 @@ in {
     virtualHost = mkOption {
       type = nullOr str;
       default = "icingaweb2";
-      description = ''
+      description = lib.mdDoc ''
         Name of the nginx virtualhost to use and setup. If null, no virtualhost is set up.
       '';
     };
@@ -45,15 +45,15 @@ in {
       type = str;
       default = "UTC";
       example = "Europe/Berlin";
-      description = "PHP-compliant timezone specification";
+      description = lib.mdDoc "PHP-compliant timezone specification";
     };
 
     modules = {
-      doc.enable = mkEnableOption "the icingaweb2 doc module";
-      migrate.enable = mkEnableOption "the icingaweb2 migrate module";
-      setup.enable = mkEnableOption "the icingaweb2 setup module";
-      test.enable = mkEnableOption "the icingaweb2 test module";
-      translation.enable = mkEnableOption "the icingaweb2 translation module";
+      doc.enable = mkEnableOption (lib.mdDoc "the icingaweb2 doc module");
+      migrate.enable = mkEnableOption (lib.mdDoc "the icingaweb2 migrate module");
+      setup.enable = mkEnableOption (lib.mdDoc "the icingaweb2 setup module");
+      test.enable = mkEnableOption (lib.mdDoc "the icingaweb2 test module");
+      translation.enable = mkEnableOption (lib.mdDoc "the icingaweb2 translation module");
     };
 
     modulePackages = mkOption {
@@ -64,7 +64,7 @@ in {
           "snow" = icingaweb2Modules.theme-snow;
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Name-package attrset of Icingaweb 2 modules packages to enable.
 
         If you enable modules manually (e.g. via the web ui), they will not be touched.
@@ -84,7 +84,7 @@ in {
           level = "CRITICAL";
         };
       };
-      description = ''
+      description = lib.mdDoc ''
         config.ini contents.
         Will automatically be converted to a .ini file.
         If you don't set global.module_path, the module will take care of it.
@@ -108,7 +108,7 @@ in {
           dbname = "icingaweb2";
         };
       };
-      description = ''
+      description = lib.mdDoc ''
         resources.ini contents.
         Will automatically be converted to a .ini file.
 
@@ -127,7 +127,7 @@ in {
           resource = "icingaweb_db";
         };
       };
-      description = ''
+      description = lib.mdDoc ''
         authentication.ini contents.
         Will automatically be converted to a .ini file.
 
@@ -145,7 +145,7 @@ in {
           resource = "icingaweb_db";
         };
       };
-      description = ''
+      description = lib.mdDoc ''
         groups.ini contents.
         Will automatically be converted to a .ini file.
 
@@ -163,7 +163,7 @@ in {
           permissions = "*";
         };
       };
-      description = ''
+      description = lib.mdDoc ''
         roles.ini contents.
         Will automatically be converted to a .ini file.
 
diff --git a/nixos/modules/services/web-apps/icingaweb2/module-monitoring.nix b/nixos/modules/services/web-apps/icingaweb2/module-monitoring.nix
index e9c1d4ffe5e..9a848870e9d 100644
--- a/nixos/modules/services/web-apps/icingaweb2/module-monitoring.nix
+++ b/nixos/modules/services/web-apps/icingaweb2/module-monitoring.nix
@@ -34,50 +34,50 @@ in {
     enable = mkOption {
       type = bool;
       default = true;
-      description = "Whether to enable the icingaweb2 monitoring module.";
+      description = lib.mdDoc "Whether to enable the icingaweb2 monitoring module.";
     };
 
     generalConfig = {
       mutable = mkOption {
         type = bool;
         default = false;
-        description = "Make config.ini of the monitoring module mutable (e.g. via the web interface).";
+        description = lib.mdDoc "Make config.ini of the monitoring module mutable (e.g. via the web interface).";
       };
 
       protectedVars = mkOption {
         type = listOf str;
         default = [ "*pw*" "*pass*" "community" ];
-        description = "List of string patterns for custom variables which should be excluded from user’s view.";
+        description = lib.mdDoc "List of string patterns for custom variables which should be excluded from user’s view.";
       };
     };
 
     mutableBackends = mkOption {
       type = bool;
       default = false;
-      description = "Make backends.ini of the monitoring module mutable (e.g. via the web interface).";
+      description = lib.mdDoc "Make backends.ini of the monitoring module mutable (e.g. via the web interface).";
     };
 
     backends = mkOption {
       default = { icinga = { resource = "icinga_ido"; }; };
-      description = "Monitoring backends to define";
+      description = lib.mdDoc "Monitoring backends to define";
       type = attrsOf (submodule ({ name, ... }: {
         options = {
           name = mkOption {
             visible = false;
             default = name;
             type = str;
-            description = "Name of this backend";
+            description = lib.mdDoc "Name of this backend";
           };
 
           resource = mkOption {
             type = str;
-            description = "Name of the IDO resource";
+            description = lib.mdDoc "Name of the IDO resource";
           };
 
           disabled = mkOption {
             type = bool;
             default = false;
-            description = "Disable this backend";
+            description = lib.mdDoc "Disable this backend";
           };
         };
       }));
@@ -86,62 +86,62 @@ in {
     mutableTransports = mkOption {
       type = bool;
       default = true;
-      description = "Make commandtransports.ini of the monitoring module mutable (e.g. via the web interface).";
+      description = lib.mdDoc "Make commandtransports.ini of the monitoring module mutable (e.g. via the web interface).";
     };
 
     transports = mkOption {
       default = {};
-      description = "Command transports to define";
+      description = lib.mdDoc "Command transports to define";
       type = attrsOf (submodule ({ name, ... }: {
         options = {
           name = mkOption {
             visible = false;
             default = name;
             type = str;
-            description = "Name of this transport";
+            description = lib.mdDoc "Name of this transport";
           };
 
           type = mkOption {
             type = enum [ "api" "local" "remote" ];
             default = "api";
-            description = "Type of  this transport";
+            description = lib.mdDoc "Type of  this transport";
           };
 
           instance = mkOption {
             type = nullOr str;
             default = null;
-            description = "Assign a icinga instance to this transport";
+            description = lib.mdDoc "Assign a icinga instance to this transport";
           };
 
           path = mkOption {
             type = str;
-            description = "Path to the socket for local or remote transports";
+            description = lib.mdDoc "Path to the socket for local or remote transports";
           };
 
           host = mkOption {
             type = str;
-            description = "Host for the api or remote transport";
+            description = lib.mdDoc "Host for the api or remote transport";
           };
 
           port = mkOption {
             type = nullOr str;
             default = null;
-            description = "Port to connect to for the api or remote transport";
+            description = lib.mdDoc "Port to connect to for the api or remote transport";
           };
 
           username = mkOption {
             type = str;
-            description = "Username for the api or remote transport";
+            description = lib.mdDoc "Username for the api or remote transport";
           };
 
           password = mkOption {
             type = str;
-            description = "Password for the api transport";
+            description = lib.mdDoc "Password for the api transport";
           };
 
           resource = mkOption {
             type = str;
-            description = "SSH identity resource for the remote transport";
+            description = lib.mdDoc "SSH identity resource for the remote transport";
           };
         };
       }));
diff --git a/nixos/modules/services/web-apps/ihatemoney/default.nix b/nixos/modules/services/web-apps/ihatemoney/default.nix
index ad314c885ba..b0da0acfcf8 100644
--- a/nixos/modules/services/web-apps/ihatemoney/default.nix
+++ b/nixos/modules/services/web-apps/ihatemoney/default.nix
@@ -47,60 +47,60 @@ let
 in
   {
     options.services.ihatemoney = {
-      enable = mkEnableOption "ihatemoney webapp. Note that this will set uwsgi to emperor mode";
+      enable = mkEnableOption (lib.mdDoc "ihatemoney webapp. Note that this will set uwsgi to emperor mode");
       backend = mkOption {
         type = types.enum [ "sqlite" "postgresql" ];
         default = "sqlite";
-        description = ''
+        description = lib.mdDoc ''
           The database engine to use for ihatemoney.
-          If <literal>postgresql</literal> is selected, then a database called
-          <literal>${db}</literal> will be created. If you disable this option,
+          If `postgresql` is selected, then a database called
+          `${db}` will be created. If you disable this option,
           it will however not be removed.
         '';
       };
       adminHashedPassword = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "The hashed password of the administrator. To obtain it, run <literal>ihatemoney generate_password_hash</literal>";
+        description = lib.mdDoc "The hashed password of the administrator. To obtain it, run `ihatemoney generate_password_hash`";
       };
       uwsgiConfig = mkOption {
         type = types.attrs;
         example = {
           http = ":8000";
         };
-        description = "Additionnal configuration of the UWSGI vassal running ihatemoney. It should notably specify on which interfaces and ports the vassal should listen.";
+        description = lib.mdDoc "Additionnal configuration of the UWSGI vassal running ihatemoney. It should notably specify on which interfaces and ports the vassal should listen.";
       };
       defaultSender = {
         name = mkOption {
           type = types.str;
           default = "Budget manager";
-          description = "The display name of the sender of ihatemoney emails";
+          description = lib.mdDoc "The display name of the sender of ihatemoney emails";
         };
         email = mkOption {
           type = types.str;
           default = "ihatemoney@${config.networking.hostName}";
           defaultText = literalExpression ''"ihatemoney@''${config.networking.hostName}"'';
-          description = "The email of the sender of ihatemoney emails";
+          description = lib.mdDoc "The email of the sender of ihatemoney emails";
         };
       };
       secureCookie = mkOption {
         type = types.bool;
         default = true;
-        description = "Use secure cookies. Disable this when ihatemoney is served via http instead of https";
+        description = lib.mdDoc "Use secure cookies. Disable this when ihatemoney is served via http instead of https";
       };
-      enableDemoProject = mkEnableOption "access to the demo project in ihatemoney";
-      enablePublicProjectCreation = mkEnableOption "permission to create projects in ihatemoney by anyone";
-      enableAdminDashboard = mkEnableOption "ihatemoney admin dashboard";
-      enableCaptcha = mkEnableOption "a simplistic captcha for some forms";
+      enableDemoProject = mkEnableOption (lib.mdDoc "access to the demo project in ihatemoney");
+      enablePublicProjectCreation = mkEnableOption (lib.mdDoc "permission to create projects in ihatemoney by anyone");
+      enableAdminDashboard = mkEnableOption (lib.mdDoc "ihatemoney admin dashboard");
+      enableCaptcha = mkEnableOption (lib.mdDoc "a simplistic captcha for some forms");
       legalLink = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "The URL to a page explaining legal statements about your service, eg. GDPR-related information.";
+        description = lib.mdDoc "The URL to a page explaining legal statements about your service, eg. GDPR-related information.";
       };
       extraConfig = mkOption {
         type = types.str;
         default = "";
-        description = "Extra configuration appended to ihatemoney's configuration file. It is a python file, so pay attention to indentation.";
+        description = lib.mdDoc "Extra configuration appended to ihatemoney's configuration file. It is a python file, so pay attention to indentation.";
       };
     };
     config = mkIf cfg.enable {
diff --git a/nixos/modules/services/web-apps/invidious.nix b/nixos/modules/services/web-apps/invidious.nix
index 10b30bf1fd1..e106478628f 100644
--- a/nixos/modules/services/web-apps/invidious.nix
+++ b/nixos/modules/services/web-apps/invidious.nix
@@ -146,33 +146,33 @@ let
 in
 {
   options.services.invidious = {
-    enable = lib.mkEnableOption "Invidious";
+    enable = lib.mkEnableOption (lib.mdDoc "Invidious");
 
     package = lib.mkOption {
       type = types.package;
       default = pkgs.invidious;
       defaultText = "pkgs.invidious";
-      description = "The Invidious package to use.";
+      description = lib.mdDoc "The Invidious package to use.";
     };
 
     settings = lib.mkOption {
       type = settingsFormat.type;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         The settings Invidious should use.
 
-        See <link xlink:href="https://github.com/iv-org/invidious/blob/master/config/config.example.yml">config.example.yml</link> for a list of all possible options.
+        See [config.example.yml](https://github.com/iv-org/invidious/blob/master/config/config.example.yml) for a list of all possible options.
       '';
     };
 
     extraSettingsFile = lib.mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         A file including Invidious settings.
 
-        It gets merged with the setttings specified in <option>services.invidious.settings</option>
-        and can be used to store secrets like <literal>hmac_key</literal> outside of the nix store.
+        It gets merged with the setttings specified in {option}`services.invidious.settings`
+        and can be used to store secrets like `hmac_key` outside of the nix store.
       '';
     };
 
@@ -182,7 +182,7 @@ in
     domain = lib.mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         The FQDN Invidious is reachable on.
 
         This is used to configure nginx and for building absolute URLs.
@@ -193,12 +193,12 @@ in
       type = types.port;
       # Default from https://docs.invidious.io/Configuration.md
       default = 3000;
-      description = ''
+      description = lib.mdDoc ''
         The port Invidious should listen on.
 
         To allow access from outside,
-        you can use either <option>services.invidious.nginx</option>
-        or add <literal>config.services.invidious.port</literal> to <option>networking.firewall.allowedTCPPorts</option>.
+        you can use either {option}`services.invidious.nginx`
+        or add `config.services.invidious.port` to {option}`networking.firewall.allowedTCPPorts`.
       '';
     };
 
@@ -206,7 +206,7 @@ in
       createLocally = lib.mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to create a local database with PostgreSQL.
         '';
       };
@@ -214,10 +214,10 @@ in
       host = lib.mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The database host Invidious should use.
 
-          If <literal>null</literal>, the local unix socket is used. Otherwise
+          If `null`, the local unix socket is used. Otherwise
           TCP is used.
         '';
       };
@@ -226,7 +226,7 @@ in
         type = types.port;
         default = options.services.postgresql.port.default;
         defaultText = lib.literalExpression "options.services.postgresql.port.default";
-        description = ''
+        description = lib.mdDoc ''
           The port of the database Invidious should use.
 
           Defaults to the the default postgresql port.
@@ -237,7 +237,7 @@ in
         type = types.nullOr types.str;
         apply = lib.mapNullable toString;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to file containing the database password.
         '';
       };
@@ -246,11 +246,11 @@ in
     nginx.enable = lib.mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to configure nginx as a reverse proxy for Invidious.
 
-        It serves it under the domain specified in <option>services.invidious.settings.domain</option> with enabled TLS and ACME.
-        Further configuration can be done through <option>services.nginx.virtualHosts.''${config.services.invidious.settings.domain}.*</option>,
+        It serves it under the domain specified in {option}`services.invidious.settings.domain` with enabled TLS and ACME.
+        Further configuration can be done through {option}`services.nginx.virtualHosts.''${config.services.invidious.settings.domain}.*`,
         which can also be used to disable AMCE and TLS.
       '';
     };
diff --git a/nixos/modules/services/web-apps/invoiceplane.nix b/nixos/modules/services/web-apps/invoiceplane.nix
index 095eec36dec..99e7b1f96ea 100644
--- a/nixos/modules/services/web-apps/invoiceplane.nix
+++ b/nixos/modules/services/web-apps/invoiceplane.nix
@@ -25,6 +25,7 @@ let
     ENCRYPTION_KEY=
     ENCRYPTION_CIPHER=AES-256
     SETUP_COMPLETED=false
+    REMOVE_INDEXPHP=true
   '';
 
   extraConfig = hostName: cfg: pkgs.writeText "extraConfig.php" ''
@@ -36,10 +37,10 @@ let
     version = src.version;
     src = pkgs.invoiceplane;
 
-    patchPhase = ''
+    postPhase = ''
       # Patch index.php file to load additional config file
       substituteInPlace index.php \
-        --replace "require('vendor/autoload.php');" "require('vendor/autoload.php'); \$dotenv = new \Dotenv\Dotenv(__DIR__, 'extraConfig.php'); \$dotenv->load();";
+        --replace "require('vendor/autoload.php');" "require('vendor/autoload.php'); \$dotenv = Dotenv\Dotenv::createImmutable(__DIR__, 'extraConfig.php'); \$dotenv->load();";
     '';
 
     installPhase = ''
@@ -67,12 +68,12 @@ let
     {
       options = {
 
-        enable = mkEnableOption "InvoicePlane web application";
+        enable = mkEnableOption (lib.mdDoc "InvoicePlane web application");
 
         stateDir = mkOption {
           type = types.path;
           default = "/var/lib/invoiceplane/${name}";
-          description = ''
+          description = lib.mdDoc ''
             This directory is used for uploads of attachements and cache.
             The directory passed here is automatically created and permissions
             adjusted as required.
@@ -83,50 +84,53 @@ let
           host = mkOption {
             type = types.str;
             default = "localhost";
-            description = "Database host address.";
+            description = lib.mdDoc "Database host address.";
           };
 
           port = mkOption {
             type = types.port;
             default = 3306;
-            description = "Database host port.";
+            description = lib.mdDoc "Database host port.";
           };
 
           name = mkOption {
             type = types.str;
             default = "invoiceplane";
-            description = "Database name.";
+            description = lib.mdDoc "Database name.";
           };
 
           user = mkOption {
             type = types.str;
             default = "invoiceplane";
-            description = "Database user.";
+            description = lib.mdDoc "Database user.";
           };
 
           passwordFile = mkOption {
             type = types.nullOr types.path;
             default = null;
             example = "/run/keys/invoiceplane-dbpassword";
-            description = ''
+            description = lib.mdDoc ''
               A file containing the password corresponding to
-              <option>database.user</option>.
+              {option}`database.user`.
             '';
           };
 
           createLocally = mkOption {
             type = types.bool;
             default = true;
-            description = "Create the database and database user locally.";
+            description = lib.mdDoc "Create the database and database user locally.";
           };
         };
 
         invoiceTemplates = mkOption {
           type = types.listOf types.path;
           default = [];
-          description = ''
+          description = lib.mdDoc ''
             List of path(s) to respective template(s) which are copied from the 'invoice_templates/pdf' directory.
-            <note><para>These templates need to be packaged before use, see example.</para></note>
+
+            ::: {.note}
+            These templates need to be packaged before use, see example.
+            :::
           '';
           example = literalExpression ''
             let
@@ -160,8 +164,8 @@ let
             "pm.max_spare_servers" = 4;
             "pm.max_requests" = 500;
           };
-          description = ''
-            Options for the InvoicePlane PHP pool. See the documentation on <literal>php-fpm.conf</literal>
+          description = lib.mdDoc ''
+            Options for the InvoicePlane PHP pool. See the documentation on `php-fpm.conf`
             for details on configuration directives.
           '';
         };
@@ -174,13 +178,33 @@ let
             DISABLE_SETUP=true
             IP_URL=https://invoice.example.com
           '';
-          description = ''
+          description = lib.mdDoc ''
             InvoicePlane configuration. Refer to
-            <link xlink:href="https://github.com/InvoicePlane/InvoicePlane/blob/master/ipconfig.php.example"/>
+            <https://github.com/InvoicePlane/InvoicePlane/blob/master/ipconfig.php.example>
             for details on supported values.
           '';
         };
 
+        cron = {
+
+          enable = mkOption {
+            type = types.bool;
+            default = false;
+            description = lib.mdDoc ''
+              Enable cron service which periodically runs Invoiceplane tasks.
+              Requires key taken from the administration page. Refer to
+              <https://wiki.invoiceplane.com/en/1.0/modules/recurring-invoices>
+              on how to configure it.
+            '';
+          };
+
+          key = mkOption {
+            type = types.str;
+            description = lib.mdDoc "Cron key taken from the administration page.";
+          };
+
+        };
+
       };
 
     };
@@ -194,20 +218,20 @@ in
         options.sites = mkOption {
           type = types.attrsOf (types.submodule siteOpts);
           default = {};
-          description = "Specification of one or more WordPress sites to serve";
+          description = lib.mdDoc "Specification of one or more WordPress sites to serve";
         };
 
         options.webserver = mkOption {
           type = types.enum [ "caddy" ];
           default = "caddy";
-          description = ''
+          description = lib.mdDoc ''
             Which webserver to use for virtual host management. Currently only
             caddy is supported.
           '';
         };
       };
       default = {};
-      description = "InvoicePlane configuration.";
+      description = lib.mdDoc "InvoicePlane configuration.";
     };
 
   };
@@ -221,8 +245,11 @@ in
       }
       { assertion = cfg.database.createLocally -> cfg.database.passwordFile == null;
         message = ''services.invoiceplane.sites."${hostName}".database.passwordFile cannot be specified if services.invoiceplane.sites."${hostName}".database.createLocally is set to true.'';
-      }]
-    ) eachSite);
+      }
+      { assertion = cfg.cron.enable -> cfg.cron.key != null;
+        message = ''services.invoiceplane.sites."${hostName}".cron.key must be set in order to use cron service.'';
+      }
+    ]) eachSite);
 
     services.mysql = mkIf (any (v: v.database.createLocally) (attrValues eachSite)) {
       enable = true;
@@ -236,7 +263,7 @@ in
     };
 
     services.phpfpm = {
-      phpPackage = pkgs.php74;
+      phpPackage = pkgs.php81;
       pools = mapAttrs' (hostName: cfg: (
         nameValuePair "invoiceplane-${hostName}" {
           inherit user;
@@ -252,6 +279,7 @@ in
   }
 
   {
+
     systemd.tmpfiles.rules = flatten (mapAttrsToList (hostName: cfg: [
       "d ${cfg.stateDir} 0750 ${user} ${webserver.group} - -"
       "f ${cfg.stateDir}/ipconfig.php 0750 ${user} ${webserver.group} - -"
@@ -281,6 +309,34 @@ in
       group = webserver.group;
       isSystemUser = true;
     };
+
+  }
+  {
+
+    # Cron service implementation
+
+    systemd.timers = mapAttrs' (hostName: cfg: (
+      nameValuePair "invoiceplane-cron-${hostName}" (mkIf cfg.cron.enable {
+        wantedBy = [ "timers.target" ];
+        timerConfig = {
+          OnBootSec = "5m";
+          OnUnitActiveSec = "5m";
+          Unit = "invoiceplane-cron-${hostName}.service";
+        };
+      })
+    )) eachSite;
+
+    systemd.services =
+      mapAttrs' (hostName: cfg: (
+        nameValuePair "invoiceplane-cron-${hostName}" (mkIf cfg.cron.enable {
+          serviceConfig = {
+            Type = "oneshot";
+            User = user;
+            ExecStart = "${pkgs.curl}/bin/curl --header 'Host: ${hostName}' http://localhost/invoices/cron/recur/${cfg.cron.key}";
+          };
+        })
+    )) eachSite;
+
   }
 
   (mkIf (cfg.webserver == "caddy") {
@@ -289,9 +345,8 @@ in
       virtualHosts = mapAttrs' (hostName: cfg: (
         nameValuePair "http://${hostName}" {
           extraConfig = ''
-            root    * ${pkg hostName cfg}
+            root * ${pkg hostName cfg}
             file_server
-
             php_fastcgi unix/${config.services.phpfpm.pools."invoiceplane-${hostName}".socket}
           '';
         }
@@ -299,7 +354,5 @@ in
     };
   })
 
-
   ]);
 }
-
diff --git a/nixos/modules/services/web-apps/isso.nix b/nixos/modules/services/web-apps/isso.nix
index 4c01781a6a2..1a852ec352f 100644
--- a/nixos/modules/services/web-apps/isso.nix
+++ b/nixos/modules/services/web-apps/isso.nix
@@ -11,19 +11,19 @@ in {
 
   options = {
     services.isso = {
-      enable = mkEnableOption ''
+      enable = mkEnableOption (lib.mdDoc ''
         A commenting server similar to Disqus.
 
         Note: The application's author suppose to run isso behind a reverse proxy.
         The embedded solution offered by NixOS is also only suitable for small installations
         below 20 requests per second.
-      '';
+      '');
 
       settings = mkOption {
-        description = ''
-          Configuration for <package>isso</package>.
+        description = lib.mdDoc ''
+          Configuration for `isso`.
 
-          See <link xlink:href="https://posativ.org/isso/docs/configuration/server/">Isso Server Configuration</link>
+          See [Isso Server Configuration](https://posativ.org/isso/docs/configuration/server/)
           for supported values.
         '';
 
@@ -63,6 +63,28 @@ in {
 
         Restart = "on-failure";
         RestartSec = 1;
+
+        # Hardening
+        CapabilityBoundingSet = [ "" ];
+        DeviceAllow = [ "" ];
+        LockPersonality = true;
+        PrivateDevices = true;
+        PrivateUsers = true;
+        ProcSubset = "pid";
+        ProtectClock = true;
+        ProtectControlGroups = true;
+        ProtectHome = true;
+        ProtectHostname = true;
+        ProtectKernelLogs = true;
+        ProtectKernelModules = true;
+        ProtectKernelTunables = true;
+        ProtectProc = "invisible";
+        RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
+        RestrictNamespaces = true;
+        RestrictRealtime = true;
+        SystemCallArchitectures = "native";
+        SystemCallFilter = [ "@system-service" "~@privileged" "~@resources" ];
+        UMask = "0077";
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/jirafeau.nix b/nixos/modules/services/web-apps/jirafeau.nix
index 328c61c8e64..293cbb3af42 100644
--- a/nixos/modules/services/web-apps/jirafeau.nix
+++ b/nixos/modules/services/web-apps/jirafeau.nix
@@ -25,7 +25,7 @@ in
     adminPasswordSha256 = mkOption {
       type = types.str;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         SHA-256 of the desired administration password. Leave blank/unset for no password.
       '';
     };
@@ -33,10 +33,10 @@ in
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/jirafeau/data/";
-      description = "Location of Jirafeau storage directory.";
+      description = lib.mdDoc "Location of Jirafeau storage directory.";
     };
 
-    enable = mkEnableOption "Jirafeau file upload application.";
+    enable = mkEnableOption (lib.mdDoc "Jirafeau file upload application.");
 
     extraConfig = mkOption {
       type = types.lines;
@@ -45,12 +45,12 @@ in
         $cfg['style'] = 'courgette';
         $cfg['organisation'] = 'ACME';
       '';
-      description = let
+      description =  let
         documentationLink =
           "https://gitlab.com/mojo42/Jirafeau/-/blob/${cfg.package.version}/lib/config.original.php";
       in
-        ''
-          Jirefeau configuration. Refer to <link xlink:href="${documentationLink}"/> for supported
+        lib.mdDoc ''
+          Jirefeau configuration. Refer to <${documentationLink}> for supported
           values.
         '';
     };
@@ -58,13 +58,13 @@ in
     hostName = mkOption {
       type = types.str;
       default = "localhost";
-      description = "URL of instance. Must have trailing slash.";
+      description = lib.mdDoc "URL of instance. Must have trailing slash.";
     };
 
     maxUploadSizeMegabytes = mkOption {
       type = types.int;
       default = 0;
-      description = "Maximum upload size of accepted files.";
+      description = lib.mdDoc "Maximum upload size of accepted files.";
     };
 
     maxUploadTimeout = mkOption {
@@ -73,10 +73,10 @@ in
       description = let
         nginxCoreDocumentation = "http://nginx.org/en/docs/http/ngx_http_core_module.html";
       in
-        ''
+        lib.mdDoc ''
           Timeout for reading client request bodies and headers. Refer to
-          <link xlink:href="${nginxCoreDocumentation}#client_body_timeout"/> and
-          <link xlink:href="${nginxCoreDocumentation}#client_header_timeout"/> for accepted values.
+          <${nginxCoreDocumentation}#client_body_timeout> and
+          <${nginxCoreDocumentation}#client_header_timeout> for accepted values.
         '';
     };
 
@@ -89,14 +89,14 @@ in
           serverAliases = [ "wiki.''${config.networking.domain}" ];
         }
       '';
-      description = "Extra configuration for the nginx virtual host of Jirafeau.";
+      description = lib.mdDoc "Extra configuration for the nginx virtual host of Jirafeau.";
     };
 
     package = mkOption {
       type = types.package;
       default = pkgs.jirafeau;
       defaultText = literalExpression "pkgs.jirafeau";
-      description = "Jirafeau package to use";
+      description = lib.mdDoc "Jirafeau package to use";
     };
 
     poolConfig = mkOption {
@@ -109,8 +109,8 @@ in
         "pm.max_spare_servers" = 4;
         "pm.max_requests" = 500;
       };
-      description = ''
-        Options for Jirafeau PHP pool. See documentation on <literal>php-fpm.conf</literal> for
+      description = lib.mdDoc ''
+        Options for Jirafeau PHP pool. See documentation on `php-fpm.conf` for
         details on configuration directives.
       '';
     };
diff --git a/nixos/modules/services/web-apps/jitsi-meet.nix b/nixos/modules/services/web-apps/jitsi-meet.nix
index 2f1c4acec1e..a42e249189f 100644
--- a/nixos/modules/services/web-apps/jitsi-meet.nix
+++ b/nixos/modules/services/web-apps/jitsi-meet.nix
@@ -46,12 +46,12 @@ let
 in
 {
   options.services.jitsi-meet = with types; {
-    enable = mkEnableOption "Jitsi Meet - Secure, Simple and Scalable Video Conferences";
+    enable = mkEnableOption (lib.mdDoc "Jitsi Meet - Secure, Simple and Scalable Video Conferences");
 
     hostName = mkOption {
       type = str;
       example = "meet.example.org";
-      description = ''
+      description = lib.mdDoc ''
         FQDN of the Jitsi Meet instance.
       '';
     };
@@ -65,10 +65,10 @@ in
           defaultLang = "fi";
         }
       '';
-      description = ''
-        Client-side web application settings that override the defaults in <filename>config.js</filename>.
+      description = lib.mdDoc ''
+        Client-side web application settings that override the defaults in {file}`config.js`.
 
-        See <link xlink:href="https://github.com/jitsi/jitsi-meet/blob/master/config.js" /> for default
+        See <https://github.com/jitsi/jitsi-meet/blob/master/config.js> for default
         configuration with comments.
       '';
     };
@@ -76,8 +76,8 @@ in
     extraConfig = mkOption {
       type = lines;
       default = "";
-      description = ''
-        Text to append to <filename>config.js</filename> web application config file.
+      description = lib.mdDoc ''
+        Text to append to {file}`config.js` web application config file.
 
         Can be used to insert JavaScript logic to determine user's region in cascading bridges setup.
       '';
@@ -92,10 +92,10 @@ in
           SHOW_WATERMARK_FOR_GUESTS = false;
         }
       '';
-      description = ''
-        Client-side web-app interface settings that override the defaults in <filename>interface_config.js</filename>.
+      description = lib.mdDoc ''
+        Client-side web-app interface settings that override the defaults in {file}`interface_config.js`.
 
-        See <link xlink:href="https://github.com/jitsi/jitsi-meet/blob/master/interface_config.js" /> for
+        See <https://github.com/jitsi/jitsi-meet/blob/master/interface_config.js> for
         default configuration with comments.
       '';
     };
@@ -104,10 +104,10 @@ in
       enable = mkOption {
         type = bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable Jitsi Videobridge instance and configure it to connect to Prosody.
 
-          Additional configuration is possible with <option>services.jitsi-videobridge</option>.
+          Additional configuration is possible with {option}`services.jitsi-videobridge`.
         '';
       };
 
@@ -115,10 +115,10 @@ in
         type = nullOr str;
         default = null;
         example = "/run/keys/videobridge";
-        description = ''
+        description = lib.mdDoc ''
           File containing password to the Prosody account for videobridge.
 
-          If <literal>null</literal>, a file with password will be generated automatically. Setting
+          If `null`, a file with password will be generated automatically. Setting
           this option is useful if you plan to connect additional videobridges to the XMPP server.
         '';
       };
@@ -127,44 +127,44 @@ in
     jicofo.enable = mkOption {
       type = bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable JiCoFo instance and configure it to connect to Prosody.
 
-        Additional configuration is possible with <option>services.jicofo</option>.
+        Additional configuration is possible with {option}`services.jicofo`.
       '';
     };
 
     jibri.enable = mkOption {
       type = bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable a Jibri instance and configure it to connect to Prosody.
 
-        Additional configuration is possible with <option>services.jibri</option>, and
-        <option>services.jibri.finalizeScript</option> is especially useful.
+        Additional configuration is possible with {option}`services.jibri`, and
+        {option}`services.jibri.finalizeScript` is especially useful.
       '';
     };
 
     nginx.enable = mkOption {
       type = bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable nginx virtual host that will serve the javascript application and act as
         a proxy for the XMPP server. Further nginx configuration can be done by adapting
-        <option>services.nginx.virtualHosts.&lt;hostName&gt;</option>.
+        {option}`services.nginx.virtualHosts.<hostName>`.
         When this is enabled, ACME will be used to retrieve a TLS certificate by default. To disable
-        this, set the <option>services.nginx.virtualHosts.&lt;hostName&gt;.enableACME</option> to
-        <literal>false</literal> and if appropriate do the same for
-        <option>services.nginx.virtualHosts.&lt;hostName&gt;.forceSSL</option>.
+        this, set the {option}`services.nginx.virtualHosts.<hostName>.enableACME` to
+        `false` and if appropriate do the same for
+        {option}`services.nginx.virtualHosts.<hostName>.forceSSL`.
       '';
     };
 
-    caddy.enable = mkEnableOption "Whether to enablle caddy reverse proxy to expose jitsi-meet";
+    caddy.enable = mkEnableOption (lib.mdDoc "Whether to enable caddy reverse proxy to expose jitsi-meet");
 
     prosody.enable = mkOption {
       type = bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to configure Prosody to relay XMPP messages between Jitsi Meet components. Turn this
         off if you want to configure it manually.
       '';
@@ -253,9 +253,21 @@ in
         '';
       };
     };
-    systemd.services.prosody.serviceConfig = mkIf cfg.prosody.enable {
-      EnvironmentFile = [ "/var/lib/jitsi-meet/secrets-env" ];
-      SupplementaryGroups = [ "jitsi-meet" ];
+    systemd.services.prosody = mkIf cfg.prosody.enable {
+      preStart = let
+        videobridgeSecret = if cfg.videobridge.passwordFile != null then cfg.videobridge.passwordFile else "/var/lib/jitsi-meet/videobridge-secret";
+      in ''
+        ${config.services.prosody.package}/bin/prosodyctl register focus auth.${cfg.hostName} "$(cat /var/lib/jitsi-meet/jicofo-user-secret)"
+        ${config.services.prosody.package}/bin/prosodyctl register jvb auth.${cfg.hostName} "$(cat ${videobridgeSecret})"
+        ${config.services.prosody.package}/bin/prosodyctl mod_roster_command subscribe focus.${cfg.hostName} focus@auth.${cfg.hostName}
+        ${config.services.prosody.package}/bin/prosodyctl register jibri auth.${cfg.hostName} "$(cat /var/lib/jitsi-meet/jibri-auth-secret)"
+        ${config.services.prosody.package}/bin/prosodyctl register recorder recorder.${cfg.hostName} "$(cat /var/lib/jitsi-meet/jibri-recorder-secret)"
+      '';
+      serviceConfig = {
+        EnvironmentFile = [ "/var/lib/jitsi-meet/secrets-env" ];
+        SupplementaryGroups = [ "jitsi-meet" ];
+      };
+      reloadIfChanged = true;
     };
 
     users.groups.jitsi-meet = {};
@@ -266,14 +278,12 @@ in
     systemd.services.jitsi-meet-init-secrets = {
       wantedBy = [ "multi-user.target" ];
       before = [ "jicofo.service" "jitsi-videobridge2.service" ] ++ (optional cfg.prosody.enable "prosody.service");
-      path = [ config.services.prosody.package ];
       serviceConfig = {
         Type = "oneshot";
       };
 
       script = let
         secrets = [ "jicofo-component-secret" "jicofo-user-secret" "jibri-auth-secret" "jibri-recorder-secret" ] ++ (optional (cfg.videobridge.passwordFile == null) "videobridge-secret");
-        videobridgeSecret = if cfg.videobridge.passwordFile != null then cfg.videobridge.passwordFile else "/var/lib/jitsi-meet/videobridge-secret";
       in
       ''
         cd /var/lib/jitsi-meet
@@ -291,12 +301,6 @@ in
         chmod 640 secrets-env
       ''
       + optionalString cfg.prosody.enable ''
-        prosodyctl register focus auth.${cfg.hostName} "$(cat /var/lib/jitsi-meet/jicofo-user-secret)"
-        prosodyctl register jvb auth.${cfg.hostName} "$(cat ${videobridgeSecret})"
-        prosodyctl mod_roster_command subscribe focus.${cfg.hostName} focus@auth.${cfg.hostName}
-        prosodyctl register jibri auth.${cfg.hostName} "$(cat /var/lib/jitsi-meet/jibri-auth-secret)"
-        prosodyctl register recorder recorder.${cfg.hostName} "$(cat /var/lib/jitsi-meet/jibri-recorder-secret)"
-
         # generate self-signed certificates
         if [ ! -f /var/lib/jitsi-meet.crt ]; then
           ${getBin pkgs.openssl}/bin/openssl req \
diff --git a/nixos/modules/services/web-apps/keycloak.nix b/nixos/modules/services/web-apps/keycloak.nix
index c4a2127663a..d52190a2864 100644
--- a/nixos/modules/services/web-apps/keycloak.nix
+++ b/nixos/modules/services/web-apps/keycloak.nix
@@ -4,115 +4,115 @@ let
   cfg = config.services.keycloak;
   opt = options.services.keycloak;
 
-  inherit (lib) types mkOption concatStringsSep mapAttrsToList
-    escapeShellArg recursiveUpdate optionalAttrs boolToString mkOrder
-    sort filterAttrs concatMapStringsSep concatStrings mkIf
-    optionalString optionals mkDefault literalExpression hasSuffix
-    foldl' isAttrs filter attrNames elem literalDocBook
-    maintainers;
-
-  inherit (builtins) match typeOf;
+  inherit (lib)
+    types
+    mkMerge
+    mkOption
+    mkChangedOptionModule
+    mkRenamedOptionModule
+    mkRemovedOptionModule
+    concatStringsSep
+    mapAttrsToList
+    escapeShellArg
+    mkIf
+    optionalString
+    optionals
+    mkDefault
+    literalExpression
+    isAttrs
+    literalMD
+    maintainers
+    catAttrs
+    collect
+    splitString
+    hasPrefix
+    ;
+
+  inherit (builtins)
+    elem
+    typeOf
+    isInt
+    isString
+    hashString
+    isPath
+    ;
+
+  prefixUnlessEmpty = prefix: string: optionalString (string != "") "${prefix}${string}";
 in
 {
+  imports =
+    [
+      (mkRenamedOptionModule
+        [ "services" "keycloak" "bindAddress" ]
+        [ "services" "keycloak" "settings" "http-host" ])
+      (mkRenamedOptionModule
+        [ "services" "keycloak" "forceBackendUrlToFrontendUrl"]
+        [ "services" "keycloak" "settings" "hostname-strict-backchannel"])
+      (mkChangedOptionModule
+        [ "services" "keycloak" "httpPort" ]
+        [ "services" "keycloak" "settings" "http-port" ]
+        (config:
+          builtins.fromJSON config.services.keycloak.httpPort))
+      (mkChangedOptionModule
+        [ "services" "keycloak" "httpsPort" ]
+        [ "services" "keycloak" "settings" "https-port" ]
+        (config:
+          builtins.fromJSON config.services.keycloak.httpsPort))
+      (mkRemovedOptionModule
+        [ "services" "keycloak" "frontendUrl" ]
+        ''
+          Set `services.keycloak.settings.hostname' and `services.keycloak.settings.http-relative-path' instead.
+          NOTE: You likely want to set 'http-relative-path' to '/auth' to keep compatibility with your clients.
+                See its description for more information.
+        '')
+      (mkRemovedOptionModule
+        [ "services" "keycloak" "extraConfig" ]
+        "Use `services.keycloak.settings' instead.")
+    ];
+
   options.services.keycloak =
     let
-      inherit (types) bool str nullOr attrsOf path enum anything
-        package port;
+      inherit (types)
+        bool
+        str
+        int
+        nullOr
+        attrsOf
+        oneOf
+        path
+        enum
+        package
+        port;
+
+      assertStringPath = optionName: value:
+        if isPath value then
+          throw ''
+            services.keycloak.${optionName}:
+              ${toString value}
+              is a Nix path, but should be a string, since Nix
+              paths are copied into the world-readable Nix store.
+          ''
+        else value;
     in
     {
       enable = mkOption {
         type = bool;
         default = false;
         example = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Keycloak identity and access management
           server.
         '';
       };
 
-      bindAddress = mkOption {
-        type = str;
-        default = "\${jboss.bind.address:0.0.0.0}";
-        example = "127.0.0.1";
-        description = ''
-          On which address Keycloak should accept new connections.
-
-          A special syntax can be used to allow command line Java system
-          properties to override the value: ''${property.name:value}
-        '';
-      };
-
-      httpPort = mkOption {
-        type = str;
-        default = "\${jboss.http.port:80}";
-        example = "8080";
-        description = ''
-          On which port Keycloak should listen for new HTTP connections.
-
-          A special syntax can be used to allow command line Java system
-          properties to override the value: ''${property.name:value}
-        '';
-      };
-
-      httpsPort = mkOption {
-        type = str;
-        default = "\${jboss.https.port:443}";
-        example = "8443";
-        description = ''
-          On which port Keycloak should listen for new HTTPS connections.
-
-          A special syntax can be used to allow command line Java system
-          properties to override the value: ''${property.name:value}
-        '';
-      };
-
-      frontendUrl = mkOption {
-        type = str;
-        apply = x:
-          if x == "" || hasSuffix "/" x then
-            x
-          else
-            x + "/";
-        example = "keycloak.example.com/auth";
-        description = ''
-          The public URL used as base for all frontend requests. Should
-          normally include a trailing <literal>/auth</literal>.
-
-          See <link xlink:href="https://www.keycloak.org/docs/latest/server_installation/#_hostname">the
-          Hostname section of the Keycloak server installation
-          manual</link> for more information.
-        '';
-      };
-
-      forceBackendUrlToFrontendUrl = mkOption {
-        type = bool;
-        default = false;
-        example = true;
-        description = ''
-          Whether Keycloak should force all requests to go through the
-          frontend URL configured in <xref
-          linkend="opt-services.keycloak.frontendUrl" />. By default,
-          Keycloak allows backend requests to instead use its local
-          hostname or IP address and may also advertise it to clients
-          through its OpenID Connect Discovery endpoint.
-
-          See <link
-          xlink:href="https://www.keycloak.org/docs/latest/server_installation/#_hostname">the
-          Hostname section of the Keycloak server installation
-          manual</link> for more information.
-        '';
-      };
-
       sslCertificate = mkOption {
         type = nullOr path;
         default = null;
         example = "/run/keys/ssl_cert";
-        description = ''
+        apply = assertStringPath "sslCertificate";
+        description = lib.mdDoc ''
           The path to a PEM formatted certificate to use for TLS/SSL
           connections.
-
-          This should be a string, not a Nix path, since Nix paths are
-          copied into the world-readable Nix store.
         '';
       };
 
@@ -120,29 +120,29 @@ in
         type = nullOr path;
         default = null;
         example = "/run/keys/ssl_key";
-        description = ''
+        apply = assertStringPath "sslCertificateKey";
+        description = lib.mdDoc ''
           The path to a PEM formatted private key to use for TLS/SSL
           connections.
-
-          This should be a string, not a Nix path, since Nix paths are
-          copied into the world-readable Nix store.
         '';
       };
 
       plugins = lib.mkOption {
         type = lib.types.listOf lib.types.path;
-        default = [];
-        description = ''
-          Keycloak plugin jar, ear files or derivations with them
+        default = [ ];
+        description = lib.mdDoc ''
+          Keycloak plugin jar, ear files or derivations containing
+          them. Packaged plugins are available through
+          `pkgs.keycloak.plugins`.
         '';
       };
 
       database = {
         type = mkOption {
-          type = enum [ "mysql" "postgresql" ];
+          type = enum [ "mysql" "mariadb" "postgresql" ];
           default = "postgresql";
-          example = "mysql";
-          description = ''
+          example = "mariadb";
+          description = lib.mdDoc ''
             The type of database Keycloak should connect to.
           '';
         };
@@ -150,7 +150,7 @@ in
         host = mkOption {
           type = str;
           default = "localhost";
-          description = ''
+          description = lib.mdDoc ''
             Hostname of the database to connect to.
           '';
         };
@@ -159,14 +159,15 @@ in
           let
             dbPorts = {
               postgresql = 5432;
+              mariadb = 3306;
               mysql = 3306;
             };
           in
           mkOption {
             type = port;
             default = dbPorts.${cfg.database.type};
-            defaultText = literalDocBook "default port of selected database";
-            description = ''
+            defaultText = literalMD "default port of selected database";
+            description = lib.mdDoc ''
               Port of the database to connect to.
             '';
           };
@@ -175,7 +176,7 @@ in
           type = bool;
           default = cfg.database.host != "localhost";
           defaultText = literalExpression ''config.${opt.database.host} != "localhost"'';
-          description = ''
+          description = lib.mdDoc ''
             Whether the database connection should be secured by SSL /
             TLS.
           '';
@@ -184,13 +185,13 @@ in
         caCert = mkOption {
           type = nullOr path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The SSL / TLS CA certificate that verifies the identity of the
             database server.
 
             Required when PostgreSQL is used and SSL is turned on.
 
-            For MySQL, if left at <literal>null</literal>, the default
+            For MySQL, if left at `null`, the default
             Java keystore is used, which should suffice if the server
             certificate is issued by an official CA.
           '';
@@ -199,7 +200,7 @@ in
         createLocally = mkOption {
           type = bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether a database should be automatically created on the
             local host. Set this to false if you plan on provisioning a
             local database yourself. This has no effect if
@@ -207,30 +208,40 @@ in
           '';
         };
 
+        name = mkOption {
+          type = str;
+          default = "keycloak";
+          description = lib.mdDoc ''
+            Database name to use when connecting to an external or
+            manually provisioned database; has no effect when a local
+            database is automatically provisioned.
+
+            To use this with a local database, set [](#opt-services.keycloak.database.createLocally) to
+            `false` and create the database and user
+            manually.
+          '';
+        };
+
         username = mkOption {
           type = str;
           default = "keycloak";
-          description = ''
+          description = lib.mdDoc ''
             Username to use when connecting to an external or manually
             provisioned database; has no effect when a local database is
             automatically provisioned.
 
-            To use this with a local database, set <xref
-            linkend="opt-services.keycloak.database.createLocally" /> to
-            <literal>false</literal> and create the database and user
-            manually. The database should be called
-            <literal>keycloak</literal>.
+            To use this with a local database, set [](#opt-services.keycloak.database.createLocally) to
+            `false` and create the database and user
+            manually.
           '';
         };
 
         passwordFile = mkOption {
           type = path;
           example = "/run/keys/db_password";
-          description = ''
-            File containing the database password.
-
-            This should be a string, not a Nix path, since Nix paths are
-            copied into the world-readable Nix store.
+          apply = assertStringPath "passwordFile";
+          description = lib.mdDoc ''
+            The path to a file containing the database password.
           '';
         };
       };
@@ -239,7 +250,7 @@ in
         type = package;
         default = pkgs.keycloak;
         defaultText = literalExpression "pkgs.keycloak";
-        description = ''
+        description = lib.mdDoc ''
           Keycloak package to use.
         '';
       };
@@ -247,8 +258,8 @@ in
       initialAdminPassword = mkOption {
         type = str;
         default = "changeme";
-        description = ''
-          Initial password set for the <literal>admin</literal>
+        description = lib.mdDoc ''
+          Initial password set for the `admin`
           user. The password is not stored safely and should be changed
           immediately in the admin panel.
         '';
@@ -257,78 +268,166 @@ in
       themes = mkOption {
         type = attrsOf package;
         default = { };
-        description = ''
+        description = lib.mdDoc ''
           Additional theme packages for Keycloak. Each theme is linked into
           subdirectory with a corresponding attribute name.
 
           Theme packages consist of several subdirectories which provide
-          different theme types: for example, <literal>account</literal>,
-          <literal>login</literal> etc. After adding a theme to this option you
+          different theme types: for example, `account`,
+          `login` etc. After adding a theme to this option you
           can select it by its name in Keycloak administration console.
         '';
       };
 
-      extraConfig = mkOption {
-        type = attrsOf anything;
-        default = { };
+      settings = mkOption {
+        type = lib.types.submodule {
+          freeformType = attrsOf (nullOr (oneOf [ str int bool (attrsOf path) ]));
+
+          options = {
+            http-host = mkOption {
+              type = str;
+              default = "0.0.0.0";
+              example = "127.0.0.1";
+              description = lib.mdDoc ''
+                On which address Keycloak should accept new connections.
+              '';
+            };
+
+            http-port = mkOption {
+              type = port;
+              default = 80;
+              example = 8080;
+              description = lib.mdDoc ''
+                On which port Keycloak should listen for new HTTP connections.
+              '';
+            };
+
+            https-port = mkOption {
+              type = port;
+              default = 443;
+              example = 8443;
+              description = lib.mdDoc ''
+                On which port Keycloak should listen for new HTTPS connections.
+              '';
+            };
+
+            http-relative-path = mkOption {
+              type = str;
+              default = "/";
+              example = "/auth";
+              apply = x: if !(hasPrefix "/") x then "/" + x else x;
+              description = lib.mdDoc ''
+                The path relative to `/` for serving
+                resources.
+
+                ::: {.note}
+                In versions of Keycloak using Wildfly (&lt;17),
+                this defaulted to `/auth`. If
+                upgrading from the Wildfly version of Keycloak,
+                i.e. a NixOS version before 22.05, you'll likely
+                want to set this to `/auth` to
+                keep compatibility with your clients.
+
+                See <https://www.keycloak.org/migration/migrating-to-quarkus>
+                for more information on migrating from Wildfly to Quarkus.
+                :::
+              '';
+            };
+
+            hostname = mkOption {
+              type = str;
+              example = "keycloak.example.com";
+              description = lib.mdDoc ''
+                The hostname part of the public URL used as base for
+                all frontend requests.
+
+                See <https://www.keycloak.org/server/hostname>
+                for more information about hostname configuration.
+              '';
+            };
+
+            hostname-strict-backchannel = mkOption {
+              type = bool;
+              default = false;
+              example = true;
+              description = lib.mdDoc ''
+                Whether Keycloak should force all requests to go
+                through the frontend URL. By default, Keycloak allows
+                backend requests to instead use its local hostname or
+                IP address and may also advertise it to clients
+                through its OpenID Connect Discovery endpoint.
+
+                See <https://www.keycloak.org/server/hostname>
+                for more information about hostname configuration.
+              '';
+            };
+
+            proxy = mkOption {
+              type = enum [ "edge" "reencrypt" "passthrough" "none" ];
+              default = "none";
+              example = "edge";
+              description = lib.mdDoc ''
+                The proxy address forwarding mode if the server is
+                behind a reverse proxy.
+
+                - `edge`:
+                  Enables communication through HTTP between the
+                  proxy and Keycloak.
+                - `reencrypt`:
+                  Requires communication through HTTPS between the
+                  proxy and Keycloak.
+                - `passthrough`:
+                  Enables communication through HTTP or HTTPS between
+                  the proxy and Keycloak.
+
+                See <https://www.keycloak.org/server/reverseproxy> for more information.
+              '';
+            };
+          };
+        };
+
         example = literalExpression ''
           {
-            "subsystem=keycloak-server" = {
-              "spi=hostname" = {
-                "provider=default" = null;
-                "provider=fixed" = {
-                  enabled = true;
-                  properties.hostname = "keycloak.example.com";
-                };
-                default-provider = "fixed";
-              };
-            };
+            hostname = "keycloak.example.com";
+            proxy = "reencrypt";
+            https-key-store-file = "/path/to/file";
+            https-key-store-password = { _secret = "/run/keys/store_password"; };
           }
         '';
-        description = ''
-          Additional Keycloak configuration options to set in
-          <literal>standalone.xml</literal>.
-
-          Options are expressed as a Nix attribute set which matches the
-          structure of the jboss-cli configuration. The configuration is
-          effectively overlayed on top of the default configuration
-          shipped with Keycloak. To remove existing nodes and undefine
-          attributes from the default configuration, set them to
-          <literal>null</literal>.
-
-          The example configuration does the equivalent of the following
-          script, which removes the hostname provider
-          <literal>default</literal>, adds the deprecated hostname
-          provider <literal>fixed</literal> and defines it the default:
-
-          <programlisting>
-          /subsystem=keycloak-server/spi=hostname/provider=default:remove()
-          /subsystem=keycloak-server/spi=hostname/provider=fixed:add(enabled = true, properties = { hostname = "keycloak.example.com" })
-          /subsystem=keycloak-server/spi=hostname:write-attribute(name=default-provider, value="fixed")
-          </programlisting>
-
-          You can discover available options by using the <link
-          xlink:href="http://docs.wildfly.org/21/Admin_Guide.html#Command_Line_Interface">jboss-cli.sh</link>
-          program and by referring to the <link
-          xlink:href="https://www.keycloak.org/docs/latest/server_installation/index.html">Keycloak
-          Server Installation and Configuration Guide</link>.
+
+        description = lib.mdDoc ''
+          Configuration options corresponding to parameters set in
+          {file}`conf/keycloak.conf`.
+
+          Most available options are documented at <https://www.keycloak.org/server/all-config>.
+
+          Options containing secret data should be set to an attribute
+          set containing the attribute `_secret` - a
+          string pointing to a file containing the value the option
+          should be set to. See the example to get a better picture of
+          this: in the resulting
+          {file}`conf/keycloak.conf` file, the
+          `https-key-store-password` key will be set
+          to the contents of the
+          {file}`/run/keys/store_password` file.
         '';
       };
-
     };
 
   config =
     let
-      # We only want to create a database if we're actually going to connect to it.
+      # We only want to create a database if we're actually going to
+      # connect to it.
       databaseActuallyCreateLocally = cfg.database.createLocally && cfg.database.host == "localhost";
       createLocalPostgreSQL = databaseActuallyCreateLocally && cfg.database.type == "postgresql";
-      createLocalMySQL = databaseActuallyCreateLocally && cfg.database.type == "mysql";
+      createLocalMySQL = databaseActuallyCreateLocally && elem cfg.database.type [ "mysql" "mariadb" ];
 
       mySqlCaKeystore = pkgs.runCommand "mysql-ca-keystore" { } ''
         ${pkgs.jre}/bin/keytool -importcert -trustcacerts -alias MySQLCACert -file ${cfg.database.caCert} -keystore $out -storepass notsosecretpassword -noprompt
       '';
 
-      # Both theme and theme type directories need to be actual directories in one hierarchy to pass Keycloak checks.
+      # Both theme and theme type directories need to be actual
+      # directories in one hierarchy to pass Keycloak checks.
       themesBundle = pkgs.runCommand "keycloak-themes" { } ''
         linkTheme() {
           theme="$1"
@@ -347,7 +446,7 @@ in
         }
 
         mkdir -p "$out"
-        for theme in ${cfg.package}/themes/*; do
+        for theme in ${keycloakBuild}/themes/*; do
           if [ -d "$theme" ]; then
             linkTheme "$theme" "$(basename "$theme")"
           fi
@@ -356,329 +455,25 @@ in
         ${concatStringsSep "\n" (mapAttrsToList (name: theme: "linkTheme ${theme} ${escapeShellArg name}") cfg.themes)}
       '';
 
-      keycloakConfig' = foldl' recursiveUpdate
-        {
-          "interface=public".inet-address = cfg.bindAddress;
-          "socket-binding-group=standard-sockets"."socket-binding=http".port = cfg.httpPort;
-          "subsystem=keycloak-server" = {
-            "spi=hostname"."provider=default" = {
-              enabled = true;
-              properties = {
-                inherit (cfg) frontendUrl forceBackendUrlToFrontendUrl;
-              };
-            };
-            "theme=defaults".dir = toString themesBundle;
-          };
-          "subsystem=datasources"."data-source=KeycloakDS" = {
-            max-pool-size = "20";
-            user-name = if databaseActuallyCreateLocally then "keycloak" else cfg.database.username;
-            password = "@db-password@";
-          };
-        } [
-        (optionalAttrs (cfg.database.type == "postgresql") {
-          "subsystem=datasources" = {
-            "jdbc-driver=postgresql" = {
-              driver-module-name = "org.postgresql";
-              driver-name = "postgresql";
-              driver-xa-datasource-class-name = "org.postgresql.xa.PGXADataSource";
-            };
-            "data-source=KeycloakDS" = {
-              connection-url = "jdbc:postgresql://${cfg.database.host}:${toString cfg.database.port}/keycloak";
-              driver-name = "postgresql";
-              "connection-properties=ssl".value = boolToString cfg.database.useSSL;
-            } // (optionalAttrs (cfg.database.caCert != null) {
-              "connection-properties=sslrootcert".value = cfg.database.caCert;
-              "connection-properties=sslmode".value = "verify-ca";
-            });
-          };
-        })
-        (optionalAttrs (cfg.database.type == "mysql") {
-          "subsystem=datasources" = {
-            "jdbc-driver=mysql" = {
-              driver-module-name = "com.mysql";
-              driver-name = "mysql";
-              driver-class-name = "com.mysql.jdbc.Driver";
-            };
-            "data-source=KeycloakDS" = {
-              connection-url = "jdbc:mysql://${cfg.database.host}:${toString cfg.database.port}/keycloak";
-              driver-name = "mysql";
-              "connection-properties=useSSL".value = boolToString cfg.database.useSSL;
-              "connection-properties=requireSSL".value = boolToString cfg.database.useSSL;
-              "connection-properties=verifyServerCertificate".value = boolToString cfg.database.useSSL;
-              "connection-properties=characterEncoding".value = "UTF-8";
-              valid-connection-checker-class-name = "org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker";
-              validate-on-match = true;
-              exception-sorter-class-name = "org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter";
-            } // (optionalAttrs (cfg.database.caCert != null) {
-              "connection-properties=trustCertificateKeyStoreUrl".value = "file:${mySqlCaKeystore}";
-              "connection-properties=trustCertificateKeyStorePassword".value = "notsosecretpassword";
-            });
-          };
-        })
-        (optionalAttrs (cfg.sslCertificate != null && cfg.sslCertificateKey != null) {
-          "socket-binding-group=standard-sockets"."socket-binding=https".port = cfg.httpsPort;
-          "subsystem=elytron" = mkOrder 900 {
-            "key-store=httpsKS" = mkOrder 900 {
-              path = "/run/keycloak/ssl/certificate_private_key_bundle.p12";
-              credential-reference.clear-text = "notsosecretpassword";
-              type = "JKS";
-            };
-            "key-manager=httpsKM" = mkOrder 901 {
-              key-store = "httpsKS";
-              credential-reference.clear-text = "notsosecretpassword";
-            };
-            "server-ssl-context=httpsSSC" = mkOrder 902 {
-              key-manager = "httpsKM";
-            };
-          };
-          "subsystem=undertow" = mkOrder 901 {
-            "server=default-server"."https-listener=https".ssl-context = "httpsSSC";
-          };
-        })
-        cfg.extraConfig
-      ];
-
-
-      /* Produces a JBoss CLI script that creates paths and sets
-         attributes matching those described by `attrs`. When the
-         script is run, the existing settings are effectively overlayed
-         by those from `attrs`. Existing attributes can be unset by
-         defining them `null`.
-
-         JBoss paths and attributes / maps are distinguished by their
-         name, where paths follow a `key=value` scheme.
-
-         Example:
-           mkJbossScript {
-             "subsystem=keycloak-server"."spi=hostname" = {
-               "provider=fixed" = null;
-               "provider=default" = {
-                 enabled = true;
-                 properties = {
-                   inherit frontendUrl;
-                   forceBackendUrlToFrontendUrl = false;
-                 };
-               };
-             };
-           }
-           => ''
-             if (outcome != success) of /:read-resource()
-                 /:add()
-             end-if
-             if (outcome != success) of /subsystem=keycloak-server:read-resource()
-                 /subsystem=keycloak-server:add()
-             end-if
-             if (outcome != success) of /subsystem=keycloak-server/spi=hostname:read-resource()
-                 /subsystem=keycloak-server/spi=hostname:add()
-             end-if
-             if (outcome != success) of /subsystem=keycloak-server/spi=hostname/provider=default:read-resource()
-                 /subsystem=keycloak-server/spi=hostname/provider=default:add(enabled = true, properties = { forceBackendUrlToFrontendUrl = false, frontendUrl = "https://keycloak.example.com/auth" })
-             end-if
-             if (result != true) of /subsystem=keycloak-server/spi=hostname/provider=default:read-attribute(name="enabled")
-               /subsystem=keycloak-server/spi=hostname/provider=default:write-attribute(name=enabled, value=true)
-             end-if
-             if (result != false) of /subsystem=keycloak-server/spi=hostname/provider=default:read-attribute(name="properties.forceBackendUrlToFrontendUrl")
-               /subsystem=keycloak-server/spi=hostname/provider=default:write-attribute(name=properties.forceBackendUrlToFrontendUrl, value=false)
-             end-if
-             if (result != "https://keycloak.example.com/auth") of /subsystem=keycloak-server/spi=hostname/provider=default:read-attribute(name="properties.frontendUrl")
-               /subsystem=keycloak-server/spi=hostname/provider=default:write-attribute(name=properties.frontendUrl, value="https://keycloak.example.com/auth")
-             end-if
-             if (outcome != success) of /subsystem=keycloak-server/spi=hostname/provider=fixed:read-resource()
-                 /subsystem=keycloak-server/spi=hostname/provider=fixed:remove()
-             end-if
-           ''
-      */
-      mkJbossScript = attrs:
-        let
-          /* From a JBoss path and an attrset, produces a JBoss CLI
-             snippet that writes the corresponding attributes starting
-             at `path`. Recurses down into subattrsets as necessary,
-             producing the variable name from its full path in the
-             attrset.
-
-             Example:
-               writeAttributes "/subsystem=keycloak-server/spi=hostname/provider=default" {
-                 enabled = true;
-                 properties = {
-                   forceBackendUrlToFrontendUrl = false;
-                   frontendUrl = "https://keycloak.example.com/auth";
-                 };
-               }
-               => ''
-                 if (result != true) of /subsystem=keycloak-server/spi=hostname/provider=default:read-attribute(name="enabled")
-                   /subsystem=keycloak-server/spi=hostname/provider=default:write-attribute(name=enabled, value=true)
-                 end-if
-                 if (result != false) of /subsystem=keycloak-server/spi=hostname/provider=default:read-attribute(name="properties.forceBackendUrlToFrontendUrl")
-                   /subsystem=keycloak-server/spi=hostname/provider=default:write-attribute(name=properties.forceBackendUrlToFrontendUrl, value=false)
-                 end-if
-                 if (result != "https://keycloak.example.com/auth") of /subsystem=keycloak-server/spi=hostname/provider=default:read-attribute(name="properties.frontendUrl")
-                   /subsystem=keycloak-server/spi=hostname/provider=default:write-attribute(name=properties.frontendUrl, value="https://keycloak.example.com/auth")
-                 end-if
-               ''
-          */
-          writeAttributes = path: set:
-            let
-              # JBoss expressions like `${var}` need to be prefixed
-              # with `expression` to evaluate.
-              prefixExpression = string:
-                let
-                  matchResult = match ''"\$\{.*}"'' string;
-                in
-                if matchResult != null then
-                  "expression " + string
-                else
-                  string;
-
-              writeAttribute = attribute: value:
-                let
-                  type = typeOf value;
-                in
-                if type == "set" then
-                  let
-                    names = attrNames value;
-                  in
-                  foldl' (text: name: text + (writeAttribute "${attribute}.${name}" value.${name})) "" names
-                else if value == null then ''
-                  if (outcome == success) of ${path}:read-attribute(name="${attribute}")
-                      ${path}:undefine-attribute(name="${attribute}")
-                  end-if
-                ''
-                else if elem type [ "string" "path" "bool" ] then
-                  let
-                    value' = if type == "bool" then boolToString value else ''"${value}"'';
-                  in
-                  ''
-                    if (result != ${prefixExpression value'}) of ${path}:read-attribute(name="${attribute}")
-                      ${path}:write-attribute(name=${attribute}, value=${value'})
-                    end-if
-                  ''
-                else throw "Unsupported type '${type}' for path '${path}'!";
-            in
-            concatStrings
-              (mapAttrsToList
-                (attribute: value: (writeAttribute attribute value))
-                set);
-
-
-          /* Produces an argument list for the JBoss `add()` function,
-             which adds a JBoss path and takes as its arguments the
-             required subpaths and attributes.
-
-             Example:
-               makeArgList {
-                 enabled = true;
-                 properties = {
-                   forceBackendUrlToFrontendUrl = false;
-                   frontendUrl = "https://keycloak.example.com/auth";
-                 };
-               }
-               => ''
-                 enabled = true, properties = { forceBackendUrlToFrontendUrl = false, frontendUrl = "https://keycloak.example.com/auth" }
-               ''
-          */
-          makeArgList = set:
-            let
-              makeArg = attribute: value:
-                let
-                  type = typeOf value;
-                in
-                if type == "set" then
-                  "${attribute} = { " + (makeArgList value) + " }"
-                else if elem type [ "string" "path" "bool" ] then
-                  "${attribute} = ${if type == "bool" then boolToString value else ''"${value}"''}"
-                else if value == null then
-                  ""
-                else
-                  throw "Unsupported type '${type}' for attribute '${attribute}'!";
-
-            in
-            concatStringsSep ", " (mapAttrsToList makeArg set);
-
-
-          /* Recurses into the `nodeValue` attrset. Only subattrsets that
-             are JBoss paths, i.e. follows the `key=value` format, are recursed
-             into - the rest are considered JBoss attributes / maps.
-          */
-          recurse = nodePath: nodeValue:
-            let
-              nodeContent =
-                if isAttrs nodeValue && nodeValue._type or "" == "order" then
-                  nodeValue.content
-                else
-                  nodeValue;
-              isPath = name:
-                let
-                  value = nodeContent.${name};
-                in
-                if (match ".*([=]).*" name) == [ "=" ] then
-                  if isAttrs value || value == null then
-                    true
-                  else
-                    throw "Parsing path '${concatStringsSep "." (nodePath ++ [ name ])}' failed: JBoss attributes cannot contain '='!"
-                else
-                  false;
-              jbossPath = "/" + concatStringsSep "/" nodePath;
-              children = if !isAttrs nodeContent then { } else nodeContent;
-              subPaths = filter isPath (attrNames children);
-              getPriority = name:
-                let
-                  value = children.${name};
-                in
-                if value._type or "" == "order" then value.priority else 1000;
-              orderedSubPaths = sort (a: b: getPriority a < getPriority b) subPaths;
-              jbossAttrs = filterAttrs (name: _: !(isPath name)) children;
-              text =
-                if nodeContent != null then
-                  ''
-                    if (outcome != success) of ${jbossPath}:read-resource()
-                        ${jbossPath}:add(${makeArgList jbossAttrs})
-                    end-if
-                  '' + writeAttributes jbossPath jbossAttrs
-                else
-                  ''
-                    if (outcome == success) of ${jbossPath}:read-resource()
-                        ${jbossPath}:remove()
-                    end-if
-                  '';
-            in
-            text + concatMapStringsSep "\n" (name: recurse (nodePath ++ [ name ]) children.${name}) orderedSubPaths;
-        in
-        recurse [ ] attrs;
-
-      jbossCliScript = pkgs.writeText "jboss-cli-script" (mkJbossScript keycloakConfig');
-
-      keycloakConfig = pkgs.runCommand "keycloak-config"
-        {
-          nativeBuildInputs = [ cfg.package ];
-        }
-        ''
-          export JBOSS_BASE_DIR="$(pwd -P)";
-          export JBOSS_MODULEPATH="${cfg.package}/modules";
-          export JBOSS_LOG_DIR="$JBOSS_BASE_DIR/log";
-
-          cp -r ${cfg.package}/standalone/configuration .
-          chmod -R u+rwX ./configuration
-
-          mkdir -p {deployments,ssl}
-
-          standalone.sh&
-
-          attempt=1
-          max_attempts=30
-          while ! jboss-cli.sh --connect ':read-attribute(name=server-state)'; do
-              if [[ "$attempt" == "$max_attempts" ]]; then
-                  echo "ERROR: Could not connect to Keycloak after $attempt attempts! Failing.." >&2
-                  exit 1
-              fi
-              echo "Keycloak not fully started yet, retrying.. ($attempt/$max_attempts)"
-              sleep 1
-              (( attempt++ ))
-          done
-
-          jboss-cli.sh --connect --file=${jbossCliScript} --echo-command
+      keycloakConfig = lib.generators.toKeyValue {
+        mkKeyValue = lib.flip lib.generators.mkKeyValueDefault "=" {
+          mkValueString = v: with builtins;
+            if isInt v then toString v
+            else if isString v then v
+            else if true == v then "true"
+            else if false == v then "false"
+            else if isSecret v then hashString "sha256" v._secret
+            else throw "unsupported type ${typeOf v}: ${(lib.generators.toPretty {}) v}";
+        };
+      };
 
-          cp configuration/standalone.xml $out
-        '';
+      isSecret = v: isAttrs v && v ? _secret && isString v._secret;
+      filteredConfig = lib.converge (lib.filterAttrsRecursive (_: v: ! elem v [{ } null])) cfg.settings;
+      confFile = pkgs.writeText "keycloak.conf" (keycloakConfig filteredConfig);
+      keycloakBuild = cfg.package.override {
+        inherit confFile;
+        plugins = cfg.package.enabledPlugins ++ cfg.plugins;
+      };
     in
     mkIf cfg.enable
       {
@@ -687,9 +482,52 @@ in
             assertion = (cfg.database.useSSL && cfg.database.type == "postgresql") -> (cfg.database.caCert != null);
             message = "A CA certificate must be specified (in 'services.keycloak.database.caCert') when PostgreSQL is used with SSL";
           }
+          {
+            assertion = createLocalPostgreSQL -> config.services.postgresql.settings.standard_conforming_strings or true;
+            message = "Setting up a local PostgreSQL db for Keycloak requires `standard_conforming_strings` turned on to work reliably";
+          }
         ];
 
-        environment.systemPackages = [ cfg.package ];
+        environment.systemPackages = [ keycloakBuild ];
+
+        services.keycloak.settings =
+          let
+            postgresParams = concatStringsSep "&" (
+              optionals cfg.database.useSSL [
+                "ssl=true"
+              ] ++ optionals (cfg.database.caCert != null) [
+                "sslrootcert=${cfg.database.caCert}"
+                "sslmode=verify-ca"
+              ]
+            );
+            mariadbParams = concatStringsSep "&" ([
+              "characterEncoding=UTF-8"
+            ] ++ optionals cfg.database.useSSL [
+              "useSSL=true"
+              "requireSSL=true"
+              "verifyServerCertificate=true"
+            ] ++ optionals (cfg.database.caCert != null) [
+              "trustCertificateKeyStoreUrl=file:${mySqlCaKeystore}"
+              "trustCertificateKeyStorePassword=notsosecretpassword"
+            ]);
+            dbProps = if cfg.database.type == "postgresql" then postgresParams else mariadbParams;
+          in
+          mkMerge [
+            {
+              db = if cfg.database.type == "postgresql" then "postgres" else cfg.database.type;
+              db-username = if databaseActuallyCreateLocally then "keycloak" else cfg.database.username;
+              db-password._secret = cfg.database.passwordFile;
+              db-url-host = cfg.database.host;
+              db-url-port = toString cfg.database.port;
+              db-url-database = if databaseActuallyCreateLocally then "keycloak" else cfg.database.name;
+              db-url-properties = prefixUnlessEmpty "?" dbProps;
+              db-url = null;
+            }
+            (mkIf (cfg.sslCertificate != null && cfg.sslCertificateKey != null) {
+              https-certificate-file = "/run/keycloak/ssl/ssl_cert";
+              https-certificate-key-file = "/run/keycloak/ssl/ssl_key";
+            })
+          ];
 
         systemd.services.keycloakPostgreSQLInit = mkIf createLocalPostgreSQL {
           after = [ "postgresql.service" ];
@@ -708,9 +546,15 @@ in
             shopt -s inherit_errexit
 
             create_role="$(mktemp)"
-            trap 'rm -f "$create_role"' ERR EXIT
+            trap 'rm -f "$create_role"' EXIT
 
+            # Read the password from the credentials directory and
+            # escape any single quotes by adding additional single
+            # quotes after them, following the rules laid out here:
+            # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
             db_password="$(<"$CREDENTIALS_DIRECTORY/db_password")"
+            db_password="''${db_password//\'/\'\'}"
+
             echo "CREATE ROLE keycloak WITH LOGIN PASSWORD '$db_password' CREATEDB" > "$create_role"
             psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='keycloak'" | grep -q 1 || psql -tA --file="$create_role"
             psql -tAc "SELECT 1 FROM pg_database WHERE datname = 'keycloak'" | grep -q 1 || psql -tAc 'CREATE DATABASE "keycloak" OWNER "keycloak"'
@@ -732,8 +576,16 @@ in
           script = ''
             set -o errexit -o pipefail -o nounset -o errtrace
             shopt -s inherit_errexit
+
+            # Read the password from the credentials directory and
+            # escape any single quotes by adding additional single
+            # quotes after them, following the rules laid out here:
+            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
             db_password="$(<"$CREDENTIALS_DIRECTORY/db_password")"
-            ( echo "CREATE USER IF NOT EXISTS 'keycloak'@'localhost' IDENTIFIED BY '$db_password';"
+            db_password="''${db_password//\'/\'\'}"
+
+            ( echo "SET sql_mode = 'NO_BACKSLASH_ESCAPES';"
+              echo "CREATE USER IF NOT EXISTS 'keycloak'@'localhost' IDENTIFIED BY '$db_password';"
               echo "CREATE DATABASE IF NOT EXISTS keycloak CHARACTER SET utf8 COLLATE utf8_unicode_ci;"
               echo "GRANT ALL PRIVILEGES ON keycloak.* TO 'keycloak'@'localhost';"
             ) | mysql -N
@@ -752,41 +604,37 @@ in
                 "mysql.service"
               ]
               else [ ];
+            secretPaths = catAttrs "_secret" (collect isSecret cfg.settings);
+            mkSecretReplacement = file: ''
+              replace-secret ${hashString "sha256" file} $CREDENTIALS_DIRECTORY/${baseNameOf file} /run/keycloak/conf/keycloak.conf
+            '';
+            secretReplacements = lib.concatMapStrings mkSecretReplacement secretPaths;
           in
           {
             after = databaseServices;
             bindsTo = databaseServices;
             wantedBy = [ "multi-user.target" ];
             path = with pkgs; [
-              cfg.package
+              keycloakBuild
               openssl
               replace-secret
             ];
             environment = {
-              JBOSS_LOG_DIR = "/var/log/keycloak";
-              JBOSS_BASE_DIR = "/run/keycloak";
-              JBOSS_MODULEPATH = "${cfg.package}/modules";
+              KC_HOME_DIR = "/run/keycloak";
+              KC_CONF_DIR = "/run/keycloak/conf";
             };
             serviceConfig = {
-              LoadCredential = [
-                "db_password:${cfg.database.passwordFile}"
-              ] ++ optionals (cfg.sslCertificate != null && cfg.sslCertificateKey != null) [
-                "ssl_cert:${cfg.sslCertificate}"
-                "ssl_key:${cfg.sslCertificateKey}"
-              ];
+              LoadCredential =
+                map (p: "${baseNameOf p}:${p}") secretPaths
+                ++ optionals (cfg.sslCertificate != null && cfg.sslCertificateKey != null) [
+                  "ssl_cert:${cfg.sslCertificate}"
+                  "ssl_key:${cfg.sslCertificateKey}"
+                ];
               User = "keycloak";
               Group = "keycloak";
               DynamicUser = true;
-              RuntimeDirectory = map (p: "keycloak/" + p) [
-                "configuration"
-                "deployments"
-                "data"
-                "ssl"
-                "log"
-                "tmp"
-              ];
-              RuntimeDirectoryMode = 0700;
-              LogsDirectory = "keycloak";
+              RuntimeDirectory = "keycloak";
+              RuntimeDirectoryMode = "0700";
               AmbientCapabilities = "CAP_NET_BIND_SERVICE";
             };
             script = ''
@@ -795,41 +643,35 @@ in
 
               umask u=rwx,g=,o=
 
-              install_plugin() {
-                if [ -d "$1" ]; then
-                  find "$1" -type f \( -iname \*.ear -o -iname \*.jar \) -exec install -m 0500 -o keycloak -g keycloak "{}" "/run/keycloak/deployments/" \;
-                else
-                  install -m 0500 -o keycloak -g keycloak "$1" "/run/keycloak/deployments/"
-                fi
-              }
-
-              install -m 0600 ${cfg.package}/standalone/configuration/*.properties /run/keycloak/configuration
-              install -T -m 0600 ${keycloakConfig} /run/keycloak/configuration/standalone.xml
-
-              replace-secret '@db-password@' "$CREDENTIALS_DIRECTORY/db_password" /run/keycloak/configuration/standalone.xml
-
-              export JAVA_OPTS=-Djboss.server.config.user.dir=/run/keycloak/configuration
-              add-user-keycloak.sh -u admin -p '${cfg.initialAdminPassword}'
-            ''
-            + lib.optionalString (cfg.plugins != []) (lib.concatStringsSep "\n" (map (pl: "install_plugin ${lib.escapeShellArg pl}") cfg.plugins)) + "\n"
-            + optionalString (cfg.sslCertificate != null && cfg.sslCertificateKey != null) ''
-              pushd /run/keycloak/ssl/
-              cat "$CREDENTIALS_DIRECTORY/ssl_cert" <(echo) \
-                  "$CREDENTIALS_DIRECTORY/ssl_key" <(echo) \
-                  /etc/ssl/certs/ca-certificates.crt \
-                  > allcerts.pem
-              openssl pkcs12 -export -in "$CREDENTIALS_DIRECTORY/ssl_cert" -inkey "$CREDENTIALS_DIRECTORY/ssl_key" -chain \
-                             -name "${cfg.frontendUrl}" -out certificate_private_key_bundle.p12 \
-                             -CAfile allcerts.pem -passout pass:notsosecretpassword
-              popd
+              ln -s ${themesBundle} /run/keycloak/themes
+              ln -s ${keycloakBuild}/providers /run/keycloak/
+
+              install -D -m 0600 ${confFile} /run/keycloak/conf/keycloak.conf
+
+              ${secretReplacements}
+
+              # Escape any backslashes in the db parameters, since
+              # they're otherwise unexpectedly read as escape
+              # sequences.
+              sed -i '/db-/ s|\\|\\\\|g' /run/keycloak/conf/keycloak.conf
+
+            '' + optionalString (cfg.sslCertificate != null && cfg.sslCertificateKey != null) ''
+              mkdir -p /run/keycloak/ssl
+              cp $CREDENTIALS_DIRECTORY/ssl_{cert,key} /run/keycloak/ssl/
             '' + ''
-              ${cfg.package}/bin/standalone.sh
+              export KEYCLOAK_ADMIN=admin
+              export KEYCLOAK_ADMIN_PASSWORD=${escapeShellArg cfg.initialAdminPassword}
+              kc.sh start --optimized
             '';
           };
 
         services.postgresql.enable = mkDefault createLocalPostgreSQL;
         services.mysql.enable = mkDefault createLocalMySQL;
-        services.mysql.package = mkIf createLocalMySQL pkgs.mariadb;
+        services.mysql.package =
+          let
+            dbPkg = if cfg.database.type == "mariadb" then pkgs.mariadb else pkgs.mysql80;
+          in
+          mkIf createLocalMySQL (mkDefault dbPkg);
       };
 
   meta.doc = ./keycloak.xml;
diff --git a/nixos/modules/services/web-apps/keycloak.xml b/nixos/modules/services/web-apps/keycloak.xml
index cb706932f48..861756e33ac 100644
--- a/nixos/modules/services/web-apps/keycloak.xml
+++ b/nixos/modules/services/web-apps/keycloak.xml
@@ -27,10 +27,10 @@
 
      <para>
        Refer to the <link
-       xlink:href="https://www.keycloak.org/docs/latest/server_admin/index.html#admin-console">Admin
-       Console section of the Keycloak Server Administration Guide</link> for
-       information on how to administer your
-       <productname>Keycloak</productname> instance.
+       xlink:href="https://www.keycloak.org/docs/latest/server_admin/index.html">
+       Keycloak Server Administration Guide</link> for information on
+       how to administer your <productname>Keycloak</productname>
+       instance.
      </para>
    </section>
 
@@ -38,27 +38,28 @@
      <title>Database access</title>
      <para>
        <productname>Keycloak</productname> can be used with either
-       <productname>PostgreSQL</productname> or
+       <productname>PostgreSQL</productname>,
+       <productname>MariaDB</productname> or
        <productname>MySQL</productname>. Which one is used can be
        configured in <xref
        linkend="opt-services.keycloak.database.type" />. The selected
        database will automatically be enabled and a database and role
        created unless <xref
-       linkend="opt-services.keycloak.database.host" /> is changed from
-       its default of <literal>localhost</literal> or <xref
-       linkend="opt-services.keycloak.database.createLocally" /> is set
-       to <literal>false</literal>.
+       linkend="opt-services.keycloak.database.host" /> is changed
+       from its default of <literal>localhost</literal> or <xref
+       linkend="opt-services.keycloak.database.createLocally" /> is
+       set to <literal>false</literal>.
      </para>
 
      <para>
        External database access can also be configured by setting
        <xref linkend="opt-services.keycloak.database.host" />, <xref
+       linkend="opt-services.keycloak.database.name" />, <xref
        linkend="opt-services.keycloak.database.username" />, <xref
        linkend="opt-services.keycloak.database.useSSL" /> and <xref
        linkend="opt-services.keycloak.database.caCert" /> as
-       appropriate. Note that you need to manually create a database
-       called <literal>keycloak</literal> and allow the configured
-       database user full access to it.
+       appropriate. Note that you need to manually create the database
+       and allow the configured database user full access to it.
      </para>
 
      <para>
@@ -79,22 +80,27 @@
      </warning>
    </section>
 
-   <section xml:id="module-services-keycloak-frontendurl">
-     <title>Frontend URL</title>
+   <section xml:id="module-services-keycloak-hostname">
+     <title>Hostname</title>
      <para>
-       The frontend URL is used as base for all frontend requests and
-       must be configured through <xref linkend="opt-services.keycloak.frontendUrl" />.
-       It should normally include a trailing <literal>/auth</literal>
-       (the default web context). If you use a reverse proxy, you need
-       to set this option to <literal>""</literal>, so that frontend URL
-       is derived from HTTP headers. <literal>X-Forwarded-*</literal> headers
-       support also should be enabled, using <link
-       xlink:href="https://www.keycloak.org/docs/latest/server_installation/index.html#identifying-client-ip-addresses">
-       respective guidelines</link>.
+       The hostname is used to build the public URL used as base for
+       all frontend requests and must be configured through <xref
+       linkend="opt-services.keycloak.settings.hostname" />.
      </para>
 
+     <note>
+       <para>
+         If you're migrating an old Wildfly based Keycloak instance
+         and want to keep compatibility with your current clients,
+         you'll likely want to set <xref
+         linkend="opt-services.keycloak.settings.http-relative-path"
+         /> to <literal>/auth</literal>. See the option description
+         for more details.
+       </para>
+     </note>
+
      <para>
-       <xref linkend="opt-services.keycloak.forceBackendUrlToFrontendUrl" />
+       <xref linkend="opt-services.keycloak.settings.hostname-strict-backchannel" />
        determines whether Keycloak should force all requests to go
        through the frontend URL. By default,
        <productname>Keycloak</productname> allows backend requests to
@@ -104,10 +110,10 @@
      </para>
 
      <para>
-       See the <link
-       xlink:href="https://www.keycloak.org/docs/latest/server_installation/#_hostname">Hostname
-       section of the Keycloak Server Installation and Configuration
-       Guide</link> for more information.
+        For more information on hostname configuration, see the <link
+        xlink:href="https://www.keycloak.org/server/hostname">Hostname
+        section of the Keycloak Server Installation and Configuration
+        Guide</link>.
      </para>
    </section>
 
@@ -139,68 +145,40 @@
    <section xml:id="module-services-keycloak-themes">
      <title>Themes</title>
      <para>
-        You can package custom themes and make them visible to Keycloak via
-        <xref linkend="opt-services.keycloak.themes" />
-        option. See the <link xlink:href="https://www.keycloak.org/docs/latest/server_development/#_themes">
+        You can package custom themes and make them visible to
+        Keycloak through <xref linkend="opt-services.keycloak.themes"
+        />. See the <link
+        xlink:href="https://www.keycloak.org/docs/latest/server_development/#_themes">
         Themes section of the Keycloak Server Development Guide</link>
-        and respective NixOS option description for more information.
+        and the description of the aforementioned NixOS option for
+        more information.
      </para>
    </section>
 
-   <section xml:id="module-services-keycloak-extra-config">
-     <title>Additional configuration</title>
+   <section xml:id="module-services-keycloak-settings">
+     <title>Configuration file settings</title>
      <para>
-       Additional Keycloak configuration options, for which no
-       explicit <productname>NixOS</productname> options are provided,
-       can be set in <xref linkend="opt-services.keycloak.extraConfig" />.
+       Keycloak server configuration parameters can be set in <xref
+       linkend="opt-services.keycloak.settings" />. These correspond
+       directly to options in
+       <filename>conf/keycloak.conf</filename>. Some of the most
+       important parameters are documented as suboptions, the rest can
+       be found in the <link
+       xlink:href="https://www.keycloak.org/server/all-config">All
+       configuration section of the Keycloak Server Installation and
+       Configuration Guide</link>.
      </para>
 
      <para>
-       Options are expressed as a Nix attribute set which matches the
-       structure of the jboss-cli configuration. The configuration is
-       effectively overlayed on top of the default configuration
-       shipped with Keycloak. To remove existing nodes and undefine
-       attributes from the default configuration, set them to
-       <literal>null</literal>.
-     </para>
-     <para>
-       For example, the following script, which removes the hostname
-       provider <literal>default</literal>, adds the deprecated
-       hostname provider <literal>fixed</literal> and defines it the
-       default:
-
-<programlisting>
-/subsystem=keycloak-server/spi=hostname/provider=default:remove()
-/subsystem=keycloak-server/spi=hostname/provider=fixed:add(enabled = true, properties = { hostname = "keycloak.example.com" })
-/subsystem=keycloak-server/spi=hostname:write-attribute(name=default-provider, value="fixed")
-</programlisting>
-
-       would be expressed as
-
-<programlisting>
-services.keycloak.extraConfig = {
-  "subsystem=keycloak-server" = {
-    "spi=hostname" = {
-      "provider=default" = null;
-      "provider=fixed" = {
-        enabled = true;
-        properties.hostname = "keycloak.example.com";
-      };
-      default-provider = "fixed";
-    };
-  };
-};
-</programlisting>
-     </para>
-     <para>
-       You can discover available options by using the <link
-       xlink:href="http://docs.wildfly.org/21/Admin_Guide.html#Command_Line_Interface">jboss-cli.sh</link>
-       program and by referring to the <link
-       xlink:href="https://www.keycloak.org/docs/latest/server_installation/index.html">Keycloak
-       Server Installation and Configuration Guide</link>.
+       Options containing secret data should be set to an attribute
+       set containing the attribute <literal>_secret</literal> - a
+       string pointing to a file containing the value the option
+       should be set to. See the description of <xref
+       linkend="opt-services.keycloak.settings" /> for an example.
      </para>
    </section>
 
+
    <section xml:id="module-services-keycloak-example-config">
      <title>Example configuration</title>
      <para>
@@ -208,9 +186,11 @@ services.keycloak.extraConfig = {
 <programlisting>
 services.keycloak = {
   <link linkend="opt-services.keycloak.enable">enable</link> = true;
+  settings = {
+    <link linkend="opt-services.keycloak.settings.hostname">hostname</link> = "keycloak.example.com";
+    <link linkend="opt-services.keycloak.settings.hostname-strict-backchannel">hostname-strict-backchannel</link> = true;
+  };
   <link linkend="opt-services.keycloak.initialAdminPassword">initialAdminPassword</link> = "e6Wcm0RrtegMEHl";  # change on first login
-  <link linkend="opt-services.keycloak.frontendUrl">frontendUrl</link> = "https://keycloak.example.com/auth";
-  <link linkend="opt-services.keycloak.forceBackendUrlToFrontendUrl">forceBackendUrlToFrontendUrl</link> = true;
   <link linkend="opt-services.keycloak.sslCertificate">sslCertificate</link> = "/run/keys/ssl_cert";
   <link linkend="opt-services.keycloak.sslCertificateKey">sslCertificateKey</link> = "/run/keys/ssl_key";
   <link linkend="opt-services.keycloak.database.passwordFile">database.passwordFile</link> = "/run/keys/db_password";
diff --git a/nixos/modules/services/web-apps/komga.nix b/nixos/modules/services/web-apps/komga.nix
new file mode 100644
index 00000000000..31f475fc7b0
--- /dev/null
+++ b/nixos/modules/services/web-apps/komga.nix
@@ -0,0 +1,99 @@
+{ config, pkgs, lib, ... }:
+
+with lib;
+
+let
+  cfg = config.services.komga;
+
+in {
+  options = {
+    services.komga = {
+      enable = mkEnableOption (lib.mdDoc "Komga, a free and open source comics/mangas media server");
+
+      port = mkOption {
+        type = types.port;
+        default = 8080;
+        description = lib.mdDoc ''
+          The port that Komga will listen on.
+        '';
+      };
+
+      user = mkOption {
+        type = types.str;
+        default = "komga";
+        description = lib.mdDoc ''
+          User account under which Komga runs.
+        '';
+      };
+
+      group = mkOption {
+        type = types.str;
+        default = "komga";
+        description = lib.mdDoc ''
+          Group under which Komga runs.
+        '';
+      };
+
+      stateDir = mkOption {
+        type = types.str;
+        default = "/var/lib/komga";
+        description = lib.mdDoc ''
+          State and configuration directory Komga will use.
+        '';
+      };
+
+      openFirewall = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Whether to open the firewall for the port in {option}`services.komga.port`.
+        '';
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ];
+
+    users.groups = mkIf (cfg.group == "komga") {
+      komga = {};
+    };
+
+    users.users = mkIf (cfg.user == "komga") {
+      komga = {
+        group = cfg.group;
+        home = cfg.stateDir;
+        description = "Komga Daemon user";
+        isSystemUser = true;
+      };
+    };
+
+    systemd.services.komga = {
+      environment = {
+        SERVER_PORT = builtins.toString cfg.port;
+        KOMGA_CONFIGDIR = cfg.stateDir;
+      };
+
+      description = "Komga is a free and open source comics/mangas media server";
+
+      wantedBy = [ "multi-user.target" ];
+      wants = [ "network-online.target" ];
+      after = [ "network-online.target" ];
+
+      serviceConfig = {
+        User = cfg.user;
+        Group = cfg.group;
+
+        Type = "simple";
+        Restart = "on-failure";
+        ExecStart = "${pkgs.komga}/bin/komga";
+
+        StateDirectory = mkIf (cfg.stateDir == "/var/lib/komga") "komga";
+      };
+
+    };
+  };
+
+  meta.maintainers = with maintainers; [ govanify ];
+}
diff --git a/nixos/modules/services/web-apps/lemmy.md b/nixos/modules/services/web-apps/lemmy.md
index e6599cd843e..faafe096d13 100644
--- a/nixos/modules/services/web-apps/lemmy.md
+++ b/nixos/modules/services/web-apps/lemmy.md
@@ -13,13 +13,10 @@ services.lemmy = {
     hostname = "lemmy.union.rocks";
     database.createLocally = true;
   };
-  jwtSecretPath = "/run/secrets/lemmyJwt";
   caddy.enable = true;
 }
 ```
 
-(note that you can use something like agenix to get your secret jwt to the specified path)
-
 this will start the backend on port 8536 and the frontend on port 1234.
 It will expose your instance with a caddy reverse proxy to the hostname you've provided.
 Postgres will be initialized on that same instance automatically.
diff --git a/nixos/modules/services/web-apps/lemmy.nix b/nixos/modules/services/web-apps/lemmy.nix
index 7cd2357c455..267584dd0ca 100644
--- a/nixos/modules/services/web-apps/lemmy.nix
+++ b/nixos/modules/services/web-apps/lemmy.nix
@@ -10,28 +10,29 @@ in
   # `pandoc lemmy.md -t docbook --top-level-division=chapter --extract-media=media -f markdown+smart > lemmy.xml`
   meta.doc = ./lemmy.xml;
 
-  options.services.lemmy = {
+  imports = [
+    (mkRemovedOptionModule [ "services" "lemmy" "jwtSecretPath" ] "As of v0.13.0, Lemmy auto-generates the JWT secret.")
+  ];
 
-    enable = mkEnableOption "lemmy a federated alternative to reddit in rust";
+  options.services.lemmy = {
 
-    jwtSecretPath = mkOption {
-      type = types.path;
-      description = "Path to read the jwt secret from.";
-    };
+    enable = mkEnableOption (lib.mdDoc "lemmy a federated alternative to reddit in rust");
 
     ui = {
       port = mkOption {
         type = types.port;
         default = 1234;
-        description = "Port where lemmy-ui should listen for incoming requests.";
+        description = lib.mdDoc "Port where lemmy-ui should listen for incoming requests.";
       };
     };
 
-    caddy.enable = mkEnableOption "exposing lemmy with the caddy reverse proxy";
+    caddy.enable = mkEnableOption (lib.mdDoc "exposing lemmy with the caddy reverse proxy");
+
+    database.createLocally = mkEnableOption (lib.mdDoc "creation of database on the instance");
 
     settings = mkOption {
       default = { };
-      description = "Lemmy configuration";
+      description = lib.mdDoc "Lemmy configuration";
 
       type = types.submodule {
         freeformType = settingsFormat.type;
@@ -39,43 +40,37 @@ in
         options.hostname = mkOption {
           type = types.str;
           default = null;
-          description = "The domain name of your instance (eg 'lemmy.ml').";
+          description = lib.mdDoc "The domain name of your instance (eg 'lemmy.ml').";
         };
 
         options.port = mkOption {
           type = types.port;
           default = 8536;
-          description = "Port where lemmy should listen for incoming requests.";
+          description = lib.mdDoc "Port where lemmy should listen for incoming requests.";
         };
 
         options.federation = {
-          enabled = mkEnableOption "activitypub federation";
+          enabled = mkEnableOption (lib.mdDoc "activitypub federation");
         };
 
         options.captcha = {
           enabled = mkOption {
             type = types.bool;
             default = true;
-            description = "Enable Captcha.";
+            description = lib.mdDoc "Enable Captcha.";
           };
           difficulty = mkOption {
             type = types.enum [ "easy" "medium" "hard" ];
             default = "medium";
-            description = "The difficultly of the captcha to solve.";
+            description = lib.mdDoc "The difficultly of the captcha to solve.";
           };
         };
-
-        options.database.createLocally = mkEnableOption "creation of database on the instance";
-
       };
     };
 
   };
 
   config =
-    let
-      localPostgres = (cfg.settings.database.host == "localhost" || cfg.settings.database.host == "/run/postgresql");
-    in
     lib.mkIf cfg.enable {
       services.lemmy.settings = (mapAttrs (name: mkDefault)
         {
@@ -102,8 +97,13 @@ in
         };
       });
 
-      services.postgresql = mkIf localPostgres {
-        enable = mkDefault true;
+      services.postgresql = mkIf cfg.database.createLocally {
+        enable = true;
+        ensureDatabases = [ cfg.settings.database.database ];
+        ensureUsers = [{
+          name = cfg.settings.database.user;
+          ensurePermissions."DATABASE ${cfg.settings.database.database}" = "ALL PRIVILEGES";
+        }];
       };
 
       services.pict-rs.enable = true;
@@ -117,7 +117,7 @@ in
               file_server
             }
             @for_backend {
-              path /api/* /pictrs/* feeds/* nodeinfo/*
+              path /api/* /pictrs/* /feeds/* /nodeinfo/*
             }
             handle @for_backend {
               reverse_proxy 127.0.0.1:${toString cfg.settings.port}
@@ -143,7 +143,7 @@ in
       };
 
       assertions = [{
-        assertion = cfg.settings.database.createLocally -> localPostgres;
+        assertion = cfg.database.createLocally -> cfg.settings.database.host == "localhost" || cfg.settings.database.host == "/run/postgresql";
         message = "if you want to create the database locally, you need to use a local database";
       }];
 
@@ -164,22 +164,15 @@ in
 
         wantedBy = [ "multi-user.target" ];
 
-        after = [ "pict-rs.service " ] ++ lib.optionals cfg.settings.database.createLocally [ "lemmy-postgresql.service" ];
-
-        requires = lib.optionals cfg.settings.database.createLocally [ "lemmy-postgresql.service" ];
+        after = [ "pict-rs.service" ] ++ lib.optionals cfg.database.createLocally [ "postgresql.service" ];
 
-        # script is needed here since loadcredential is not accessible on ExecPreStart
-        script = ''
-          ${pkgs.coreutils}/bin/install -m 600 ${settingsFormat.generate "config.hjson" cfg.settings} /run/lemmy/config.hjson
-          jwtSecret="$(< $CREDENTIALS_DIRECTORY/jwt_secret )"
-          ${pkgs.jq}/bin/jq ".jwt_secret = \"$jwtSecret\"" /run/lemmy/config.hjson | ${pkgs.moreutils}/bin/sponge /run/lemmy/config.hjson
-          ${pkgs.lemmy-server}/bin/lemmy_server
-        '';
+        requires = lib.optionals cfg.database.createLocally [ "postgresql.service" ];
 
         serviceConfig = {
           DynamicUser = true;
           RuntimeDirectory = "lemmy";
-          LoadCredential = "jwt_secret:${cfg.jwtSecretPath}";
+          ExecStartPre = "${pkgs.coreutils}/bin/install -m 600 ${settingsFormat.generate "config.hjson" cfg.settings} /run/lemmy/config.hjson";
+          ExecStart = "${pkgs.lemmy-server}/bin/lemmy_server";
         };
       };
 
@@ -210,27 +203,6 @@ in
           ExecStart = "${pkgs.nodejs}/bin/node ${pkgs.lemmy-ui}/dist/js/server.js";
         };
       };
-
-      systemd.services.lemmy-postgresql = mkIf cfg.settings.database.createLocally {
-        description = "Lemmy postgresql db";
-        after = [ "postgresql.service" ];
-        partOf = [ "lemmy.service" ];
-        script = with cfg.settings.database; ''
-          PSQL() {
-            ${config.services.postgresql.package}/bin/psql --port=${toString cfg.settings.database.port} "$@"
-          }
-          # check if the database already exists
-          if ! PSQL -lqt | ${pkgs.coreutils}/bin/cut -d \| -f 1 | ${pkgs.gnugrep}/bin/grep -qw ${database} ; then
-            PSQL -tAc "CREATE ROLE ${user} WITH LOGIN;"
-            PSQL -tAc "CREATE DATABASE ${database} WITH OWNER ${user};"
-          fi
-        '';
-        serviceConfig = {
-          User = config.services.postgresql.superUser;
-          Type = "oneshot";
-          RemainAfterExit = true;
-        };
-      };
     };
 
 }
diff --git a/nixos/modules/services/web-apps/lemmy.xml b/nixos/modules/services/web-apps/lemmy.xml
index 0be9fb8aefa..f04316b3c51 100644
--- a/nixos/modules/services/web-apps/lemmy.xml
+++ b/nixos/modules/services/web-apps/lemmy.xml
@@ -8,22 +8,17 @@
     <para>
       the minimum to start lemmy is
     </para>
-    <programlisting language="bash">
+    <programlisting language="nix">
 services.lemmy = {
   enable = true;
   settings = {
     hostname = &quot;lemmy.union.rocks&quot;;
     database.createLocally = true;
   };
-  jwtSecretPath = &quot;/run/secrets/lemmyJwt&quot;;
   caddy.enable = true;
 }
 </programlisting>
     <para>
-      (note that you can use something like agenix to get your secret
-      jwt to the specified path)
-    </para>
-    <para>
       this will start the backend on port 8536 and the frontend on port
       1234. It will expose your instance with a caddy reverse proxy to
       the hostname you’ve provided. Postgres will be initialized on that
diff --git a/nixos/modules/services/web-apps/limesurvey.nix b/nixos/modules/services/web-apps/limesurvey.nix
index 5ccd742a303..f6a1b559524 100644
--- a/nixos/modules/services/web-apps/limesurvey.nix
+++ b/nixos/modules/services/web-apps/limesurvey.nix
@@ -32,48 +32,48 @@ in
   # interface
 
   options.services.limesurvey = {
-    enable = mkEnableOption "Limesurvey web application.";
+    enable = mkEnableOption (lib.mdDoc "Limesurvey web application.");
 
     database = {
       type = mkOption {
         type = types.enum [ "mysql" "pgsql" "odbc" "mssql" ];
         example = "pgsql";
         default = "mysql";
-        description = "Database engine to use.";
+        description = lib.mdDoc "Database engine to use.";
       };
 
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Database host address.";
+        description = lib.mdDoc "Database host address.";
       };
 
       port = mkOption {
         type = types.int;
         default = if cfg.database.type == "pgsql" then 5442 else 3306;
         defaultText = literalExpression "3306";
-        description = "Database host port.";
+        description = lib.mdDoc "Database host port.";
       };
 
       name = mkOption {
         type = types.str;
         default = "limesurvey";
-        description = "Database name.";
+        description = lib.mdDoc "Database name.";
       };
 
       user = mkOption {
         type = types.str;
         default = "limesurvey";
-        description = "Database user.";
+        description = lib.mdDoc "Database user.";
       };
 
       passwordFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/run/keys/limesurvey-dbpassword";
-        description = ''
+        description = lib.mdDoc ''
           A file containing the password corresponding to
-          <option>database.user</option>.
+          {option}`database.user`.
         '';
       };
 
@@ -85,14 +85,14 @@ in
           else null
         ;
         defaultText = literalExpression "/run/mysqld/mysqld.sock";
-        description = "Path to the unix socket file to use for authentication.";
+        description = lib.mdDoc "Path to the unix socket file to use for authentication.";
       };
 
       createLocally = mkOption {
         type = types.bool;
         default = cfg.database.type == "mysql";
         defaultText = literalExpression "true";
-        description = ''
+        description = lib.mdDoc ''
           Create the database and database user locally.
           This currently only applies if database type "mysql" is selected.
         '';
@@ -109,9 +109,9 @@ in
           enableACME = true;
         }
       '';
-      description = ''
-        Apache configuration can be done by adapting <literal>services.httpd.virtualHosts.&lt;name&gt;</literal>.
-        See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
+      description = lib.mdDoc ''
+        Apache configuration can be done by adapting `services.httpd.virtualHosts.<name>`.
+        See [](#opt-services.httpd.virtualHosts) for further information.
       '';
     };
 
@@ -125,8 +125,8 @@ in
         "pm.max_spare_servers" = 4;
         "pm.max_requests" = 500;
       };
-      description = ''
-        Options for the LimeSurvey PHP pool. See the documentation on <literal>php-fpm.conf</literal>
+      description = lib.mdDoc ''
+        Options for the LimeSurvey PHP pool. See the documentation on `php-fpm.conf`
         for details on configuration directives.
       '';
     };
@@ -134,9 +134,9 @@ in
     config = mkOption {
       type = configType;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         LimeSurvey configuration. Refer to
-        <link xlink:href="https://manual.limesurvey.org/Optional_settings"/>
+        <https://manual.limesurvey.org/Optional_settings>
         for details on supported values.
       '';
     };
diff --git a/nixos/modules/services/web-apps/mastodon.nix b/nixos/modules/services/web-apps/mastodon.nix
index 8208c85bfd7..a221186adf6 100644
--- a/nixos/modules/services/web-apps/mastodon.nix
+++ b/nixos/modules/services/web-apps/mastodon.nix
@@ -9,6 +9,8 @@ let
     RAILS_ENV = "production";
     NODE_ENV = "production";
 
+    LD_PRELOAD = "${pkgs.jemalloc}/lib/libjemalloc.so";
+
     # mastodon-web concurrency.
     WEB_CONCURRENCY = toString cfg.webProcesses;
     MAX_THREADS = toString cfg.webThreads;
@@ -102,51 +104,51 @@ in {
 
   options = {
     services.mastodon = {
-      enable = lib.mkEnableOption "Mastodon, a federated social network server";
+      enable = lib.mkEnableOption (lib.mdDoc "Mastodon, a federated social network server");
 
       configureNginx = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Configure nginx as a reverse proxy for mastodon.
           Note that this makes some assumptions on your setup, and sets settings that will
           affect other virtualHosts running on your nginx instance, if any.
           Alternatively you can configure a reverse-proxy of your choice to serve these paths:
 
-          <code>/ -> $(nix-instantiate --eval '&lt;nixpkgs&gt;' -A mastodon.outPath)/public</code>
+          `/ -> $(nix-instantiate --eval '<nixpkgs>' -A mastodon.outPath)/public`
 
-          <code>/ -> 127.0.0.1:{{ webPort }} </code>(If there was no file in the directory above.)
+          `/ -> 127.0.0.1:{{ webPort }} `(If there was no file in the directory above.)
 
-          <code>/system/ -> /var/lib/mastodon/public-system/</code>
+          `/system/ -> /var/lib/mastodon/public-system/`
 
-          <code>/api/v1/streaming/ -> 127.0.0.1:{{ streamingPort }}</code>
+          `/api/v1/streaming/ -> 127.0.0.1:{{ streamingPort }}`
 
           Make sure that websockets are forwarded properly. You might want to set up caching
           of some requests. Take a look at mastodon's provided nginx configuration at
-          <code>https://github.com/tootsuite/mastodon/blob/master/dist/nginx.conf</code>.
+          `https://github.com/mastodon/mastodon/blob/master/dist/nginx.conf`.
         '';
         type = lib.types.bool;
         default = false;
       };
 
       user = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           User under which mastodon runs. If it is set to "mastodon",
           that user will be created, otherwise it should be set to the
           name of a user created elsewhere.  In both cases,
-          <package>mastodon</package> and a package containing only
-          the shell script <code>mastodon-env</code> will be added to
+          `mastodon` and a package containing only
+          the shell script `mastodon-env` will be added to
           the user's package set. To run a command from
-          <package>mastodon</package> such as <code>tootctl</code>
+          `mastodon` such as `tootctl`
           with the environment configured by this module use
-          <code>mastodon-env</code>, as in:
+          `mastodon-env`, as in:
 
-          <code>mastodon-env tootctl accounts create newuser --email newuser@example.com</code>
+          `mastodon-env tootctl accounts create newuser --email newuser@example.com`
         '';
         type = lib.types.str;
         default = "mastodon";
       };
 
       group = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Group under which mastodon runs.
         '';
         type = lib.types.str;
@@ -154,12 +156,12 @@ in {
       };
 
       streamingPort = lib.mkOption {
-        description = "TCP port used by the mastodon-streaming service.";
+        description = lib.mdDoc "TCP port used by the mastodon-streaming service.";
         type = lib.types.port;
         default = 55000;
       };
       streamingProcesses = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Processes used by the mastodon-streaming service.
           Defaults to the number of CPU cores minus one.
         '';
@@ -168,41 +170,41 @@ in {
       };
 
       webPort = lib.mkOption {
-        description = "TCP port used by the mastodon-web service.";
+        description = lib.mdDoc "TCP port used by the mastodon-web service.";
         type = lib.types.port;
         default = 55001;
       };
       webProcesses = lib.mkOption {
-        description = "Processes used by the mastodon-web service.";
+        description = lib.mdDoc "Processes used by the mastodon-web service.";
         type = lib.types.int;
         default = 2;
       };
       webThreads = lib.mkOption {
-        description = "Threads per process used by the mastodon-web service.";
+        description = lib.mdDoc "Threads per process used by the mastodon-web service.";
         type = lib.types.int;
         default = 5;
       };
 
       sidekiqPort = lib.mkOption {
-        description = "TCP port used by the mastodon-sidekiq service.";
+        description = lib.mdDoc "TCP port used by the mastodon-sidekiq service.";
         type = lib.types.port;
         default = 55002;
       };
       sidekiqThreads = lib.mkOption {
-        description = "Worker threads used by the mastodon-sidekiq service.";
+        description = lib.mdDoc "Worker threads used by the mastodon-sidekiq service.";
         type = lib.types.int;
         default = 25;
       };
 
       vapidPublicKeyFile = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Path to file containing the public key used for Web Push
           Voluntary Application Server Identification.  A new keypair can
           be generated by running:
 
-          <code>nix build -f '&lt;nixpkgs&gt;' mastodon; cd result; bin/rake webpush:generate_keys</code>
+          `nix build -f '<nixpkgs>' mastodon; cd result; bin/rake webpush:generate_keys`
 
-          If <option>mastodon.vapidPrivateKeyFile</option>does not
+          If {option}`mastodon.vapidPrivateKeyFile`does not
           exist, it and this file will be created with a new keypair.
         '';
         default = "/var/lib/mastodon/secrets/vapid-public-key";
@@ -210,17 +212,17 @@ in {
       };
 
       localDomain = lib.mkOption {
-        description = "The domain serving your Mastodon instance.";
+        description = lib.mdDoc "The domain serving your Mastodon instance.";
         example = "social.example.org";
         type = lib.types.str;
       };
 
       secretKeyBaseFile = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Path to file containing the secret key base.
           A new secret key base can be generated by running:
 
-          <code>nix build -f '&lt;nixpkgs&gt;' mastodon; cd result; bin/rake secret</code>
+          `nix build -f '<nixpkgs>' mastodon; cd result; bin/rake secret`
 
           If this file does not exist, it will be created with a new secret key base.
         '';
@@ -229,11 +231,11 @@ in {
       };
 
       otpSecretFile = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Path to file containing the OTP secret.
           A new OTP secret can be generated by running:
 
-          <code>nix build -f '&lt;nixpkgs&gt;' mastodon; cd result; bin/rake secret</code>
+          `nix build -f '<nixpkgs>' mastodon; cd result; bin/rake secret`
 
           If this file does not exist, it will be created with a new OTP secret.
         '';
@@ -242,12 +244,12 @@ in {
       };
 
       vapidPrivateKeyFile = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Path to file containing the private key used for Web Push
           Voluntary Application Server Identification.  A new keypair can
           be generated by running:
 
-          <code>nix build -f '&lt;nixpkgs&gt;' mastodon; cd result; bin/rake webpush:generate_keys</code>
+          `nix build -f '<nixpkgs>' mastodon; cd result; bin/rake webpush:generate_keys`
 
           If this file does not exist, it will be created with a new
           private key.
@@ -257,7 +259,7 @@ in {
       };
 
       trustedProxy = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           You need to set it to the IP from which your reverse proxy sends requests to Mastodon's web process,
           otherwise Mastodon will record the reverse proxy's own IP as the IP of all requests, which would be
           bad because IP addresses are used for important rate limits and security functions.
@@ -267,7 +269,7 @@ in {
       };
 
       enableUnixSocket = lib.mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Instead of binding to an IP address like 127.0.0.1, you may bind to a Unix socket. This variable
           is process-specific, e.g. you need different values for every process, and it works for both web (Puma)
           processes and streaming API (Node.js) processes.
@@ -278,27 +280,27 @@ in {
 
       redis = {
         createLocally = lib.mkOption {
-          description = "Configure local Redis server for Mastodon.";
+          description = lib.mdDoc "Configure local Redis server for Mastodon.";
           type = lib.types.bool;
           default = true;
         };
 
         host = lib.mkOption {
-          description = "Redis host.";
+          description = lib.mdDoc "Redis host.";
           type = lib.types.str;
           default = "127.0.0.1";
         };
 
         port = lib.mkOption {
-          description = "Redis port.";
+          description = lib.mdDoc "Redis port.";
           type = lib.types.port;
-          default = 6379;
+          default = 31637;
         };
       };
 
       database = {
         createLocally = lib.mkOption {
-          description = "Configure local PostgreSQL database server for Mastodon.";
+          description = lib.mdDoc "Configure local PostgreSQL database server for Mastodon.";
           type = lib.types.bool;
           default = true;
         };
@@ -307,86 +309,88 @@ in {
           type = lib.types.str;
           default = "/run/postgresql";
           example = "192.168.23.42";
-          description = "Database host address or unix socket.";
+          description = lib.mdDoc "Database host address or unix socket.";
         };
 
         port = lib.mkOption {
-          type = lib.types.int;
+          type = lib.types.port;
           default = 5432;
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = lib.mkOption {
           type = lib.types.str;
           default = "mastodon";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = lib.mkOption {
           type = lib.types.str;
           default = "mastodon";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         passwordFile = lib.mkOption {
           type = lib.types.nullOr lib.types.path;
           default = "/var/lib/mastodon/secrets/db-password";
           example = "/run/keys/mastodon-db-password";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
       };
 
       smtp = {
         createLocally = lib.mkOption {
-          description = "Configure local Postfix SMTP server for Mastodon.";
+          description = lib.mdDoc "Configure local Postfix SMTP server for Mastodon.";
           type = lib.types.bool;
           default = true;
         };
 
         authenticate = lib.mkOption {
-          description = "Authenticate with the SMTP server using username and password.";
+          description = lib.mdDoc "Authenticate with the SMTP server using username and password.";
           type = lib.types.bool;
           default = false;
         };
 
         host = lib.mkOption {
-          description = "SMTP host used when sending emails to users.";
+          description = lib.mdDoc "SMTP host used when sending emails to users.";
           type = lib.types.str;
           default = "127.0.0.1";
         };
 
         port = lib.mkOption {
-          description = "SMTP port used when sending emails to users.";
+          description = lib.mdDoc "SMTP port used when sending emails to users.";
           type = lib.types.port;
           default = 25;
         };
 
         fromAddress = lib.mkOption {
-          description = ''"From" address used when sending Emails to users.'';
+          description = lib.mdDoc ''"From" address used when sending Emails to users.'';
           type = lib.types.str;
         };
 
         user = lib.mkOption {
-          description = "SMTP login name.";
-          type = lib.types.str;
+          type = lib.types.nullOr lib.types.str;
+          default = null;
+          example = "mastodon@example.com";
+          description = lib.mdDoc "SMTP login name.";
         };
 
         passwordFile = lib.mkOption {
-          description = ''
+          type = lib.types.nullOr lib.types.path;
+          default = null;
+          example = "/var/lib/mastodon/secrets/smtp-password";
+          description = lib.mdDoc ''
             Path to file containing the SMTP password.
           '';
-          default = "/var/lib/mastodon/secrets/smtp-password";
-          example = "/run/keys/mastodon-smtp-password";
-          type = lib.types.str;
         };
       };
 
       elasticsearch = {
         host = lib.mkOption {
-          description = ''
+          description = lib.mdDoc ''
             Elasticsearch host.
             If it is not null, Elasticsearch full text search will be enabled.
           '';
@@ -395,7 +399,7 @@ in {
         };
 
         port = lib.mkOption {
-          description = "Elasticsearch port.";
+          description = lib.mdDoc "Elasticsearch port.";
           type = lib.types.port;
           default = 9200;
         };
@@ -405,13 +409,13 @@ in {
         type = lib.types.package;
         default = pkgs.mastodon;
         defaultText = lib.literalExpression "pkgs.mastodon";
-        description = "Mastodon package to use.";
+        description = lib.mdDoc "Mastodon package to use.";
       };
 
       extraConfig = lib.mkOption {
         type = lib.types.attrs;
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Extra environment variables to pass to all mastodon services.
         '';
       };
@@ -419,10 +423,43 @@ in {
       automaticMigrations = lib.mkOption {
         type = lib.types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Do automatic database migrations.
         '';
       };
+
+      mediaAutoRemove = {
+        enable = lib.mkOption {
+          type = lib.types.bool;
+          default = true;
+          example = false;
+          description = lib.mdDoc ''
+            Automatically remove remote media attachments and preview cards older than the configured amount of days.
+
+            Recommended in https://docs.joinmastodon.org/admin/setup/.
+          '';
+        };
+
+        startAt = lib.mkOption {
+          type = lib.types.str;
+          default = "daily";
+          example = "hourly";
+          description = lib.mdDoc ''
+            How often to remove remote media.
+
+            The format is described in {manpage}`systemd.time(7)`.
+          '';
+        };
+
+        olderThanDays = lib.mkOption {
+          type = lib.types.int;
+          default = 30;
+          example = 14;
+          description = lib.mdDoc ''
+            How old remote media needs to be in order to be removed.
+          '';
+        };
+      };
     };
   };
 
@@ -432,6 +469,20 @@ in {
         assertion = databaseActuallyCreateLocally -> (cfg.user == cfg.database.user);
         message = ''For local automatic database provisioning (services.mastodon.database.createLocally == true) with peer authentication (services.mastodon.database.host == "/run/postgresql") to work services.mastodon.user and services.mastodon.database.user must be identical.'';
       }
+      {
+        assertion = cfg.smtp.authenticate -> (cfg.smtp.user != null);
+        message = ''
+          <option>services.mastodon.smtp.user</option> needs to be set if
+            <option>services.mastodon.smtp.authenticate</option> is enabled.
+        '';
+      }
+      {
+        assertion = cfg.smtp.authenticate -> (cfg.smtp.passwordFile != null);
+        message = ''
+          <option>services.mastodon.smtp.passwordFile</option> needs to be set if
+            <option>services.mastodon.smtp.authenticate</option> is enabled.
+        '';
+      }
     ];
 
     systemd.services.mastodon-init-dirs = {
@@ -473,7 +524,6 @@ in {
       } // cfgService;
 
       after = [ "network.target" ];
-      wantedBy = [ "multi-user.target" ];
     };
 
     systemd.services.mastodon-init-db = lib.mkIf cfg.automaticMigrations {
@@ -498,16 +548,21 @@ in {
         # System Call Filtering
         SystemCallFilter = [ ("~" + lib.concatStringsSep " " (systemCallsList ++ [ "@resources" ])) "@chown" "pipe" "pipe2" ];
       } // cfgService;
-      after = [ "mastodon-init-dirs.service" "network.target" ] ++ (if databaseActuallyCreateLocally then [ "postgresql.service" ] else []);
-      wantedBy = [ "multi-user.target" ];
+      after = [ "network.target" "mastodon-init-dirs.service" ]
+        ++ lib.optional databaseActuallyCreateLocally "postgresql.service";
+      requires = [ "mastodon-init-dirs.service" ]
+        ++ lib.optional databaseActuallyCreateLocally "postgresql.service";
     };
 
     systemd.services.mastodon-streaming = {
-      after = [ "network.target" ]
-        ++ (if databaseActuallyCreateLocally then [ "postgresql.service" ] else [])
-        ++ (if cfg.automaticMigrations then [ "mastodon-init-db.service" ] else [ "mastodon-init-dirs.service" ]);
-      description = "Mastodon streaming";
+      after = [ "network.target" "mastodon-init-dirs.service" ]
+        ++ lib.optional databaseActuallyCreateLocally "postgresql.service"
+        ++ lib.optional cfg.automaticMigrations "mastodon-init-db.service";
+      requires = [ "mastodon-init-dirs.service" ]
+        ++ lib.optional databaseActuallyCreateLocally "postgresql.service"
+        ++ lib.optional cfg.automaticMigrations "mastodon-init-db.service";
       wantedBy = [ "multi-user.target" ];
+      description = "Mastodon streaming";
       environment = env // (if cfg.enableUnixSocket
         then { SOCKET = "/run/mastodon-streaming/streaming.socket"; }
         else { PORT = toString(cfg.streamingPort); }
@@ -527,11 +582,14 @@ in {
     };
 
     systemd.services.mastodon-web = {
-      after = [ "network.target" ]
-        ++ (if databaseActuallyCreateLocally then [ "postgresql.service" ] else [])
-        ++ (if cfg.automaticMigrations then [ "mastodon-init-db.service" ] else [ "mastodon-init-dirs.service" ]);
-      description = "Mastodon web";
+      after = [ "network.target" "mastodon-init-dirs.service" ]
+        ++ lib.optional databaseActuallyCreateLocally "postgresql.service"
+        ++ lib.optional cfg.automaticMigrations "mastodon-init-db.service";
+      requires = [ "mastodon-init-dirs.service" ]
+        ++ lib.optional databaseActuallyCreateLocally "postgresql.service"
+        ++ lib.optional cfg.automaticMigrations "mastodon-init-db.service";
       wantedBy = [ "multi-user.target" ];
+      description = "Mastodon web";
       environment = env // (if cfg.enableUnixSocket
         then { SOCKET = "/run/mastodon-web/web.socket"; }
         else { PORT = toString(cfg.webPort); }
@@ -552,11 +610,14 @@ in {
     };
 
     systemd.services.mastodon-sidekiq = {
-      after = [ "network.target" ]
-        ++ (if databaseActuallyCreateLocally then [ "postgresql.service" ] else [])
-        ++ (if cfg.automaticMigrations then [ "mastodon-init-db.service" ] else [ "mastodon-init-dirs.service" ]);
-      description = "Mastodon sidekiq";
+      after = [ "network.target" "mastodon-init-dirs.service" ]
+        ++ lib.optional databaseActuallyCreateLocally "postgresql.service"
+        ++ lib.optional cfg.automaticMigrations "mastodon-init-db.service";
+      requires = [ "mastodon-init-dirs.service" ]
+        ++ lib.optional databaseActuallyCreateLocally "postgresql.service"
+        ++ lib.optional cfg.automaticMigrations "mastodon-init-db.service";
       wantedBy = [ "multi-user.target" ];
+      description = "Mastodon sidekiq";
       environment = env // {
         PORT = toString(cfg.sidekiqPort);
         DB_POOL = toString cfg.sidekiqThreads;
@@ -573,6 +634,22 @@ in {
       path = with pkgs; [ file imagemagick ffmpeg ];
     };
 
+    systemd.services.mastodon-media-auto-remove = lib.mkIf cfg.mediaAutoRemove.enable {
+      description = "Mastodon media auto remove";
+      environment = env;
+      serviceConfig = {
+        Type = "oneshot";
+        EnvironmentFile = "/var/lib/mastodon/.secrets_env";
+      } // cfgService;
+      script = let
+        olderThanDays = toString cfg.mediaAutoRemove.olderThanDays;
+      in ''
+        ${cfg.package}/bin/tootctl media remove --days=${olderThanDays}
+        ${cfg.package}/bin/tootctl preview_cards remove --days=${olderThanDays}
+      '';
+      startAt = cfg.mediaAutoRemove.startAt;
+    };
+
     services.nginx = lib.mkIf cfg.configureNginx {
       enable = true;
       recommendedProxySettings = true; # required for redirections to work
@@ -603,8 +680,10 @@ in {
       enable = true;
       hostname = lib.mkDefault "${cfg.localDomain}";
     };
-    services.redis = lib.mkIf (cfg.redis.createLocally && cfg.redis.host == "127.0.0.1") {
+    services.redis.servers.mastodon = lib.mkIf (cfg.redis.createLocally && cfg.redis.host == "127.0.0.1") {
       enable = true;
+      port = cfg.redis.port;
+      bind = "127.0.0.1";
     };
     services.postgresql = lib.mkIf databaseActuallyCreateLocally {
       enable = true;
@@ -625,7 +704,7 @@ in {
           inherit (cfg) group;
         };
       })
-      (lib.attrsets.setAttrByPath [ cfg.user "packages" ] [ cfg.package mastodonEnv ])
+      (lib.attrsets.setAttrByPath [ cfg.user "packages" ] [ cfg.package mastodonEnv pkgs.imagemagick ])
     ];
 
     users.groups.${cfg.group}.members = lib.optional cfg.configureNginx config.services.nginx.user;
diff --git a/nixos/modules/services/web-apps/matomo.nix b/nixos/modules/services/web-apps/matomo.nix
index c6d4ed6d39d..117d540ba36 100644
--- a/nixos/modules/services/web-apps/matomo.nix
+++ b/nixos/modules/services/web-apps/matomo.nix
@@ -12,8 +12,6 @@ let
   phpExecutionUnit = "phpfpm-${pool}";
   databaseService = "mysql.service";
 
-  fqdn = if config.networking.domain != null then config.networking.fqdn else config.networking.hostName;
-
 in {
   imports = [
     (mkRenamedOptionModule [ "services" "piwik" "enable" ] [ "services" "matomo" "enable" ])
@@ -32,7 +30,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable Matomo web analytics with php-fpm backend.
           Either the nginx option or the webServerUser option is mandatory.
         '';
@@ -40,7 +38,7 @@ in {
 
       package = mkOption {
         type = types.package;
-        description = ''
+        description = lib.mdDoc ''
           Matomo package for the service to use.
           This can be used to point to newer releases from nixos-unstable,
           as they don't get backported if they are not security-relevant.
@@ -53,8 +51,8 @@ in {
         type = types.nullOr types.str;
         default = null;
         example = "lighttpd";
-        description = ''
-          Name of the web server user that forwards requests to <option>services.phpfpm.pools.&lt;name&gt;.socket</option> the fastcgi socket for Matomo if the nginx
+        description = lib.mdDoc ''
+          Name of the web server user that forwards requests to {option}`services.phpfpm.pools.<name>.socket` the fastcgi socket for Matomo if the nginx
           option is not used. Either this option or the nginx option is mandatory.
           If you want to use another webserver than nginx, you need to set this to that server's user
           and pass fastcgi requests to `index.php`, `matomo.php` and `piwik.php` (legacy name) to this socket.
@@ -64,27 +62,25 @@ in {
       periodicArchiveProcessing = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Enable periodic archive processing, which generates aggregated reports from the visits.
 
           This means that you can safely disable browser triggers for Matomo archiving,
           and safely enable to delete old visitor logs.
           Before deleting visitor logs,
-          make sure though that you run <literal>systemctl start matomo-archive-processing.service</literal>
+          make sure though that you run `systemctl start matomo-archive-processing.service`
           at least once without errors if you have already collected data before.
         '';
       };
 
       hostname = mkOption {
         type = types.str;
-        default = "${user}.${fqdn}";
+        default = "${user}.${config.networking.fqdnOrHostName}";
         defaultText = literalExpression ''
-          if config.${options.networking.domain} != null
-          then "${user}.''${config.${options.networking.fqdn}}"
-          else "${user}.''${config.${options.networking.hostName}}"
+          "${user}.''${config.${options.networking.fqdnOrHostName}}"
         '';
         example = "matomo.yourdomain.org";
-        description = ''
+        description = lib.mdDoc ''
           URL of the host, without https prefix. You may want to change it if you
           run Matomo on a different URL than matomo.yourdomain.
         '';
@@ -112,12 +108,12 @@ in {
             enableACME = false;
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
             With this option, you can customize an nginx virtualHost which already has sensible defaults for Matomo.
             Either this option or the webServerUser option is mandatory.
             Set this to {} to just enable the virtualHost if you don't need any customization.
-            If enabled, then by default, the <option>serverName</option> is
-            <literal>''${user}.''${config.networking.hostName}.''${config.networking.domain}</literal>,
+            If enabled, then by default, the {option}`serverName` is
+            `''${user}.''${config.networking.hostName}.''${config.networking.domain}`,
             SSL is active, and certificates are acquired via ACME.
             If this is set to null (the default), no nginx virtualHost will be configured.
         '';
diff --git a/nixos/modules/services/web-apps/mattermost.nix b/nixos/modules/services/web-apps/mattermost.nix
index 2901f307dc5..71292c47d63 100644
--- a/nixos/modules/services/web-apps/mattermost.nix
+++ b/nixos/modules/services/web-apps/mattermost.nix
@@ -101,25 +101,25 @@ in
 {
   options = {
     services.mattermost = {
-      enable = mkEnableOption "Mattermost chat server";
+      enable = mkEnableOption (lib.mdDoc "Mattermost chat server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.mattermost;
         defaultText = "pkgs.mattermost";
-        description = "Mattermost derivation to use.";
+        description = lib.mdDoc "Mattermost derivation to use.";
       };
 
       statePath = mkOption {
         type = types.str;
         default = "/var/lib/mattermost";
-        description = "Mattermost working directory";
+        description = lib.mdDoc "Mattermost working directory";
       };
 
       siteUrl = mkOption {
         type = types.str;
         example = "https://chat.example.com";
-        description = ''
+        description = lib.mdDoc ''
           URL this Mattermost instance is reachable under, without trailing slash.
         '';
       };
@@ -127,14 +127,14 @@ in
       siteName = mkOption {
         type = types.str;
         default = "Mattermost";
-        description = "Name of this Mattermost site.";
+        description = lib.mdDoc "Name of this Mattermost site.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = ":8065";
         example = "[::1]:8065";
-        description = ''
+        description = lib.mdDoc ''
           Address and port this Mattermost instance listens to.
         '';
       };
@@ -142,7 +142,7 @@ in
       mutableConfig = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether the Mattermost config.json is writeable by Mattermost.
 
           Most of the settings can be edited in the system console of
@@ -159,7 +159,7 @@ in
       preferNixConfig = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           If both mutableConfig and this option are set, the Nix configuration
           will take precedence over any settings configured in the server
           console.
@@ -169,7 +169,7 @@ in
       extraConfig = mkOption {
         type = types.attrs;
         default = { };
-        description = ''
+        description = lib.mdDoc ''
           Addtional configuration options as Nix attribute set in config.json schema.
         '';
       };
@@ -178,7 +178,7 @@ in
         type = types.listOf (types.oneOf [types.path types.package]);
         default = [];
         example = "[ ./com.github.moussetc.mattermost.plugin.giphy-2.0.0.tar.gz ]";
-        description = ''
+        description = lib.mdDoc ''
           Plugins to add to the configuration. Overrides any installed if non-null.
           This is a list of paths to .tar.gz files or derivations evaluating to
           .tar.gz files.
@@ -188,7 +188,7 @@ in
       localDatabaseCreate = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Create a local PostgreSQL database for Mattermost automatically.
         '';
       };
@@ -196,7 +196,7 @@ in
       localDatabaseName = mkOption {
         type = types.str;
         default = "mattermost";
-        description = ''
+        description = lib.mdDoc ''
           Local Mattermost database name.
         '';
       };
@@ -204,7 +204,7 @@ in
       localDatabaseUser = mkOption {
         type = types.str;
         default = "mattermost";
-        description = ''
+        description = lib.mdDoc ''
           Local Mattermost database username.
         '';
       };
@@ -212,7 +212,7 @@ in
       localDatabasePassword = mkOption {
         type = types.str;
         default = "mmpgsecret";
-        description = ''
+        description = lib.mdDoc ''
           Password for local Mattermost database user.
         '';
       };
@@ -220,7 +220,7 @@ in
       user = mkOption {
         type = types.str;
         default = "mattermost";
-        description = ''
+        description = lib.mdDoc ''
           User which runs the Mattermost service.
         '';
       };
@@ -228,24 +228,24 @@ in
       group = mkOption {
         type = types.str;
         default = "mattermost";
-        description = ''
+        description = lib.mdDoc ''
           Group which runs the Mattermost service.
         '';
       };
 
       matterircd = {
-        enable = mkEnableOption "Mattermost IRC bridge";
+        enable = mkEnableOption (lib.mdDoc "Mattermost IRC bridge");
         package = mkOption {
           type = types.package;
           default = pkgs.matterircd;
           defaultText = "pkgs.matterircd";
-          description = "matterircd derivation to use.";
+          description = lib.mdDoc "matterircd derivation to use.";
         };
         parameters = mkOption {
           type = types.listOf types.str;
           default = [ ];
           example = [ "-mmserver chat.example.com" "-bind [::]:6667" ];
-          description = ''
+          description = lib.mdDoc ''
             Set commandline parameters to pass to matterircd. See
             https://github.com/42wim/matterircd#usage for more information.
           '';
diff --git a/nixos/modules/services/web-apps/mediawiki.nix b/nixos/modules/services/web-apps/mediawiki.nix
index 977b6f60b23..e332847f5a2 100644
--- a/nixos/modules/services/web-apps/mediawiki.nix
+++ b/nixos/modules/services/web-apps/mediawiki.nix
@@ -35,7 +35,7 @@ let
   };
 
   mediawikiScripts = pkgs.runCommand "mediawiki-scripts" {
-    buildInputs = [ pkgs.makeWrapper ];
+    nativeBuildInputs = [ pkgs.makeWrapper ];
     preferLocalBuild = true;
   } ''
     mkdir -p $out/bin
@@ -171,26 +171,26 @@ in
   options = {
     services.mediawiki = {
 
-      enable = mkEnableOption "MediaWiki";
+      enable = mkEnableOption (lib.mdDoc "MediaWiki");
 
       package = mkOption {
         type = types.package;
         default = pkgs.mediawiki;
         defaultText = literalExpression "pkgs.mediawiki";
-        description = "Which MediaWiki package to use.";
+        description = lib.mdDoc "Which MediaWiki package to use.";
       };
 
       name = mkOption {
         type = types.str;
         default = "MediaWiki";
         example = "Foobar Wiki";
-        description = "Name of the wiki.";
+        description = lib.mdDoc "Name of the wiki.";
       };
 
       uploadsDir = mkOption {
         type = types.nullOr types.path;
         default = "${stateDir}/uploads";
-        description = ''
+        description = lib.mdDoc ''
           This directory is used for uploads of pictures. The directory passed here is automatically
           created and permissions adjusted as required.
         '';
@@ -198,15 +198,15 @@ in
 
       passwordFile = mkOption {
         type = types.path;
-        description = "A file containing the initial password for the admin user.";
+        description = lib.mdDoc "A file containing the initial password for the admin user.";
         example = "/run/keys/mediawiki-password";
       };
 
       skins = mkOption {
         default = {};
         type = types.attrsOf types.path;
-        description = ''
-          Attribute set of paths whose content is copied to the <filename>skins</filename>
+        description = lib.mdDoc ''
+          Attribute set of paths whose content is copied to the {file}`skins`
           subdirectory of the MediaWiki installation in addition to the default skins.
         '';
       };
@@ -214,11 +214,11 @@ in
       extensions = mkOption {
         default = {};
         type = types.attrsOf (types.nullOr types.path);
-        description = ''
-          Attribute set of paths whose content is copied to the <filename>extensions</filename>
+        description = lib.mdDoc ''
+          Attribute set of paths whose content is copied to the {file}`extensions`
           subdirectory of the MediaWiki installation and enabled in configuration.
 
-          Use <literal>null</literal> instead of path to enable extensions that are part of MediaWiki.
+          Use `null` instead of path to enable extensions that are part of MediaWiki.
         '';
         example = literalExpression ''
           {
@@ -235,52 +235,52 @@ in
         type = mkOption {
           type = types.enum [ "mysql" "postgres" "sqlite" "mssql" "oracle" ];
           default = "mysql";
-          description = "Database engine to use. MySQL/MariaDB is the database of choice by MediaWiki developers.";
+          description = lib.mdDoc "Database engine to use. MySQL/MariaDB is the database of choice by MediaWiki developers.";
         };
 
         host = mkOption {
           type = types.str;
           default = "localhost";
-          description = "Database host address.";
+          description = lib.mdDoc "Database host address.";
         };
 
         port = mkOption {
           type = types.port;
           default = 3306;
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = mkOption {
           type = types.str;
           default = "mediawiki";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = mkOption {
           type = types.str;
           default = "mediawiki";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/mediawiki-dbpassword";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
 
         tablePrefix = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             If you only have access to a single database and wish to install more than
             one version of MediaWiki, or have other applications that also use the
             database, you can give the table names a unique prefix to stop any naming
             conflicts or confusion.
-            See <link xlink:href='https://www.mediawiki.org/wiki/Manual:$wgDBprefix'/>.
+            See <https://www.mediawiki.org/wiki/Manual:$wgDBprefix>.
           '';
         };
 
@@ -288,14 +288,14 @@ in
           type = types.nullOr types.path;
           default = if cfg.database.createLocally then "/run/mysqld/mysqld.sock" else null;
           defaultText = literalExpression "/run/mysqld/mysqld.sock";
-          description = "Path to the unix socket file to use for authentication.";
+          description = lib.mdDoc "Path to the unix socket file to use for authentication.";
         };
 
         createLocally = mkOption {
           type = types.bool;
           default = cfg.database.type == "mysql";
           defaultText = literalExpression "true";
-          description = ''
+          description = lib.mdDoc ''
             Create the database and database user locally.
             This currently only applies if database type "mysql" is selected.
           '';
@@ -312,9 +312,9 @@ in
             enableACME = true;
           }
         '';
-        description = ''
-          Apache configuration can be done by adapting <option>services.httpd.virtualHosts</option>.
-          See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
+        description = lib.mdDoc ''
+          Apache configuration can be done by adapting {option}`services.httpd.virtualHosts`.
+          See [](#opt-services.httpd.virtualHosts) for further information.
         '';
       };
 
@@ -328,18 +328,18 @@ in
           "pm.max_spare_servers" = 4;
           "pm.max_requests" = 500;
         };
-        description = ''
-          Options for the MediaWiki PHP pool. See the documentation on <literal>php-fpm.conf</literal>
+        description = lib.mdDoc ''
+          Options for the MediaWiki PHP pool. See the documentation on `php-fpm.conf`
           for details on configuration directives.
         '';
       };
 
       extraConfig = mkOption {
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           Any additional text to be appended to MediaWiki's
           LocalSettings.php configuration file. For configuration
-          settings, see <link xlink:href="https://www.mediawiki.org/wiki/Manual:Configuration_settings"/>.
+          settings, see <https://www.mediawiki.org/wiki/Manual:Configuration_settings>.
         '';
         default = "";
         example = ''
@@ -449,6 +449,7 @@ in
           --dbuser ${cfg.database.user} \
           ${optionalString (cfg.database.passwordFile != null) "--dbpassfile ${cfg.database.passwordFile}"} \
           --passfile ${cfg.passwordFile} \
+          --dbtype ${cfg.database.type} \
           ${cfg.name} \
           admin
 
diff --git a/nixos/modules/services/web-apps/miniflux.nix b/nixos/modules/services/web-apps/miniflux.nix
index 641c9be85d8..34a108cebd2 100644
--- a/nixos/modules/services/web-apps/miniflux.nix
+++ b/nixos/modules/services/web-apps/miniflux.nix
@@ -19,7 +19,7 @@ in
 {
   options = {
     services.miniflux = {
-      enable = mkEnableOption "miniflux and creates a local postgres database for it";
+      enable = mkEnableOption (lib.mdDoc "miniflux and creates a local postgres database for it");
 
       config = mkOption {
         type = types.attrsOf types.str;
@@ -29,9 +29,9 @@ in
             LISTEN_ADDR = "localhost:8080";
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Configuration for Miniflux, refer to
-          <link xlink:href="https://miniflux.app/docs/configuration.html"/>
+          <https://miniflux.app/docs/configuration.html>
           for documentation on the supported values.
 
           Correct configuration for the database is already provided.
@@ -41,7 +41,7 @@ in
 
       adminCredentialsFile = mkOption  {
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           File containing the ADMIN_USERNAME and
           ADMIN_PASSWORD (length >= 6) in the format of
           an EnvironmentFile=, as described by systemd.exec(5).
@@ -116,7 +116,7 @@ in
         RestrictRealtime = true;
         RestrictSUIDSGID = true;
         SystemCallArchitectures = "native";
-        SystemCallFilter = [ "@system-service" "~@privileged" "~@resources" ];
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
         UMask = "0077";
       };
 
diff --git a/nixos/modules/services/web-apps/moodle.nix b/nixos/modules/services/web-apps/moodle.nix
index 19f3e754691..dc434d0fc80 100644
--- a/nixos/modules/services/web-apps/moodle.nix
+++ b/nixos/modules/services/web-apps/moodle.nix
@@ -56,25 +56,27 @@ let
   mysqlLocal = cfg.database.createLocally && cfg.database.type == "mysql";
   pgsqlLocal = cfg.database.createLocally && cfg.database.type == "pgsql";
 
-  phpExt = pkgs.php74.withExtensions
-        ({ enabled, all }: with all; [ iconv mbstring curl openssl tokenizer xmlrpc soap ctype zip gd simplexml dom  intl json sqlite3 pgsql pdo_sqlite pdo_pgsql pdo_odbc pdo_mysql pdo mysqli session zlib xmlreader fileinfo filter opcache ]);
+  phpExt = pkgs.php80.buildEnv {
+    extensions = { all, ... }: with all; [ iconv mbstring curl openssl tokenizer soap ctype zip gd simplexml dom intl sqlite3 pgsql pdo_sqlite pdo_pgsql pdo_odbc pdo_mysql pdo mysqli session zlib xmlreader fileinfo filter opcache exif sodium ];
+    extraConfig = "max_input_vars = 5000";
+  };
 in
 {
   # interface
   options.services.moodle = {
-    enable = mkEnableOption "Moodle web application";
+    enable = mkEnableOption (lib.mdDoc "Moodle web application");
 
     package = mkOption {
       type = types.package;
       default = pkgs.moodle;
       defaultText = literalExpression "pkgs.moodle";
-      description = "The Moodle package to use.";
+      description = lib.mdDoc "The Moodle package to use.";
     };
 
     initialPassword = mkOption {
       type = types.str;
       example = "correcthorsebatterystaple";
-      description = ''
+      description = lib.mdDoc ''
         Specifies the initial password for the admin, i.e. the password assigned if the user does not already exist.
         The password specified here is world-readable in the Nix store, so it should be changed promptly.
       '';
@@ -84,18 +86,18 @@ in
       type = mkOption {
         type = types.enum [ "mysql" "pgsql" ];
         default = "mysql";
-        description = "Database engine to use.";
+        description = lib.mdDoc "Database engine to use.";
       };
 
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Database host address.";
+        description = lib.mdDoc "Database host address.";
       };
 
       port = mkOption {
         type = types.int;
-        description = "Database host port.";
+        description = lib.mdDoc "Database host port.";
         default = {
           mysql = 3306;
           pgsql = 5432;
@@ -106,22 +108,22 @@ in
       name = mkOption {
         type = types.str;
         default = "moodle";
-        description = "Database name.";
+        description = lib.mdDoc "Database name.";
       };
 
       user = mkOption {
         type = types.str;
         default = "moodle";
-        description = "Database user.";
+        description = lib.mdDoc "Database user.";
       };
 
       passwordFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/run/keys/moodle-dbpassword";
-        description = ''
+        description = lib.mdDoc ''
           A file containing the password corresponding to
-          <option>database.user</option>.
+          {option}`database.user`.
         '';
       };
 
@@ -132,13 +134,13 @@ in
           else if pgsqlLocal then "/run/postgresql"
           else null;
         defaultText = literalExpression "/run/mysqld/mysqld.sock";
-        description = "Path to the unix socket file to use for authentication.";
+        description = lib.mdDoc "Path to the unix socket file to use for authentication.";
       };
 
       createLocally = mkOption {
         type = types.bool;
         default = true;
-        description = "Create the database and database user locally.";
+        description = lib.mdDoc "Create the database and database user locally.";
       };
     };
 
@@ -152,9 +154,9 @@ in
           enableACME = true;
         }
       '';
-      description = ''
-        Apache configuration can be done by adapting <option>services.httpd.virtualHosts</option>.
-        See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
+      description = lib.mdDoc ''
+        Apache configuration can be done by adapting {option}`services.httpd.virtualHosts`.
+        See [](#opt-services.httpd.virtualHosts) for further information.
       '';
     };
 
@@ -168,8 +170,8 @@ in
         "pm.max_spare_servers" = 4;
         "pm.max_requests" = 500;
       };
-      description = ''
-        Options for the Moodle PHP pool. See the documentation on <literal>php-fpm.conf</literal>
+      description = lib.mdDoc ''
+        Options for the Moodle PHP pool. See the documentation on `php-fpm.conf`
         for details on configuration directives.
       '';
     };
@@ -177,10 +179,10 @@ in
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Any additional text to be appended to the config.php
         configuration file. This is a PHP script. For configuration
-        details, see <link xlink:href="https://docs.moodle.org/37/en/Configuration_file"/>.
+        details, see <https://docs.moodle.org/37/en/Configuration_file>.
       '';
       example = ''
         $CFG->disableupdatenotifications = true;
@@ -230,6 +232,7 @@ in
       phpOptions = ''
         zend_extension = opcache.so
         opcache.enable = 1
+        max_input_vars = 5000
       '';
       settings = {
         "listen.owner" = config.services.httpd.user;
diff --git a/nixos/modules/services/web-apps/netbox.nix b/nixos/modules/services/web-apps/netbox.nix
new file mode 100644
index 00000000000..800af234e27
--- /dev/null
+++ b/nixos/modules/services/web-apps/netbox.nix
@@ -0,0 +1,270 @@
+{ config, lib, pkgs, buildEnv, ... }:
+
+with lib;
+
+let
+  cfg = config.services.netbox;
+  staticDir = cfg.dataDir + "/static";
+  configFile = pkgs.writeTextFile {
+    name = "configuration.py";
+    text = ''
+      STATIC_ROOT = '${staticDir}'
+      MEDIA_ROOT = '${cfg.dataDir}/media'
+      REPORTS_ROOT = '${cfg.dataDir}/reports'
+      SCRIPTS_ROOT = '${cfg.dataDir}/scripts'
+
+      ALLOWED_HOSTS = ['*']
+      DATABASE = {
+        'NAME': 'netbox',
+        'USER': 'netbox',
+        'HOST': '/run/postgresql',
+      }
+
+      # Redis database settings. Redis is used for caching and for queuing background tasks such as webhook events. A separate
+      # configuration exists for each. Full connection details are required in both sections, and it is strongly recommended
+      # to use two separate database IDs.
+      REDIS = {
+          'tasks': {
+              'URL': 'unix://${config.services.redis.servers.netbox.unixSocket}?db=0',
+              'SSL': False,
+          },
+          'caching': {
+              'URL': 'unix://${config.services.redis.servers.netbox.unixSocket}?db=1',
+              'SSL': False,
+          }
+      }
+
+      with open("${cfg.secretKeyFile}", "r") as file:
+          SECRET_KEY = file.readline()
+
+      ${optionalString cfg.enableLdap "REMOTE_AUTH_BACKEND = 'netbox.authentication.LDAPBackend'"}
+
+      ${cfg.extraConfig}
+    '';
+  };
+  pkg = (pkgs.netbox.overrideAttrs (old: {
+    installPhase = old.installPhase + ''
+      ln -s ${configFile} $out/opt/netbox/netbox/netbox/configuration.py
+    '' + optionalString cfg.enableLdap ''
+      ln -s ${cfg.ldapConfigPath} $out/opt/netbox/netbox/netbox/ldap_config.py
+    '';
+  })).override {
+    inherit (cfg) plugins;
+  };
+  netboxManageScript = with pkgs; (writeScriptBin "netbox-manage" ''
+    #!${stdenv.shell}
+    export PYTHONPATH=${pkg.pythonPath}
+    sudo -u netbox ${pkg}/bin/netbox "$@"
+  '');
+
+in {
+  options.services.netbox = {
+    enable = mkOption {
+      type = lib.types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Enable Netbox.
+
+        This module requires a reverse proxy that serves `/static` separately.
+        See this [example](https://github.com/netbox-community/netbox/blob/develop/contrib/nginx.conf/) on how to configure this.
+      '';
+    };
+
+    listenAddress = mkOption {
+      type = types.str;
+      default = "[::1]";
+      description = lib.mdDoc ''
+        Address the server will listen on.
+      '';
+    };
+
+    port = mkOption {
+      type = types.port;
+      default = 8001;
+      description = lib.mdDoc ''
+        Port the server will listen on.
+      '';
+    };
+
+    plugins = mkOption {
+      type = types.functionTo (types.listOf types.package);
+      default = _: [];
+      defaultText = literalExpression ''
+        python3Packages: with python3Packages; [];
+      '';
+      description = lib.mdDoc ''
+        List of plugin packages to install.
+      '';
+    };
+
+    dataDir = mkOption {
+      type = types.str;
+      default = "/var/lib/netbox";
+      description = lib.mdDoc ''
+        Storage path of netbox.
+      '';
+    };
+
+    secretKeyFile = mkOption {
+      type = types.path;
+      description = lib.mdDoc ''
+        Path to a file containing the secret key.
+      '';
+    };
+
+    extraConfig = mkOption {
+      type = types.lines;
+      default = "";
+      description = lib.mdDoc ''
+        Additional lines of configuration appended to the `configuration.py`.
+        See the [documentation](https://netbox.readthedocs.io/en/stable/configuration/optional-settings/) for more possible options.
+      '';
+    };
+
+    enableLdap = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Enable LDAP-Authentication for Netbox.
+
+        This requires a configuration file being pass through `ldapConfigPath`.
+      '';
+    };
+
+    ldapConfigPath = mkOption {
+      type = types.path;
+      default = "";
+      description = lib.mdDoc ''
+        Path to the Configuration-File for LDAP-Authentification, will be loaded as `ldap_config.py`.
+        See the [documentation](https://netbox.readthedocs.io/en/stable/installation/6-ldap/#configuration) for possible options.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+    services.netbox.plugins = mkIf cfg.enableLdap (ps: [ ps.django-auth-ldap ]);
+
+    services.redis.servers.netbox.enable = true;
+
+    services.postgresql = {
+      enable = true;
+      ensureDatabases = [ "netbox" ];
+      ensureUsers = [
+        {
+          name = "netbox";
+          ensurePermissions = {
+            "DATABASE netbox" = "ALL PRIVILEGES";
+          };
+        }
+      ];
+    };
+
+    environment.systemPackages = [ netboxManageScript ];
+
+    systemd.targets.netbox = {
+      description = "Target for all NetBox services";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "network-online.target" "redis-netbox.service" ];
+    };
+
+    systemd.services = let
+      defaultServiceConfig = {
+        WorkingDirectory = "${cfg.dataDir}";
+        User = "netbox";
+        Group = "netbox";
+        StateDirectory = "netbox";
+        StateDirectoryMode = "0750";
+        Restart = "on-failure";
+      };
+    in {
+      netbox-migration = {
+        description = "NetBox migrations";
+        wantedBy = [ "netbox.target" ];
+
+        environment = {
+          PYTHONPATH = pkg.pythonPath;
+        };
+
+        serviceConfig = defaultServiceConfig // {
+          Type = "oneshot";
+          ExecStart = ''
+            ${pkg}/bin/netbox migrate
+          '';
+        };
+      };
+
+      netbox = {
+        description = "NetBox WSGI Service";
+        wantedBy = [ "netbox.target" ];
+        after = [ "netbox-migration.service" ];
+
+        preStart = ''
+          ${pkg}/bin/netbox trace_paths --no-input
+          ${pkg}/bin/netbox collectstatic --no-input
+          ${pkg}/bin/netbox remove_stale_contenttypes --no-input
+        '';
+
+        environment = {
+          PYTHONPATH = pkg.pythonPath;
+        };
+
+        serviceConfig = defaultServiceConfig // {
+          ExecStart = ''
+            ${pkgs.python3Packages.gunicorn}/bin/gunicorn netbox.wsgi \
+              --bind ${cfg.listenAddress}:${toString cfg.port} \
+              --pythonpath ${pkg}/opt/netbox/netbox
+          '';
+        };
+      };
+
+      netbox-rq = {
+        description = "NetBox Request Queue Worker";
+        wantedBy = [ "netbox.target" ];
+        after = [ "netbox.service" ];
+
+        environment = {
+          PYTHONPATH = pkg.pythonPath;
+        };
+
+        serviceConfig = defaultServiceConfig // {
+          ExecStart = ''
+            ${pkg}/bin/netbox rqworker high default low
+          '';
+        };
+      };
+
+      netbox-housekeeping = {
+        description = "NetBox housekeeping job";
+        after = [ "netbox.service" ];
+
+        environment = {
+          PYTHONPATH = pkg.pythonPath;
+        };
+
+        serviceConfig = defaultServiceConfig // {
+          Type = "oneshot";
+          ExecStart = ''
+            ${pkg}/bin/netbox housekeeping
+          '';
+        };
+      };
+    };
+
+    systemd.timers.netbox-housekeeping = {
+      description = "Run NetBox housekeeping job";
+      wantedBy = [ "timers.target" ];
+
+      timerConfig = {
+        OnCalendar = "daily";
+      };
+    };
+
+    users.users.netbox = {
+      home = "${cfg.dataDir}";
+      isSystemUser = true;
+      group = "netbox";
+    };
+    users.groups.netbox = {};
+    users.groups."${config.services.redis.servers.netbox.user}".members = [ "netbox" ];
+  };
+}
diff --git a/nixos/modules/services/web-apps/nextcloud.nix b/nixos/modules/services/web-apps/nextcloud.nix
index b32220a5e57..da621573f2a 100644
--- a/nixos/modules/services/web-apps/nextcloud.nix
+++ b/nixos/modules/services/web-apps/nextcloud.nix
@@ -6,12 +6,19 @@ let
   cfg = config.services.nextcloud;
   fpm = config.services.phpfpm.pools.nextcloud;
 
+  jsonFormat = pkgs.formats.json {};
+
   inherit (cfg) datadir;
 
   phpPackage = cfg.phpPackage.buildEnv {
     extensions = { enabled, all }:
       (with all;
-        enabled
+        # disable default openssl extension
+        (lib.filter (e: e.pname != "php-openssl") enabled)
+        # use OpenSSL 1.1 for RC4 Nextcloud encryption if user
+        # has acknowledged the brokeness of the ciphers (RC4).
+        # TODO: remove when https://github.com/nextcloud/server/issues/32003 is fixed.
+        ++ (if cfg.enableBrokenCiphersForSSE then [ cfg.phpPackage.extensions.openssl-legacy ] else [ cfg.phpPackage.extensions.openssl ])
         ++ optional cfg.enableImagemagick imagick
         # Optionally enabled depending on caching settings
         ++ optional cfg.caching.apcu apcu
@@ -77,21 +84,56 @@ in {
   ];
 
   options.services.nextcloud = {
-    enable = mkEnableOption "nextcloud";
+    enable = mkEnableOption (lib.mdDoc "nextcloud");
+
+    enableBrokenCiphersForSSE = mkOption {
+      type = types.bool;
+      default = versionOlder stateVersion "22.11";
+      defaultText = literalExpression "versionOlder system.stateVersion \"22.11\"";
+      description = lib.mdDoc ''
+        This option enables using the OpenSSL PHP extension linked against OpenSSL 1.1
+        rather than latest OpenSSL (≥ 3), this is not recommended unless you need
+        it for server-side encryption (SSE). SSE uses the legacy RC4 cipher which is
+        considered broken for several years now. See also [RFC7465](https://datatracker.ietf.org/doc/html/rfc7465).
+
+        This cipher has been disabled in OpenSSL ≥ 3 and requires
+        a specific legacy profile to re-enable it.
+
+        If you deploy Nextcloud using OpenSSL ≥ 3 for PHP and have
+        server-side encryption configured, you will not be able to access
+        your files anymore. Enabling this option can restore access to your files.
+        Upon testing we didn't encounter any data corruption when turning
+        this on and off again, but this cannot be guaranteed for
+        each Nextcloud installation.
+
+        It is `true` by default for systems with a [](#opt-system.stateVersion) below
+        `22.11` to make sure that existing installations won't break on update. On newer
+        NixOS systems you have to explicitly enable it on your own.
+
+        Please note that this only provides additional value when using
+        external storage such as S3 since it's not an end-to-end encryption.
+        If this is not the case,
+        it is advised to [disable server-side encryption](https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/encryption_configuration.html#disabling-encryption) and set this to `false`.
+
+        In the future, Nextcloud may move to AES-256-GCM, by then,
+        this option will be removed.
+      '';
+    };
     hostName = mkOption {
       type = types.str;
-      description = "FQDN for the nextcloud instance.";
+      description = lib.mdDoc "FQDN for the nextcloud instance.";
     };
     home = mkOption {
       type = types.str;
       default = "/var/lib/nextcloud";
-      description = "Storage path of nextcloud.";
+      description = lib.mdDoc "Storage path of nextcloud.";
     };
     datadir = mkOption {
       type = types.str;
-      defaultText = "config.services.nextcloud.home";
-      description = ''
-        Data storage path of nextcloud.  Will be <xref linkend="opt-services.nextcloud.home" /> by default.
+      default = config.services.nextcloud.home;
+      defaultText = literalExpression "config.services.nextcloud.home";
+      description = lib.mdDoc ''
+        Data storage path of nextcloud.  Will be [](#opt-services.nextcloud.home) by default.
         This folder will be populated with a config.php and data folder which contains the state of the instance (excl the database).";
       '';
       example = "/mnt/nextcloud-file";
@@ -99,10 +141,10 @@ in {
     extraApps = mkOption {
       type = types.attrsOf types.package;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         Extra apps to install. Should be an attrSet of appid to packages generated by fetchNextcloudApp.
         The appid must be identical to the "id" value in the apps appinfo/info.xml.
-        Using this will disable the appstore to prevent Nextcloud from updating these apps (see <xref linkend="opt-services.nextcloud.appstoreEnable" />).
+        Using this will disable the appstore to prevent Nextcloud from updating these apps (see [](#opt-services.nextcloud.appstoreEnable)).
       '';
       example = literalExpression ''
         {
@@ -124,8 +166,8 @@ in {
     extraAppsEnable = mkOption {
       type = types.bool;
       default = true;
-      description = ''
-        Automatically enable the apps in <xref linkend="opt-services.nextcloud.extraApps" /> every time nextcloud starts.
+      description = lib.mdDoc ''
+        Automatically enable the apps in [](#opt-services.nextcloud.extraApps) every time nextcloud starts.
         If set to false, apps need to be enabled in the Nextcloud user interface or with nextcloud-occ app:enable.
       '';
     };
@@ -133,33 +175,42 @@ in {
       type = types.nullOr types.bool;
       default = null;
       example = true;
-      description = ''
+      description = lib.mdDoc ''
         Allow the installation of apps and app updates from the store.
-        Enabled by default unless there are packages in <xref linkend="opt-services.nextcloud.extraApps" />.
-        Set to true to force enable the store even if <xref linkend="opt-services.nextcloud.extraApps" /> is used.
+        Enabled by default unless there are packages in [](#opt-services.nextcloud.extraApps).
+        Set to true to force enable the store even if [](#opt-services.nextcloud.extraApps) is used.
         Set to false to disable the installation of apps from the global appstore. App management is always enabled regardless of this setting.
       '';
     };
     logLevel = mkOption {
       type = types.ints.between 0 4;
       default = 2;
-      description = "Log level value between 0 (DEBUG) and 4 (FATAL).";
+      description = lib.mdDoc "Log level value between 0 (DEBUG) and 4 (FATAL).";
+    };
+    logType = mkOption {
+      type = types.enum [ "errorlog" "file" "syslog" "systemd" ];
+      default = "syslog";
+      description = lib.mdDoc ''
+        Logging backend to use.
+        systemd requires the php-systemd package to be added to services.nextcloud.phpExtraExtensions.
+        See the [nextcloud documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/logging_configuration.html) for details.
+      '';
     };
     https = mkOption {
       type = types.bool;
       default = false;
-      description = "Use https for generated links.";
+      description = lib.mdDoc "Use https for generated links.";
     };
     package = mkOption {
       type = types.package;
-      description = "Which package to use for the Nextcloud instance.";
-      relatedPackages = [ "nextcloud22" "nextcloud23" ];
+      description = lib.mdDoc "Which package to use for the Nextcloud instance.";
+      relatedPackages = [ "nextcloud24" "nextcloud25" ];
     };
     phpPackage = mkOption {
       type = types.package;
-      relatedPackages = [ "php74" "php80" ];
+      relatedPackages = [ "php80" "php81" ];
       defaultText = "pkgs.php";
-      description = ''
+      description = lib.mdDoc ''
         PHP package to use for Nextcloud.
       '';
     };
@@ -167,7 +218,7 @@ in {
     maxUploadSize = mkOption {
       default = "512M";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Defines the upload limit for files. This changes the relevant options
         in php.ini and nginx if enabled.
       '';
@@ -176,7 +227,7 @@ in {
     skeletonDirectory = mkOption {
       default = "";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The directory where the skeleton files are located. These files will be
         copied to the data directory of new users. Leave empty to not copy any
         skeleton files.
@@ -186,7 +237,7 @@ in {
     webfinger = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable this option if you plan on using the webfinger plugin.
         The appropriate nginx rewrite rules will be added to your configuration.
       '';
@@ -196,7 +247,7 @@ in {
       type = with types; functionTo (listOf package);
       default = all: [];
       defaultText = literalExpression "all: []";
-      description = ''
+      description = lib.mdDoc ''
         Additional PHP extensions to use for nextcloud.
         By default, only extensions necessary for a vanilla nextcloud installation are enabled,
         but you may choose from the list of available extensions and add further ones.
@@ -223,7 +274,7 @@ in {
         "openssl.cafile" = "/etc/ssl/certs/ca-certificates.crt";
         catch_workers_output = "yes";
       };
-      description = ''
+      description = lib.mdDoc ''
         Options for PHP's php.ini file for nextcloud.
       '';
     };
@@ -238,89 +289,114 @@ in {
         "pm.max_spare_servers" = "4";
         "pm.max_requests" = "500";
       };
-      description = ''
-        Options for nextcloud's PHP pool. See the documentation on <literal>php-fpm.conf</literal> for details on configuration directives.
+      description = lib.mdDoc ''
+        Options for nextcloud's PHP pool. See the documentation on `php-fpm.conf` for details on configuration directives.
       '';
     };
 
     poolConfig = mkOption {
       type = types.nullOr types.lines;
       default = null;
-      description = ''
-        Options for nextcloud's PHP pool. See the documentation on <literal>php-fpm.conf</literal> for details on configuration directives.
+      description = lib.mdDoc ''
+        Options for nextcloud's PHP pool. See the documentation on `php-fpm.conf` for details on configuration directives.
+      '';
+    };
+
+    fastcgiTimeout = mkOption {
+      type = types.int;
+      default = 120;
+      description = lib.mdDoc ''
+        FastCGI timeout for database connection in seconds.
       '';
     };
 
+    database = {
+
+      createLocally = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          Create the database and database user locally. Only available for
+          mysql database.
+          Note that this option will use the latest version of MariaDB which
+          is not officially supported by Nextcloud. As for now a workaround
+          is used to also support MariaDB version >= 10.6.
+        '';
+      };
+
+    };
+
+
     config = {
       dbtype = mkOption {
         type = types.enum [ "sqlite" "pgsql" "mysql" ];
         default = "sqlite";
-        description = "Database type.";
+        description = lib.mdDoc "Database type.";
       };
       dbname = mkOption {
         type = types.nullOr types.str;
         default = "nextcloud";
-        description = "Database name.";
+        description = lib.mdDoc "Database name.";
       };
       dbuser = mkOption {
         type = types.nullOr types.str;
         default = "nextcloud";
-        description = "Database user.";
+        description = lib.mdDoc "Database user.";
       };
       dbpassFile = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The full path to a file that contains the database password.
         '';
       };
       dbhost = mkOption {
         type = types.nullOr types.str;
         default = "localhost";
-        description = ''
+        description = lib.mdDoc ''
           Database host.
 
           Note: for using Unix authentication with PostgreSQL, this should be
-          set to <literal>/run/postgresql</literal>.
+          set to `/run/postgresql`.
         '';
       };
       dbport = mkOption {
         type = with types; nullOr (either int str);
         default = null;
-        description = "Database port.";
+        description = lib.mdDoc "Database port.";
       };
       dbtableprefix = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "Table prefix in Nextcloud database.";
+        description = lib.mdDoc "Table prefix in Nextcloud database.";
       };
       adminuser = mkOption {
         type = types.str;
         default = "root";
-        description = "Admin username.";
+        description = lib.mdDoc "Admin username.";
       };
       adminpassFile = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The full path to a file that contains the admin's password. Must be
-          readable by user <literal>nextcloud</literal>.
+          readable by user `nextcloud`.
         '';
       };
 
       extraTrustedDomains = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Trusted domains, from which the nextcloud installation will be
           acessible.  You don't need to add
-          <literal>services.nextcloud.hostname</literal> here.
+          `services.nextcloud.hostname` here.
         '';
       };
 
       trustedProxies = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           Trusted proxies, to provide if the nextcloud installation is being
           proxied to secure against e.g. spoofing.
         '';
@@ -331,10 +407,10 @@ in {
         default = null;
         example = "https";
 
-        description = ''
+        description = lib.mdDoc ''
           Force Nextcloud to always use HTTPS i.e. for link generation. Nextcloud
           uses the currently used protocol by default, but when behind a reverse-proxy,
-          it may use <literal>http</literal> for everything although Nextcloud
+          it may use `http` for everything although Nextcloud
           may be served via HTTPS.
         '';
       };
@@ -343,78 +419,78 @@ in {
         default = null;
         type = types.nullOr types.str;
         example = "DE";
-        description = ''
-          <warning>
-           <para>This option exists since Nextcloud 21! If older versions are used,
-            this will throw an eval-error!</para>
-          </warning>
+        description = lib.mdDoc ''
+          ::: {.warning}
+          This option exists since Nextcloud 21! If older versions are used,
+          this will throw an eval-error!
+          :::
 
-          <link xlink:href="https://www.iso.org/iso-3166-country-codes.html">ISO 3611-1</link>
+          [ISO 3611-1](https://www.iso.org/iso-3166-country-codes.html)
           country codes for automatic phone-number detection without a country code.
 
-          With e.g. <literal>DE</literal> set, the <literal>+49</literal> can be omitted for
+          With e.g. `DE` set, the `+49` can be omitted for
           phone-numbers.
         '';
       };
 
       objectstore = {
         s3 = {
-          enable = mkEnableOption ''
+          enable = mkEnableOption (lib.mdDoc ''
             S3 object storage as primary storage.
 
             This mounts a bucket on an Amazon S3 object storage or compatible
             implementation into the virtual filesystem.
 
             Further details about this feature can be found in the
-            <link xlink:href="https://docs.nextcloud.com/server/22/admin_manual/configuration_files/primary_storage.html">upstream documentation</link>.
-          '';
+            [upstream documentation](https://docs.nextcloud.com/server/22/admin_manual/configuration_files/primary_storage.html).
+          '');
           bucket = mkOption {
             type = types.str;
             example = "nextcloud";
-            description = ''
+            description = lib.mdDoc ''
               The name of the S3 bucket.
             '';
           };
           autocreate = mkOption {
             type = types.bool;
-            description = ''
+            description = lib.mdDoc ''
               Create the objectstore if it does not exist.
             '';
           };
           key = mkOption {
             type = types.str;
             example = "EJ39ITYZEUH5BGWDRUFY";
-            description = ''
+            description = lib.mdDoc ''
               The access key for the S3 bucket.
             '';
           };
           secretFile = mkOption {
             type = types.str;
             example = "/var/nextcloud-objectstore-s3-secret";
-            description = ''
+            description = lib.mdDoc ''
               The full path to a file that contains the access secret. Must be
-              readable by user <literal>nextcloud</literal>.
+              readable by user `nextcloud`.
             '';
           };
           hostname = mkOption {
             type = types.nullOr types.str;
             default = null;
             example = "example.com";
-            description = ''
+            description = lib.mdDoc ''
               Required for some non-Amazon implementations.
             '';
           };
           port = mkOption {
             type = types.nullOr types.port;
             default = null;
-            description = ''
+            description = lib.mdDoc ''
               Required for some non-Amazon implementations.
             '';
           };
           useSsl = mkOption {
             type = types.bool;
             default = true;
-            description = ''
+            description = lib.mdDoc ''
               Use SSL for objectstore access.
             '';
           };
@@ -422,33 +498,33 @@ in {
             type = types.nullOr types.str;
             default = null;
             example = "REGION";
-            description = ''
+            description = lib.mdDoc ''
               Required for some non-Amazon implementations.
             '';
           };
           usePathStyle = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Required for some non-Amazon S3 implementations.
 
               Ordinarily, requests will be made with
-              <literal>http://bucket.hostname.domain/</literal>, but with path style
+              `http://bucket.hostname.domain/`, but with path style
               enabled requests are made with
-              <literal>http://hostname.domain/bucket</literal> instead.
+              `http://hostname.domain/bucket` instead.
             '';
           };
         };
       };
     };
 
-    enableImagemagick = mkEnableOption ''
+    enableImagemagick = mkEnableOption (lib.mdDoc ''
         the ImageMagick module for PHP.
         This is used by the theming app and for generating previews of certain images (e.g. SVG and HEIF).
         You may want to disable it for increased security. In that case, previews will still be available
         for some images (e.g. JPEG and PNG).
-        See <link xlink:href="https://github.com/nextcloud/server/issues/13099" />.
-    '' // {
+        See <https://github.com/nextcloud/server/issues/13099>.
+    '') // {
       default = true;
     };
 
@@ -456,14 +532,14 @@ in {
       apcu = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to load the APCu module into PHP.
         '';
       };
       redis = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to load the Redis module into PHP.
           You still need to enable Redis in your config.php.
           See https://docs.nextcloud.com/server/14/admin_manual/configuration_server/caching_configuration.html
@@ -472,7 +548,7 @@ in {
       memcached = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to load the Memcached module into PHP.
           You still need to enable Memcached in your config.php.
           See https://docs.nextcloud.com/server/14/admin_manual/configuration_server/caching_configuration.html
@@ -483,7 +559,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Run regular auto update of all apps installed from the nextcloud app store.
         '';
       };
@@ -491,31 +567,92 @@ in {
         type = with types; either str (listOf str);
         default = "05:00:00";
         example = "Sun 14:00:00";
-        description = ''
-          When to run the update. See `systemd.services.&lt;name&gt;.startAt`.
+        description = lib.mdDoc ''
+          When to run the update. See `systemd.services.<name>.startAt`.
         '';
       };
     };
     occ = mkOption {
       type = types.package;
       default = occ;
-      defaultText = literalDocBook "generated script";
+      defaultText = literalMD "generated script";
       internal = true;
-      description = ''
+      description = lib.mdDoc ''
         The nextcloud-occ program preconfigured to target this Nextcloud instance.
       '';
     };
+    globalProfiles = mkEnableOption (lib.mdDoc "global profiles") // {
+      description = lib.mdDoc ''
+        Makes user-profiles globally available under `nextcloud.tld/u/user.name`.
+        Even though it's enabled by default in Nextcloud, it must be explicitly enabled
+        here because it has the side-effect that personal information is even accessible to
+        unauthenticated users by default.
+
+        By default, the following properties are set to “Show to everyone”
+        if this flag is enabled:
+        - About
+        - Full name
+        - Headline
+        - Organisation
+        - Profile picture
+        - Role
+        - Twitter
+        - Website
+
+        Only has an effect in Nextcloud 23 and later.
+      '';
+    };
 
-    nginx.recommendedHttpHeaders = mkOption {
-      type = types.bool;
-      default = true;
-      description = "Enable additional recommended HTTP response headers";
+    extraOptions = mkOption {
+      type = jsonFormat.type;
+      default = {};
+      description = lib.mdDoc ''
+        Extra options which should be appended to nextcloud's config.php file.
+      '';
+      example = literalExpression '' {
+        redis = {
+          host = "/run/redis/redis.sock";
+          port = 0;
+          dbindex = 0;
+          password = "secret";
+          timeout = 1.5;
+        };
+      } '';
+    };
+
+    secretFile = mkOption {
+      type = types.nullOr types.str;
+      default = null;
+      description = lib.mdDoc ''
+        Secret options which will be appended to nextcloud's config.php file (written as JSON, in the same
+        form as the [](#opt-services.nextcloud.extraOptions) option), for example
+        `{"redis":{"password":"secret"}}`.
+      '';
+    };
+
+    nginx = {
+      recommendedHttpHeaders = mkOption {
+        type = types.bool;
+        default = true;
+        description = lib.mdDoc "Enable additional recommended HTTP response headers";
+      };
+      hstsMaxAge = mkOption {
+        type = types.ints.positive;
+        default = 15552000;
+        description = lib.mdDoc ''
+          Value for the `max-age` directive of the HTTP
+          `Strict-Transport-Security` header.
+
+          See section 6.1.1 of IETF RFC 6797 for detailed information on this
+          directive and header.
+        '';
+      };
     };
   };
 
   config = mkIf cfg.enable (mkMerge [
     { warnings = let
-        latest = 23;
+        latest = 25;
         upgradeWarning = major: nixos:
           ''
             A legacy Nextcloud install (from before NixOS ${nixos}) may be installed.
@@ -548,9 +685,26 @@ in {
           Using config.services.nextcloud.poolConfig is deprecated and will become unsupported in a future release.
           Please migrate your configuration to config.services.nextcloud.poolSettings.
         '')
-        ++ (optional (versionOlder cfg.package.version "21") (upgradeWarning 20 "21.05"))
-        ++ (optional (versionOlder cfg.package.version "22") (upgradeWarning 21 "21.11"))
         ++ (optional (versionOlder cfg.package.version "23") (upgradeWarning 22 "22.05"))
+        ++ (optional (versionOlder cfg.package.version "24") (upgradeWarning 23 "22.05"))
+        ++ (optional (versionOlder cfg.package.version "25") (upgradeWarning 24 "22.11"))
+        ++ (optional cfg.enableBrokenCiphersForSSE ''
+          You're using PHP's openssl extension built against OpenSSL 1.1 for Nextcloud.
+          This is only necessary if you're using Nextcloud's server-side encryption.
+          Please keep in mind that it's using the broken RC4 cipher.
+
+          If you don't use that feature, you can switch to OpenSSL 3 and get
+          rid of this warning by declaring
+
+            services.nextcloud.enableBrokenCiphersForSSE = false;
+
+          If you need to use server-side encryption you can ignore this waring.
+          Otherwise you'd have to disable server-side encryption first in order
+          to be able to safely disable this option and get rid of this warning.
+          See <https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/encryption_configuration.html#disabling-encryption> on how to achieve this.
+
+          For more context, here is the implementing pull request: https://github.com/NixOS/nixpkgs/pull/198470
+        '')
         ++ (optional isUnsupportedMariadb ''
             You seem to be using MariaDB at an unsupported version (i.e. at least 10.6)!
             Please note that this isn't supported officially by Nextcloud. You can either
@@ -571,20 +725,24 @@ in {
               nextcloud defined in an overlay, please set `services.nextcloud.package` to
               `pkgs.nextcloud`.
             ''
-          else if versionOlder stateVersion "21.11" then nextcloud21
-          else if versionOlder stateVersion "22.05" then nextcloud22
-          else nextcloud23
+          else if versionOlder stateVersion "22.11" then nextcloud24
+          else nextcloud25
         );
 
-      services.nextcloud.datadir = mkOptionDefault config.services.nextcloud.home;
-
       services.nextcloud.phpPackage =
-        if versionOlder cfg.package.version "21" then pkgs.php74
-        else pkgs.php80;
+        if versionOlder cfg.package.version "24" then pkgs.php80
+        else pkgs.php81;
     }
 
+    { assertions = [
+      { assertion = cfg.database.createLocally -> cfg.config.dbtype == "mysql";
+        message = ''services.nextcloud.config.dbtype must be set to mysql if services.nextcloud.database.createLocally is set to true.'';
+      }
+    ]; }
+
     { systemd.timers.nextcloud-cron = {
         wantedBy = [ "timers.target" ];
+        after = [ "nextcloud-setup.service" ];
         timerConfig.OnBootSec = "5m";
         timerConfig.OnUnitActiveSec = "5m";
         timerConfig.Unit = "nextcloud-cron.service";
@@ -627,6 +785,8 @@ in {
               if x == null then "false"
               else boolToString x;
 
+          nextcloudGreaterOrEqualThan = req: versionAtLeast cfg.package.version req;
+
           overrideConfig = pkgs.writeText "nextcloud-config.php" ''
             <?php
             ${optionalString requiresReadSecretFunction ''
@@ -639,10 +799,20 @@ in {
                     $file
                   ));
                 }
-
                 return trim(file_get_contents($file));
+              }''}
+            function nix_decode_json_file($file, $error) {
+              if (!file_exists($file)) {
+                throw new \RuntimeException(sprintf($error, $file));
               }
-            ''}
+              $decoded = json_decode(file_get_contents($file), true);
+
+              if (json_last_error() !== JSON_ERROR_NONE) {
+                throw new \RuntimeException(sprintf("Cannot decode %s, because: %s", $file, json_last_error_msg()));
+              }
+
+              return $decoded;
+            }
             $CONFIG = [
               'apps_paths' => [
                 ${optionalString (cfg.extraApps != { }) "[ 'path' => '${cfg.home}/nix-apps', 'url' => '/nix-apps', 'writable' => false ],"}
@@ -653,21 +823,39 @@ in {
               'datadirectory' => '${datadir}/data',
               'skeletondirectory' => '${cfg.skeletonDirectory}',
               ${optionalString cfg.caching.apcu "'memcache.local' => '\\OC\\Memcache\\APCu',"}
-              'log_type' => 'syslog',
-              'log_level' => '${builtins.toString cfg.logLevel}',
+              'log_type' => '${cfg.logType}',
+              'loglevel' => '${builtins.toString cfg.logLevel}',
               ${optionalString (c.overwriteProtocol != null) "'overwriteprotocol' => '${c.overwriteProtocol}',"}
               ${optionalString (c.dbname != null) "'dbname' => '${c.dbname}',"}
               ${optionalString (c.dbhost != null) "'dbhost' => '${c.dbhost}',"}
               ${optionalString (c.dbport != null) "'dbport' => '${toString c.dbport}',"}
               ${optionalString (c.dbuser != null) "'dbuser' => '${c.dbuser}',"}
               ${optionalString (c.dbtableprefix != null) "'dbtableprefix' => '${toString c.dbtableprefix}',"}
-              ${optionalString (c.dbpassFile != null) "'dbpassword' => nix_read_secret('${c.dbpassFile}'),"}
+              ${optionalString (c.dbpassFile != null) ''
+                  'dbpassword' => nix_read_secret(
+                    "${c.dbpassFile}"
+                  ),
+                ''
+              }
               'dbtype' => '${c.dbtype}',
               'trusted_domains' => ${writePhpArrary ([ cfg.hostName ] ++ c.extraTrustedDomains)},
               'trusted_proxies' => ${writePhpArrary (c.trustedProxies)},
               ${optionalString (c.defaultPhoneRegion != null) "'default_phone_region' => '${c.defaultPhoneRegion}',"}
+              ${optionalString (nextcloudGreaterOrEqualThan "23") "'profile.enabled' => ${boolToString cfg.globalProfiles},"}
               ${objectstoreConfig}
             ];
+
+            $CONFIG = array_replace_recursive($CONFIG, nix_decode_json_file(
+              "${jsonFormat.generate "nextcloud-extraOptions.json" cfg.extraOptions}",
+              "impossible: this should never happen (decoding generated extraOptions file %s failed)"
+            ));
+
+            ${optionalString (cfg.secretFile != null) ''
+              $CONFIG = array_replace_recursive($CONFIG, nix_decode_json_file(
+                "${cfg.secretFile}",
+                "Cannot start Nextcloud, secrets file %s set by NixOS doesn't exist!"
+              ));
+            ''}
           '';
           occInstallCmd = let
             mkExport = { arg, value }: "export ${arg}=${value}";
@@ -691,9 +879,9 @@ in {
               ${if c.dbhost != null then "--database-host" else null} = ''"${c.dbhost}"'';
               ${if c.dbport != null then "--database-port" else null} = ''"${toString c.dbport}"'';
               ${if c.dbuser != null then "--database-user" else null} = ''"${c.dbuser}"'';
-              "--database-pass" = "\$${dbpass.arg}";
+              "--database-pass" = "\"\$${dbpass.arg}\"";
               "--admin-user" = ''"${c.adminuser}"'';
-              "--admin-pass" = "\$${adminpass.arg}";
+              "--admin-pass" = "\"\$${adminpass.arg}\"";
               "--data-dir" = ''"${datadir}/data"'';
             });
           in ''
@@ -762,7 +950,7 @@ in {
             ${occ}/bin/nextcloud-occ config:system:delete trusted_domains
 
             ${optionalString (cfg.extraAppsEnable && cfg.extraApps != { }) ''
-                # Try to enable apps (don't fail when one of them cannot be enabled , eg. due to incompatible version)
+                # Try to enable apps
                 ${occ}/bin/nextcloud-occ app:enable ${concatStringsSep " " (attrNames cfg.extraApps)}
             ''}
 
@@ -772,12 +960,14 @@ in {
           serviceConfig.User = "nextcloud";
         };
         nextcloud-cron = {
+          after = [ "nextcloud-setup.service" ];
           environment.NEXTCLOUD_CONFIG_DIR = "${datadir}/config";
           serviceConfig.Type = "oneshot";
           serviceConfig.User = "nextcloud";
           serviceConfig.ExecStart = "${phpPackage}/bin/php -f ${cfg.package}/cron.php";
         };
         nextcloud-update-plugins = mkIf cfg.autoUpdateApps.enable {
+          after = [ "nextcloud-setup.service" ];
           serviceConfig.Type = "oneshot";
           serviceConfig.ExecStart = "${occ}/bin/nextcloud-occ app:update --all";
           serviceConfig.User = "nextcloud";
@@ -811,6 +1001,32 @@ in {
 
       environment.systemPackages = [ occ ];
 
+      services.mysql = lib.mkIf cfg.database.createLocally {
+        enable = true;
+        package = lib.mkDefault pkgs.mariadb;
+        ensureDatabases = [ cfg.config.dbname ];
+        ensureUsers = [{
+          name = cfg.config.dbuser;
+          ensurePermissions = { "${cfg.config.dbname}.*" = "ALL PRIVILEGES"; };
+        }];
+        # FIXME(@Ma27) Nextcloud isn't compatible with mariadb 10.6,
+        # this is a workaround.
+        # See https://help.nextcloud.com/t/update-to-next-cloud-21-0-2-has-get-an-error/117028/22
+        settings = mkIf (versionOlder cfg.package.version "24") {
+          mysqld = {
+            innodb_read_only_compressed = 0;
+          };
+        };
+        initialScript = pkgs.writeText "mysql-init" ''
+          CREATE USER '${cfg.config.dbname}'@'localhost' IDENTIFIED BY '${builtins.readFile( cfg.config.dbpassFile )}';
+          CREATE DATABASE IF NOT EXISTS ${cfg.config.dbname};
+          GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER,
+            CREATE TEMPORARY TABLES ON ${cfg.config.dbname}.* TO '${cfg.config.dbuser}'@'localhost'
+            IDENTIFIED BY '${builtins.readFile( cfg.config.dbpassFile )}';
+          FLUSH privileges;
+        '';
+      };
+
       services.nginx.enable = mkDefault true;
 
       services.nginx.virtualHosts.${cfg.hostName} = {
@@ -820,7 +1036,6 @@ in {
             priority = 100;
             extraConfig = ''
               allow all;
-              log_not_found off;
               access_log off;
             '';
           };
@@ -881,7 +1096,7 @@ in {
               fastcgi_pass unix:${fpm.socket};
               fastcgi_intercept_errors on;
               fastcgi_request_buffering off;
-              fastcgi_read_timeout 120s;
+              fastcgi_read_timeout ${builtins.toString cfg.fastcgiTimeout}s;
             '';
           };
           "~ \\.(?:css|js|woff2?|svg|gif|map)$".extraConfig = ''
@@ -908,7 +1123,9 @@ in {
             add_header X-Permitted-Cross-Domain-Policies none;
             add_header X-Frame-Options sameorigin;
             add_header Referrer-Policy no-referrer;
-            add_header Strict-Transport-Security "max-age=15552000; includeSubDomains" always;
+          ''}
+          ${optionalString (cfg.https) ''
+            add_header Strict-Transport-Security "max-age=${toString cfg.nginx.hstsMaxAge}; includeSubDomains" always;
           ''}
           client_max_body_size ${cfg.maxUploadSize};
           fastcgi_buffers 64 4K;
diff --git a/nixos/modules/services/web-apps/nextcloud.xml b/nixos/modules/services/web-apps/nextcloud.xml
index 8f55086a2bd..ca57692fc16 100644
--- a/nixos/modules/services/web-apps/nextcloud.xml
+++ b/nixos/modules/services/web-apps/nextcloud.xml
@@ -11,7 +11,7 @@
   desktop client is packaged at <literal>pkgs.nextcloud-client</literal>.
  </para>
  <para>
-  The current default by NixOS is <package>nextcloud23</package> which is also the latest
+  The current default by NixOS is <package>nextcloud25</package> which is also the latest
   major version available.
  </para>
  <section xml:id="module-services-nextcloud-basic-usage">
@@ -170,6 +170,20 @@
      </listitem>
     </itemizedlist>
    </listitem>
+   <listitem>
+    <formalpara>
+     <title>Server-side encryption</title>
+     <para>
+      Nextcloud supports <link xlink:href="https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/encryption_configuration.html">server-side encryption (SSE)</link>.
+      This is not an end-to-end encryption, but can be used to encrypt files that will be persisted
+      to external storage such as S3. Please note that this won't work anymore when using OpenSSL 3
+      for PHP's openssl extension because this is implemented using the legacy cipher RC4.
+      If <xref linkend="opt-system.stateVersion" /> is <emphasis>above</emphasis> <literal>22.05</literal>,
+      this is disabled by default. To turn it on again and for further information please refer to
+      <xref linkend="opt-services.nextcloud.enableBrokenCiphersForSSE" />.
+     </para>
+    </formalpara>
+   </listitem>
   </itemizedlist>
  </section>
 
diff --git a/nixos/modules/services/web-apps/nexus.nix b/nixos/modules/services/web-apps/nexus.nix
index dc50a06705f..1f4a758b87e 100644
--- a/nixos/modules/services/web-apps/nexus.nix
+++ b/nixos/modules/services/web-apps/nexus.nix
@@ -11,43 +11,43 @@ in
 {
   options = {
     services.nexus = {
-      enable = mkEnableOption "Sonatype Nexus3 OSS service";
+      enable = mkEnableOption (lib.mdDoc "Sonatype Nexus3 OSS service");
 
       package = mkOption {
         type = types.package;
         default = pkgs.nexus;
         defaultText = literalExpression "pkgs.nexus";
-        description = "Package which runs Nexus3";
+        description = lib.mdDoc "Package which runs Nexus3";
       };
 
       user = mkOption {
         type = types.str;
         default = "nexus";
-        description = "User which runs Nexus3.";
+        description = lib.mdDoc "User which runs Nexus3.";
       };
 
       group = mkOption {
         type = types.str;
         default = "nexus";
-        description = "Group which runs Nexus3.";
+        description = lib.mdDoc "Group which runs Nexus3.";
       };
 
       home = mkOption {
         type = types.str;
         default = "/var/lib/sonatype-work";
-        description = "Home directory of the Nexus3 instance.";
+        description = lib.mdDoc "Home directory of the Nexus3 instance.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "Address to listen on.";
+        description = lib.mdDoc "Address to listen on.";
       };
 
       listenPort = mkOption {
         type = types.int;
         default = 8081;
-        description = "Port to listen on.";
+        description = lib.mdDoc "Port to listen on.";
       };
 
       jvmOpts = mkOption {
@@ -93,7 +93,7 @@ in
           '''
         '';
 
-        description = ''
+        description = lib.mdDoc ''
           Options for the JVM written to `nexus.jvmopts`.
           Please refer to the docs (https://help.sonatype.com/repomanager3/installation/configuring-the-runtime-environment)
           for further information.
diff --git a/nixos/modules/services/web-apps/nifi.nix b/nixos/modules/services/web-apps/nifi.nix
new file mode 100644
index 00000000000..f643e24d81d
--- /dev/null
+++ b/nixos/modules/services/web-apps/nifi.nix
@@ -0,0 +1,318 @@
+{ lib, pkgs, config, options, ... }:
+
+let
+  cfg = config.services.nifi;
+  opt = options.services.nifi;
+
+  env = {
+    NIFI_OVERRIDE_NIFIENV = "true";
+    NIFI_HOME = "/var/lib/nifi";
+    NIFI_PID_DIR = "/run/nifi";
+    NIFI_LOG_DIR = "/var/log/nifi";
+  };
+
+  envFile = pkgs.writeText "nifi.env" (lib.concatMapStrings (s: s + "\n") (
+    (lib.concatLists (lib.mapAttrsToList (name: value:
+      if value != null then [
+        "${name}=\"${toString value}\""
+      ] else []
+    ) env))));
+
+  nifiEnv = pkgs.writeShellScriptBin "nifi-env" ''
+    set -a
+    source "${envFile}"
+    eval -- "\$@"
+  '';
+
+in {
+  options = {
+    services.nifi = {
+      enable = lib.mkEnableOption (lib.mdDoc "Apache NiFi");
+
+      package = lib.mkOption {
+        type = lib.types.package;
+        default = pkgs.nifi;
+        defaultText = lib.literalExpression "pkgs.nifi";
+        description = lib.mdDoc "Apache NiFi package to use.";
+      };
+
+      user = lib.mkOption {
+        type = lib.types.str;
+        default = "nifi";
+        description = lib.mdDoc "User account where Apache NiFi runs.";
+      };
+
+      group = lib.mkOption {
+        type = lib.types.str;
+        default = "nifi";
+        description = lib.mdDoc "Group account where Apache NiFi runs.";
+      };
+
+      enableHTTPS = lib.mkOption {
+        type = lib.types.bool;
+        default = true;
+        description = lib.mdDoc "Enable HTTPS protocol. Don`t use in production.";
+      };
+
+      listenHost = lib.mkOption {
+        type = lib.types.str;
+        default = if cfg.enableHTTPS then "0.0.0.0" else "127.0.0.1";
+        defaultText = lib.literalExpression ''
+          if config.${opt.enableHTTPS}
+          then "0.0.0.0"
+          else "127.0.0.1"
+        '';
+        description = lib.mdDoc "Bind to an ip for Apache NiFi web-ui.";
+      };
+
+      listenPort = lib.mkOption {
+        type = lib.types.int;
+        default = if cfg.enableHTTPS then 8443 else 8080;
+        defaultText = lib.literalExpression ''
+          if config.${opt.enableHTTPS}
+          then "8443"
+          else "8000"
+        '';
+        description = lib.mdDoc "Bind to a port for Apache NiFi web-ui.";
+      };
+
+      proxyHost = lib.mkOption {
+        type = lib.types.nullOr lib.types.str;
+        default = if cfg.enableHTTPS then "0.0.0.0" else null;
+        defaultText = lib.literalExpression ''
+          if config.${opt.enableHTTPS}
+          then "0.0.0.0"
+          else null
+        '';
+        description = lib.mdDoc "Allow requests from a specific host.";
+      };
+
+      proxyPort = lib.mkOption {
+        type = lib.types.nullOr lib.types.int;
+        default = if cfg.enableHTTPS then 8443 else null;
+        defaultText = lib.literalExpression ''
+          if config.${opt.enableHTTPS}
+          then "8443"
+          else null
+        '';
+        description = lib.mdDoc "Allow requests from a specific port.";
+      };
+
+      initUser = lib.mkOption {
+        type = lib.types.nullOr lib.types.str;
+        default = null;
+        description = lib.mdDoc "Initial user account for Apache NiFi. Username must be at least 4 characters.";
+      };
+
+      initPasswordFile = lib.mkOption {
+        type = lib.types.nullOr lib.types.path;
+        default = null;
+        example = "/run/keys/nifi/password-nifi";
+        description = lib.mdDoc "nitial password for Apache NiFi. Password must be at least 12 characters.";
+      };
+
+      initJavaHeapSize = lib.mkOption {
+        type = lib.types.nullOr lib.types.int;
+        default = null;
+        example = 1024;
+        description = lib.mdDoc "Set the initial heap size for the JVM in MB.";
+      };
+
+      maxJavaHeapSize = lib.mkOption {
+        type = lib.types.nullOr lib.types.int;
+        default = null;
+        example = 2048;
+        description = lib.mdDoc "Set the initial heap size for the JVM in MB.";
+      };
+    };
+  };
+
+  config = lib.mkIf cfg.enable {
+    assertions = [
+      { assertion = cfg.initUser!=null || cfg.initPasswordFile==null;
+          message = ''
+            <option>services.nifi.initUser</option> needs to be set if <option>services.nifi.initPasswordFile</option> enabled.
+          '';
+      }
+      { assertion = cfg.initUser==null || cfg.initPasswordFile!=null;
+          message = ''
+            <option>services.nifi.initPasswordFile</option> needs to be set if <option>services.nifi.initUser</option> enabled.
+          '';
+      }
+      { assertion = cfg.proxyHost==null || cfg.proxyPort!=null;
+          message = ''
+            <option>services.nifi.proxyPort</option> needs to be set if <option>services.nifi.proxyHost</option> value specified.
+          '';
+      }
+      { assertion = cfg.proxyHost!=null || cfg.proxyPort==null;
+          message = ''
+            <option>services.nifi.proxyHost</option> needs to be set if <option>services.nifi.proxyPort</option> value specified.
+          '';
+      }
+      { assertion = cfg.initJavaHeapSize==null || cfg.maxJavaHeapSize!=null;
+          message = ''
+            <option>services.nifi.maxJavaHeapSize</option> needs to be set if <option>services.nifi.initJavaHeapSize</option> value specified.
+          '';
+      }
+      { assertion = cfg.initJavaHeapSize!=null || cfg.maxJavaHeapSize==null;
+          message = ''
+            <option>services.nifi.initJavaHeapSize</option> needs to be set if <option>services.nifi.maxJavaHeapSize</option> value specified.
+          '';
+      }
+    ];
+
+    warnings = lib.optional (cfg.enableHTTPS==false) ''
+      Please do not disable HTTPS mode in production. In this mode, access to the nifi is opened without authentication.
+    '';
+
+    systemd.tmpfiles.rules = [
+      "d '/var/lib/nifi/conf' 0750 ${cfg.user} ${cfg.group}"
+      "L+ '/var/lib/nifi/lib' - - - - ${cfg.package}/lib"
+    ];
+
+
+    systemd.services.nifi = {
+      description = "Apache NiFi";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+
+      environment = env;
+      path = [ pkgs.gawk ];
+
+      serviceConfig = {
+        Type = "forking";
+        PIDFile = "/run/nifi/nifi.pid";
+        ExecStartPre = pkgs.writeScript "nifi-pre-start.sh" ''
+          #!/bin/sh
+          umask 077
+          test -f '/var/lib/nifi/conf/authorizers.xml'                      || (cp '${cfg.package}/share/nifi/conf/authorizers.xml' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/authorizers.xml')
+          test -f '/var/lib/nifi/conf/bootstrap.conf'                       || (cp '${cfg.package}/share/nifi/conf/bootstrap.conf' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/bootstrap.conf')
+          test -f '/var/lib/nifi/conf/bootstrap-hashicorp-vault.conf'       || (cp '${cfg.package}/share/nifi/conf/bootstrap-hashicorp-vault.conf' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/bootstrap-hashicorp-vault.conf')
+          test -f '/var/lib/nifi/conf/bootstrap-notification-services.xml'  || (cp '${cfg.package}/share/nifi/conf/bootstrap-notification-services.xml' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/bootstrap-notification-services.xml')
+          test -f '/var/lib/nifi/conf/logback.xml'                          || (cp '${cfg.package}/share/nifi/conf/logback.xml' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/logback.xml')
+          test -f '/var/lib/nifi/conf/login-identity-providers.xml'         || (cp '${cfg.package}/share/nifi/conf/login-identity-providers.xml' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/login-identity-providers.xml')
+          test -f '/var/lib/nifi/conf/nifi.properties'                      || (cp '${cfg.package}/share/nifi/conf/nifi.properties' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/nifi.properties')
+          test -f '/var/lib/nifi/conf/stateless-logback.xml'                || (cp '${cfg.package}/share/nifi/conf/stateless-logback.xml' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/stateless-logback.xml')
+          test -f '/var/lib/nifi/conf/stateless.properties'                 || (cp '${cfg.package}/share/nifi/conf/stateless.properties' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/stateless.properties')
+          test -f '/var/lib/nifi/conf/state-management.xml'                 || (cp '${cfg.package}/share/nifi/conf/state-management.xml' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/state-management.xml')
+          test -f '/var/lib/nifi/conf/zookeeper.properties'                 || (cp '${cfg.package}/share/nifi/conf/zookeeper.properties' '/var/lib/nifi/conf/' && chmod 0640 '/var/lib/nifi/conf/zookeeper.properties')
+          test -d '/var/lib/nifi/docs/html'                                 || (mkdir -p /var/lib/nifi/docs && cp -r '${cfg.package}/share/nifi/docs/html' '/var/lib/nifi/docs/html')
+          ${lib.optionalString ((cfg.initUser != null) && (cfg.initPasswordFile != null)) ''
+            awk -F'[<|>]' '/property name="Username"/ {if ($3!="") f=1} END{exit !f}' /var/lib/nifi/conf/login-identity-providers.xml || ${cfg.package}/bin/nifi.sh set-single-user-credentials ${cfg.initUser} $(cat ${cfg.initPasswordFile})
+          ''}
+          ${lib.optionalString (cfg.enableHTTPS == false) ''
+            sed -i /var/lib/nifi/conf/nifi.properties \
+              -e 's|nifi.remote.input.secure=.*|nifi.remote.input.secure=false|g' \
+              -e 's|nifi.web.http.host=.*|nifi.web.http.host=${cfg.listenHost}|g' \
+              -e 's|nifi.web.http.port=.*|nifi.web.http.port=${(toString cfg.listenPort)}|g' \
+              -e 's|nifi.web.https.host=.*|nifi.web.https.host=|g' \
+              -e 's|nifi.web.https.port=.*|nifi.web.https.port=|g' \
+              -e 's|nifi.security.keystore=.*|nifi.security.keystore=|g' \
+              -e 's|nifi.security.keystoreType=.*|nifi.security.keystoreType=|g' \
+              -e 's|nifi.security.truststore=.*|nifi.security.truststore=|g' \
+              -e 's|nifi.security.truststoreType=.*|nifi.security.truststoreType=|g' \
+              -e '/nifi.security.keystorePasswd/s|^|#|' \
+              -e '/nifi.security.keyPasswd/s|^|#|' \
+              -e '/nifi.security.truststorePasswd/s|^|#|'
+          ''}
+          ${lib.optionalString (cfg.enableHTTPS == true) ''
+            sed -i /var/lib/nifi/conf/nifi.properties \
+              -e 's|nifi.remote.input.secure=.*|nifi.remote.input.secure=true|g' \
+              -e 's|nifi.web.http.host=.*|nifi.web.http.host=|g' \
+              -e 's|nifi.web.http.port=.*|nifi.web.http.port=|g' \
+              -e 's|nifi.web.https.host=.*|nifi.web.https.host=${cfg.listenHost}|g' \
+              -e 's|nifi.web.https.port=.*|nifi.web.https.port=${(toString cfg.listenPort)}|g' \
+              -e 's|nifi.security.keystore=.*|nifi.security.keystore=./conf/keystore.p12|g' \
+              -e 's|nifi.security.keystoreType=.*|nifi.security.keystoreType=PKCS12|g' \
+              -e 's|nifi.security.truststore=.*|nifi.security.truststore=./conf/truststore.p12|g' \
+              -e 's|nifi.security.truststoreType=.*|nifi.security.truststoreType=PKCS12|g' \
+              -e '/nifi.security.keystorePasswd/s|^#\+||' \
+              -e '/nifi.security.keyPasswd/s|^#\+||' \
+              -e '/nifi.security.truststorePasswd/s|^#\+||'
+          ''}
+          ${lib.optionalString ((cfg.enableHTTPS == true) && (cfg.proxyHost != null) && (cfg.proxyPort != null)) ''
+            sed -i /var/lib/nifi/conf/nifi.properties \
+              -e 's|nifi.web.proxy.host=.*|nifi.web.proxy.host=${cfg.proxyHost}:${(toString cfg.proxyPort)}|g'
+          ''}
+          ${lib.optionalString ((cfg.enableHTTPS == false) || (cfg.proxyHost == null) && (cfg.proxyPort == null)) ''
+            sed -i /var/lib/nifi/conf/nifi.properties \
+              -e 's|nifi.web.proxy.host=.*|nifi.web.proxy.host=|g'
+          ''}
+          ${lib.optionalString ((cfg.initJavaHeapSize != null) && (cfg.maxJavaHeapSize != null))''
+            sed -i /var/lib/nifi/conf/bootstrap.conf \
+              -e 's|java.arg.2=.*|java.arg.2=-Xms${(toString cfg.initJavaHeapSize)}m|g' \
+              -e 's|java.arg.3=.*|java.arg.3=-Xmx${(toString cfg.maxJavaHeapSize)}m|g'
+          ''}
+          ${lib.optionalString ((cfg.initJavaHeapSize == null) && (cfg.maxJavaHeapSize == null))''
+            sed -i /var/lib/nifi/conf/bootstrap.conf \
+              -e 's|java.arg.2=.*|java.arg.2=-Xms512m|g' \
+              -e 's|java.arg.3=.*|java.arg.3=-Xmx512m|g'
+          ''}
+        '';
+        ExecStart = "${cfg.package}/bin/nifi.sh start";
+        ExecStop = "${cfg.package}/bin/nifi.sh stop";
+        # User and group
+        User = cfg.user;
+        Group = cfg.group;
+        # Runtime directory and mode
+        RuntimeDirectory = "nifi";
+        RuntimeDirectoryMode = "0750";
+        # State directory and mode
+        StateDirectory = "nifi";
+        StateDirectoryMode = "0750";
+        # Logs directory and mode
+        LogsDirectory = "nifi";
+        LogsDirectoryMode = "0750";
+        # Proc filesystem
+        ProcSubset = "pid";
+        ProtectProc = "invisible";
+        # Access write directories
+        ReadWritePaths = [ cfg.initPasswordFile ];
+        UMask = "0027";
+        # Capabilities
+        CapabilityBoundingSet = "";
+        # Security
+        NoNewPrivileges = true;
+        # Sandboxing
+        ProtectSystem = "strict";
+        ProtectHome = true;
+        PrivateTmp = true;
+        PrivateDevices = true;
+        PrivateIPC = true;
+        PrivateUsers = true;
+        ProtectHostname = true;
+        ProtectClock = true;
+        ProtectKernelTunables = true;
+        ProtectKernelModules = true;
+        ProtectKernelLogs = true;
+        ProtectControlGroups = true;
+        RestrictAddressFamilies = [ "AF_INET AF_INET6" ];
+        RestrictNamespaces = true;
+        LockPersonality = true;
+        MemoryDenyWriteExecute  = false;
+        RestrictRealtime = true;
+        RestrictSUIDSGID = true;
+        RemoveIPC = true;
+        PrivateMounts = true;
+        # System Call Filtering
+        SystemCallArchitectures = "native";
+        SystemCallFilter = [ "~@cpu-emulation @debug @keyring @memlock @mount @obsolete @resources @privileged @setuid" "@chown" ];
+      };
+    };
+
+    users.users = lib.mkMerge [
+      (lib.mkIf (cfg.user == "nifi") {
+        nifi = {
+          group = cfg.group;
+          isSystemUser = true;
+          home = cfg.package;
+        };
+      })
+      (lib.attrsets.setAttrByPath [ cfg.user "packages" ] [ cfg.package nifiEnv ])
+    ];
+
+    users.groups = lib.optionalAttrs (cfg.group == "nifi") {
+      nifi = { };
+    };
+  };
+}
diff --git a/nixos/modules/services/web-apps/node-red.nix b/nixos/modules/services/web-apps/node-red.nix
index 4512907f027..f4d4ad9681a 100644
--- a/nixos/modules/services/web-apps/node-red.nix
+++ b/nixos/modules/services/web-apps/node-red.nix
@@ -17,19 +17,19 @@ let
 in
 {
   options.services.node-red = {
-    enable = mkEnableOption "the Node-RED service";
+    enable = mkEnableOption (lib.mdDoc "the Node-RED service");
 
     package = mkOption {
       default = pkgs.nodePackages.node-red;
       defaultText = literalExpression "pkgs.nodePackages.node-red";
       type = types.package;
-      description = "Node-RED package to use.";
+      description = lib.mdDoc "Node-RED package to use.";
     };
 
     openFirewall = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Open ports in the firewall for the server.
       '';
     };
@@ -37,7 +37,7 @@ in
     withNpmAndGcc = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Give Node-RED access to NPM and GCC at runtime, so 'Nodes' can be
         downloaded and managed imperatively via the 'Palette Manager'.
       '';
@@ -47,10 +47,9 @@ in
       type = types.path;
       default = "${cfg.package}/lib/node_modules/node-red/settings.js";
       defaultText = literalExpression ''"''${package}/lib/node_modules/node-red/settings.js"'';
-      description = ''
+      description = lib.mdDoc ''
         Path to the JavaScript configuration file.
-        See <link
-        xlink:href="https://github.com/node-red/node-red/blob/master/packages/node_modules/node-red/settings.js"/>
+        See <https://github.com/node-red/node-red/blob/master/packages/node_modules/node-red/settings.js>
         for a configuration example.
       '';
     };
@@ -58,13 +57,13 @@ in
     port = mkOption {
       type = types.port;
       default = 1880;
-      description = "Listening port.";
+      description = lib.mdDoc "Listening port.";
     };
 
     user = mkOption {
       type = types.str;
       default = defaultUser;
-      description = ''
+      description = lib.mdDoc ''
         User under which Node-RED runs.If left as the default value this user
         will automatically be created on system activation, otherwise the
         sysadmin is responsible for ensuring the user exists.
@@ -74,7 +73,7 @@ in
     group = mkOption {
       type = types.str;
       default = defaultUser;
-      description = ''
+      description = lib.mdDoc ''
         Group under which Node-RED runs.If left as the default value this group
         will automatically be created on system activation, otherwise the
         sysadmin is responsible for ensuring the group exists.
@@ -84,7 +83,7 @@ in
     userDir = mkOption {
       type = types.path;
       default = "/var/lib/node-red";
-      description = ''
+      description = lib.mdDoc ''
         The directory to store all user data, such as flow and credential files and all library data. If left
         as the default value this directory will automatically be created before the node-red service starts,
         otherwise the sysadmin is responsible for ensuring the directory exists with appropriate ownership
@@ -95,13 +94,13 @@ in
     safe = mkOption {
       type = types.bool;
       default = false;
-      description = "Whether to launch Node-RED in --safe mode.";
+      description = lib.mdDoc "Whether to launch Node-RED in --safe mode.";
     };
 
     define = mkOption {
       type = types.attrs;
       default = {};
-      description = "List of settings.js overrides to pass via -D to Node-RED.";
+      description = lib.mdDoc "List of settings.js overrides to pass via -D to Node-RED.";
       example = literalExpression ''
         {
           "logging.console.level" = "trace";
diff --git a/nixos/modules/services/web-apps/onlyoffice.nix b/nixos/modules/services/web-apps/onlyoffice.nix
new file mode 100644
index 00000000000..db4a9582794
--- /dev/null
+++ b/nixos/modules/services/web-apps/onlyoffice.nix
@@ -0,0 +1,291 @@
+{ lib, config, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.onlyoffice;
+in
+{
+  options.services.onlyoffice = {
+    enable = mkEnableOption (lib.mdDoc "OnlyOffice DocumentServer");
+
+    enableExampleServer = mkEnableOption (lib.mdDoc "OnlyOffice example server");
+
+    hostname = mkOption {
+      type = types.str;
+      default = "localhost";
+      description = lib.mdDoc "FQDN for the onlyoffice instance.";
+    };
+
+    jwtSecretFile = mkOption {
+      type = types.nullOr types.str;
+      default = null;
+      description = lib.mdDoc ''
+        Path to a file that contains the secret to sign web requests using JSON Web Tokens.
+        If left at the default value null signing is disabled.
+      '';
+    };
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.onlyoffice-documentserver;
+      defaultText = "pkgs.onlyoffice-documentserver";
+      description = lib.mdDoc "Which package to use for the OnlyOffice instance.";
+    };
+
+    port = mkOption {
+      type = types.port;
+      default = 8000;
+      description = lib.mdDoc "Port the OnlyOffice DocumentServer should listens on.";
+    };
+
+    examplePort = mkOption {
+      type = types.port;
+      default = null;
+      description = lib.mdDoc "Port the OnlyOffice Example server should listens on.";
+    };
+
+    postgresHost = mkOption {
+      type = types.str;
+      default = "/run/postgresql";
+      description = lib.mdDoc "The Postgresql hostname or socket path OnlyOffice should connect to.";
+    };
+
+    postgresName = mkOption {
+      type = types.str;
+      default = "onlyoffice";
+      description = lib.mdDoc "The name of databse OnlyOffice should user.";
+    };
+
+    postgresPasswordFile = mkOption {
+      type = types.nullOr types.str;
+      default = null;
+      description = lib.mdDoc ''
+        Path to a file that contains the password OnlyOffice should use to connect to Postgresql.
+        Unused when using socket authentication.
+      '';
+    };
+
+    postgresUser = mkOption {
+      type = types.str;
+      default = "onlyoffice";
+      description = lib.mdDoc ''
+        The username OnlyOffice should use to connect to Postgresql.
+        Unused when using socket authentication.
+      '';
+    };
+
+    rabbitmqUrl = mkOption {
+      type = types.str;
+      default = "amqp://guest:guest@localhost:5672";
+      description = lib.mdDoc "The Rabbitmq in amqp URI style OnlyOffice should connect to.";
+    };
+  };
+
+  config = lib.mkIf cfg.enable {
+    services = {
+      nginx = {
+        enable = mkDefault true;
+        # misses text/csv, font/ttf, application/x-font-ttf, application/rtf, application/wasm
+        recommendedGzipSettings = mkDefault true;
+        recommendedProxySettings = mkDefault true;
+
+        upstreams = {
+          # /etc/nginx/includes/http-common.conf
+          onlyoffice-docservice = {
+            servers = { "localhost:${toString cfg.port}" = { }; };
+          };
+          onlyoffice-example = lib.mkIf cfg.enableExampleServer {
+            servers = { "localhost:${toString cfg.examplePort}" = { }; };
+          };
+        };
+
+        virtualHosts.${cfg.hostname} = {
+          locations = {
+            # /etc/nginx/includes/ds-docservice.conf
+            "~ ^(\/[\d]+\.[\d]+\.[\d]+[\.|-][\d]+)?\/(web-apps\/apps\/api\/documents\/api\.js)$".extraConfig = ''
+              expires -1;
+              alias ${cfg.package}/var/www/onlyoffice/documentserver/$2;
+            '';
+            "~ ^(\/[\d]+\.[\d]+\.[\d]+[\.|-][\d]+)?\/(web-apps)(\/.*\.json)$".extraConfig = ''
+              expires 365d;
+              error_log /dev/null crit;
+              alias ${cfg.package}/var/www/onlyoffice/documentserver/$2$3;
+            '';
+            "~ ^(\/[\d]+\.[\d]+\.[\d]+[\.|-][\d]+)?\/(sdkjs-plugins)(\/.*\.json)$".extraConfig = ''
+              expires 365d;
+              error_log /dev/null crit;
+              alias ${cfg.package}/var/www/onlyoffice/documentserver/$2$3;
+            '';
+            "~ ^(\/[\d]+\.[\d]+\.[\d]+[\.|-][\d]+)?\/(web-apps|sdkjs|sdkjs-plugins|fonts)(\/.*)$".extraConfig = ''
+              expires 365d;
+              alias ${cfg.package}/var/www/onlyoffice/documentserver/$2$3;
+            '';
+            "~* ^(\/cache\/files.*)(\/.*)".extraConfig = ''
+              alias /var/lib/onlyoffice/documentserver/App_Data$1;
+              add_header Content-Disposition "attachment; filename*=UTF-8''$arg_filename";
+
+              set $secret_string verysecretstring;
+              secure_link $arg_md5,$arg_expires;
+              secure_link_md5 "$secure_link_expires$uri$secret_string";
+
+              if ($secure_link = "") {
+                return 403;
+              }
+
+              if ($secure_link = "0") {
+                return 410;
+              }
+            '';
+            "~* ^(\/[\d]+\.[\d]+\.[\d]+[\.|-][\d]+)?\/(internal)(\/.*)$".extraConfig = ''
+              allow 127.0.0.1;
+              deny all;
+              proxy_pass http://onlyoffice-docservice/$2$3;
+            '';
+            "~* ^(\/[\d]+\.[\d]+\.[\d]+[\.|-][\d]+)?\/(info)(\/.*)$".extraConfig = ''
+              allow 127.0.0.1;
+              deny all;
+              proxy_pass http://onlyoffice-docservice/$2$3;
+            '';
+            "/".extraConfig = ''
+              proxy_pass http://onlyoffice-docservice;
+            '';
+            "~ ^(\/[\d]+\.[\d]+\.[\d]+[\.|-][\d]+)?(\/doc\/.*)".extraConfig = ''
+              proxy_pass http://onlyoffice-docservice$2;
+              proxy_http_version 1.1;
+            '';
+            "/${cfg.package.version}/".extraConfig = ''
+              proxy_pass http://onlyoffice-docservice/;
+            '';
+            "~ ^(\/[\d]+\.[\d]+\.[\d]+[\.|-][\d]+)?\/(dictionaries)(\/.*)$".extraConfig = ''
+              expires 365d;
+              alias ${cfg.package}/var/www/onlyoffice/documentserver/$2$3;
+            '';
+            # /etc/nginx/includes/ds-example.conf
+            "~ ^(\/welcome\/.*)$".extraConfig = ''
+              expires 365d;
+              alias ${cfg.package}/var/www/onlyoffice/documentserver-example$1;
+              index docker.html;
+            '';
+            "/example/".extraConfig = lib.mkIf cfg.enableExampleServer ''
+              proxy_pass http://onlyoffice-example/;
+              proxy_set_header X-Forwarded-Path /example;
+            '';
+          };
+          extraConfig = ''
+            rewrite ^/$ /welcome/ redirect;
+            rewrite ^\/OfficeWeb(\/apps\/.*)$ /${cfg.package.version}/web-apps$1 redirect;
+            rewrite ^(\/web-apps\/apps\/(?!api\/).*)$ /${cfg.package.version}$1 redirect;
+
+            # based on https://github.com/ONLYOFFICE/document-server-package/blob/master/common/documentserver/nginx/includes/http-common.conf.m4#L29-L34
+            # without variable indirection and correct variable names
+            proxy_set_header Host $host;
+            proxy_set_header X-Forwarded-Host $host;
+            proxy_set_header X-Forwarded-Proto $scheme;
+            # required for CSP to take effect
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            # required for websocket
+            proxy_set_header Upgrade $http_upgrade;
+            proxy_set_header Connection $connection_upgrade;
+          '';
+        };
+      };
+
+      rabbitmq.enable = lib.mkDefault true;
+
+      postgresql = {
+        enable = lib.mkDefault true;
+        ensureDatabases = [ "onlyoffice" ];
+        ensureUsers = [{
+          name = "onlyoffice";
+          ensurePermissions = { "DATABASE \"onlyoffice\"" = "ALL PRIVILEGES"; };
+        }];
+      };
+    };
+
+    systemd.services = {
+      onlyoffice-converter = {
+        description = "onlyoffice converter";
+        after = [ "network.target" "onlyoffice-docservice.service" "postgresql.service" ];
+        requires = [ "network.target" "onlyoffice-docservice.service" "postgresql.service" ];
+        wantedBy = [ "multi-user.target" ];
+        serviceConfig = {
+          ExecStart = "${cfg.package.fhs}/bin/onlyoffice-wrapper FileConverter/converter /run/onlyoffice/config";
+          Group = "onlyoffice";
+          Restart = "always";
+          RuntimeDirectory = "onlyoffice";
+          StateDirectory = "onlyoffice";
+          Type = "simple";
+          User = "onlyoffice";
+        };
+      };
+
+      onlyoffice-docservice =
+        let
+          onlyoffice-prestart = pkgs.writeShellScript "onlyoffice-prestart" ''
+            PATH=$PATH:${lib.makeBinPath (with pkgs; [ jq moreutils config.services.postgresql.package ])}
+            umask 077
+            mkdir -p /run/onlyoffice/config/ /var/lib/onlyoffice/documentserver/sdkjs/{slide/themes,common}/ /var/lib/onlyoffice/documentserver/{fonts,server/FileConverter/bin}/
+            cp -r ${cfg.package}/etc/onlyoffice/documentserver/* /run/onlyoffice/config/
+            chmod u+w /run/onlyoffice/config/default.json
+
+            cp /run/onlyoffice/config/default.json{,.orig}
+
+            # for a mapping of environment variables from the docker container to json options see
+            # https://github.com/ONLYOFFICE/Docker-DocumentServer/blob/master/run-document-server.sh
+            jq '
+              .services.CoAuthoring.server.port = ${toString cfg.port} |
+              .services.CoAuthoring.sql.dbHost = "${cfg.postgresHost}" |
+              .services.CoAuthoring.sql.dbName = "${cfg.postgresName}" |
+            ${lib.optionalString (cfg.postgresPasswordFile != null) ''
+              .services.CoAuthoring.sql.dbPass = "'"$(cat ${cfg.postgresPasswordFile})"'" |
+            ''}
+              .services.CoAuthoring.sql.dbUser = "${cfg.postgresUser}" |
+            ${lib.optionalString (cfg.jwtSecretFile != null) ''
+              .services.CoAuthoring.token.enable.browser = true |
+              .services.CoAuthoring.token.enable.request.inbox = true |
+              .services.CoAuthoring.token.enable.request.outbox = true |
+              .services.CoAuthoring.secret.inbox.string = "'"$(cat ${cfg.jwtSecretFile})"'" |
+              .services.CoAuthoring.secret.outbox.string = "'"$(cat ${cfg.jwtSecretFile})"'" |
+              .services.CoAuthoring.secret.session.string = "'"$(cat ${cfg.jwtSecretFile})"'" |
+            ''}
+              .rabbitmq.url = "${cfg.rabbitmqUrl}"
+              ' /run/onlyoffice/config/default.json | sponge /run/onlyoffice/config/default.json
+
+            if psql -d onlyoffice -c "SELECT 'task_result'::regclass;" >/dev/null; then
+              psql -f ${cfg.package}/var/www/onlyoffice/documentserver/server/schema/postgresql/removetbl.sql
+              psql -f ${cfg.package}/var/www/onlyoffice/documentserver/server/schema/postgresql/createdb.sql
+            else
+              psql -f ${cfg.package}/var/www/onlyoffice/documentserver/server/schema/postgresql/createdb.sql
+            fi
+          '';
+        in
+        {
+          description = "onlyoffice documentserver";
+          after = [ "network.target" "postgresql.service" ];
+          requires = [ "postgresql.service" ];
+          wantedBy = [ "multi-user.target" ];
+          serviceConfig = {
+            ExecStart = "${cfg.package.fhs}/bin/onlyoffice-wrapper DocService/docservice /run/onlyoffice/config";
+            ExecStartPre = onlyoffice-prestart;
+            Group = "onlyoffice";
+            Restart = "always";
+            RuntimeDirectory = "onlyoffice";
+            StateDirectory = "onlyoffice";
+            Type = "simple";
+            User = "onlyoffice";
+          };
+        };
+    };
+
+    users.users = {
+      onlyoffice = {
+        description = "OnlyOffice Service";
+        group = "onlyoffice";
+        isSystemUser = true;
+      };
+    };
+
+    users.groups.onlyoffice = { };
+  };
+}
diff --git a/nixos/modules/services/web-apps/openwebrx.nix b/nixos/modules/services/web-apps/openwebrx.nix
index 9e90c01e0bb..72c5d6c7818 100644
--- a/nixos/modules/services/web-apps/openwebrx.nix
+++ b/nixos/modules/services/web-apps/openwebrx.nix
@@ -4,13 +4,13 @@ let
 in
 {
   options.services.openwebrx = with lib; {
-    enable = mkEnableOption "OpenWebRX Web interface for Software-Defined Radios on http://localhost:8073";
+    enable = mkEnableOption (lib.mdDoc "OpenWebRX Web interface for Software-Defined Radios on http://localhost:8073");
 
     package = mkOption {
       type = types.package;
       default = pkgs.openwebrx;
       defaultText = literalExpression "pkgs.openwebrx";
-      description = "OpenWebRX package to use for the service";
+      description = lib.mdDoc "OpenWebRX package to use for the service";
     };
   };
 
@@ -19,6 +19,10 @@ in
       wantedBy = [ "multi-user.target" ];
       path = with pkgs; [
         csdr
+        digiham
+        codec2
+        js8call
+        m17-cxx-demod
         alsaUtils
         netcat
       ];
diff --git a/nixos/modules/services/web-apps/outline.nix b/nixos/modules/services/web-apps/outline.nix
new file mode 100644
index 00000000000..701930393f0
--- /dev/null
+++ b/nixos/modules/services/web-apps/outline.nix
@@ -0,0 +1,788 @@
+{ config, lib, pkgs, ...}:
+
+let
+  defaultUser = "outline";
+  cfg = config.services.outline;
+in
+{
+  # See here for a reference of all the options:
+  #   https://github.com/outline/outline/blob/v0.67.0/.env.sample
+  #   https://github.com/outline/outline/blob/v0.67.0/app.json
+  #   https://github.com/outline/outline/blob/v0.67.0/server/env.ts
+  #   https://github.com/outline/outline/blob/v0.67.0/shared/types.ts
+  # The order is kept the same here to make updating easier.
+  options.services.outline = {
+    enable = lib.mkEnableOption (lib.mdDoc "outline");
+
+    package = lib.mkOption {
+      default = pkgs.outline;
+      defaultText = lib.literalExpression "pkgs.outline";
+      type = lib.types.package;
+      example = lib.literalExpression ''
+        pkgs.outline.overrideAttrs (super: {
+          # Ignore the domain part in emails that come from OIDC. This is might
+          # be helpful if you want multiple users with different email providers
+          # to still land in the same team. Note that this effectively makes
+          # Outline a single-team instance.
+          patchPhase = ${"''"}
+            sed -i 's/const domain = parts\.length && parts\[1\];/const domain = "example.com";/g' server/routes/auth/providers/oidc.ts
+          ${"''"};
+        })
+      '';
+      description = lib.mdDoc "Outline package to use.";
+    };
+
+    user = lib.mkOption {
+      type = lib.types.str;
+      default = defaultUser;
+      description = lib.mdDoc ''
+        User under which the service should run. If this is the default value,
+        the user will be created, with the specified group as the primary
+        group.
+      '';
+    };
+
+    group = lib.mkOption {
+      type = lib.types.str;
+      default = defaultUser;
+      description = lib.mdDoc ''
+        Group under which the service should run. If this is the default value,
+        the group will be created.
+      '';
+    };
+
+    sequelizeArguments = lib.mkOption {
+      type = lib.types.str;
+      default = "";
+      example = "--env=production-ssl-disabled";
+      description = lib.mdDoc ''
+        Optional arguments to pass to `sequelize` calls.
+      '';
+    };
+
+    #
+    # Required options
+    #
+
+    secretKeyFile = lib.mkOption {
+      type = lib.types.str;
+      default = "/var/lib/outline/secret_key";
+      description = lib.mdDoc ''
+        File path that contains the application secret key. It must be 32
+        bytes long and hex-encoded. If the file does not exist, a new key will
+        be generated and saved here.
+      '';
+    };
+
+    utilsSecretFile = lib.mkOption {
+      type = lib.types.str;
+      default = "/var/lib/outline/utils_secret";
+      description = lib.mdDoc ''
+        File path that contains the utility secret key. If the file does not
+        exist, a new key will be generated and saved here.
+      '';
+    };
+
+    databaseUrl = lib.mkOption {
+      type = lib.types.str;
+      default = "local";
+      description = lib.mdDoc ''
+        URI to use for the main PostgreSQL database. If this needs to include
+        credentials that shouldn't be world-readable in the Nix store, set an
+        environment file on the systemd service and override the
+        `DATABASE_URL` entry. Pass the string
+        `local` to setup a database on the local server.
+      '';
+    };
+
+    redisUrl = lib.mkOption {
+      type = lib.types.str;
+      default = "local";
+      description = lib.mdDoc ''
+        Connection to a redis server. If this needs to include credentials
+        that shouldn't be world-readable in the Nix store, set an environment
+        file on the systemd service and override the
+        `REDIS_URL` entry. Pass the string
+        `local` to setup a local Redis database.
+      '';
+    };
+
+    publicUrl = lib.mkOption {
+      type = lib.types.str;
+      default = "http://localhost:3000";
+      description = lib.mdDoc "The fully qualified, publicly accessible URL";
+    };
+
+    port = lib.mkOption {
+      type = lib.types.port;
+      default = 3000;
+      description = lib.mdDoc "Listening port.";
+    };
+
+    storage = lib.mkOption {
+      description = lib.mdDoc ''
+        To support uploading of images for avatars and document attachments an
+        s3-compatible storage must be provided. AWS S3 is recommended for
+        redundancy however if you want to keep all file storage local an
+        alternative such as [minio](https://github.com/minio/minio)
+        can be used.
+
+        A more detailed guide on setting up S3 is available
+        [here](https://wiki.generaloutline.com/share/125de1cc-9ff6-424b-8415-0d58c809a40f).
+      '';
+      example = lib.literalExpression ''
+        {
+          accessKey = "...";
+          secretKeyFile = "/somewhere";
+          uploadBucketUrl = "https://minio.example.com";
+          uploadBucketName = "outline";
+          region = "us-east-1";
+        }
+      '';
+      type = lib.types.submodule {
+        options = {
+          accessKey = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "S3 access key.";
+          };
+          secretKeyFile = lib.mkOption {
+            type = lib.types.path;
+            description = lib.mdDoc "File path that contains the S3 secret key.";
+          };
+          region = lib.mkOption {
+            type = lib.types.str;
+            default = "xx-xxxx-x";
+            description = lib.mdDoc "AWS S3 region name.";
+          };
+          uploadBucketUrl = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc ''
+              URL endpoint of an S3-compatible API where uploads should be
+              stored.
+            '';
+          };
+          uploadBucketName = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Name of the bucket where uploads should be stored.";
+          };
+          uploadMaxSize = lib.mkOption {
+            type = lib.types.int;
+            default = 26214400;
+            description = lib.mdDoc "Maxmium file size for uploads.";
+          };
+          forcePathStyle = lib.mkOption {
+            type = lib.types.bool;
+            default = true;
+            description = lib.mdDoc "Force S3 path style.";
+          };
+          acl = lib.mkOption {
+            type = lib.types.str;
+            default = "private";
+            description = lib.mdDoc "ACL setting.";
+          };
+        };
+      };
+    };
+
+    #
+    # Authentication
+    #
+
+    slackAuthentication = lib.mkOption {
+      description = lib.mdDoc ''
+        To configure Slack auth, you'll need to create an Application at
+        https://api.slack.com/apps
+
+        When configuring the Client ID, add a redirect URL under "OAuth & Permissions"
+        to `https://[publicUrl]/auth/slack.callback`.
+      '';
+      default = null;
+      type = lib.types.nullOr (lib.types.submodule {
+        options = {
+          clientId = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Authentication key.";
+          };
+          secretFile = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "File path containing the authentication secret.";
+          };
+        };
+      });
+    };
+
+    googleAuthentication = lib.mkOption {
+      description = lib.mdDoc ''
+        To configure Google auth, you'll need to create an OAuth Client ID at
+        https://console.cloud.google.com/apis/credentials
+
+        When configuring the Client ID, add an Authorized redirect URI to
+        `https://[publicUrl]/auth/google.callback`.
+      '';
+      default = null;
+      type = lib.types.nullOr (lib.types.submodule {
+        options = {
+          clientId = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Authentication client identifier.";
+          };
+          clientSecretFile = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "File path containing the authentication secret.";
+          };
+        };
+      });
+    };
+
+    azureAuthentication = lib.mkOption {
+      description = lib.mdDoc ''
+        To configure Microsoft/Azure auth, you'll need to create an OAuth
+        Client. See
+        [the guide](https://wiki.generaloutline.com/share/dfa77e56-d4d2-4b51-8ff8-84ea6608faa4)
+        for details on setting up your Azure App.
+      '';
+      default = null;
+      type = lib.types.nullOr (lib.types.submodule {
+        options = {
+          clientId = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Authentication client identifier.";
+          };
+          clientSecretFile = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "File path containing the authentication secret.";
+          };
+          resourceAppId = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Authentication application resource ID.";
+          };
+        };
+      });
+    };
+
+    oidcAuthentication = lib.mkOption {
+      description = lib.mdDoc ''
+        To configure generic OIDC auth, you'll need some kind of identity
+        provider. See the documentation for whichever IdP you use to fill out
+        all the fields. The redirect URL is
+        `https://[publicUrl]/auth/oidc.callback`.
+      '';
+      default = null;
+      type = lib.types.nullOr (lib.types.submodule {
+        options = {
+          clientId = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Authentication client identifier.";
+          };
+          clientSecretFile = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "File path containing the authentication secret.";
+          };
+          authUrl = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "OIDC authentication URL endpoint.";
+          };
+          tokenUrl = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "OIDC token URL endpoint.";
+          };
+          userinfoUrl = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "OIDC userinfo URL endpoint.";
+          };
+          usernameClaim = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc ''
+              Specify which claims to derive user information from. Supports any
+              valid JSON path with the JWT payload
+            '';
+            default = "preferred_username";
+          };
+          displayName = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Display name for OIDC authentication.";
+            default = "OpenID";
+          };
+          scopes = lib.mkOption {
+            type = lib.types.listOf lib.types.str;
+            description = lib.mdDoc "OpenID authentication scopes.";
+            default = [ "openid" "profile" "email" ];
+          };
+        };
+      });
+    };
+
+    #
+    # Optional configuration
+    #
+
+    sslKeyFile = lib.mkOption {
+      type = lib.types.nullOr lib.types.str;
+      default = null;
+      description = lib.mdDoc ''
+        File path that contains the Base64-encoded private key for HTTPS
+        termination. This is only required if you do not use an external reverse
+        proxy. See
+        [the documentation](https://wiki.generaloutline.com/share/dfa77e56-d4d2-4b51-8ff8-84ea6608faa4).
+      '';
+    };
+    sslCertFile = lib.mkOption {
+      type = lib.types.nullOr lib.types.str;
+      default = null;
+      description = lib.mdDoc ''
+        File path that contains the Base64-encoded certificate for HTTPS
+        termination. This is only required if you do not use an external reverse
+        proxy. See
+        [the documentation](https://wiki.generaloutline.com/share/dfa77e56-d4d2-4b51-8ff8-84ea6608faa4).
+      '';
+    };
+
+    cdnUrl = lib.mkOption {
+      type = lib.types.str;
+      default = "";
+      description = lib.mdDoc ''
+        If using a Cloudfront/Cloudflare distribution or similar it can be set
+        using this option. This will cause paths to JavaScript files,
+        stylesheets and images to be updated to the hostname defined here. In
+        your CDN configuration the origin server should be set to public URL.
+      '';
+    };
+
+    forceHttps = lib.mkOption {
+      type = lib.types.bool;
+      default = true;
+      description = lib.mdDoc ''
+        Auto-redirect to HTTPS in production. The default is
+        `true` but you may set this to `false`
+        if you can be sure that SSL is terminated at an external loadbalancer.
+      '';
+    };
+
+    enableUpdateCheck = lib.mkOption {
+      type = lib.types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Have the installation check for updates by sending anonymized statistics
+        to the maintainers.
+      '';
+    };
+
+    concurrency = lib.mkOption {
+      type = lib.types.int;
+      default = 1;
+      description = lib.mdDoc ''
+        How many processes should be spawned. For a rough estimate, divide your
+        server's available memory by 512.
+      '';
+    };
+
+    maximumImportSize = lib.mkOption {
+      type = lib.types.int;
+      default = 5120000;
+      description = lib.mdDoc ''
+        The maximum size of document imports. Overriding this could be required
+        if you have especially large Word documents with embedded imagery.
+      '';
+    };
+
+    debugOutput = lib.mkOption {
+      type = lib.types.nullOr (lib.types.enum [ "http" ]);
+      default = null;
+      description = lib.mdDoc "Set this to `http` log HTTP requests.";
+    };
+
+    slackIntegration = lib.mkOption {
+      description = lib.mdDoc ''
+        For a complete Slack integration with search and posting to channels
+        this configuration is also needed. See here for details:
+        https://wiki.generaloutline.com/share/be25efd1-b3ef-4450-b8e5-c4a4fc11e02a
+      '';
+      default = null;
+      type = lib.types.nullOr (lib.types.submodule {
+        options = {
+          verificationTokenFile = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "File path containing the verification token.";
+          };
+          appId = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Application ID.";
+          };
+          messageActions = lib.mkOption {
+            type = lib.types.bool;
+            default = true;
+            description = lib.mdDoc "Whether to enable message actions.";
+          };
+        };
+      });
+    };
+
+    googleAnalyticsId = lib.mkOption {
+      type = lib.types.nullOr lib.types.str;
+      default = null;
+      description = lib.mdDoc ''
+        Optionally enable Google Analytics to track page views in the knowledge
+        base.
+      '';
+    };
+
+    sentryDsn = lib.mkOption {
+      type = lib.types.nullOr lib.types.str;
+      default = null;
+      description = lib.mdDoc ''
+        Optionally enable [Sentry](https://sentry.io/) to
+        track errors and performance.
+      '';
+    };
+
+    sentryTunnel = lib.mkOption {
+      type = lib.types.nullOr lib.types.str;
+      default = null;
+      description = lib.mdDoc ''
+        Optionally add a
+        [Sentry proxy tunnel](https://docs.sentry.io/platforms/javascript/troubleshooting/#using-the-tunnel-option)
+        for bypassing ad blockers in the UI.
+      '';
+    };
+
+    logo = lib.mkOption {
+      type = lib.types.nullOr lib.types.str;
+      default = null;
+      description = lib.mdDoc ''
+        Custom logo displayed on the authentication screen. This will be scaled
+        to a height of 60px.
+      '';
+    };
+
+    smtp = lib.mkOption {
+      description = lib.mdDoc ''
+        To support sending outgoing transactional emails such as
+        "document updated" or "you've been invited" you'll need to provide
+        authentication for an SMTP server.
+      '';
+      default = null;
+      type = lib.types.nullOr (lib.types.submodule {
+        options = {
+          host = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Host name or IP adress of the SMTP server.";
+          };
+          port = lib.mkOption {
+            type = lib.types.port;
+            description = lib.mdDoc "TCP port of the SMTP server.";
+          };
+          username = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Username to authenticate with.";
+          };
+          passwordFile = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc ''
+              File path containing the password to authenticate with.
+            '';
+          };
+          fromEmail = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Sender email in outgoing mail.";
+          };
+          replyEmail = lib.mkOption {
+            type = lib.types.str;
+            description = lib.mdDoc "Reply address in outgoing mail.";
+          };
+          tlsCiphers = lib.mkOption {
+            type = lib.types.str;
+            default = "";
+            description = lib.mdDoc "Override SMTP cipher configuration.";
+          };
+          secure = lib.mkOption {
+            type = lib.types.bool;
+            default = true;
+            description = lib.mdDoc "Use a secure SMTP connection.";
+          };
+        };
+      });
+    };
+
+    defaultLanguage = lib.mkOption {
+      type = lib.types.enum [
+         "da_DK"
+         "de_DE"
+         "en_US"
+         "es_ES"
+         "fa_IR"
+         "fr_FR"
+         "it_IT"
+         "ja_JP"
+         "ko_KR"
+         "nl_NL"
+         "pl_PL"
+         "pt_BR"
+         "pt_PT"
+         "ru_RU"
+         "sv_SE"
+         "th_TH"
+         "vi_VN"
+         "zh_CN"
+         "zh_TW"
+      ];
+      default = "en_US";
+      description = lib.mdDoc ''
+        The default interface language. See
+        [translate.getoutline.com](https://translate.getoutline.com/)
+        for a list of available language codes and their rough percentage
+        translated.
+      '';
+    };
+
+    rateLimiter.enable = lib.mkEnableOption (lib.mdDoc "rate limiter for the application web server");
+    rateLimiter.requests = lib.mkOption {
+      type = lib.types.int;
+      default = 5000;
+      description = lib.mdDoc "Maximum number of requests in a throttling window.";
+    };
+    rateLimiter.durationWindow = lib.mkOption {
+      type = lib.types.int;
+      default = 60;
+      description = lib.mdDoc "Length of a throttling window.";
+    };
+  };
+
+  config = lib.mkIf cfg.enable {
+    users.users = lib.optionalAttrs (cfg.user == defaultUser) {
+      ${defaultUser} = {
+        isSystemUser = true;
+        group = cfg.group;
+      };
+    };
+
+    users.groups = lib.optionalAttrs (cfg.group == defaultUser) {
+      ${defaultUser} = { };
+    };
+
+    systemd.tmpfiles.rules = [
+      "f ${cfg.secretKeyFile} 0600 ${cfg.user} ${cfg.group} -"
+      "f ${cfg.utilsSecretFile} 0600 ${cfg.user} ${cfg.group} -"
+      "f ${cfg.storage.secretKeyFile} 0600 ${cfg.user} ${cfg.group} -"
+    ];
+
+    services.postgresql = lib.mkIf (cfg.databaseUrl == "local") {
+      enable = true;
+      ensureUsers = [{
+        name = "outline";
+        ensurePermissions."DATABASE outline" = "ALL PRIVILEGES";
+      }];
+      ensureDatabases = [ "outline" ];
+    };
+
+    services.redis.servers.outline = lib.mkIf (cfg.redisUrl == "local") {
+      enable = true;
+      user = config.services.outline.user;
+      port = 0; # Disable the TCP listener
+    };
+
+    systemd.services.outline = let
+      localRedisUrl = "redis+unix:///run/redis-outline/redis.sock";
+      localPostgresqlUrl = "postgres://localhost/outline?host=/run/postgresql";
+
+      # Create an outline-sequalize wrapper (a wrapper around the wrapper) that
+      # has the config file's path baked in. This is necessary because there is
+      # at least one occurrence of outline calling this from its own code.
+      sequelize = pkgs.writeShellScriptBin "outline-sequelize" ''
+        exec ${cfg.package}/bin/outline-sequelize \
+          --config $RUNTIME_DIRECTORY/database.json \
+          ${cfg.sequelizeArguments} \
+          "$@"
+      '';
+    in {
+      description = "Outline wiki and knowledge base";
+      wantedBy = [ "multi-user.target" ];
+      after = [ "networking.target" ]
+        ++ lib.optional (cfg.databaseUrl == "local") "postgresql.service"
+        ++ lib.optional (cfg.redisUrl == "local") "redis-outline.service";
+      requires = lib.optional (cfg.databaseUrl == "local") "postgresql.service"
+        ++ lib.optional (cfg.redisUrl == "local") "redis-outline.service";
+      path = [
+        pkgs.openssl # Required by the preStart script
+        sequelize
+      ];
+
+
+      environment = lib.mkMerge [
+        {
+          NODE_ENV = "production";
+
+          REDIS_URL = if cfg.redisUrl == "local" then localRedisUrl else cfg.redisUrl;
+          URL = cfg.publicUrl;
+          PORT = builtins.toString cfg.port;
+
+          AWS_ACCESS_KEY_ID = cfg.storage.accessKey;
+          AWS_REGION = cfg.storage.region;
+          AWS_S3_UPLOAD_BUCKET_URL = cfg.storage.uploadBucketUrl;
+          AWS_S3_UPLOAD_BUCKET_NAME = cfg.storage.uploadBucketName;
+          AWS_S3_UPLOAD_MAX_SIZE = builtins.toString cfg.storage.uploadMaxSize;
+          AWS_S3_FORCE_PATH_STYLE = builtins.toString cfg.storage.forcePathStyle;
+          AWS_S3_ACL = cfg.storage.acl;
+
+          CDN_URL = cfg.cdnUrl;
+          FORCE_HTTPS = builtins.toString cfg.forceHttps;
+          ENABLE_UPDATES = builtins.toString cfg.enableUpdateCheck;
+          WEB_CONCURRENCY = builtins.toString cfg.concurrency;
+          MAXIMUM_IMPORT_SIZE = builtins.toString cfg.maximumImportSize;
+          DEBUG = cfg.debugOutput;
+          GOOGLE_ANALYTICS_ID = lib.optionalString (cfg.googleAnalyticsId != null) cfg.googleAnalyticsId;
+          SENTRY_DSN = lib.optionalString (cfg.sentryDsn != null) cfg.sentryDsn;
+          SENTRY_TUNNEL = lib.optionalString (cfg.sentryTunnel != null) cfg.sentryTunnel;
+          TEAM_LOGO = lib.optionalString (cfg.logo != null) cfg.logo;
+          DEFAULT_LANGUAGE = cfg.defaultLanguage;
+
+          RATE_LIMITER_ENABLED = builtins.toString cfg.rateLimiter.enable;
+          RATE_LIMITER_REQUESTS = builtins.toString cfg.rateLimiter.requests;
+          RATE_LIMITER_DURATION_WINDOW = builtins.toString cfg.rateLimiter.durationWindow;
+        }
+
+        (lib.mkIf (cfg.slackAuthentication != null) {
+          SLACK_CLIENT_ID = cfg.slackAuthentication.clientId;
+        })
+
+        (lib.mkIf (cfg.googleAuthentication != null) {
+          GOOGLE_CLIENT_ID = cfg.googleAuthentication.clientId;
+        })
+
+        (lib.mkIf (cfg.azureAuthentication != null) {
+          AZURE_CLIENT_ID = cfg.azureAuthentication.clientId;
+          AZURE_RESOURCE_APP_ID = cfg.azureAuthentication.resourceAppId;
+        })
+
+        (lib.mkIf (cfg.oidcAuthentication != null) {
+          OIDC_CLIENT_ID = cfg.oidcAuthentication.clientId;
+          OIDC_AUTH_URI = cfg.oidcAuthentication.authUrl;
+          OIDC_TOKEN_URI = cfg.oidcAuthentication.tokenUrl;
+          OIDC_USERINFO_URI = cfg.oidcAuthentication.userinfoUrl;
+          OIDC_USERNAME_CLAIM = cfg.oidcAuthentication.usernameClaim;
+          OIDC_DISPLAY_NAME = cfg.oidcAuthentication.displayName;
+          OIDC_SCOPES = lib.concatStringsSep " " cfg.oidcAuthentication.scopes;
+        })
+
+        (lib.mkIf (cfg.slackIntegration != null) {
+          SLACK_APP_ID = cfg.slackIntegration.appId;
+          SLACK_MESSAGE_ACTIONS = builtins.toString cfg.slackIntegration.messageActions;
+        })
+
+        (lib.mkIf (cfg.smtp != null) {
+          SMTP_HOST = cfg.smtp.host;
+          SMTP_PORT = builtins.toString cfg.smtp.port;
+          SMTP_USERNAME = cfg.smtp.username;
+          SMTP_FROM_EMAIL = cfg.smtp.fromEmail;
+          SMTP_REPLY_EMAIL = cfg.smtp.replyEmail;
+          SMTP_TLS_CIPHERS = cfg.smtp.tlsCiphers;
+          SMTP_SECURE = builtins.toString cfg.smtp.secure;
+        })
+      ];
+
+      preStart = ''
+        if [ ! -s ${lib.escapeShellArg cfg.secretKeyFile} ]; then
+          openssl rand -hex 32 > ${lib.escapeShellArg cfg.secretKeyFile}
+        fi
+        if [ ! -s ${lib.escapeShellArg cfg.utilsSecretFile} ]; then
+          openssl rand -hex 32 > ${lib.escapeShellArg cfg.utilsSecretFile}
+        fi
+
+        # The config file is required for the CLI, the DATABASE_URL environment
+        # variable is read by the app.
+        ${if (cfg.databaseUrl == "local") then ''
+          cat <<EOF > $RUNTIME_DIRECTORY/database.json
+          {
+            "production": {
+              "dialect": "postgres",
+              "host": "/run/postgresql",
+              "username": null,
+              "password": null
+            }
+          }
+          EOF
+          export DATABASE_URL=${lib.escapeShellArg localPostgresqlUrl}
+          export PGSSLMODE=disable
+        '' else ''
+          cat <<EOF > $RUNTIME_DIRECTORY/database.json
+          {
+            "production": {
+              "use_env_variable": "DATABASE_URL",
+              "dialect": "postgres",
+              "dialectOptions": {
+                "ssl": {
+                  "rejectUnauthorized": false
+                }
+              }
+            },
+            "production-ssl-disabled": {
+              "use_env_variable": "DATABASE_URL",
+              "dialect": "postgres"
+            }
+          }
+          EOF
+          export DATABASE_URL=${lib.escapeShellArg cfg.databaseUrl}
+        ''}
+
+        cd $RUNTIME_DIRECTORY
+        ${sequelize}/bin/outline-sequelize db:migrate
+      '';
+
+      script = ''
+        export SECRET_KEY="$(head -n1 ${lib.escapeShellArg cfg.secretKeyFile})"
+        export UTILS_SECRET="$(head -n1 ${lib.escapeShellArg cfg.utilsSecretFile})"
+        export AWS_SECRET_ACCESS_KEY="$(head -n1 ${lib.escapeShellArg cfg.storage.secretKeyFile})"
+        ${lib.optionalString (cfg.slackAuthentication != null) ''
+          export SLACK_CLIENT_SECRET="$(head -n1 ${lib.escapeShellArg cfg.slackAuthentication.secretFile})"
+        ''}
+        ${lib.optionalString (cfg.googleAuthentication != null) ''
+          export GOOGLE_CLIENT_SECRET="$(head -n1 ${lib.escapeShellArg cfg.googleAuthentication.clientSecretFile})"
+        ''}
+        ${lib.optionalString (cfg.azureAuthentication != null) ''
+          export AZURE_CLIENT_SECRET="$(head -n1 ${lib.escapeShellArg cfg.azureAuthentication.clientSecretFile})"
+        ''}
+        ${lib.optionalString (cfg.oidcAuthentication != null) ''
+          export OIDC_CLIENT_SECRET="$(head -n1 ${lib.escapeShellArg cfg.oidcAuthentication.clientSecretFile})"
+        ''}
+        ${lib.optionalString (cfg.sslKeyFile != null) ''
+          export SSL_KEY="$(head -n1 ${lib.escapeShellArg cfg.sslKeyFile})"
+        ''}
+        ${lib.optionalString (cfg.sslCertFile != null) ''
+          export SSL_CERT="$(head -n1 ${lib.escapeShellArg cfg.sslCertFile})"
+        ''}
+        ${lib.optionalString (cfg.slackIntegration != null) ''
+          export SLACK_VERIFICATION_TOKEN="$(head -n1 ${lib.escapeShellArg cfg.slackIntegration.verificationTokenFile})"
+        ''}
+        ${lib.optionalString (cfg.smtp != null) ''
+          export SMTP_PASSWORD="$(head -n1 ${lib.escapeShellArg cfg.smtp.passwordFile})"
+        ''}
+
+        ${if (cfg.databaseUrl == "local") then ''
+          export DATABASE_URL=${lib.escapeShellArg localPostgresqlUrl}
+          export PGSSLMODE=disable
+        '' else ''
+          export DATABASE_URL=${lib.escapeShellArg cfg.databaseUrl}
+        ''}
+
+        ${cfg.package}/bin/outline-server
+      '';
+
+      serviceConfig = {
+        User = cfg.user;
+        Group = cfg.group;
+        Restart = "always";
+        ProtectSystem = "strict";
+        PrivateHome = true;
+        PrivateTmp = true;
+        UMask = "0007";
+
+        StateDirectory = "outline";
+        StateDirectoryMode = "0750";
+        RuntimeDirectory = "outline";
+        RuntimeDirectoryMode = "0750";
+        # This working directory is required to find stuff like the set of
+        # onboarding files:
+        WorkingDirectory = "${cfg.package}/share/outline/build";
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/web-apps/peertube.nix b/nixos/modules/services/web-apps/peertube.nix
index e195e6e6e82..4dbcb09d2ae 100644
--- a/nixos/modules/services/web-apps/peertube.nix
+++ b/nixos/modules/services/web-apps/peertube.nix
@@ -11,6 +11,7 @@ let
     NODE_CONFIG_DIR = "/var/lib/peertube/config";
     NODE_ENV = "production";
     NODE_EXTRA_CA_CERTS = "/etc/ssl/certs/ca-certificates.crt";
+    NPM_CONFIG_CACHE = "/var/cache/peertube/.npm";
     NPM_CONFIG_PREFIX = cfg.package;
     HOME = cfg.package;
   };
@@ -66,58 +67,68 @@ let
     node ~/dist/server/tools/peertube.js $@
   '';
 
+  nginxCommonHeaders = lib.optionalString cfg.enableWebHttps ''
+    add_header Strict-Transport-Security      'max-age=63072000; includeSubDomains';
+  '' + lib.optionalString config.services.nginx.virtualHosts.${cfg.localDomain}.http3 ''
+    add_header Alt-Svc                        'h3=":443"; ma=86400';
+  '' + ''
+    add_header Access-Control-Allow-Origin    '*';
+    add_header Access-Control-Allow-Methods   'GET, OPTIONS';
+    add_header Access-Control-Allow-Headers   'Range,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
+  '';
+
 in {
   options.services.peertube = {
-    enable = lib.mkEnableOption "Enable Peertube’s service";
+    enable = lib.mkEnableOption (lib.mdDoc "Peertube");
 
     user = lib.mkOption {
       type = lib.types.str;
       default = "peertube";
-      description = "User account under which Peertube runs.";
+      description = lib.mdDoc "User account under which Peertube runs.";
     };
 
     group = lib.mkOption {
       type = lib.types.str;
       default = "peertube";
-      description = "Group under which Peertube runs.";
+      description = lib.mdDoc "Group under which Peertube runs.";
     };
 
     localDomain = lib.mkOption {
       type = lib.types.str;
       example = "peertube.example.com";
-      description = "The domain serving your PeerTube instance.";
+      description = lib.mdDoc "The domain serving your PeerTube instance.";
     };
 
     listenHttp = lib.mkOption {
-      type = lib.types.int;
+      type = lib.types.port;
       default = 9000;
-      description = "listen port for HTTP server.";
+      description = lib.mdDoc "listen port for HTTP server.";
     };
 
     listenWeb = lib.mkOption {
-      type = lib.types.int;
+      type = lib.types.port;
       default = 9000;
-      description = "listen port for WEB server.";
+      description = lib.mdDoc "listen port for WEB server.";
     };
 
     enableWebHttps = lib.mkOption {
       type = lib.types.bool;
       default = false;
-      description = "Enable or disable HTTPS protocol.";
+      description = lib.mdDoc "Enable or disable HTTPS protocol.";
     };
 
     dataDirs = lib.mkOption {
       type = lib.types.listOf lib.types.path;
       default = [ ];
       example = [ "/opt/peertube/storage" "/var/cache/peertube" ];
-      description = "Allow access to custom data locations.";
+      description = lib.mdDoc "Allow access to custom data locations.";
     };
 
     serviceEnvironmentFile = lib.mkOption {
       type = lib.types.nullOr lib.types.path;
       default = null;
       example = "/run/keys/peertube/password-init-root";
-      description = ''
+      description = lib.mdDoc ''
         Set environment variables for the service. Mainly useful for setting the initial root password.
         For example write to file:
         PT_INITIAL_ROOT_PASSWORD=changeme
@@ -141,14 +152,20 @@ in {
           };
         }
       '';
-      description = "Configuration for peertube.";
+      description = lib.mdDoc "Configuration for peertube.";
+    };
+
+    configureNginx = lib.mkOption {
+      type = lib.types.bool;
+      default = false;
+      description = lib.mdDoc "Configure nginx as a reverse proxy for peertube.";
     };
 
     database = {
       createLocally = lib.mkOption {
         type = lib.types.bool;
         default = false;
-        description = "Configure local PostgreSQL database server for PeerTube.";
+        description = lib.mdDoc "Configure local PostgreSQL database server for PeerTube.";
       };
 
       host = lib.mkOption {
@@ -160,32 +177,32 @@ in {
           else null
         '';
         example = "192.168.15.47";
-        description = "Database host address or unix socket.";
+        description = lib.mdDoc "Database host address or unix socket.";
       };
 
       port = lib.mkOption {
-        type = lib.types.int;
+        type = lib.types.port;
         default = 5432;
-        description = "Database host port.";
+        description = lib.mdDoc "Database host port.";
       };
 
       name = lib.mkOption {
         type = lib.types.str;
         default = "peertube";
-        description = "Database name.";
+        description = lib.mdDoc "Database name.";
       };
 
       user = lib.mkOption {
         type = lib.types.str;
         default = "peertube";
-        description = "Database user.";
+        description = lib.mdDoc "Database user.";
       };
 
       passwordFile = lib.mkOption {
         type = lib.types.nullOr lib.types.path;
         default = null;
         example = "/run/keys/peertube/password-posgressql-db";
-        description = "Password for PostgreSQL database.";
+        description = lib.mdDoc "Password for PostgreSQL database.";
       };
     };
 
@@ -193,7 +210,7 @@ in {
       createLocally = lib.mkOption {
         type = lib.types.bool;
         default = false;
-        description = "Configure local Redis server for PeerTube.";
+        description = lib.mdDoc "Configure local Redis server for PeerTube.";
       };
 
       host = lib.mkOption {
@@ -204,32 +221,32 @@ in {
           then "127.0.0.1"
           else null
         '';
-        description = "Redis host.";
+        description = lib.mdDoc "Redis host.";
       };
 
       port = lib.mkOption {
         type = lib.types.nullOr lib.types.port;
-        default = if cfg.redis.createLocally && cfg.redis.enableUnixSocket then null else 6379;
+        default = if cfg.redis.createLocally && cfg.redis.enableUnixSocket then null else 31638;
         defaultText = lib.literalExpression ''
           if config.${opt.redis.createLocally} && config.${opt.redis.enableUnixSocket}
           then null
           else 6379
         '';
-        description = "Redis port.";
+        description = lib.mdDoc "Redis port.";
       };
 
       passwordFile = lib.mkOption {
         type = lib.types.nullOr lib.types.path;
         default = null;
         example = "/run/keys/peertube/password-redis-db";
-        description = "Password for redis database.";
+        description = lib.mdDoc "Password for redis database.";
       };
 
       enableUnixSocket = lib.mkOption {
         type = lib.types.bool;
         default = cfg.redis.createLocally;
         defaultText = lib.literalExpression "config.${opt.redis.createLocally}";
-        description = "Use Unix socket.";
+        description = lib.mdDoc "Use Unix socket.";
       };
     };
 
@@ -237,14 +254,14 @@ in {
       createLocally = lib.mkOption {
         type = lib.types.bool;
         default = false;
-        description = "Configure local Postfix SMTP server for PeerTube.";
+        description = lib.mdDoc "Configure local Postfix SMTP server for PeerTube.";
       };
 
       passwordFile = lib.mkOption {
         type = lib.types.nullOr lib.types.path;
         default = null;
         example = "/run/keys/peertube/password-smtp";
-        description = "Password for smtp server.";
+        description = lib.mdDoc "Password for smtp server.";
       };
     };
 
@@ -252,7 +269,7 @@ in {
       type = lib.types.package;
       default = pkgs.peertube;
       defaultText = lib.literalExpression "pkgs.peertube";
-      description = "Peertube package to use.";
+      description = lib.mdDoc "Peertube package to use.";
     };
   };
 
@@ -344,18 +361,20 @@ in {
           };
         };
       }
-      (lib.mkIf cfg.redis.enableUnixSocket { redis = { socket = "/run/redis/redis.sock"; }; })
+      (lib.mkIf cfg.redis.enableUnixSocket { redis = { socket = "/run/redis-peertube/redis.sock"; }; })
     ];
 
     systemd.tmpfiles.rules = [
       "d '/var/lib/peertube/config' 0700 ${cfg.user} ${cfg.group} - -"
       "z '/var/lib/peertube/config' 0700 ${cfg.user} ${cfg.group} - -"
+      "d '/var/lib/peertube/www' 0750 ${cfg.user} ${cfg.group} - -"
+      "z '/var/lib/peertube/www' 0750 ${cfg.user} ${cfg.group} - -"
     ];
 
     systemd.services.peertube-init-db = lib.mkIf cfg.database.createLocally {
       description = "Initialization database for PeerTube daemon";
       after = [ "network.target" "postgresql.service" ];
-      wantedBy = [ "multi-user.target" ];
+      requires = [ "postgresql.service" ];
 
       script = let
         psqlSetupCommands = pkgs.writeText "peertube-init.sql" ''
@@ -384,7 +403,9 @@ in {
     systemd.services.peertube = {
       description = "PeerTube daemon";
       after = [ "network.target" ]
-        ++ lib.optionals cfg.redis.createLocally [ "redis.service" ]
+        ++ lib.optional cfg.redis.createLocally "redis-peertube.service"
+        ++ lib.optionals cfg.database.createLocally [ "postgresql.service" "peertube-init-db.service" ];
+      requires = lib.optional cfg.redis.createLocally "redis-peertube.service"
         ++ lib.optionals cfg.database.createLocally [ "postgresql.service" "peertube-init-db.service" ];
       wantedBy = [ "multi-user.target" ];
 
@@ -409,8 +430,11 @@ in {
           password: '$(cat ${cfg.smtp.passwordFile})'
         ''}
         EOF
-        ln -sf ${cfg.package}/config/default.yaml /var/lib/peertube/config/default.yaml
+        umask 027
         ln -sf ${configFile} /var/lib/peertube/config/production.json
+        ln -sf ${cfg.package}/config/default.yaml /var/lib/peertube/config/default.yaml
+        ln -sf ${cfg.package}/client/dist -T /var/lib/peertube/www/client
+        ln -sf ${cfg.settings.storage.client_overrides} -T /var/lib/peertube/www/client-overrides
         npm start
       '';
       serviceConfig = {
@@ -425,6 +449,9 @@ in {
         # State directory and mode
         StateDirectory = "peertube";
         StateDirectoryMode = "0750";
+        # Cache directory and mode
+        CacheDirectory = "peertube";
+        CacheDirectoryMode = "0750";
         # Access write directories
         ReadWritePaths = cfg.dataDirs;
         # Environment
@@ -437,17 +464,300 @@ in {
       } // cfgService;
     };
 
+    services.nginx = lib.mkIf cfg.configureNginx {
+      enable = true;
+      virtualHosts."${cfg.localDomain}" = {
+        root = "/var/lib/peertube";
+
+        # Application
+        locations."/" = {
+          tryFiles = "/dev/null @api";
+          priority = 1110;
+        };
+
+        locations."= /api/v1/videos/upload-resumable" = {
+          tryFiles = "/dev/null @api";
+          priority = 1120;
+
+          extraConfig = ''
+            client_max_body_size                        0;
+            proxy_request_buffering                     off;
+          '';
+        };
+
+        locations."~ ^/api/v1/videos/(upload|([^/]+/studio/edit))$" = {
+          tryFiles = "/dev/null @api";
+          root = cfg.settings.storage.tmp;
+          priority = 1130;
+
+          extraConfig = ''
+            client_max_body_size                        12G;
+            add_header X-File-Maximum-Size              8G always;
+          '' + lib.optionalString cfg.enableWebHttps ''
+            add_header Strict-Transport-Security        'max-age=63072000; includeSubDomains';
+          '' + lib.optionalString config.services.nginx.virtualHosts.${cfg.localDomain}.http3 ''
+            add_header Alt-Svc                          'h3=":443"; ma=86400';
+          '';
+        };
+
+        locations."~ ^/api/v1/(videos|video-playlists|video-channels|users/me)" = {
+          tryFiles = "/dev/null @api";
+          priority = 1140;
+
+          extraConfig = ''
+            client_max_body_size                        6M;
+            add_header X-File-Maximum-Size              4M always;
+          '' + lib.optionalString cfg.enableWebHttps ''
+            add_header Strict-Transport-Security        'max-age=63072000; includeSubDomains';
+          '' + lib.optionalString config.services.nginx.virtualHosts.${cfg.localDomain}.http3 ''
+            add_header Alt-Svc                          'h3=":443"; ma=86400';
+          '';
+        };
+
+        locations."@api" = {
+          proxyPass = "http://127.0.0.1:${toString cfg.listenHttp}";
+          priority = 1150;
+
+          extraConfig = ''
+            proxy_set_header X-Forwarded-For            $proxy_add_x_forwarded_for;
+            proxy_set_header Host                       $host;
+            proxy_set_header X-Real-IP                  $remote_addr;
+
+            proxy_connect_timeout                       10m;
+
+            proxy_send_timeout                          10m;
+            proxy_read_timeout                          10m;
+
+            client_max_body_size                        100k;
+            send_timeout                                10m;
+          '';
+        };
+
+        # Websocket
+        locations."/socket.io" = {
+          tryFiles = "/dev/null @api_websocket";
+          priority = 1210;
+        };
+
+        locations."/tracker/socket" = {
+          tryFiles = "/dev/null @api_websocket";
+          priority = 1220;
+
+          extraConfig = ''
+            proxy_read_timeout                          15m;
+          '';
+        };
+
+        locations."@api_websocket" = {
+          proxyPass = "http://127.0.0.1:${toString cfg.listenHttp}";
+          priority = 1230;
+
+          extraConfig = ''
+            proxy_set_header X-Forwarded-For            $proxy_add_x_forwarded_for;
+            proxy_set_header Host                       $host;
+            proxy_set_header X-Real-IP                  $remote_addr;
+            proxy_set_header Upgrade                    $http_upgrade;
+            proxy_set_header Connection                 'upgrade';
+
+            proxy_http_version                          1.1;
+          '';
+        };
+
+        # Bypass PeerTube for performance reasons.
+        locations."~ ^/client/(assets/images/(icons/icon-36x36\.png|icons/icon-48x48\.png|icons/icon-72x72\.png|icons/icon-96x96\.png|icons/icon-144x144\.png|icons/icon-192x192\.png|icons/icon-512x512\.png|logo\.svg|favicon\.png|default-playlist\.jpg|default-avatar-account\.png|default-avatar-account-48x48\.png|default-avatar-video-channel\.png|default-avatar-video-channel-48x48\.png))$" = {
+          tryFiles = "/www/client-overrides/$1 /www/client/$1 $1";
+          priority = 1310;
+        };
+
+        locations."~ ^/client/(.*\.(js|css|png|svg|woff2|otf|ttf|woff|eot))$" = {
+          alias = "${cfg.package}/client/dist/$1";
+          priority = 1320;
+          extraConfig = ''
+            add_header Cache-Control                    'public, max-age=604800, immutable';
+          '' + lib.optionalString cfg.enableWebHttps ''
+            add_header Strict-Transport-Security        'max-age=63072000; includeSubDomains';
+          '' + lib.optionalString config.services.nginx.virtualHosts.${cfg.localDomain}.http3 ''
+            add_header Alt-Svc                          'h3=":443"; ma=86400';
+          '';
+        };
+
+        locations."~ ^/lazy-static/(avatars|banners)/" = {
+          tryFiles = "$uri @api";
+          root = cfg.settings.storage.avatars;
+          priority = 1330;
+          extraConfig = ''
+            if ($request_method = 'OPTIONS') {
+              ${nginxCommonHeaders}
+              add_header Access-Control-Max-Age         1728000;
+              add_header Cache-Control                  'no-cache';
+              add_header Content-Type                   'text/plain charset=UTF-8';
+              add_header Content-Length                 0;
+              return                                    204;
+            }
+
+            ${nginxCommonHeaders}
+            add_header Cache-Control                    'public, max-age=7200';
+
+            rewrite ^/lazy-static/avatars/(.*)$         /$1 break;
+            rewrite ^/lazy-static/banners/(.*)$         /$1 break;
+          '';
+        };
+
+        locations."^~ /lazy-static/previews/" = {
+          tryFiles = "$uri @api";
+          root = cfg.settings.storage.previews;
+          priority = 1340;
+          extraConfig = ''
+            if ($request_method = 'OPTIONS') {
+              ${nginxCommonHeaders}
+              add_header Access-Control-Max-Age         1728000;
+              add_header Cache-Control                  'no-cache';
+              add_header Content-Type                   'text/plain charset=UTF-8';
+              add_header Content-Length                 0;
+              return                                    204;
+            }
+
+            ${nginxCommonHeaders}
+            add_header Cache-Control                    'public, max-age=7200';
+
+            rewrite ^/lazy-static/previews/(.*)$        /$1 break;
+          '';
+        };
+
+        locations."^~ /static/thumbnails/" = {
+          tryFiles = "$uri @api";
+          root = cfg.settings.storage.thumbnails;
+          priority = 1350;
+          extraConfig = ''
+            if ($request_method = 'OPTIONS') {
+              ${nginxCommonHeaders}
+              add_header Access-Control-Max-Age         1728000;
+              add_header Cache-Control                  'no-cache';
+              add_header Content-Type                   'text/plain charset=UTF-8';
+              add_header Content-Length                 0;
+              return                                    204;
+            }
+
+            ${nginxCommonHeaders}
+            add_header Cache-Control                    'public, max-age=7200';
+
+            rewrite ^/static/thumbnails/(.*)$           /$1 break;
+          '';
+        };
+
+        locations."^~ /static/redundancy/" = {
+          tryFiles = "$uri @api";
+          root = cfg.settings.storage.redundancy;
+          priority = 1360;
+          extraConfig = ''
+            if ($request_method = 'OPTIONS') {
+              ${nginxCommonHeaders}
+              add_header Access-Control-Max-Age         1728000;
+              add_header Content-Type                   'text/plain charset=UTF-8';
+              add_header Content-Length                 0;
+              return                                    204;
+            }
+            if ($request_method = 'GET') {
+              ${nginxCommonHeaders}
+
+              access_log                                off;
+            }
+            aio                                         threads;
+            sendfile                                    on;
+            sendfile_max_chunk                          1M;
+
+            limit_rate_after                            5M;
+
+            set $peertube_limit_rate                    800k;
+            set $limit_rate                             $peertube_limit_rate;
+
+            rewrite ^/static/redundancy/(.*)$           /$1 break;
+          '';
+        };
+
+        locations."^~ /static/streaming-playlists/" = {
+          tryFiles = "$uri @api";
+          root = cfg.settings.storage.streaming_playlists;
+          priority = 1370;
+          extraConfig = ''
+            if ($request_method = 'OPTIONS') {
+              ${nginxCommonHeaders}
+              add_header Access-Control-Max-Age         1728000;
+              add_header Content-Type                   'text/plain charset=UTF-8';
+              add_header Content-Length                 0;
+              return                                    204;
+            }
+            if ($request_method = 'GET') {
+              ${nginxCommonHeaders}
+
+              access_log                                off;
+            }
+
+            aio                                         threads;
+            sendfile                                    on;
+            sendfile_max_chunk                          1M;
+
+            limit_rate_after                            5M;
+
+            set $peertube_limit_rate                    5M;
+            set $limit_rate                             $peertube_limit_rate;
+
+            rewrite ^/static/streaming-playlists/(.*)$  /$1 break;
+          '';
+        };
+
+        locations."~ ^/static/webseed/" = {
+          tryFiles = "$uri @api";
+          root = cfg.settings.storage.videos;
+          priority = 1380;
+          extraConfig = ''
+            if ($request_method = 'OPTIONS') {
+              ${nginxCommonHeaders}
+              add_header Access-Control-Max-Age         1728000;
+              add_header Content-Type                   'text/plain charset=UTF-8';
+              add_header Content-Length                 0;
+              return                                    204;
+            }
+            if ($request_method = 'GET') {
+              ${nginxCommonHeaders}
+
+              access_log                                off;
+            }
+
+            aio                                         threads;
+            sendfile                                    on;
+            sendfile_max_chunk                          1M;
+
+            limit_rate_after                            5M;
+
+            set $peertube_limit_rate                    800k;
+            set $limit_rate                             $peertube_limit_rate;
+
+            rewrite ^/static/webseed/(.*)$              /$1 break;
+          '';
+        };
+
+        extraConfig = lib.optionalString cfg.enableWebHttps ''
+          add_header Strict-Transport-Security          'max-age=63072000; includeSubDomains';
+        '';
+      };
+    };
+
     services.postgresql = lib.mkIf cfg.database.createLocally {
       enable = true;
     };
 
-    services.redis = lib.mkMerge [
+    services.redis.servers.peertube = lib.mkMerge [
       (lib.mkIf cfg.redis.createLocally {
         enable = true;
       })
+      (lib.mkIf (cfg.redis.createLocally && !cfg.redis.enableUnixSocket) {
+        bind = "127.0.0.1";
+        port = cfg.redis.port;
+      })
       (lib.mkIf (cfg.redis.createLocally && cfg.redis.enableUnixSocket) {
-        unixSocket = "/run/redis/redis.sock";
-        unixSocketPerm = 770;
+        unixSocket = "/run/redis-peertube/redis.sock";
+        unixSocketPerm = 660;
       })
     ];
 
@@ -465,11 +775,13 @@ in {
         };
       })
       (lib.attrsets.setAttrByPath [ cfg.user "packages" ] [ cfg.package peertubeEnv peertubeCli pkgs.ffmpeg pkgs.nodejs-16_x pkgs.yarn ])
-      (lib.mkIf cfg.redis.enableUnixSocket {${config.services.peertube.user}.extraGroups = [ "redis" ];})
+      (lib.mkIf cfg.redis.enableUnixSocket {${config.services.peertube.user}.extraGroups = [ "redis-peertube" ];})
     ];
 
-    users.groups = lib.optionalAttrs (cfg.group == "peertube") {
-      peertube = { };
+    users.groups = {
+      ${cfg.group} = {
+        members = lib.optional cfg.configureNginx config.services.nginx.user;
+      };
     };
   };
 }
diff --git a/nixos/modules/services/web-apps/pgpkeyserver-lite.nix b/nixos/modules/services/web-apps/pgpkeyserver-lite.nix
index faf0ce13238..0ab39b07931 100644
--- a/nixos/modules/services/web-apps/pgpkeyserver-lite.nix
+++ b/nixos/modules/services/web-apps/pgpkeyserver-lite.nix
@@ -18,40 +18,40 @@ in
 
     services.pgpkeyserver-lite = {
 
-      enable = mkEnableOption "pgpkeyserver-lite on a nginx vHost proxying to a gpg keyserver";
+      enable = mkEnableOption (lib.mdDoc "pgpkeyserver-lite on a nginx vHost proxying to a gpg keyserver");
 
       package = mkOption {
         default = pkgs.pgpkeyserver-lite;
         defaultText = literalExpression "pkgs.pgpkeyserver-lite";
         type = types.package;
-        description = "
+        description = lib.mdDoc ''
           Which webgui derivation to use.
-        ";
+        '';
       };
 
       hostname = mkOption {
         type = types.str;
-        description = "
+        description = lib.mdDoc ''
           Which hostname to set the vHost to that is proxying to sks.
-        ";
+        '';
       };
 
       hkpAddress = mkOption {
         default = builtins.head sksCfg.hkpAddress;
         defaultText = literalExpression "head config.${sksOpt.hkpAddress}";
         type = types.str;
-        description = "
+        description = lib.mdDoc ''
           Wich ip address the sks-keyserver is listening on.
-        ";
+        '';
       };
 
       hkpPort = mkOption {
         default = sksCfg.hkpPort;
         defaultText = literalExpression "config.${sksOpt.hkpPort}";
         type = types.int;
-        description = "
+        description = lib.mdDoc ''
           Which port the sks-keyserver is listening on.
-        ";
+        '';
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/phylactery.nix b/nixos/modules/services/web-apps/phylactery.nix
new file mode 100644
index 00000000000..4801bd203b4
--- /dev/null
+++ b/nixos/modules/services/web-apps/phylactery.nix
@@ -0,0 +1,51 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let cfg = config.services.phylactery;
+in {
+  options.services.phylactery = {
+    enable = mkEnableOption (lib.mdDoc "Whether to enable Phylactery server");
+
+    host = mkOption {
+      type = types.str;
+      default = "localhost";
+      description = lib.mdDoc "Listen host for Phylactery";
+    };
+
+    port = mkOption {
+      type = types.port;
+      description = lib.mdDoc "Listen port for Phylactery";
+    };
+
+    library = mkOption {
+      type = types.path;
+      description = lib.mdDoc "Path to CBZ library";
+    };
+
+    package = mkOption {
+      type = types.package;
+      default = pkgs.phylactery;
+      defaultText = literalExpression "pkgs.phylactery";
+      description = lib.mdDoc "The Phylactery package to use";
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.services.phylactery = {
+      environment = {
+        PHYLACTERY_ADDRESS = "${cfg.host}:${toString cfg.port}";
+        PHYLACTERY_LIBRARY = "${cfg.library}";
+      };
+
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = {
+        ConditionPathExists = cfg.library;
+        DynamicUser = true;
+        ExecStart = "${cfg.package}/bin/phylactery";
+      };
+    };
+  };
+
+  meta.maintainers = with maintainers; [ McSinyx ];
+}
diff --git a/nixos/modules/services/web-apps/pict-rs.nix b/nixos/modules/services/web-apps/pict-rs.nix
index e1847fbd531..ee9ff9b484f 100644
--- a/nixos/modules/services/web-apps/pict-rs.nix
+++ b/nixos/modules/services/web-apps/pict-rs.nix
@@ -10,25 +10,25 @@ in
   meta.doc = ./pict-rs.xml;
 
   options.services.pict-rs = {
-    enable = mkEnableOption "pict-rs server";
+    enable = mkEnableOption (lib.mdDoc "pict-rs server");
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/pict-rs";
-      description = ''
+      description = lib.mdDoc ''
         The directory where to store the uploaded images.
       '';
     };
     address = mkOption {
       type = types.str;
       default = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         The IPv4 address to deploy the service to.
       '';
     };
     port = mkOption {
       type = types.port;
       default = 8080;
-      description = ''
+      description = lib.mdDoc ''
         The port which to bind the service to.
       '';
     };
diff --git a/nixos/modules/services/web-apps/plantuml-server.nix b/nixos/modules/services/web-apps/plantuml-server.nix
index 9ea37b8a4ca..5ebee48c3e0 100644
--- a/nixos/modules/services/web-apps/plantuml-server.nix
+++ b/nixos/modules/services/web-apps/plantuml-server.nix
@@ -11,13 +11,13 @@ in
 {
   options = {
     services.plantuml-server = {
-      enable = mkEnableOption "PlantUML server";
+      enable = mkEnableOption (lib.mdDoc "PlantUML server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.plantuml-server;
         defaultText = literalExpression "pkgs.plantuml-server";
-        description = "PlantUML server package to use";
+        description = lib.mdDoc "PlantUML server package to use";
       };
 
       packages = {
@@ -25,75 +25,75 @@ in
           type = types.package;
           default = pkgs.jdk;
           defaultText = literalExpression "pkgs.jdk";
-          description = "JDK package to use for the server";
+          description = lib.mdDoc "JDK package to use for the server";
         };
         jetty = mkOption {
           type = types.package;
           default = pkgs.jetty;
           defaultText = literalExpression "pkgs.jetty";
-          description = "Jetty package to use for the server";
+          description = lib.mdDoc "Jetty package to use for the server";
         };
       };
 
       user = mkOption {
         type = types.str;
         default = "plantuml";
-        description = "User which runs PlantUML server.";
+        description = lib.mdDoc "User which runs PlantUML server.";
       };
 
       group = mkOption {
         type = types.str;
         default = "plantuml";
-        description = "Group which runs PlantUML server.";
+        description = lib.mdDoc "Group which runs PlantUML server.";
       };
 
       home = mkOption {
         type = types.str;
         default = "/var/lib/plantuml";
-        description = "Home directory of the PlantUML server instance.";
+        description = lib.mdDoc "Home directory of the PlantUML server instance.";
       };
 
       listenHost = mkOption {
         type = types.str;
         default = "127.0.0.1";
-        description = "Host to listen on.";
+        description = lib.mdDoc "Host to listen on.";
       };
 
       listenPort = mkOption {
         type = types.int;
         default = 8080;
-        description = "Port to listen on.";
+        description = lib.mdDoc "Port to listen on.";
       };
 
       plantumlLimitSize = mkOption {
         type = types.int;
         default = 4096;
-        description = "Limits image width and height.";
+        description = lib.mdDoc "Limits image width and height.";
       };
 
       graphvizPackage = mkOption {
         type = types.package;
         default = pkgs.graphviz;
         defaultText = literalExpression "pkgs.graphviz";
-        description = "Package containing the dot executable.";
+        description = lib.mdDoc "Package containing the dot executable.";
       };
 
       plantumlStats = mkOption {
         type = types.bool;
         default = false;
-        description = "Set it to on to enable statistics report (https://plantuml.com/statistics-report).";
+        description = lib.mdDoc "Set it to on to enable statistics report (https://plantuml.com/statistics-report).";
       };
 
       httpAuthorization = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "When calling the proxy endpoint, the value of HTTP_AUTHORIZATION will be used to set the HTTP Authorization header.";
+        description = lib.mdDoc "When calling the proxy endpoint, the value of HTTP_AUTHORIZATION will be used to set the HTTP Authorization header.";
       };
 
       allowPlantumlInclude = mkOption {
         type = types.bool;
         default = false;
-        description = "Enables !include processing which can read files from the server into diagrams. Files are read relative to the current working directory.";
+        description = lib.mdDoc "Enables !include processing which can read files from the server into diagrams. Files are read relative to the current working directory.";
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/plausible.nix b/nixos/modules/services/web-apps/plausible.nix
index 5d550ae5ca8..e5dc1b10360 100644
--- a/nixos/modules/services/web-apps/plausible.nix
+++ b/nixos/modules/services/web-apps/plausible.nix
@@ -7,11 +7,11 @@ let
 
 in {
   options.services.plausible = {
-    enable = mkEnableOption "plausible";
+    enable = mkEnableOption (lib.mdDoc "plausible");
 
     releaseCookiePath = mkOption {
       type = with types; either str path;
-      description = ''
+      description = lib.mdDoc ''
         The path to the file with release cookie. (used for remote connection to the running node).
       '';
     };
@@ -20,7 +20,7 @@ in {
       name = mkOption {
         default = "admin";
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Name of the admin user that plausible will created on initial startup.
         '';
       };
@@ -28,46 +28,46 @@ in {
       email = mkOption {
         type = types.str;
         example = "admin@localhost";
-        description = ''
+        description = lib.mdDoc ''
           Email-address of the admin-user.
         '';
       };
 
       passwordFile = mkOption {
         type = types.either types.str types.path;
-        description = ''
+        description = lib.mdDoc ''
           Path to the file which contains the password of the admin user.
         '';
       };
 
-      activate = mkEnableOption "activating the freshly created admin-user";
+      activate = mkEnableOption (lib.mdDoc "activating the freshly created admin-user");
     };
 
     database = {
       clickhouse = {
-        setup = mkEnableOption "creating a clickhouse instance" // { default = true; };
+        setup = mkEnableOption (lib.mdDoc "creating a clickhouse instance") // { default = true; };
         url = mkOption {
           default = "http://localhost:8123/default";
           type = types.str;
-          description = ''
-            The URL to be used to connect to <package>clickhouse</package>.
+          description = lib.mdDoc ''
+            The URL to be used to connect to `clickhouse`.
           '';
         };
       };
       postgres = {
-        setup = mkEnableOption "creating a postgresql instance" // { default = true; };
+        setup = mkEnableOption (lib.mdDoc "creating a postgresql instance") // { default = true; };
         dbname = mkOption {
           default = "plausible";
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             Name of the database to use.
           '';
         };
         socket = mkOption {
           default = "/run/postgresql";
           type = types.str;
-          description = ''
-            Path to the UNIX domain-socket to communicate with <package>postgres</package>.
+          description = lib.mdDoc ''
+            Path to the UNIX domain-socket to communicate with `postgres`.
           '';
         };
       };
@@ -77,35 +77,35 @@ in {
       disableRegistration = mkOption {
         default = true;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Whether to prohibit creating an account in plausible's UI.
         '';
       };
       secretKeybaseFile = mkOption {
         type = types.either types.path types.str;
-        description = ''
-          Path to the secret used by the <literal>phoenix</literal>-framework. Instructions
+        description = lib.mdDoc ''
+          Path to the secret used by the `phoenix`-framework. Instructions
           how to generate one are documented in the
-          <link xlink:href="https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Secret.html#content">
-          framework docs</link>.
+          [
+          framework docs](https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Secret.html#content).
         '';
       };
       port = mkOption {
         default = 8000;
         type = types.port;
-        description = ''
+        description = lib.mdDoc ''
           Port where the service should be available.
         '';
       };
       baseUrl = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Public URL where plausible is available.
 
-          Note that <literal>/path</literal> components are currently ignored:
-          <link xlink:href="https://github.com/plausible/analytics/issues/1182">
+          Note that `/path` components are currently ignored:
+          [
             https://github.com/plausible/analytics/issues/1182
-          </link>.
+          ](https://github.com/plausible/analytics/issues/1182).
         '';
       };
     };
@@ -114,8 +114,8 @@ in {
       email = mkOption {
         default = "hello@plausible.local";
         type = types.str;
-        description = ''
-          The email id to use for as <emphasis>from</emphasis> address of all communications
+        description = lib.mdDoc ''
+          The email id to use for as *from* address of all communications
           from Plausible.
         '';
       };
@@ -123,36 +123,36 @@ in {
         hostAddr = mkOption {
           default = "localhost";
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             The host address of your smtp server.
           '';
         };
         hostPort = mkOption {
           default = 25;
           type = types.port;
-          description = ''
+          description = lib.mdDoc ''
             The port of your smtp server.
           '';
         };
         user = mkOption {
           default = null;
           type = types.nullOr types.str;
-          description = ''
+          description = lib.mdDoc ''
             The username/email in case SMTP auth is enabled.
           '';
         };
         passwordFile = mkOption {
           default = null;
           type = with types; nullOr (either str path);
-          description = ''
+          description = lib.mdDoc ''
             The path to the file with the password in case SMTP auth is enabled.
           '';
         };
-        enableSSL = mkEnableOption "SSL when connecting to the SMTP server";
+        enableSSL = mkEnableOption (lib.mdDoc "SSL when connecting to the SMTP server");
         retries = mkOption {
           type = types.ints.unsigned;
           default = 2;
-          description = ''
+          description = lib.mdDoc ''
             Number of retries to make until mailer gives up.
           '';
         };
@@ -188,7 +188,11 @@ in {
           inherit (pkgs.plausible.meta) description;
           documentation = [ "https://plausible.io/docs/self-hosting" ];
           wantedBy = [ "multi-user.target" ];
-          after = optionals cfg.database.postgres.setup [ "postgresql.service" "plausible-postgres.service" ];
+          after = optional cfg.database.clickhouse.setup "clickhouse.service"
+          ++ optionals cfg.database.postgres.setup [
+              "postgresql.service"
+              "plausible-postgres.service"
+            ];
           requires = optional cfg.database.clickhouse.setup "clickhouse.service"
             ++ optionals cfg.database.postgres.setup [
               "postgresql.service"
diff --git a/nixos/modules/services/web-apps/powerdns-admin.nix b/nixos/modules/services/web-apps/powerdns-admin.nix
index 4661ba80c5d..e9f7f41055e 100644
--- a/nixos/modules/services/web-apps/powerdns-admin.nix
+++ b/nixos/modules/services/web-apps/powerdns-admin.nix
@@ -19,7 +19,7 @@ let
 in
 {
   options.services.powerdns-admin = {
-    enable = mkEnableOption "the PowerDNS web interface";
+    enable = mkEnableOption (lib.mdDoc "the PowerDNS web interface");
 
     extraArgs = mkOption {
       type = types.listOf types.str;
@@ -27,7 +27,7 @@ in
       example = literalExpression ''
         [ "-b" "127.0.0.1:8000" ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         Extra arguments passed to powerdns-admin.
       '';
     };
@@ -40,9 +40,9 @@ in
         PORT = 8000
         SQLALCHEMY_DATABASE_URI = 'postgresql://powerdnsadmin@/powerdnsadmin?host=/run/postgresql'
       '';
-      description = ''
+      description = lib.mdDoc ''
         Configuration python file.
-        See <link xlink:href="https://github.com/ngoduykhanh/PowerDNS-Admin/blob/v${pkgs.powerdns-admin.version}/configs/development.py">the example configuration</link>
+        See [the example configuration](https://github.com/ngoduykhanh/PowerDNS-Admin/blob/v${pkgs.powerdns-admin.version}/configs/development.py)
         for options.
       '';
     };
@@ -50,7 +50,7 @@ in
     secretKeyFile = mkOption {
       type = types.nullOr types.path;
       example = "/etc/powerdns-admin/secret";
-      description = ''
+      description = lib.mdDoc ''
         The secret used to create cookies.
         This needs to be set, otherwise the default is used and everyone can forge valid login cookies.
         Set this to null to ignore this setting and configure it through another way.
@@ -60,7 +60,7 @@ in
     saltFile = mkOption {
       type = types.nullOr types.path;
       example = "/etc/powerdns-admin/salt";
-      description = ''
+      description = lib.mdDoc ''
         The salt used for serialization.
         This should be set, otherwise the default is used.
         Set this to null to ignore this setting and configure it through another way.
diff --git a/nixos/modules/services/web-apps/prosody-filer.nix b/nixos/modules/services/web-apps/prosody-filer.nix
index a901a95fd5f..84953546d8e 100644
--- a/nixos/modules/services/web-apps/prosody-filer.nix
+++ b/nixos/modules/services/web-apps/prosody-filer.nix
@@ -11,12 +11,12 @@ in {
 
   options = {
     services.prosody-filer = {
-      enable = mkEnableOption "Prosody Filer XMPP upload file server";
+      enable = mkEnableOption (lib.mdDoc "Prosody Filer XMPP upload file server");
 
       settings = mkOption {
-        description = ''
+        description = lib.mdDoc ''
           Configuration for Prosody Filer.
-          Refer to <link xlink:href="https://github.com/ThomasLeister/prosody-filer#configure-prosody-filer"/> for details on supported values.
+          Refer to <https://github.com/ThomasLeister/prosody-filer#configure-prosody-filer> for details on supported values.
         '';
 
         type = settingsFormat.type;
@@ -79,7 +79,7 @@ in {
         LockPersonality = true;
         RemoveIPC = true;
         RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
-        SystemCallFilter = [ "@system-service" "~@privileged" "~@resources" ];
+        SystemCallFilter = [ "@system-service" "~@privileged" ];
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/restya-board.nix b/nixos/modules/services/web-apps/restya-board.nix
index 4b36cc8754c..4b32f06826e 100644
--- a/nixos/modules/services/web-apps/restya-board.nix
+++ b/nixos/modules/services/web-apps/restya-board.nix
@@ -25,12 +25,12 @@ in
 
     services.restya-board = {
 
-      enable = mkEnableOption "restya-board";
+      enable = mkEnableOption (lib.mdDoc "restya-board");
 
       dataDir = mkOption {
         type = types.path;
         default = "/var/lib/restya-board";
-        description = ''
+        description = lib.mdDoc ''
           Data of the application.
         '';
       };
@@ -38,7 +38,7 @@ in
       user = mkOption {
         type = types.str;
         default = "restya-board";
-        description = ''
+        description = lib.mdDoc ''
           User account under which the web-application runs.
         '';
       };
@@ -46,7 +46,7 @@ in
       group = mkOption {
         type = types.str;
         default = "nginx";
-        description = ''
+        description = lib.mdDoc ''
           Group account under which the web-application runs.
         '';
       };
@@ -55,7 +55,7 @@ in
         serverName = mkOption {
           type = types.str;
           default = "restya.board";
-          description = ''
+          description = lib.mdDoc ''
             Name of the nginx virtualhost to use.
           '';
         };
@@ -63,15 +63,15 @@ in
         listenHost = mkOption {
           type = types.str;
           default = "localhost";
-          description = ''
+          description = lib.mdDoc ''
             Listen address for the virtualhost to use.
           '';
         };
 
         listenPort = mkOption {
-          type = types.int;
+          type = types.port;
           default = 3000;
-          description = ''
+          description = lib.mdDoc ''
             Listen port for the virtualhost to use.
           '';
         };
@@ -81,7 +81,7 @@ in
         host = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Host of the database. Leave 'null' to use a local PostgreSQL database.
             A local PostgreSQL database is initialized automatically.
           '';
@@ -90,7 +90,7 @@ in
         port = mkOption {
           type = types.nullOr types.int;
           default = 5432;
-          description = ''
+          description = lib.mdDoc ''
             The database's port.
           '';
         };
@@ -98,7 +98,7 @@ in
         name = mkOption {
           type = types.str;
           default = "restya_board";
-          description = ''
+          description = lib.mdDoc ''
             Name of the database. The database must exist.
           '';
         };
@@ -106,7 +106,7 @@ in
         user = mkOption {
           type = types.str;
           default = "restya_board";
-          description = ''
+          description = lib.mdDoc ''
             The database user. The user must exist and have access to
             the specified database.
           '';
@@ -115,7 +115,7 @@ in
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The database user's password. 'null' if no password is set.
           '';
         };
@@ -126,15 +126,15 @@ in
           type = types.nullOr types.str;
           default = null;
           example = "localhost";
-          description = ''
+          description = lib.mdDoc ''
             Hostname to send outgoing mail. Null to use the system MTA.
           '';
         };
 
         port = mkOption {
-          type = types.int;
+          type = types.port;
           default = 25;
-          description = ''
+          description = lib.mdDoc ''
             Port used to connect to SMTP server.
           '';
         };
@@ -142,7 +142,7 @@ in
         login = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             SMTP authentication login used when sending outgoing mail.
           '';
         };
@@ -150,7 +150,7 @@ in
         password = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             SMTP authentication password used when sending outgoing mail.
 
             ATTENTION: The password is stored world-readable in the nix-store!
@@ -161,7 +161,7 @@ in
       timezone = mkOption {
         type = types.lines;
         default = "GMT";
-        description = ''
+        description = lib.mdDoc ''
           Timezone the web-app runs in.
         '';
       };
@@ -263,8 +263,8 @@ in
       serviceConfig.RemainAfterExit = true;
 
       wantedBy = [ "multi-user.target" ];
-      requires = [ "postgresql.service" ];
-      after = [ "network.target" "postgresql.service" ];
+      requires = if cfg.database.host == null then [] else [ "postgresql.service" ];
+      after = [ "network.target" ] ++ (if cfg.database.host == null then [] else [ "postgresql.service" ]);
 
       script = ''
         rm -rf "${runDir}"
@@ -282,7 +282,7 @@ in
           sed -i "s/^.*'R_DB_PASSWORD'.*$/define('R_DB_PASSWORD', 'restya');/g" "${runDir}/server/php/config.inc.php"
         '' else ''
           sed -i "s/^.*'R_DB_HOST'.*$/define('R_DB_HOST', '${cfg.database.host}');/g" "${runDir}/server/php/config.inc.php"
-          sed -i "s/^.*'R_DB_PASSWORD'.*$/define('R_DB_PASSWORD', ${if cfg.database.passwordFile == null then "''" else "'file_get_contents(${cfg.database.passwordFile})'"});/g" "${runDir}/server/php/config.inc.php
+          sed -i "s/^.*'R_DB_PASSWORD'.*$/define('R_DB_PASSWORD', ${if cfg.database.passwordFile == null then "''" else "'$(cat ${cfg.database.passwordFile})');/g"}" "${runDir}/server/php/config.inc.php"
         ''}
         sed -i "s/^.*'R_DB_PORT'.*$/define('R_DB_PORT', '${toString cfg.database.port}');/g" "${runDir}/server/php/config.inc.php"
         sed -i "s/^.*'R_DB_NAME'.*$/define('R_DB_NAME', '${cfg.database.name}');/g" "${runDir}/server/php/config.inc.php"
@@ -294,7 +294,7 @@ in
         ln -sf "${cfg.dataDir}/client/img" "${runDir}/client/img"
 
         chmod g+w "${runDir}/tmp/cache"
-        chown -R "${cfg.user}"."${cfg.group}" "${runDir}"
+        chown -R "${cfg.user}":"${cfg.group}" "${runDir}"
 
 
         mkdir -m 0750 -p "${cfg.dataDir}"
@@ -302,9 +302,9 @@ in
         mkdir -m 0750 -p "${cfg.dataDir}/client/img"
         cp -r "${pkgs.restya-board}/media/"* "${cfg.dataDir}/media"
         cp -r "${pkgs.restya-board}/client/img/"* "${cfg.dataDir}/client/img"
-        chown "${cfg.user}"."${cfg.group}" "${cfg.dataDir}"
-        chown -R "${cfg.user}"."${cfg.group}" "${cfg.dataDir}/media"
-        chown -R "${cfg.user}"."${cfg.group}" "${cfg.dataDir}/client/img"
+        chown "${cfg.user}":"${cfg.group}" "${cfg.dataDir}"
+        chown -R "${cfg.user}":"${cfg.group}" "${cfg.dataDir}/media"
+        chown -R "${cfg.user}":"${cfg.group}" "${cfg.dataDir}/client/img"
 
         ${optionalString (cfg.database.host == null) ''
           if ! [ -e "${cfg.dataDir}/.db-initialized" ]; then
diff --git a/nixos/modules/services/web-apps/rss-bridge.nix b/nixos/modules/services/web-apps/rss-bridge.nix
index f2b6d955982..1a710f4a6a6 100644
--- a/nixos/modules/services/web-apps/rss-bridge.nix
+++ b/nixos/modules/services/web-apps/rss-bridge.nix
@@ -11,12 +11,12 @@ in
 {
   options = {
     services.rss-bridge = {
-      enable = mkEnableOption "rss-bridge";
+      enable = mkEnableOption (lib.mdDoc "rss-bridge");
 
       user = mkOption {
         type = types.str;
         default = "nginx";
-        description = ''
+        description = lib.mdDoc ''
           User account under which both the service and the web-application run.
         '';
       };
@@ -24,7 +24,7 @@ in
       group = mkOption {
         type = types.str;
         default = "nginx";
-        description = ''
+        description = lib.mdDoc ''
           Group under which the web-application run.
         '';
       };
@@ -32,7 +32,7 @@ in
       pool = mkOption {
         type = types.str;
         default = poolName;
-        description = ''
+        description = lib.mdDoc ''
           Name of existing phpfpm pool that is used to run web-application.
           If not specified a pool will be created automatically with
           default values.
@@ -42,16 +42,16 @@ in
       dataDir = mkOption {
         type = types.str;
         default = "/var/lib/rss-bridge";
-        description = ''
+        description = lib.mdDoc ''
           Location in which cache directory will be created.
-          You can put <literal>config.ini.php</literal> in here.
+          You can put `config.ini.php` in here.
         '';
       };
 
       virtualHost = mkOption {
         type = types.nullOr types.str;
         default = "rss-bridge";
-        description = ''
+        description = lib.mdDoc ''
           Name of the nginx virtualhost to use and setup. If null, do not setup any virtualhost.
         '';
       };
@@ -66,10 +66,10 @@ in
             "Twitter"
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           List of bridges to be whitelisted.
           If the list is empty, rss-bridge will use whitelist.default.txt.
-          Use <literal>[ "*" ]</literal> to whitelist all.
+          Use `[ "*" ]` to whitelist all.
         '';
       };
     };
diff --git a/nixos/modules/services/web-apps/selfoss.nix b/nixos/modules/services/web-apps/selfoss.nix
index 899976ac696..8debd4904e8 100644
--- a/nixos/modules/services/web-apps/selfoss.nix
+++ b/nixos/modules/services/web-apps/selfoss.nix
@@ -30,12 +30,12 @@ in
   {
     options = {
       services.selfoss = {
-        enable = mkEnableOption "selfoss";
+        enable = mkEnableOption (lib.mdDoc "selfoss");
 
         user = mkOption {
           type = types.str;
           default = "nginx";
-          description = ''
+          description = lib.mdDoc ''
             User account under which both the service and the web-application run.
           '';
         };
@@ -43,7 +43,7 @@ in
         pool = mkOption {
           type = types.str;
           default = "${poolName}";
-          description = ''
+          description = lib.mdDoc ''
             Name of existing phpfpm pool that is used to run web-application.
             If not specified a pool will be created automatically with
             default values.
@@ -54,7 +54,7 @@ in
         type = mkOption {
           type = types.enum ["pgsql" "mysql" "sqlite"];
           default = "sqlite";
-          description = ''
+          description = lib.mdDoc ''
             Database to store feeds. Supported are sqlite, pgsql and mysql.
           '';
         };
@@ -62,7 +62,7 @@ in
         host = mkOption {
           type = types.str;
           default = "localhost";
-          description = ''
+          description = lib.mdDoc ''
             Host of the database (has no effect if type is "sqlite").
           '';
         };
@@ -70,7 +70,7 @@ in
         name = mkOption {
           type = types.str;
           default = "tt_rss";
-          description = ''
+          description = lib.mdDoc ''
             Name of the existing database (has no effect if type is "sqlite").
           '';
         };
@@ -78,7 +78,7 @@ in
         user = mkOption {
           type = types.str;
           default = "tt_rss";
-          description = ''
+          description = lib.mdDoc ''
             The database user. The user must exist and has access to
             the specified database (has no effect if type is "sqlite").
           '';
@@ -87,7 +87,7 @@ in
         password = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The database user's password (has no effect if type is "sqlite").
           '';
         };
@@ -95,7 +95,7 @@ in
         port = mkOption {
           type = types.nullOr types.int;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The database's port. If not set, the default ports will be
             provided (5432 and 3306 for pgsql and mysql respectively)
             (has no effect if type is "sqlite").
@@ -105,7 +105,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration added to config.ini
         '';
       };
diff --git a/nixos/modules/services/web-apps/shiori.nix b/nixos/modules/services/web-apps/shiori.nix
index bb2fc684e83..f0505e052e1 100644
--- a/nixos/modules/services/web-apps/shiori.nix
+++ b/nixos/modules/services/web-apps/shiori.nix
@@ -6,19 +6,19 @@ let
 in {
   options = {
     services.shiori = {
-      enable = mkEnableOption "Shiori simple bookmarks manager";
+      enable = mkEnableOption (lib.mdDoc "Shiori simple bookmarks manager");
 
       package = mkOption {
         type = types.package;
         default = pkgs.shiori;
         defaultText = literalExpression "pkgs.shiori";
-        description = "The Shiori package to use.";
+        description = lib.mdDoc "The Shiori package to use.";
       };
 
       address = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           The IP address on which Shiori will listen.
           If empty, listens on all interfaces.
         '';
@@ -27,7 +27,7 @@ in {
       port = mkOption {
         type = types.port;
         default = 8080;
-        description = "The port of the Shiori web application";
+        description = lib.mdDoc "The port of the Shiori web application";
       };
     };
   };
@@ -86,7 +86,7 @@ in {
         SystemCallErrorNumber = "EPERM";
         SystemCallFilter = [
           "@system-service"
-          "~@cpu-emulation" "~@debug" "~@keyring" "~@memlock" "~@obsolete" "~@privileged" "~@resources" "~@setuid"
+          "~@cpu-emulation" "~@debug" "~@keyring" "~@memlock" "~@obsolete" "~@privileged" "~@setuid"
         ];
       };
     };
diff --git a/nixos/modules/services/web-apps/snipe-it.nix b/nixos/modules/services/web-apps/snipe-it.nix
new file mode 100644
index 00000000000..6da44f1bdf3
--- /dev/null
+++ b/nixos/modules/services/web-apps/snipe-it.nix
@@ -0,0 +1,509 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.snipe-it;
+  snipe-it = pkgs.snipe-it.override {
+    dataDir = cfg.dataDir;
+  };
+  db = cfg.database;
+  mail = cfg.mail;
+
+  user = cfg.user;
+  group = cfg.group;
+
+  tlsEnabled = cfg.nginx.addSSL || cfg.nginx.forceSSL || cfg.nginx.onlySSL || cfg.nginx.enableACME;
+
+  # shell script for local administration
+  artisan = pkgs.writeScriptBin "snipe-it" ''
+    #! ${pkgs.runtimeShell}
+    cd ${snipe-it}
+    sudo=exec
+    if [[ "$USER" != ${user} ]]; then
+      sudo='exec /run/wrappers/bin/sudo -u ${user}'
+    fi
+    $sudo ${pkgs.php}/bin/php artisan $*
+  '';
+in {
+  options.services.snipe-it = {
+
+    enable = mkEnableOption (lib.mdDoc "A free open source IT asset/license management system");
+
+    user = mkOption {
+      default = "snipeit";
+      description = lib.mdDoc "User snipe-it runs as.";
+      type = types.str;
+    };
+
+    group = mkOption {
+      default = "snipeit";
+      description = lib.mdDoc "Group snipe-it runs as.";
+      type = types.str;
+    };
+
+    appKeyFile = mkOption {
+      description = lib.mdDoc ''
+        A file containing the Laravel APP_KEY - a 32 character long,
+        base64 encoded key used for encryption where needed. Can be
+        generated with `head -c 32 /dev/urandom | base64`.
+      '';
+      example = "/run/keys/snipe-it/appkey";
+      type = types.path;
+    };
+
+    hostName = lib.mkOption {
+      type = lib.types.str;
+      default = config.networking.fqdnOrHostName;
+      defaultText = lib.literalExpression "config.networking.fqdnOrHostName";
+      example = "snipe-it.example.com";
+      description = lib.mdDoc ''
+        The hostname to serve Snipe-IT on.
+      '';
+    };
+
+    appURL = mkOption {
+      description = lib.mdDoc ''
+        The root URL that you want to host Snipe-IT on. All URLs in Snipe-IT will be generated using this value.
+        If you change this in the future you may need to run a command to update stored URLs in the database.
+        Command example: `snipe-it snipe-it:update-url https://old.example.com https://new.example.com`
+      '';
+      default = "http${lib.optionalString tlsEnabled "s"}://${cfg.hostName}";
+      defaultText = ''
+        http''${lib.optionalString tlsEnabled "s"}://''${cfg.hostName}
+      '';
+      example = "https://example.com";
+      type = types.str;
+    };
+
+    dataDir = mkOption {
+      description = lib.mdDoc "snipe-it data directory";
+      default = "/var/lib/snipe-it";
+      type = types.path;
+    };
+
+    database = {
+      host = mkOption {
+        type = types.str;
+        default = "localhost";
+        description = lib.mdDoc "Database host address.";
+      };
+      port = mkOption {
+        type = types.port;
+        default = 3306;
+        description = lib.mdDoc "Database host port.";
+      };
+      name = mkOption {
+        type = types.str;
+        default = "snipeit";
+        description = lib.mdDoc "Database name.";
+      };
+      user = mkOption {
+        type = types.str;
+        default = user;
+        defaultText = literalExpression "user";
+        description = lib.mdDoc "Database username.";
+      };
+      passwordFile = mkOption {
+        type = with types; nullOr path;
+        default = null;
+        example = "/run/keys/snipe-it/dbpassword";
+        description = lib.mdDoc ''
+          A file containing the password corresponding to
+          {option}`database.user`.
+        '';
+      };
+      createLocally = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc "Create the database and database user locally.";
+      };
+    };
+
+    mail = {
+      driver = mkOption {
+        type = types.enum [ "smtp" "sendmail" ];
+        default = "smtp";
+        description = lib.mdDoc "Mail driver to use.";
+      };
+      host = mkOption {
+        type = types.str;
+        default = "localhost";
+        description = lib.mdDoc "Mail host address.";
+      };
+      port = mkOption {
+        type = types.port;
+        default = 1025;
+        description = lib.mdDoc "Mail host port.";
+      };
+      encryption = mkOption {
+        type = with types; nullOr (enum [ "tls" "ssl" ]);
+        default = null;
+        description = lib.mdDoc "SMTP encryption mechanism to use.";
+      };
+      user = mkOption {
+        type = with types; nullOr str;
+        default = null;
+        example = "snipeit";
+        description = lib.mdDoc "Mail username.";
+      };
+      passwordFile = mkOption {
+        type = with types; nullOr path;
+        default = null;
+        example = "/run/keys/snipe-it/mailpassword";
+        description = lib.mdDoc ''
+          A file containing the password corresponding to
+          {option}`mail.user`.
+        '';
+      };
+      backupNotificationAddress = mkOption {
+        type = types.str;
+        default = "backup@example.com";
+        description = lib.mdDoc "Email Address to send Backup Notifications to.";
+      };
+      from = {
+        name = mkOption {
+          type = types.str;
+          default = "Snipe-IT Asset Management";
+          description = lib.mdDoc "Mail \"from\" name.";
+        };
+        address = mkOption {
+          type = types.str;
+          default = "mail@example.com";
+          description = lib.mdDoc "Mail \"from\" address.";
+        };
+      };
+      replyTo = {
+        name = mkOption {
+          type = types.str;
+          default = "Snipe-IT Asset Management";
+          description = lib.mdDoc "Mail \"reply-to\" name.";
+        };
+        address = mkOption {
+          type = types.str;
+          default = "mail@example.com";
+          description = lib.mdDoc "Mail \"reply-to\" address.";
+        };
+      };
+    };
+
+    maxUploadSize = mkOption {
+      type = types.str;
+      default = "18M";
+      example = "1G";
+      description = lib.mdDoc "The maximum size for uploads (e.g. images).";
+    };
+
+    poolConfig = mkOption {
+      type = with types; attrsOf (oneOf [ str int bool ]);
+      default = {
+        "pm" = "dynamic";
+        "pm.max_children" = 32;
+        "pm.start_servers" = 2;
+        "pm.min_spare_servers" = 2;
+        "pm.max_spare_servers" = 4;
+        "pm.max_requests" = 500;
+      };
+      description = lib.mdDoc ''
+        Options for the snipe-it PHP pool. See the documentation on `php-fpm.conf`
+        for details on configuration directives.
+      '';
+    };
+
+    nginx = mkOption {
+      type = types.submodule (
+        recursiveUpdate
+          (import ../web-servers/nginx/vhost-options.nix { inherit config lib; }) {}
+      );
+      default = {};
+      example = literalExpression ''
+        {
+          serverAliases = [
+            "snipe-it.''${config.networking.domain}"
+          ];
+          # To enable encryption and let let's encrypt take care of certificate
+          forceSSL = true;
+          enableACME = true;
+        }
+      '';
+      description = lib.mdDoc ''
+        With this option, you can customize the nginx virtualHost settings.
+      '';
+    };
+
+    config = mkOption {
+      type = with types;
+        attrsOf
+          (nullOr
+            (either
+              (oneOf [
+                bool
+                int
+                port
+                path
+                str
+              ])
+              (submodule {
+                options = {
+                  _secret = mkOption {
+                    type = nullOr (oneOf [ str path ]);
+                    description = lib.mdDoc ''
+                      The path to a file containing the value the
+                      option should be set to in the final
+                      configuration file.
+                    '';
+                  };
+                };
+              })));
+      default = {};
+      example = literalExpression ''
+        {
+          ALLOWED_IFRAME_HOSTS = "https://example.com";
+          WKHTMLTOPDF = "''${pkgs.wkhtmltopdf}/bin/wkhtmltopdf";
+          AUTH_METHOD = "oidc";
+          OIDC_NAME = "MyLogin";
+          OIDC_DISPLAY_NAME_CLAIMS = "name";
+          OIDC_CLIENT_ID = "snipe-it";
+          OIDC_CLIENT_SECRET = {_secret = "/run/keys/oidc_secret"};
+          OIDC_ISSUER = "https://keycloak.example.com/auth/realms/My%20Realm";
+          OIDC_ISSUER_DISCOVER = true;
+        }
+      '';
+      description = lib.mdDoc ''
+        Snipe-IT configuration options to set in the
+        {file}`.env` file.
+        Refer to <https://snipe-it.readme.io/docs/configuration>
+        for details on supported values.
+
+        Settings containing secret data should be set to an attribute
+        set containing the attribute `_secret` - a
+        string pointing to a file containing the value the option
+        should be set to. See the example to get a better picture of
+        this: in the resulting {file}`.env` file, the
+        `OIDC_CLIENT_SECRET` key will be set to the
+        contents of the {file}`/run/keys/oidc_secret`
+        file.
+      '';
+    };
+  };
+
+  config = mkIf cfg.enable {
+
+    assertions = [
+      { assertion = db.createLocally -> db.user == user;
+        message = "services.snipe-it.database.user must be set to ${user} if services.snipe-it.database.createLocally is set true.";
+      }
+      { assertion = db.createLocally -> db.passwordFile == null;
+        message = "services.snipe-it.database.passwordFile cannot be specified if services.snipe-it.database.createLocally is set to true.";
+      }
+    ];
+
+    environment.systemPackages = [ artisan ];
+
+    services.snipe-it.config = {
+      APP_ENV = "production";
+      APP_KEY._secret = cfg.appKeyFile;
+      APP_URL = cfg.appURL;
+      DB_HOST = db.host;
+      DB_PORT = db.port;
+      DB_DATABASE = db.name;
+      DB_USERNAME = db.user;
+      DB_PASSWORD._secret = db.passwordFile;
+      MAIL_DRIVER = mail.driver;
+      MAIL_FROM_NAME = mail.from.name;
+      MAIL_FROM_ADDR = mail.from.address;
+      MAIL_REPLYTO_NAME = mail.from.name;
+      MAIL_REPLYTO_ADDR = mail.from.address;
+      MAIL_BACKUP_NOTIFICATION_ADDRESS = mail.backupNotificationAddress;
+      MAIL_HOST = mail.host;
+      MAIL_PORT = mail.port;
+      MAIL_USERNAME = mail.user;
+      MAIL_ENCRYPTION = mail.encryption;
+      MAIL_PASSWORD._secret = mail.passwordFile;
+      APP_SERVICES_CACHE = "/run/snipe-it/cache/services.php";
+      APP_PACKAGES_CACHE = "/run/snipe-it/cache/packages.php";
+      APP_CONFIG_CACHE = "/run/snipe-it/cache/config.php";
+      APP_ROUTES_CACHE = "/run/snipe-it/cache/routes-v7.php";
+      APP_EVENTS_CACHE = "/run/snipe-it/cache/events.php";
+      SESSION_SECURE_COOKIE = tlsEnabled;
+    };
+
+    services.mysql = mkIf db.createLocally {
+      enable = true;
+      package = mkDefault pkgs.mariadb;
+      ensureDatabases = [ db.name ];
+      ensureUsers = [
+        { name = db.user;
+          ensurePermissions = { "${db.name}.*" = "ALL PRIVILEGES"; };
+        }
+      ];
+    };
+
+    services.phpfpm.pools.snipe-it = {
+      inherit user group;
+      phpPackage = pkgs.php81;
+      phpOptions = ''
+        post_max_size = ${cfg.maxUploadSize}
+        upload_max_filesize = ${cfg.maxUploadSize}
+      '';
+      settings = {
+        "listen.mode" = "0660";
+        "listen.owner" = user;
+        "listen.group" = group;
+      } // cfg.poolConfig;
+    };
+
+    services.nginx = {
+      enable = mkDefault true;
+      virtualHosts."${cfg.hostName}" = mkMerge [ cfg.nginx {
+        root = mkForce "${snipe-it}/public";
+        extraConfig = optionalString (cfg.nginx.addSSL || cfg.nginx.forceSSL || cfg.nginx.onlySSL || cfg.nginx.enableACME) "fastcgi_param HTTPS on;";
+        locations = {
+          "/" = {
+            index = "index.php";
+            extraConfig = ''try_files $uri $uri/ /index.php?$query_string;'';
+          };
+          "~ \.php$" = {
+            extraConfig = ''
+              try_files $uri $uri/ /index.php?$query_string;
+              include ${config.services.nginx.package}/conf/fastcgi_params;
+              fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
+              fastcgi_param REDIRECT_STATUS 200;
+              fastcgi_pass unix:${config.services.phpfpm.pools."snipe-it".socket};
+              ${optionalString (cfg.nginx.addSSL || cfg.nginx.forceSSL || cfg.nginx.onlySSL || cfg.nginx.enableACME) "fastcgi_param HTTPS on;"}
+            '';
+          };
+          "~ \.(js|css|gif|png|ico|jpg|jpeg)$" = {
+            extraConfig = "expires 365d;";
+          };
+        };
+      }];
+    };
+
+    systemd.services.snipe-it-setup = {
+      description = "Preperation tasks for snipe-it";
+      before = [ "phpfpm-snipe-it.service" ];
+      after = optional db.createLocally "mysql.service";
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        Type = "oneshot";
+        RemainAfterExit = true;
+        User = user;
+        WorkingDirectory = snipe-it;
+        RuntimeDirectory = "snipe-it/cache";
+        RuntimeDirectoryMode = "0700";
+      };
+      path = [ pkgs.replace-secret ];
+      script =
+        let
+          isSecret  = v: isAttrs v && v ? _secret && (isString v._secret || builtins.isPath v._secret);
+          snipeITEnvVars = lib.generators.toKeyValue {
+            mkKeyValue = lib.flip lib.generators.mkKeyValueDefault "=" {
+              mkValueString = v: with builtins;
+                if isInt             v then toString v
+                else if isString     v then "\"${v}\""
+                else if true  ==     v then "true"
+                else if false ==     v then "false"
+                else if isSecret     v then
+                  if (isString v._secret) then
+                    hashString "sha256" v._secret
+                  else
+                    hashString "sha256" (builtins.readFile v._secret)
+                else throw "unsupported type ${typeOf v}: ${(lib.generators.toPretty {}) v}";
+            };
+          };
+          secretPaths = lib.mapAttrsToList (_: v: v._secret) (lib.filterAttrs (_: isSecret) cfg.config);
+          mkSecretReplacement = file: ''
+            replace-secret ${escapeShellArgs [
+              (
+                if (isString file) then
+                  builtins.hashString "sha256" file
+                else
+                  builtins.hashString "sha256" (builtins.readFile file)
+              )
+              file
+              "${cfg.dataDir}/.env"
+            ]}
+          '';
+          secretReplacements = lib.concatMapStrings mkSecretReplacement secretPaths;
+          filteredConfig = lib.converge (lib.filterAttrsRecursive (_: v: ! elem v [ {} null ])) cfg.config;
+          snipeITEnv = pkgs.writeText "snipeIT.env" (snipeITEnvVars filteredConfig);
+        in ''
+          # error handling
+          set -euo pipefail
+
+          # set permissions
+          umask 077
+
+          # create .env file
+          install -T -m 0600 -o ${user} ${snipeITEnv} "${cfg.dataDir}/.env"
+
+          # replace secrets
+          ${secretReplacements}
+
+          # prepend `base64:` if it does not exist in APP_KEY
+          if ! grep 'APP_KEY=base64:' "${cfg.dataDir}/.env" >/dev/null; then
+              sed -i 's/APP_KEY=/APP_KEY=base64:/' "${cfg.dataDir}/.env"
+          fi
+
+          # purge cache
+          rm "${cfg.dataDir}"/bootstrap/cache/*.php || true
+
+          # migrate db
+          ${pkgs.php}/bin/php artisan migrate --force
+
+          # A placeholder file for invalid barcodes
+          invalid_barcode_location="${cfg.dataDir}/public/uploads/barcodes/invalid_barcode.gif"
+          [ ! -e "$invalid_barcode_location" ] \
+              && cp ${snipe-it}/share/snipe-it/invalid_barcode.gif "$invalid_barcode_location"
+        '';
+    };
+
+    systemd.tmpfiles.rules = [
+      "d ${cfg.dataDir}                              0710 ${user} ${group} - -"
+      "d ${cfg.dataDir}/bootstrap                    0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/bootstrap/cache              0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public                       0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads               0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/accessories   0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/assets        0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/avatars       0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/barcodes      0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/categories    0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/companies     0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/components    0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/consumables   0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/departments   0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/locations     0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/manufacturers 0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/models        0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/public/uploads/suppliers     0750 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage                      0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/app                  0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/fonts                0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/framework            0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/framework/cache      0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/framework/sessions   0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/framework/views      0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/logs                 0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/uploads              0700 ${user} ${group} - -"
+      "d ${cfg.dataDir}/storage/private_uploads      0700 ${user} ${group} - -"
+    ];
+
+    users = {
+      users = mkIf (user == "snipeit") {
+        snipeit = {
+          inherit group;
+          isSystemUser = true;
+        };
+        "${config.services.nginx.user}".extraGroups = [ group ];
+      };
+      groups = mkIf (group == "snipeit") {
+        snipeit = {};
+      };
+    };
+
+  };
+
+  meta.maintainers = with maintainers; [ yayayayaka ];
+}
diff --git a/nixos/modules/services/web-apps/sogo.nix b/nixos/modules/services/web-apps/sogo.nix
index 4610bb96cb5..ca1f426623f 100644
--- a/nixos/modules/services/web-apps/sogo.nix
+++ b/nixos/modules/services/web-apps/sogo.nix
@@ -18,34 +18,34 @@
 
 in {
   options.services.sogo = with types; {
-    enable = mkEnableOption "SOGo groupware";
+    enable = mkEnableOption (lib.mdDoc "SOGo groupware");
 
     vhostName = mkOption {
-      description = "Name of the nginx vhost";
+      description = lib.mdDoc "Name of the nginx vhost";
       type = str;
       default = "sogo";
     };
 
     timezone = mkOption {
-      description = "Timezone of your SOGo instance";
+      description = lib.mdDoc "Timezone of your SOGo instance";
       type = str;
       example = "America/Montreal";
     };
 
     language = mkOption {
-      description = "Language of SOGo";
+      description = lib.mdDoc "Language of SOGo";
       type = str;
       default = "English";
     };
 
     ealarmsCredFile = mkOption {
-      description = "Optional path to a credentials file for email alarms";
+      description = lib.mdDoc "Optional path to a credentials file for email alarms";
       type = nullOr str;
       default = null;
     };
 
     configReplaces = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Replacement-filepath mapping for sogo.conf.
         Every key is replaced with the contents of the file specified as value.
 
@@ -60,7 +60,7 @@ in {
     };
 
     extraConfig = mkOption {
-      description = "Extra sogo.conf configuration lines";
+      description = lib.mdDoc "Extra sogo.conf configuration lines";
       type = lines;
       default = "";
     };
diff --git a/nixos/modules/services/web-apps/timetagger.nix b/nixos/modules/services/web-apps/timetagger.nix
deleted file mode 100644
index 373f4fcd52f..00000000000
--- a/nixos/modules/services/web-apps/timetagger.nix
+++ /dev/null
@@ -1,80 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-let
-  inherit (lib) mkEnableOption mkIf mkOption types literalExpression;
-
-  cfg = config.services.timetagger;
-in {
-
-  options = {
-    services.timetagger = {
-      enable = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Tag your time, get the insight
-
-          <note><para>
-            This app does not do authentication.
-            You must setup authentication yourself or run it in an environment where
-            only allowed users have access.
-          </para></note>
-        '';
-      };
-
-      bindAddr = mkOption {
-        description = "Address to bind to.";
-        type = types.str;
-        default = "127.0.0.1";
-      };
-
-      port = mkOption {
-        description = "Port to bind to.";
-        type = types.port;
-        default = 8080;
-      };
-
-      package = mkOption {
-        description = ''
-          Use own package for starting timetagger web application.
-
-          The ${literalExpression ''pkgs.timetagger''} package only provides a
-          "run.py" script for the actual package
-          ${literalExpression ''pkgs.python3Packages.timetagger''}.
-
-          If you want to provide a "run.py" script for starting timetagger
-          yourself, you can do so with this option.
-          If you do so, the 'bindAddr' and 'port' options are ignored.
-        '';
-
-        default = pkgs.timetagger.override { addr = cfg.bindAddr; port = cfg.port; };
-        defaultText = literalExpression ''
-          pkgs.timetagger.override {
-            addr = ${cfg.bindAddr};
-            port = ${cfg.port};
-          };
-        '';
-        type = types.package;
-      };
-    };
-  };
-
-  config = mkIf cfg.enable {
-    systemd.services.timetagger = {
-      description = "Timetagger service";
-      wantedBy = [ "multi-user.target" ];
-
-      serviceConfig = {
-        User = "timetagger";
-        Group = "timetagger";
-        StateDirectory = "timetagger";
-
-        ExecStart = "${cfg.package}/bin/timetagger";
-
-        Restart = "on-failure";
-        RestartSec = 1;
-      };
-    };
-  };
-}
-
diff --git a/nixos/modules/services/web-apps/trilium.nix b/nixos/modules/services/web-apps/trilium.nix
index 35383c992fe..a91d64f620b 100644
--- a/nixos/modules/services/web-apps/trilium.nix
+++ b/nixos/modules/services/web-apps/trilium.nix
@@ -10,6 +10,7 @@ let
     # Disable automatically generating desktop icon
     noDesktopIcon=true
     noBackup=${lib.boolToString cfg.noBackup}
+    noAuthentication=${lib.boolToString cfg.noAuthentication}
 
     [Network]
     # host setting is relevant only for web deployments - set the host on which the server will listen
@@ -23,12 +24,12 @@ in
 {
 
   options.services.trilium-server = with lib; {
-    enable = mkEnableOption "trilium-server";
+    enable = mkEnableOption (lib.mdDoc "trilium-server");
 
     dataDir = mkOption {
       type = types.str;
       default = "/var/lib/trilium";
-      description = ''
+      description = lib.mdDoc ''
         The directory storing the notes database and the configuration.
       '';
     };
@@ -36,7 +37,7 @@ in
     instanceName = mkOption {
       type = types.str;
       default = "Trilium";
-      description = ''
+      description = lib.mdDoc ''
         Instance name used to distinguish between different instances
       '';
     };
@@ -44,30 +45,38 @@ in
     noBackup = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Disable periodic database backups.
       '';
     };
 
+    noAuthentication = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        If set to true, no password is required to access the web frontend.
+      '';
+    };
+
     host = mkOption {
       type = types.str;
       default = "127.0.0.1";
-      description = ''
+      description = lib.mdDoc ''
         The host address to bind to (defaults to localhost).
       '';
     };
 
     port = mkOption {
-      type = types.int;
+      type = types.port;
       default = 8080;
-      description = ''
+      description = lib.mdDoc ''
         The port number to bind to.
       '';
     };
 
     nginx = mkOption {
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         Configuration for nginx reverse proxy.
       '';
 
@@ -76,14 +85,14 @@ in
           enable = mkOption {
             type = types.bool;
             default = false;
-            description = ''
+            description = lib.mdDoc ''
               Configure the nginx reverse proxy settings.
             '';
           };
 
           hostName = mkOption {
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               The hostname use to setup the virtualhost configuration
             '';
           };
diff --git a/nixos/modules/services/web-apps/tt-rss.nix b/nixos/modules/services/web-apps/tt-rss.nix
index 9aa38ab25c9..6f494fae4cc 100644
--- a/nixos/modules/services/web-apps/tt-rss.nix
+++ b/nixos/modules/services/web-apps/tt-rss.nix
@@ -121,12 +121,12 @@ let
 
     services.tt-rss = {
 
-      enable = mkEnableOption "tt-rss";
+      enable = mkEnableOption (lib.mdDoc "tt-rss");
 
       root = mkOption {
         type = types.path;
         default = "/var/lib/tt-rss";
-        description = ''
+        description = lib.mdDoc ''
           Root of the application.
         '';
       };
@@ -134,7 +134,7 @@ let
       user = mkOption {
         type = types.str;
         default = "tt_rss";
-        description = ''
+        description = lib.mdDoc ''
           User account under which both the update daemon and the web-application run.
         '';
       };
@@ -142,7 +142,7 @@ let
       pool = mkOption {
         type = types.str;
         default = "${poolName}";
-        description = ''
+        description = lib.mdDoc ''
           Name of existing phpfpm pool that is used to run web-application.
           If not specified a pool will be created automatically with
           default values.
@@ -152,7 +152,7 @@ let
       virtualHost = mkOption {
         type = types.nullOr types.str;
         default = "tt-rss";
-        description = ''
+        description = lib.mdDoc ''
           Name of the nginx virtualhost to use and setup. If null, do not setup any virtualhost.
         '';
       };
@@ -161,7 +161,7 @@ let
         type = mkOption {
           type = types.enum ["pgsql" "mysql"];
           default = "pgsql";
-          description = ''
+          description = lib.mdDoc ''
             Database to store feeds. Supported are pgsql and mysql.
           '';
         };
@@ -169,7 +169,7 @@ let
         host = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Host of the database. Leave null to use Unix domain socket.
           '';
         };
@@ -177,7 +177,7 @@ let
         name = mkOption {
           type = types.str;
           default = "tt_rss";
-          description = ''
+          description = lib.mdDoc ''
             Name of the existing database.
           '';
         };
@@ -185,7 +185,7 @@ let
         user = mkOption {
           type = types.str;
           default = "tt_rss";
-          description = ''
+          description = lib.mdDoc ''
             The database user. The user must exist and has access to
             the specified database.
           '';
@@ -194,7 +194,7 @@ let
         password = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The database user's password.
           '';
         };
@@ -202,15 +202,15 @@ let
         passwordFile = mkOption {
           type = types.nullOr types.str;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The database user's password.
           '';
         };
 
         port = mkOption {
-          type = types.nullOr types.int;
+          type = types.nullOr types.port;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             The database's port. If not set, the default ports will be provided (5432
             and 3306 for pgsql and mysql respectively).
           '';
@@ -219,7 +219,7 @@ let
         createLocally = mkOption {
           type = types.bool;
           default = true;
-          description = "Create the database and database user locally.";
+          description = lib.mdDoc "Create the database and database user locally.";
         };
       };
 
@@ -227,7 +227,7 @@ let
         autoCreate = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Allow authentication modules to auto-create users in tt-rss internal
             database when authenticated successfully.
           '';
@@ -236,7 +236,7 @@ let
         autoLogin = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Automatically login user on remote or other kind of externally supplied
             authentication, otherwise redirect to login form as normal.
             If set to true, users won't be able to set application language
@@ -249,7 +249,7 @@ let
         hub = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             URL to a PubSubHubbub-compatible hub server. If defined, "Published
             articles" generated feed would automatically become PUSH-enabled.
           '';
@@ -258,7 +258,7 @@ let
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Enable client PubSubHubbub support in tt-rss. When disabled, tt-rss
             won't try to subscribe to PUSH feed updates.
           '';
@@ -269,7 +269,7 @@ let
         server = mkOption {
           type = types.str;
           default = "localhost:9312";
-          description = ''
+          description = lib.mdDoc ''
             Hostname:port combination for the Sphinx server.
           '';
         };
@@ -277,7 +277,7 @@ let
         index = mkOption {
           type = types.listOf types.str;
           default = ["ttrss" "delta"];
-          description = ''
+          description = lib.mdDoc ''
             Index names in Sphinx configuration. Example configuration
             files are available on tt-rss wiki.
           '';
@@ -288,7 +288,7 @@ let
         enable = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Allow users to register themselves. Please be aware that allowing
             random people to access your tt-rss installation is a security risk
             and potentially might lead to data loss or server exploit. Disabled
@@ -299,7 +299,7 @@ let
         notifyAddress = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Email address to send new user notifications to.
           '';
         };
@@ -307,7 +307,7 @@ let
         maxUsers = mkOption {
           type = types.int;
           default = 0;
-          description = ''
+          description = lib.mdDoc ''
             Maximum amount of users which will be allowed to register on this
             system. 0 - no limit.
           '';
@@ -319,7 +319,7 @@ let
           type = types.str;
           default = "";
           example = "localhost:25";
-          description = ''
+          description = lib.mdDoc ''
             Hostname:port combination to send outgoing mail. Blank - use system
             MTA.
           '';
@@ -328,7 +328,7 @@ let
         login = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             SMTP authentication login used when sending outgoing mail.
           '';
         };
@@ -336,7 +336,7 @@ let
         password = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             SMTP authentication password used when sending outgoing mail.
           '';
         };
@@ -344,7 +344,7 @@ let
         security = mkOption {
           type = types.enum ["" "ssl" "tls"];
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Used to select a secure SMTP connection. Allowed values: ssl, tls,
             or empty.
           '';
@@ -353,7 +353,7 @@ let
         fromName = mkOption {
           type = types.str;
           default = "Tiny Tiny RSS";
-          description = ''
+          description = lib.mdDoc ''
             Name for sending outgoing mail. This applies to password reset
             notifications, digest emails and any other mail.
           '';
@@ -362,7 +362,7 @@ let
         fromAddress = mkOption {
           type = types.str;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Address for sending outgoing mail. This applies to password reset
             notifications, digest emails and any other mail.
           '';
@@ -371,7 +371,7 @@ let
         digestSubject = mkOption {
           type = types.str;
           default = "[tt-rss] New headlines for last 24 hours";
-          description = ''
+          description = lib.mdDoc ''
             Subject line for email digests.
           '';
         };
@@ -380,7 +380,7 @@ let
       sessionCookieLifetime = mkOption {
         type = types.int;
         default = 86400;
-        description = ''
+        description = lib.mdDoc ''
           Default lifetime of a session (e.g. login) cookie. In seconds,
           0 means cookie will be deleted when browser closes.
         '';
@@ -388,7 +388,7 @@ let
 
       selfUrlPath = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           Full URL of your tt-rss installation. This should be set to the
           location of tt-rss directory, e.g. http://example.org/tt-rss/
           You need to set this option correctly otherwise several features
@@ -400,7 +400,7 @@ let
       feedCryptKey = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Key used for encryption of passwords for password-protected feeds
           in the database. A string of 24 random characters. If left blank, encryption
           is not used. Requires mcrypt functions.
@@ -413,7 +413,7 @@ let
         type = types.bool;
         default = false;
 
-        description = ''
+        description = lib.mdDoc ''
           Operate in single user mode, disables all functionality related to
           multiple users and authentication. Enabling this assumes you have
           your tt-rss directory protected by other means (e.g. http auth).
@@ -423,7 +423,7 @@ let
       simpleUpdateMode = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enables fallback update mode where tt-rss tries to update feeds in
           background while tt-rss is open in your browser.
           If you don't have a lot of feeds and don't want to or can't run
@@ -437,7 +437,7 @@ let
       forceArticlePurge = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           When this option is not 0, users ability to control feed purging
           intervals is disabled and all articles (which are not starred)
           older than this amount of days are purged.
@@ -447,7 +447,7 @@ let
       enableGZipOutput = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Selectively gzip output to improve wire performance. This requires
           PHP Zlib extension on the server.
           Enabling this can break tt-rss in several httpd/php configurations,
@@ -459,7 +459,7 @@ let
       plugins = mkOption {
         type = types.listOf types.str;
         default = ["auth_internal" "note"];
-        description = ''
+        description = lib.mdDoc ''
           List of plugins to load automatically for all users.
           System plugins have to be specified here. Please enable at least one
           authentication plugin here (auth_*).
@@ -473,27 +473,27 @@ let
       pluginPackages = mkOption {
         type = types.listOf types.package;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of plugins to install. The list elements are expected to
           be derivations. All elements in this derivation are automatically
-          copied to the <literal>plugins.local</literal> directory.
+          copied to the `plugins.local` directory.
         '';
       };
 
       themePackages = mkOption {
         type = types.listOf types.package;
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           List of themes to install. The list elements are expected to
           be derivations. All elements in this derivation are automatically
-          copied to the <literal>themes.local</literal> directory.
+          copied to the `themes.local` directory.
         '';
       };
 
       logDestination = mkOption {
         type = types.enum ["" "sql" "syslog"];
         default = "sql";
-        description = ''
+        description = lib.mdDoc ''
           Log destination to use. Possible values: sql (uses internal logging
           you can read in Preferences -> System), syslog - logs to system log.
           Setting this to blank uses PHP logging (usually to http server
@@ -504,8 +504,8 @@ let
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
-          Additional lines to append to <literal>config.php</literal>.
+        description = lib.mdDoc ''
+          Additional lines to append to `config.php`.
         '';
       };
     };
@@ -534,6 +534,7 @@ let
     services.phpfpm.pools = mkIf (cfg.pool == "${poolName}") {
       ${poolName} = {
         inherit (cfg) user;
+        phpPackage = pkgs.php80;
         settings = mapAttrs (name: mkDefault) {
           "listen.owner" = "nginx";
           "listen.group" = "nginx";
diff --git a/nixos/modules/services/web-apps/vikunja.nix b/nixos/modules/services/web-apps/vikunja.nix
index 7575e96ca81..c3552200d4e 100644
--- a/nixos/modules/services/web-apps/vikunja.nix
+++ b/nixos/modules/services/web-apps/vikunja.nix
@@ -10,23 +10,23 @@ let
   usePostgresql = cfg.database.type == "postgres";
 in {
   options.services.vikunja = with lib; {
-    enable = mkEnableOption "vikunja service";
+    enable = mkEnableOption (lib.mdDoc "vikunja service");
     package-api = mkOption {
       default = pkgs.vikunja-api;
       type = types.package;
       defaultText = literalExpression "pkgs.vikunja-api";
-      description = "vikunja-api derivation to use.";
+      description = lib.mdDoc "vikunja-api derivation to use.";
     };
     package-frontend = mkOption {
       default = pkgs.vikunja-frontend;
       type = types.package;
       defaultText = literalExpression "pkgs.vikunja-frontend";
-      description = "vikunja-frontend derivation to use.";
+      description = lib.mdDoc "vikunja-frontend derivation to use.";
     };
     environmentFiles = mkOption {
       type = types.listOf types.path;
       default = [ ];
-      description = ''
+      description = lib.mdDoc ''
         List of environment files set in the vikunja systemd service.
         For example passwords should be set in one of these files.
       '';
@@ -35,34 +35,34 @@ in {
       type = types.bool;
       default = config.services.nginx.enable;
       defaultText = literalExpression "config.services.nginx.enable";
-      description = ''
+      description = lib.mdDoc ''
         Whether to setup NGINX.
         Further nginx configuration can be done by changing
-        <option>services.nginx.virtualHosts.&lt;frontendHostname&gt;</option>.
+        {option}`services.nginx.virtualHosts.<frontendHostname>`.
         This does not enable TLS or ACME by default. To enable this, set the
-        <option>services.nginx.virtualHosts.&lt;frontendHostname&gt;.enableACME</option> to
-        <literal>true</literal> and if appropriate do the same for
-        <option>services.nginx.virtualHosts.&lt;frontendHostname&gt;.forceSSL</option>.
+        {option}`services.nginx.virtualHosts.<frontendHostname>.enableACME` to
+        `true` and if appropriate do the same for
+        {option}`services.nginx.virtualHosts.<frontendHostname>.forceSSL`.
       '';
     };
     frontendScheme = mkOption {
       type = types.enum [ "http" "https" ];
-      description = ''
+      description = lib.mdDoc ''
         Whether the site is available via http or https.
         This does not configure https or ACME in nginx!
       '';
     };
     frontendHostname = mkOption {
       type = types.str;
-      description = "The Hostname under which the frontend is running.";
+      description = lib.mdDoc "The Hostname under which the frontend is running.";
     };
 
     settings = mkOption {
       type = format.type;
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         Vikunja configuration. Refer to
-        <link xlink:href="https://vikunja.io/docs/config-options/"/>
+        <https://vikunja.io/docs/config-options/>
         for details on supported values.
         '';
     };
@@ -71,27 +71,27 @@ in {
         type = types.enum [ "sqlite" "mysql" "postgres" ];
         example = "postgres";
         default = "sqlite";
-        description = "Database engine to use.";
+        description = lib.mdDoc "Database engine to use.";
       };
       host = mkOption {
         type = types.str;
         default = "localhost";
-        description = "Database host address. Can also be a socket.";
+        description = lib.mdDoc "Database host address. Can also be a socket.";
       };
       user = mkOption {
         type = types.str;
         default = "vikunja";
-        description = "Database user.";
+        description = lib.mdDoc "Database user.";
       };
       database = mkOption {
         type = types.str;
         default = "vikunja";
-        description = "Database name.";
+        description = lib.mdDoc "Database name.";
       };
       path = mkOption {
         type = types.str;
         default = "/var/lib/vikunja/vikunja.db";
-        description = "Path to the sqlite3 database file.";
+        description = lib.mdDoc "Path to the sqlite3 database file.";
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/virtlyst.nix b/nixos/modules/services/web-apps/virtlyst.nix
deleted file mode 100644
index 37bdbb0e3b4..00000000000
--- a/nixos/modules/services/web-apps/virtlyst.nix
+++ /dev/null
@@ -1,73 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-let
-
-  cfg = config.services.virtlyst;
-  stateDir = "/var/lib/virtlyst";
-
-  ini = pkgs.writeText "virtlyst-config.ini" ''
-    [wsgi]
-    master = true
-    threads = auto
-    http-socket = ${cfg.httpSocket}
-    application = ${pkgs.virtlyst}/lib/libVirtlyst.so
-    chdir2 = ${stateDir}
-    static-map = /static=${pkgs.virtlyst}/root/static
-
-    [Cutelyst]
-    production = true
-    DatabasePath = virtlyst.sqlite
-    TemplatePath = ${pkgs.virtlyst}/root/src
-
-    [Rules]
-    cutelyst.* = true
-    virtlyst.* = true
-  '';
-
-in
-
-{
-
-  options.services.virtlyst = {
-    enable = mkEnableOption "Virtlyst libvirt web interface";
-
-    adminPassword = mkOption {
-      type = types.str;
-      description = ''
-        Initial admin password with which the database will be seeded.
-      '';
-    };
-
-    httpSocket = mkOption {
-      type = types.str;
-      default = "localhost:3000";
-      description = ''
-        IP and/or port to which to bind the http socket.
-      '';
-    };
-  };
-
-  config = mkIf cfg.enable {
-    users.users.virtlyst = {
-      home = stateDir;
-      createHome = true;
-      group = mkIf config.virtualisation.libvirtd.enable "libvirtd";
-      isSystemUser = true;
-    };
-
-    systemd.services.virtlyst = {
-      wantedBy = [ "multi-user.target" ];
-      environment = {
-        VIRTLYST_ADMIN_PASSWORD = cfg.adminPassword;
-      };
-      serviceConfig = {
-        ExecStart = "${pkgs.cutelyst}/bin/cutelyst-wsgi2 --ini ${ini}";
-        User = "virtlyst";
-        WorkingDirectory = stateDir;
-      };
-    };
-  };
-
-}
diff --git a/nixos/modules/services/web-apps/whitebophir.nix b/nixos/modules/services/web-apps/whitebophir.nix
index f9db6fe379b..b673a7c1179 100644
--- a/nixos/modules/services/web-apps/whitebophir.nix
+++ b/nixos/modules/services/web-apps/whitebophir.nix
@@ -7,25 +7,25 @@ let
 in {
   options = {
     services.whitebophir = {
-      enable = mkEnableOption "whitebophir, an online collaborative whiteboard server (persistent state will be maintained under <filename>/var/lib/whitebophir</filename>)";
+      enable = mkEnableOption (lib.mdDoc "whitebophir, an online collaborative whiteboard server (persistent state will be maintained under {file}`/var/lib/whitebophir`)");
 
       package = mkOption {
         default = pkgs.whitebophir;
         defaultText = literalExpression "pkgs.whitebophir";
         type = types.package;
-        description = "Whitebophir package to use.";
+        description = lib.mdDoc "Whitebophir package to use.";
       };
 
       listenAddress = mkOption {
         type = types.str;
         default = "0.0.0.0";
-        description = "Address to listen on (use 0.0.0.0 to allow access from any address).";
+        description = lib.mdDoc "Address to listen on (use 0.0.0.0 to allow access from any address).";
       };
 
       port = mkOption {
         type = types.port;
         default = 5001;
-        description = "Port to bind to.";
+        description = lib.mdDoc "Port to bind to.";
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/wiki-js.nix b/nixos/modules/services/web-apps/wiki-js.nix
index 1a6259dffee..c5627a28b84 100644
--- a/nixos/modules/services/web-apps/wiki-js.nix
+++ b/nixos/modules/services/web-apps/wiki-js.nix
@@ -10,13 +10,13 @@ let
   configFile = format.generate "wiki-js.yml" cfg.settings;
 in {
   options.services.wiki-js = {
-    enable = mkEnableOption "wiki-js";
+    enable = mkEnableOption (lib.mdDoc "wiki-js");
 
     environmentFile = mkOption {
       type = types.nullOr types.path;
       default = null;
       example = "/root/wiki-js.env";
-      description = ''
+      description = lib.mdDoc ''
         Environment fiel to inject e.g. secrets into the configuration.
       '';
     };
@@ -24,8 +24,8 @@ in {
     stateDirectoryName = mkOption {
       default = "wiki-js";
       type = types.str;
-      description = ''
-        Name of the directory in <filename>/var/lib</filename>.
+      description = lib.mdDoc ''
+        Name of the directory in {file}`/var/lib`.
       '';
     };
 
@@ -37,7 +37,7 @@ in {
           port = mkOption {
             type = types.port;
             default = 3000;
-            description = ''
+            description = lib.mdDoc ''
               TCP port the process should listen to.
             '';
           };
@@ -45,7 +45,7 @@ in {
           bindIP = mkOption {
             default = "0.0.0.0";
             type = types.str;
-            description = ''
+            description = lib.mdDoc ''
               IPs the service should listen to.
             '';
           };
@@ -54,24 +54,24 @@ in {
             type = mkOption {
               default = "postgres";
               type = types.enum [ "postgres" "mysql" "mariadb" "mssql" ];
-              description = ''
-                Database driver to use for persistence. Please note that <literal>sqlite</literal>
+              description = lib.mdDoc ''
+                Database driver to use for persistence. Please note that `sqlite`
                 is currently not supported as the build process for it is currently not implemented
-                in <package>pkgs.wiki-js</package> and it's not recommended by upstream for
+                in `pkgs.wiki-js` and it's not recommended by upstream for
                 production use.
               '';
             };
             host = mkOption {
               type = types.str;
               example = "/run/postgresql";
-              description = ''
+              description = lib.mdDoc ''
                 Hostname or socket-path to connect to.
               '';
             };
             db = mkOption {
               default = "wiki";
               type = types.str;
-              description = ''
+              description = lib.mdDoc ''
                 Name of the database to use.
               '';
             };
@@ -80,31 +80,28 @@ in {
           logLevel = mkOption {
             default = "info";
             type = types.enum [ "error" "warn" "info" "verbose" "debug" "silly" ];
-            description = ''
+            description = lib.mdDoc ''
               Define how much detail is supposed to be logged at runtime.
             '';
           };
 
-          offline = mkEnableOption "offline mode" // {
-            description = ''
+          offline = mkEnableOption (lib.mdDoc "offline mode") // {
+            description = lib.mdDoc ''
               Disable latest file updates and enable
-              <link xlink:href="https://docs.requarks.io/install/sideload">sideloading</link>.
+              [sideloading](https://docs.requarks.io/install/sideload).
             '';
           };
         };
       };
-      description = ''
-        Settings to configure <package>wiki-js</package>. This directly
-        corresponds to <link xlink:href="https://docs.requarks.io/install/config">the upstream
-        configuration options</link>.
+      description = lib.mdDoc ''
+        Settings to configure `wiki-js`. This directly
+        corresponds to [the upstream configuration options](https://docs.requarks.io/install/config).
 
         Secrets can be injected via the environment by
-        <itemizedlist>
-          <listitem><para>specifying <xref linkend="opt-services.wiki-js.environmentFile" />
-          to contain secrets</para></listitem>
-          <listitem><para>and setting sensitive values to <literal>$(ENVIRONMENT_VAR)</literal>
-          with this value defined in the environment-file.</para></listitem>
-        </itemizedlist>
+        - specifying [](#opt-services.wiki-js.environmentFile)
+          to contain secrets
+        - and setting sensitive values to `$(ENVIRONMENT_VAR)`
+          with this value defined in the environment-file.
       '';
     };
   };
@@ -130,7 +127,7 @@ in {
         WorkingDirectory = "/var/lib/${cfg.stateDirectoryName}";
         DynamicUser = true;
         PrivateTmp = true;
-        ExecStart = "${pkgs.nodejs}/bin/node ${pkgs.wiki-js}/server";
+        ExecStart = "${pkgs.nodejs-16_x}/bin/node ${pkgs.wiki-js}/server";
       };
     };
   };
diff --git a/nixos/modules/services/web-apps/wordpress.nix b/nixos/modules/services/web-apps/wordpress.nix
index 59471a739cb..43a6d7e75dc 100644
--- a/nixos/modules/services/web-apps/wordpress.nix
+++ b/nixos/modules/services/web-apps/wordpress.nix
@@ -22,6 +22,7 @@ let
       ln -s ${wpConfig hostName cfg} $out/share/wordpress/wp-config.php
       # symlink uploads directory
       ln -s ${cfg.uploadsDir} $out/share/wordpress/wp-content/uploads
+      ln -s ${cfg.fontsDir} $out/share/wordpress/wp-content/fonts
 
       # https://github.com/NixOS/nixpkgs/pull/53399
       #
@@ -30,9 +31,10 @@ let
       # requests that look like: https://example.com/wp-content//nix/store/...plugin/path/some-file.js
       # Since hard linking directories is not allowed, copying is the next best thing.
 
-      # copy additional plugin(s) and theme(s)
+      # copy additional plugin(s), theme(s) and language(s)
       ${concatMapStringsSep "\n" (theme: "cp -r ${theme} $out/share/wordpress/wp-content/themes/${theme.name}") cfg.themes}
       ${concatMapStringsSep "\n" (plugin: "cp -r ${plugin} $out/share/wordpress/wp-content/plugins/${plugin.name}") cfg.plugins}
+      ${concatMapStringsSep "\n" (language: "cp -r ${language} $out/share/wordpress/wp-content/languages/") cfg.languages}
     '';
   };
 
@@ -82,24 +84,36 @@ let
           type = types.package;
           default = pkgs.wordpress;
           defaultText = literalExpression "pkgs.wordpress";
-          description = "Which WordPress package to use.";
+          description = lib.mdDoc "Which WordPress package to use.";
         };
 
         uploadsDir = mkOption {
           type = types.path;
           default = "/var/lib/wordpress/${name}/uploads";
-          description = ''
+          description = lib.mdDoc ''
             This directory is used for uploads of pictures. The directory passed here is automatically
             created and permissions adjusted as required.
           '';
         };
 
+        fontsDir = mkOption {
+          type = types.path;
+          default = "/var/lib/wordpress/${name}/fonts";
+          description = lib.mdDoc ''
+            This directory is used to download fonts from a remote location, e.g.
+            to host google fonts locally.
+          '';
+        };
+
         plugins = mkOption {
           type = types.listOf types.path;
           default = [];
-          description = ''
+          description = lib.mdDoc ''
             List of path(s) to respective plugin(s) which are copied from the 'plugins' directory.
-            <note><para>These plugins need to be packaged before use, see example.</para></note>
+
+            ::: {.note}
+            These plugins need to be packaged before use, see example.
+            :::
           '';
           example = literalExpression ''
             let
@@ -124,9 +138,12 @@ let
         themes = mkOption {
           type = types.listOf types.path;
           default = [];
-          description = ''
+          description = lib.mdDoc ''
             List of path(s) to respective theme(s) which are copied from the 'theme' directory.
-            <note><para>These themes need to be packaged before use, see example.</para></note>
+
+            ::: {.note}
+            These themes need to be packaged before use, see example.
+            :::
           '';
           example = literalExpression ''
             let
@@ -148,51 +165,77 @@ let
           '';
         };
 
+        languages = mkOption {
+          type = types.listOf types.path;
+          default = [];
+          description = lib.mdDoc ''
+            List of path(s) to respective language(s) which are copied from the 'languages' directory.
+          '';
+          example = literalExpression ''
+            [(
+              # Let's package the German language.
+              # For other languages try to replace language and country code in the download URL with your desired one.
+              # Reference https://translate.wordpress.org for available translations and
+              # codes.
+              language-de = pkgs.stdenv.mkDerivation {
+                name = "language-de";
+                src = pkgs.fetchurl {
+                  url = "https://de.wordpress.org/wordpress-''${pkgs.wordpress.version}-de_DE.tar.gz";
+                  # Name is required to invalidate the hash when wordpress is updated
+                  name = "wordpress-''${pkgs.wordpress.version}-language-de"
+                  sha256 = "sha256-dlas0rXTSV4JAl8f/UyMbig57yURRYRhTMtJwF9g8h0=";
+                };
+                installPhase = "mkdir -p $out; cp -r ./wp-content/languages/* $out/";
+              };
+            )];
+          '';
+        };
+
         database = {
           host = mkOption {
             type = types.str;
             default = "localhost";
-            description = "Database host address.";
+            description = lib.mdDoc "Database host address.";
           };
 
           port = mkOption {
             type = types.port;
             default = 3306;
-            description = "Database host port.";
+            description = lib.mdDoc "Database host port.";
           };
 
           name = mkOption {
             type = types.str;
             default = "wordpress";
-            description = "Database name.";
+            description = lib.mdDoc "Database name.";
           };
 
           user = mkOption {
             type = types.str;
             default = "wordpress";
-            description = "Database user.";
+            description = lib.mdDoc "Database user.";
           };
 
           passwordFile = mkOption {
             type = types.nullOr types.path;
             default = null;
             example = "/run/keys/wordpress-dbpassword";
-            description = ''
+            description = lib.mdDoc ''
               A file containing the password corresponding to
-              <option>database.user</option>.
+              {option}`database.user`.
             '';
           };
 
           tablePrefix = mkOption {
             type = types.str;
             default = "wp_";
-            description = ''
+            description = lib.mdDoc ''
               The $table_prefix is the value placed in the front of your database tables.
               Change the value if you want to use something other than wp_ for your database
               prefix. Typically this is changed if you are installing multiple WordPress blogs
               in the same database.
 
-              See <link xlink:href='https://codex.wordpress.org/Editing_wp-config.php#table_prefix'/>.
+              See <https://codex.wordpress.org/Editing_wp-config.php#table_prefix>.
             '';
           };
 
@@ -200,13 +243,13 @@ let
             type = types.nullOr types.path;
             default = null;
             defaultText = literalExpression "/run/mysqld/mysqld.sock";
-            description = "Path to the unix socket file to use for authentication.";
+            description = lib.mdDoc "Path to the unix socket file to use for authentication.";
           };
 
           createLocally = mkOption {
             type = types.bool;
             default = true;
-            description = "Create the database and database user locally.";
+            description = lib.mdDoc "Create the database and database user locally.";
           };
         };
 
@@ -219,8 +262,8 @@ let
               enableACME = true;
             }
           '';
-          description = ''
-            Apache configuration can be done by adapting <option>services.httpd.virtualHosts</option>.
+          description = lib.mdDoc ''
+            Apache configuration can be done by adapting {option}`services.httpd.virtualHosts`.
           '';
         };
 
@@ -234,8 +277,8 @@ let
             "pm.max_spare_servers" = 4;
             "pm.max_requests" = 500;
           };
-          description = ''
-            Options for the WordPress PHP pool. See the documentation on <literal>php-fpm.conf</literal>
+          description = lib.mdDoc ''
+            Options for the WordPress PHP pool. See the documentation on `php-fpm.conf`
             for details on configuration directives.
           '';
         };
@@ -243,10 +286,10 @@ let
         extraConfig = mkOption {
           type = types.lines;
           default = "";
-          description = ''
+          description = lib.mdDoc ''
             Any additional text to be appended to the wp-config.php
             configuration file. This is a PHP script. For configuration
-            settings, see <link xlink:href='https://codex.wordpress.org/Editing_wp-config.php'/>.
+            settings, see <https://codex.wordpress.org/Editing_wp-config.php>.
           '';
           example = ''
             define( 'AUTOSAVE_INTERVAL', 60 ); // Seconds
@@ -265,20 +308,20 @@ in
       sites = mkOption {
         type = types.attrsOf (types.submodule siteOpts);
         default = {};
-        description = "Specification of one or more WordPress sites to serve";
+        description = lib.mdDoc "Specification of one or more WordPress sites to serve";
       };
 
       webserver = mkOption {
         type = types.enum [ "httpd" "nginx" "caddy" ];
         default = "httpd";
-        description = ''
+        description = lib.mdDoc ''
           Whether to use apache2 or nginx for virtual host management.
 
-          Further nginx configuration can be done by adapting <literal>services.nginx.virtualHosts.&lt;name&gt;</literal>.
-          See <xref linkend="opt-services.nginx.virtualHosts"/> for further information.
+          Further nginx configuration can be done by adapting `services.nginx.virtualHosts.<name>`.
+          See [](#opt-services.nginx.virtualHosts) for further information.
 
-          Further apache2 configuration can be done by adapting <literal>services.httpd.virtualHosts.&lt;name&gt;</literal>.
-          See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
+          Further apache2 configuration can be done by adapting `services.httpd.virtualHosts.<name>`.
+          See [](#opt-services.httpd.virtualHosts) for further information.
         '';
       };
 
@@ -366,6 +409,8 @@ in
       "d '${stateDir hostName}' 0750 ${user} ${webserver.group} - -"
       "d '${cfg.uploadsDir}' 0750 ${user} ${webserver.group} - -"
       "Z '${cfg.uploadsDir}' 0750 ${user} ${webserver.group} - -"
+      "d '${cfg.fontsDir}' 0750 ${user} ${webserver.group} - -"
+      "Z '${cfg.fontsDir}' 0750 ${user} ${webserver.group} - -"
     ]) eachSite);
 
     systemd.services = mkMerge [
diff --git a/nixos/modules/services/web-apps/writefreely.nix b/nixos/modules/services/web-apps/writefreely.nix
new file mode 100644
index 00000000000..dec00b46f33
--- /dev/null
+++ b/nixos/modules/services/web-apps/writefreely.nix
@@ -0,0 +1,485 @@
+{ config, lib, pkgs, ... }:
+
+let
+  inherit (builtins) toString;
+  inherit (lib) types mkIf mkOption mkDefault;
+  inherit (lib) optional optionals optionalAttrs optionalString;
+
+  inherit (pkgs) sqlite;
+
+  format = pkgs.formats.ini {
+    mkKeyValue = key: value:
+      let
+        value' = if builtins.isNull value then
+          ""
+        else if builtins.isBool value then
+          if value == true then "true" else "false"
+        else
+          toString value;
+      in "${key} = ${value'}";
+  };
+
+  cfg = config.services.writefreely;
+
+  isSqlite = cfg.database.type == "sqlite3";
+  isMysql = cfg.database.type == "mysql";
+  isMysqlLocal = isMysql && cfg.database.createLocally == true;
+
+  hostProtocol = if cfg.acme.enable then "https" else "http";
+
+  settings = cfg.settings // {
+    app = cfg.settings.app or { } // {
+      host = cfg.settings.app.host or "${hostProtocol}://${cfg.host}";
+    };
+
+    database = if cfg.database.type == "sqlite3" then {
+      type = "sqlite3";
+      filename = cfg.settings.database.filename or "writefreely.db";
+      database = cfg.database.name;
+    } else {
+      type = "mysql";
+      username = cfg.database.user;
+      password = "#dbpass#";
+      database = cfg.database.name;
+      host = cfg.database.host;
+      port = cfg.database.port;
+      tls = cfg.database.tls;
+    };
+
+    server = cfg.settings.server or { } // {
+      bind = cfg.settings.server.bind or "localhost";
+      gopher_port = cfg.settings.server.gopher_port or 0;
+      autocert = !cfg.nginx.enable && cfg.acme.enable;
+      templates_parent_dir =
+        cfg.settings.server.templates_parent_dir or cfg.package.src;
+      static_parent_dir = cfg.settings.server.static_parent_dir or assets;
+      pages_parent_dir =
+        cfg.settings.server.pages_parent_dir or cfg.package.src;
+      keys_parent_dir = cfg.settings.server.keys_parent_dir or cfg.stateDir;
+    };
+  };
+
+  configFile = format.generate "config.ini" settings;
+
+  assets = pkgs.stdenvNoCC.mkDerivation {
+    pname = "writefreely-assets";
+
+    inherit (cfg.package) version src;
+
+    nativeBuildInputs = with pkgs.nodePackages; [ less ];
+
+    buildPhase = ''
+      mkdir -p $out
+
+      cp -r static $out/
+    '';
+
+    installPhase = ''
+      less_dir=$src/less
+      css_dir=$out/static/css
+
+      lessc $less_dir/app.less $css_dir/write.css
+      lessc $less_dir/fonts.less $css_dir/fonts.css
+      lessc $less_dir/icons.less $css_dir/icons.css
+      lessc $less_dir/prose.less $css_dir/prose.css
+    '';
+  };
+
+  withConfigFile = text: ''
+    db_pass=${
+      optionalString (cfg.database.passwordFile != null)
+      "$(head -n1 ${cfg.database.passwordFile})"
+    }
+
+    cp -f ${configFile} '${cfg.stateDir}/config.ini'
+    sed -e "s,#dbpass#,$db_pass,g" -i '${cfg.stateDir}/config.ini'
+    chmod 440 '${cfg.stateDir}/config.ini'
+
+    ${text}
+  '';
+
+  withMysql = text:
+    withConfigFile ''
+      query () {
+        local result=$(${config.services.mysql.package}/bin/mysql \
+          --user=${cfg.database.user} \
+          --password=$db_pass \
+          --database=${cfg.database.name} \
+          --silent \
+          --raw \
+          --skip-column-names \
+          --execute "$1" \
+        )
+
+        echo $result
+      }
+
+      ${text}
+    '';
+
+  withSqlite = text:
+    withConfigFile ''
+      query () {
+        local result=$(${sqlite}/bin/sqlite3 \
+          '${cfg.stateDir}/${settings.database.filename}'
+          "$1" \
+        )
+
+        echo $result
+      }
+
+      ${text}
+    '';
+in {
+  options.services.writefreely = {
+    enable =
+      lib.mkEnableOption (lib.mdDoc "Writefreely, build a digital writing community");
+
+    package = lib.mkOption {
+      type = lib.types.package;
+      default = pkgs.writefreely;
+      defaultText = lib.literalExpression "pkgs.writefreely";
+      description = lib.mdDoc "Writefreely package to use.";
+    };
+
+    stateDir = mkOption {
+      type = types.path;
+      default = "/var/lib/writefreely";
+      description = lib.mdDoc "The state directory where keys and data are stored.";
+    };
+
+    user = mkOption {
+      type = types.str;
+      default = "writefreely";
+      description = lib.mdDoc "User under which Writefreely is ran.";
+    };
+
+    group = mkOption {
+      type = types.str;
+      default = "writefreely";
+      description = lib.mdDoc "Group under which Writefreely is ran.";
+    };
+
+    host = mkOption {
+      type = types.str;
+      default = "";
+      description = lib.mdDoc "The public host name to serve.";
+      example = "example.com";
+    };
+
+    settings = mkOption {
+      default = { };
+      description = lib.mdDoc ''
+        Writefreely configuration ({file}`config.ini`). Refer to
+        <https://writefreely.org/docs/latest/admin/config>
+        for details.
+      '';
+
+      type = types.submodule {
+        freeformType = format.type;
+
+        options = {
+          app = {
+            theme = mkOption {
+              type = types.str;
+              default = "write";
+              description = lib.mdDoc "The theme to apply.";
+            };
+          };
+
+          server = {
+            port = mkOption {
+              type = types.port;
+              default = if cfg.nginx.enable then 18080 else 80;
+              defaultText = "80";
+              description = lib.mdDoc "The port WriteFreely should listen on.";
+            };
+          };
+        };
+      };
+    };
+
+    database = {
+      type = mkOption {
+        type = types.enum [ "sqlite3" "mysql" ];
+        default = "sqlite3";
+        description = lib.mdDoc "The database provider to use.";
+      };
+
+      name = mkOption {
+        type = types.str;
+        default = "writefreely";
+        description = lib.mdDoc "The name of the database to store data in.";
+      };
+
+      user = mkOption {
+        type = types.nullOr types.str;
+        default = if cfg.database.type == "mysql" then "writefreely" else null;
+        defaultText = "writefreely";
+        description = lib.mdDoc "The database user to connect as.";
+      };
+
+      passwordFile = mkOption {
+        type = types.nullOr types.path;
+        default = null;
+        description = lib.mdDoc "The file to load the database password from.";
+      };
+
+      host = mkOption {
+        type = types.str;
+        default = "localhost";
+        description = lib.mdDoc "The database host to connect to.";
+      };
+
+      port = mkOption {
+        type = types.port;
+        default = 3306;
+        description = lib.mdDoc "The port used when connecting to the database host.";
+      };
+
+      tls = mkOption {
+        type = types.bool;
+        default = false;
+        description =
+          lib.mdDoc "Whether or not TLS should be used for the database connection.";
+      };
+
+      migrate = mkOption {
+        type = types.bool;
+        default = true;
+        description =
+          lib.mdDoc "Whether or not to automatically run migrations on startup.";
+      };
+
+      createLocally = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc ''
+          When {option}`services.writefreely.database.type` is set to
+          `"mysql"`, this option will enable the MySQL service locally.
+        '';
+      };
+    };
+
+    admin = {
+      name = mkOption {
+        type = types.nullOr types.str;
+        description = lib.mdDoc "The name of the first admin user.";
+        default = null;
+      };
+
+      initialPasswordFile = mkOption {
+        type = types.path;
+        description = lib.mdDoc ''
+          Path to a file containing the initial password for the admin user.
+          If not provided, the default password will be set to `nixos`.
+        '';
+        default = pkgs.writeText "default-admin-pass" "nixos";
+        defaultText = "/nix/store/xxx-default-admin-pass";
+      };
+    };
+
+    nginx = {
+      enable = mkOption {
+        type = types.bool;
+        default = false;
+        description =
+          lib.mdDoc "Whether or not to enable and configure nginx as a proxy for WriteFreely.";
+      };
+
+      forceSSL = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc "Whether or not to force the use of SSL.";
+      };
+    };
+
+    acme = {
+      enable = mkOption {
+        type = types.bool;
+        default = false;
+        description =
+          lib.mdDoc "Whether or not to automatically fetch and configure SSL certs.";
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    assertions = [
+      {
+        assertion = cfg.host != "";
+        message = "services.writefreely.host must be set";
+      }
+      {
+        assertion = isMysqlLocal -> cfg.database.passwordFile != null;
+        message =
+          "services.writefreely.database.passwordFile must be set if services.writefreely.database.createLocally is set to true";
+      }
+      {
+        assertion = isSqlite -> !cfg.database.createLocally;
+        message =
+          "services.writefreely.database.createLocally has no use when services.writefreely.database.type is set to sqlite3";
+      }
+    ];
+
+    users = {
+      users = optionalAttrs (cfg.user == "writefreely") {
+        writefreely = {
+          group = cfg.group;
+          home = cfg.stateDir;
+          isSystemUser = true;
+        };
+      };
+
+      groups =
+        optionalAttrs (cfg.group == "writefreely") { writefreely = { }; };
+    };
+
+    systemd.tmpfiles.rules =
+      [ "d '${cfg.stateDir}' 0750 ${cfg.user} ${cfg.group} - -" ];
+
+    systemd.services.writefreely = {
+      after = [ "network.target" ]
+        ++ optional isSqlite "writefreely-sqlite-init.service"
+        ++ optional isMysql "writefreely-mysql-init.service"
+        ++ optional isMysqlLocal "mysql.service";
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = {
+        Type = "simple";
+        User = cfg.user;
+        Group = cfg.group;
+        WorkingDirectory = cfg.stateDir;
+        Restart = "always";
+        RestartSec = 20;
+        ExecStart =
+          "${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' serve";
+        AmbientCapabilities =
+          optionalString (settings.server.port < 1024) "cap_net_bind_service";
+      };
+
+      preStart = ''
+        if ! test -d "${cfg.stateDir}/keys"; then
+          mkdir -p ${cfg.stateDir}/keys
+
+          # Key files end up with the wrong permissions by default.
+          # We need to correct them so that Writefreely can read them.
+          chmod -R 750 "${cfg.stateDir}/keys"
+
+          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' keys generate
+        fi
+      '';
+    };
+
+    systemd.services.writefreely-sqlite-init = mkIf isSqlite {
+      wantedBy = [ "multi-user.target" ];
+
+      serviceConfig = {
+        Type = "oneshot";
+        User = cfg.user;
+        Group = cfg.group;
+        WorkingDirectory = cfg.stateDir;
+        ReadOnlyPaths = optional (cfg.admin.initialPasswordFile != null)
+          cfg.admin.initialPasswordFile;
+      };
+
+      script = let
+        migrateDatabase = optionalString cfg.database.migrate ''
+          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' db migrate
+        '';
+
+        createAdmin = optionalString (cfg.admin.name != null) ''
+          if [[ $(query "SELECT COUNT(*) FROM users") == 0 ]]; then
+            admin_pass=$(head -n1 ${cfg.admin.initialPasswordFile})
+
+            ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' --create-admin ${cfg.admin.name}:$admin_pass
+          fi
+        '';
+      in withSqlite ''
+        if ! test -f '${settings.database.filename}'; then
+          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' db init
+        fi
+
+        ${migrateDatabase}
+
+        ${createAdmin}
+      '';
+    };
+
+    systemd.services.writefreely-mysql-init = mkIf isMysql {
+      wantedBy = [ "multi-user.target" ];
+      after = optional isMysqlLocal "mysql.service";
+
+      serviceConfig = {
+        Type = "oneshot";
+        User = cfg.user;
+        Group = cfg.group;
+        WorkingDirectory = cfg.stateDir;
+        ReadOnlyPaths = optional isMysqlLocal cfg.database.passwordFile
+          ++ optional (cfg.admin.initialPasswordFile != null)
+          cfg.admin.initialPasswordFile;
+      };
+
+      script = let
+        updateUser = optionalString isMysqlLocal ''
+          # WriteFreely currently *requires* a password for authentication, so we
+          # need to update the user in MySQL accordingly. By default MySQL users
+          # authenticate with auth_socket or unix_socket.
+          # See: https://github.com/writefreely/writefreely/issues/568
+          ${config.services.mysql.package}/bin/mysql --skip-column-names --execute "ALTER USER '${cfg.database.user}'@'localhost' IDENTIFIED VIA unix_socket OR mysql_native_password USING PASSWORD('$db_pass'); FLUSH PRIVILEGES;"
+        '';
+
+        migrateDatabase = optionalString cfg.database.migrate ''
+          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' db migrate
+        '';
+
+        createAdmin = optionalString (cfg.admin.name != null) ''
+          if [[ $(query 'SELECT COUNT(*) FROM users') == 0 ]]; then
+            admin_pass=$(head -n1 ${cfg.admin.initialPasswordFile})
+            ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' --create-admin ${cfg.admin.name}:$admin_pass
+          fi
+        '';
+      in withMysql ''
+        ${updateUser}
+
+        if [[ $(query "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '${cfg.database.name}'") == 0 ]]; then
+          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' db init
+        fi
+
+        ${migrateDatabase}
+
+        ${createAdmin}
+      '';
+    };
+
+    services.mysql = mkIf isMysqlLocal {
+      enable = true;
+      package = mkDefault pkgs.mariadb;
+      ensureDatabases = [ cfg.database.name ];
+      ensureUsers = [{
+        name = cfg.database.user;
+        ensurePermissions = {
+          "${cfg.database.name}.*" = "ALL PRIVILEGES";
+          # WriteFreely requires the use of passwords, so we need permissions
+          # to `ALTER` the user to add password support and also to reload
+          # permissions so they can be used.
+          "*.*" = "CREATE USER, RELOAD";
+        };
+      }];
+    };
+
+    services.nginx = lib.mkIf cfg.nginx.enable {
+      enable = true;
+      recommendedProxySettings = true;
+
+      virtualHosts."${cfg.host}" = {
+        enableACME = cfg.acme.enable;
+        forceSSL = cfg.nginx.forceSSL;
+
+        locations."/" = {
+          proxyPass = "http://127.0.0.1:${toString settings.server.port}";
+        };
+      };
+    };
+  };
+}
diff --git a/nixos/modules/services/web-apps/youtrack.nix b/nixos/modules/services/web-apps/youtrack.nix
index b83265ffeab..09a2b9e965c 100644
--- a/nixos/modules/services/web-apps/youtrack.nix
+++ b/nixos/modules/services/web-apps/youtrack.nix
@@ -21,10 +21,10 @@ in
 {
   options.services.youtrack = {
 
-    enable = mkEnableOption "YouTrack service";
+    enable = mkEnableOption (lib.mdDoc "YouTrack service");
 
     address = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The interface youtrack will listen on.
       '';
       default = "127.0.0.1";
@@ -32,7 +32,7 @@ in
     };
 
     baseUrl = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Base URL for youtrack. Will be auto-detected and stored in database.
       '';
       type = types.nullOr types.str;
@@ -41,7 +41,7 @@ in
 
     extraParams = mkOption {
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         Extra parameters to pass to youtrack. See
         https://www.jetbrains.com/help/youtrack/standalone/YouTrack-Java-Start-Parameters.html
         for more information.
@@ -55,7 +55,7 @@ in
     };
 
     package = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Package to use.
       '';
       type = types.package;
@@ -64,15 +64,15 @@ in
     };
 
     port = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The port youtrack will listen on.
       '';
       default = 8080;
-      type = types.int;
+      type = types.port;
     };
 
     statePath = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Where to keep the youtrack database.
       '';
       type = types.path;
@@ -80,7 +80,7 @@ in
     };
 
     virtualHost = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Name of the nginx virtual host to use and setup.
         If null, do not setup anything.
       '';
@@ -89,7 +89,7 @@ in
     };
 
     jvmOpts = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Extra options to pass to the JVM.
         See https://www.jetbrains.com/help/youtrack/standalone/Configure-JVM-Options.html
         for more information.
@@ -100,7 +100,7 @@ in
     };
 
     maxMemory = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Maximum Java heap size
       '';
       type = types.str;
@@ -108,7 +108,7 @@ in
     };
 
     maxMetaspaceSize = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Maximum java Metaspace memory.
       '';
       type = types.str;
diff --git a/nixos/modules/services/web-apps/zabbix.nix b/nixos/modules/services/web-apps/zabbix.nix
index 538dac0d5be..0e43922f35d 100644
--- a/nixos/modules/services/web-apps/zabbix.nix
+++ b/nixos/modules/services/web-apps/zabbix.nix
@@ -40,25 +40,25 @@ in
 
   options.services = {
     zabbixWeb = {
-      enable = mkEnableOption "the Zabbix web interface";
+      enable = mkEnableOption (lib.mdDoc "the Zabbix web interface");
 
       package = mkOption {
         type = types.package;
         default = pkgs.zabbix.web;
         defaultText = literalExpression "zabbix.web";
-        description = "Which Zabbix package to use.";
+        description = lib.mdDoc "Which Zabbix package to use.";
       };
 
       server = {
         port = mkOption {
           type = types.int;
-          description = "The port of the Zabbix server to connect to.";
+          description = lib.mdDoc "The port of the Zabbix server to connect to.";
           default = 10051;
         };
 
         address = mkOption {
           type = types.str;
-          description = "The IP address or hostname of the Zabbix server to connect to.";
+          description = lib.mdDoc "The IP address or hostname of the Zabbix server to connect to.";
           default = "localhost";
         };
       };
@@ -68,13 +68,13 @@ in
           type = types.enum [ "mysql" "pgsql" "oracle" ];
           example = "mysql";
           default = "pgsql";
-          description = "Database engine to use.";
+          description = lib.mdDoc "Database engine to use.";
         };
 
         host = mkOption {
           type = types.str;
           default = "";
-          description = "Database host address.";
+          description = lib.mdDoc "Database host address.";
         };
 
         port = mkOption {
@@ -88,28 +88,28 @@ in
             else if config.${opt.database.type} == "pgsql" then config.${options.services.postgresql.port}
             else 1521
           '';
-          description = "Database host port.";
+          description = lib.mdDoc "Database host port.";
         };
 
         name = mkOption {
           type = types.str;
           default = "zabbix";
-          description = "Database name.";
+          description = lib.mdDoc "Database name.";
         };
 
         user = mkOption {
           type = types.str;
           default = "zabbix";
-          description = "Database user.";
+          description = lib.mdDoc "Database user.";
         };
 
         passwordFile = mkOption {
           type = types.nullOr types.path;
           default = null;
           example = "/run/keys/zabbix-dbpassword";
-          description = ''
+          description = lib.mdDoc ''
             A file containing the password corresponding to
-            <option>database.user</option>.
+            {option}`database.user`.
           '';
         };
 
@@ -117,7 +117,7 @@ in
           type = types.nullOr types.path;
           default = null;
           example = "/run/postgresql";
-          description = "Path to the unix socket file to use for authentication.";
+          description = lib.mdDoc "Path to the unix socket file to use for authentication.";
         };
       };
 
@@ -131,9 +131,9 @@ in
             enableACME = true;
           }
         '';
-        description = ''
-          Apache configuration can be done by adapting <literal>services.httpd.virtualHosts.&lt;name&gt;</literal>.
-          See <xref linkend="opt-services.httpd.virtualHosts"/> for further information.
+        description = lib.mdDoc ''
+          Apache configuration can be done by adapting `services.httpd.virtualHosts.<name>`.
+          See [](#opt-services.httpd.virtualHosts) for further information.
         '';
       };
 
@@ -147,16 +147,16 @@ in
           "pm.max_spare_servers" = 4;
           "pm.max_requests" = 500;
         };
-        description = ''
-          Options for the Zabbix PHP pool. See the documentation on <literal>php-fpm.conf</literal> for details on configuration directives.
+        description = lib.mdDoc ''
+          Options for the Zabbix PHP pool. See the documentation on `php-fpm.conf` for details on configuration directives.
         '';
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
-          Additional configuration to be copied verbatim into <filename>zabbix.conf.php</filename>.
+        description = lib.mdDoc ''
+          Additional configuration to be copied verbatim into {file}`zabbix.conf.php`.
         '';
       };
 
diff --git a/nixos/modules/services/web-servers/agate.nix b/nixos/modules/services/web-servers/agate.nix
index 3afdb561c0b..9d635c64a44 100644
--- a/nixos/modules/services/web-servers/agate.nix
+++ b/nixos/modules/services/web-servers/agate.nix
@@ -8,19 +8,19 @@ in
 {
   options = {
     services.agate = {
-      enable = mkEnableOption "Agate Server";
+      enable = mkEnableOption (lib.mdDoc "Agate Server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.agate;
         defaultText = literalExpression "pkgs.agate";
-        description = "The package to use";
+        description = lib.mdDoc "The package to use";
       };
 
       addresses = mkOption {
         type = types.listOf types.str;
         default = [ "0.0.0.0:1965" ];
-        description = ''
+        description = lib.mdDoc ''
           Addresses to listen on, IP:PORT, if you haven't disabled forwarding
           only set IPv4.
         '';
@@ -29,19 +29,19 @@ in
       contentDir = mkOption {
         default = "/var/lib/agate/content";
         type = types.path;
-        description = "Root of the content directory.";
+        description = lib.mdDoc "Root of the content directory.";
       };
 
       certificatesDir = mkOption {
         default = "/var/lib/agate/certificates";
         type = types.path;
-        description = "Root of the certificate directory.";
+        description = lib.mdDoc "Root of the certificate directory.";
       };
 
       hostnames = mkOption {
         default = [ ];
         type = types.listOf types.str;
-        description = ''
+        description = lib.mdDoc ''
           Domain name of this Gemini server, enables checking hostname and port
           in requests. (multiple occurences means basic vhosts)
         '';
@@ -50,20 +50,20 @@ in
       language = mkOption {
         default = null;
         type = types.nullOr types.str;
-        description = "RFC 4646 Language code for text/gemini documents.";
+        description = lib.mdDoc "RFC 4646 Language code for text/gemini documents.";
       };
 
       onlyTls_1_3 = mkOption {
         default = false;
         type = types.bool;
-        description = "Only use TLSv1.3 (default also allows TLSv1.2).";
+        description = lib.mdDoc "Only use TLSv1.3 (default also allows TLSv1.2).";
       };
 
       extraArgs = mkOption {
         type = types.listOf types.str;
         default = [ "" ];
         example = [ "--log-ip" ];
-        description = "Extra arguments to use running agate.";
+        description = lib.mdDoc "Extra arguments to use running agate.";
       };
     };
   };
diff --git a/nixos/modules/services/web-servers/apache-httpd/default.nix b/nixos/modules/services/web-servers/apache-httpd/default.nix
index d817ff6019a..588f5ee4d00 100644
--- a/nixos/modules/services/web-servers/apache-httpd/default.nix
+++ b/nixos/modules/services/web-servers/apache-httpd/default.nix
@@ -18,7 +18,7 @@ let
     sed -i $out/bin/apachectl -e 's|$HTTPD -t|$HTTPD -t -f /etc/httpd/httpd.conf|'
   '';
 
-  php = cfg.phpPackage.override { apacheHttpd = pkg; };
+  php = cfg.phpPackage.override { apxs2Support = true; apacheHttpd = pkg; };
 
   phpModuleName = let
     majorVersion = lib.versions.major (lib.getVersion php);
@@ -168,7 +168,7 @@ let
         <VirtualHost ${concatMapStringsSep " " (listen: "${listen.ip}:${toString listen.port}") listen}>
             ServerName ${hostOpts.hostName}
             ${concatMapStrings (alias: "ServerAlias ${alias}\n") hostOpts.serverAliases}
-            ServerAdmin ${adminAddr}
+            ${optionalString (adminAddr != null) "ServerAdmin ${adminAddr}"}
             <IfModule mod_ssl.c>
                 SSLEngine off
             </IfModule>
@@ -187,7 +187,7 @@ let
         <VirtualHost ${concatMapStringsSep " " (listen: "${listen.ip}:${toString listen.port}") listenSSL}>
             ServerName ${hostOpts.hostName}
             ${concatMapStrings (alias: "ServerAlias ${alias}\n") hostOpts.serverAliases}
-            ServerAdmin ${adminAddr}
+            ${optionalString (adminAddr != null) "ServerAdmin ${adminAddr}"}
             SSLEngine on
             SSLCertificateFile ${sslServerCert}
             SSLCertificateKeyFile ${sslServerKey}
@@ -404,13 +404,13 @@ in
 
     services.httpd = {
 
-      enable = mkEnableOption "the Apache HTTP Server";
+      enable = mkEnableOption (lib.mdDoc "the Apache HTTP Server");
 
       package = mkOption {
         type = types.package;
         default = pkgs.apacheHttpd;
         defaultText = literalExpression "pkgs.apacheHttpd";
-        description = ''
+        description = lib.mdDoc ''
           Overridable attribute of the Apache HTTP Server package to use.
         '';
       };
@@ -420,7 +420,7 @@ in
         default = confFile;
         defaultText = literalExpression "confFile";
         example = literalExpression ''pkgs.writeText "httpd.conf" "# my custom config file ..."'';
-        description = ''
+        description = lib.mdDoc ''
           Override the configuration file used by Apache. By default,
           NixOS generates one automatically.
         '';
@@ -429,10 +429,10 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Configuration lines appended to the generated Apache
           configuration file. Note that this mechanism will not work
-          when <option>configFile</option> is overridden.
+          when {option}`configFile` is overridden.
         '';
       };
 
@@ -445,60 +445,61 @@ in
             { name = "jk"; path = "''${pkgs.tomcat_connectors}/modules/mod_jk.so"; }
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Additional Apache modules to be used. These can be
           specified as a string in the case of modules distributed
           with Apache, or as an attribute set specifying the
-          <varname>name</varname> and <varname>path</varname> of the
+          {var}`name` and {var}`path` of the
           module.
         '';
       };
 
       adminAddr = mkOption {
-        type = types.str;
+        type = types.nullOr types.str;
         example = "admin@example.org";
-        description = "E-mail address of the server administrator.";
+        default = null;
+        description = lib.mdDoc "E-mail address of the server administrator.";
       };
 
       logFormat = mkOption {
         type = types.str;
         default = "common";
         example = "combined";
-        description = ''
+        description = lib.mdDoc ''
           Log format for log files. Possible values are: combined, common, referer, agent, none.
-          See <link xlink:href="https://httpd.apache.org/docs/2.4/logs.html"/> for more details.
+          See <https://httpd.apache.org/docs/2.4/logs.html> for more details.
         '';
       };
 
       logPerVirtualHost = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           If enabled, each virtual host gets its own
-          <filename>access.log</filename> and
-          <filename>error.log</filename>, namely suffixed by the
-          <option>hostName</option> of the virtual host.
+          {file}`access.log` and
+          {file}`error.log`, namely suffixed by the
+          {option}`hostName` of the virtual host.
         '';
       };
 
       user = mkOption {
         type = types.str;
         default = "wwwrun";
-        description = ''
+        description = lib.mdDoc ''
           User account under which httpd children processes run.
 
           If you require the main httpd process to run as
-          <literal>root</literal> add the following configuration:
-          <programlisting>
+          `root` add the following configuration:
+          ```
           systemd.services.httpd.serviceConfig.User = lib.mkForce "root";
-          </programlisting>
+          ```
         '';
       };
 
       group = mkOption {
         type = types.str;
         default = "wwwrun";
-        description = ''
+        description = lib.mdDoc ''
           Group under which httpd children processes run.
         '';
       };
@@ -506,7 +507,7 @@ in
       logDir = mkOption {
         type = types.path;
         default = "/var/log/httpd";
-        description = ''
+        description = lib.mdDoc ''
           Directory for Apache's log files. It is created automatically.
         '';
       };
@@ -537,7 +538,7 @@ in
             };
           }
         '';
-        description = ''
+        description = lib.mdDoc ''
           Specification of the virtual hosts served by Apache. Each
           element should be an attribute set specifying the
           configuration of the virtual host.
@@ -547,20 +548,20 @@ in
       enableMellon = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the mod_auth_mellon module.";
+        description = lib.mdDoc "Whether to enable the mod_auth_mellon module.";
       };
 
       enablePHP = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the PHP module.";
+        description = lib.mdDoc "Whether to enable the PHP module.";
       };
 
       phpPackage = mkOption {
         type = types.package;
         default = pkgs.php;
         defaultText = literalExpression "pkgs.php";
-        description = ''
+        description = lib.mdDoc ''
           Overridable attribute of the PHP package to use.
         '';
       };
@@ -568,7 +569,7 @@ in
       enablePerl = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the Perl module (mod_perl).";
+        description = lib.mdDoc "Whether to enable the Perl module (mod_perl).";
       };
 
       phpOptions = mkOption {
@@ -578,8 +579,8 @@ in
           ''
             date.timezone = "CET"
           '';
-        description = ''
-          Options appended to the PHP configuration file <filename>php.ini</filename>.
+        description = lib.mdDoc ''
+          Options appended to the PHP configuration file {file}`php.ini`.
         '';
       };
 
@@ -588,13 +589,13 @@ in
         default = "event";
         example = "worker";
         description =
-          ''
+          lib.mdDoc ''
             Multi-processing module to be used by Apache. Available
-            modules are <literal>prefork</literal> (handles each
-            request in a separate child process), <literal>worker</literal>
+            modules are `prefork` (handles each
+            request in a separate child process), `worker`
             (hybrid approach that starts a number of child processes
-            each running a number of threads) and <literal>event</literal>
-            (the default; a recent variant of <literal>worker</literal>
+            each running a number of threads) and `event`
+            (the default; a recent variant of `worker`
             that handles persistent connections more efficiently).
           '';
       };
@@ -603,14 +604,14 @@ in
         type = types.int;
         default = 150;
         example = 8;
-        description = "Maximum number of httpd processes (prefork)";
+        description = lib.mdDoc "Maximum number of httpd processes (prefork)";
       };
 
       maxRequestsPerChild = mkOption {
         type = types.int;
         default = 0;
         example = 500;
-        description = ''
+        description = lib.mdDoc ''
           Maximum number of httpd requests answered per httpd child (prefork), 0 means unlimited.
         '';
       };
@@ -618,14 +619,14 @@ in
       sslCiphers = mkOption {
         type = types.str;
         default = "HIGH:!aNULL:!MD5:!EXP";
-        description = "Cipher Suite available for negotiation in SSL proxy handshake.";
+        description = lib.mdDoc "Cipher Suite available for negotiation in SSL proxy handshake.";
       };
 
       sslProtocols = mkOption {
         type = types.str;
         default = "All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1";
         example = "All -SSLv2 -SSLv3";
-        description = "Allowed SSL/TLS protocol versions.";
+        description = lib.mdDoc "Allowed SSL/TLS protocol versions.";
       };
     };
 
@@ -659,6 +660,13 @@ in
           `services.httpd.virtualHosts.<name>.useACMEHost` are mutually exclusive.
         '';
       }
+      {
+        assertion = cfg.enablePHP -> php.ztsSupport;
+        message = ''
+          The php package provided by `services.httpd.phpPackage` is not built with zts support. Please
+          ensure the php has zts support by settings `services.httpd.phpPackage = php.override { ztsSupport = true; }`
+        '';
+      }
     ] ++ map (name: mkCertOwnershipAssertion {
       inherit (cfg) group user;
       cert = config.security.acme.certs.${name};
@@ -710,20 +718,15 @@ in
 
     services.logrotate = optionalAttrs (cfg.logFormat != "none") {
       enable = mkDefault true;
-      paths.httpd = {
-        path = "${cfg.logDir}/*.log";
-        user = cfg.user;
-        group = cfg.group;
+      settings.httpd = {
+        files = "${cfg.logDir}/*.log";
+        su = "${cfg.user} ${cfg.group}";
         frequency = "daily";
-        keep = 28;
-        extraConfig = ''
-          sharedscripts
-          compress
-          delaycompress
-          postrotate
-            systemctl reload httpd.service > /dev/null 2>/dev/null || true
-          endscript
-        '';
+        rotate = 28;
+        sharedscripts = true;
+        compress = true;
+        delaycompress = true;
+        postrotate = "systemctl reload httpd.service > /dev/null 2>/dev/null || true";
       };
     };
 
diff --git a/nixos/modules/services/web-servers/apache-httpd/location-options.nix b/nixos/modules/services/web-servers/apache-httpd/location-options.nix
index 8ea88f94f97..f2d4f835704 100644
--- a/nixos/modules/services/web-servers/apache-httpd/location-options.nix
+++ b/nixos/modules/services/web-servers/apache-httpd/location-options.nix
@@ -9,8 +9,8 @@ in
       type = with types; nullOr str;
       default = null;
       example = "http://www.example.org/";
-      description = ''
-        Sets up a simple reverse proxy as described by <link xlink:href="https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html#simple" />.
+      description = lib.mdDoc ''
+        Sets up a simple reverse proxy as described by <https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html#simple>.
       '';
     };
 
@@ -18,8 +18,8 @@ in
       type = with types; nullOr str;
       default = null;
       example = "index.php index.html";
-      description = ''
-        Adds DirectoryIndex directive. See <link xlink:href="https://httpd.apache.org/docs/2.4/mod/mod_dir.html#directoryindex" />.
+      description = lib.mdDoc ''
+        Adds DirectoryIndex directive. See <https://httpd.apache.org/docs/2.4/mod/mod_dir.html#directoryindex>.
       '';
     };
 
@@ -27,15 +27,15 @@ in
       type = with types; nullOr path;
       default = null;
       example = "/your/alias/directory";
-      description = ''
-        Alias directory for requests. See <link xlink:href="https://httpd.apache.org/docs/2.4/mod/mod_alias.html#alias" />.
+      description = lib.mdDoc ''
+        Alias directory for requests. See <https://httpd.apache.org/docs/2.4/mod/mod_alias.html#alias>.
       '';
     };
 
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         These lines go to the end of the location verbatim.
       '';
     };
@@ -43,7 +43,7 @@ in
     priority = mkOption {
       type = types.int;
       default = 1000;
-      description = ''
+      description = lib.mdDoc ''
         Order of this location block in relation to the others in the vhost.
         The semantics are the same as with `lib.mkOrder`. Smaller values have
         a greater priority.
diff --git a/nixos/modules/services/web-servers/apache-httpd/vhost-options.nix b/nixos/modules/services/web-servers/apache-httpd/vhost-options.nix
index c52ab2c596e..0d60d533c99 100644
--- a/nixos/modules/services/web-servers/apache-httpd/vhost-options.nix
+++ b/nixos/modules/services/web-servers/apache-httpd/vhost-options.nix
@@ -8,14 +8,14 @@ in
     hostName = mkOption {
       type = types.str;
       default = name;
-      description = "Canonical hostname for the server.";
+      description = lib.mdDoc "Canonical hostname for the server.";
     };
 
     serverAliases = mkOption {
       type = types.listOf types.str;
       default = [];
       example = ["www.example.org" "www.example.org:8080" "example.org"];
-      description = ''
+      description = lib.mdDoc ''
         Additional names of virtual hosts served by this virtual host configuration.
       '';
     };
@@ -25,17 +25,17 @@ in
         options = {
           port = mkOption {
             type = types.port;
-            description = "Port to listen on";
+            description = lib.mdDoc "Port to listen on";
           };
           ip = mkOption {
             type = types.str;
             default = "*";
-            description = "IP to listen on. 0.0.0.0 for IPv4 only, * for all.";
+            description = lib.mdDoc "IP to listen on. 0.0.0.0 for IPv4 only, * for all.";
           };
           ssl = mkOption {
             type = types.bool;
             default = false;
-            description = "Whether to enable SSL (https) support.";
+            description = lib.mdDoc "Whether to enable SSL (https) support.";
           };
         };
       }));
@@ -45,25 +45,23 @@ in
         { ip = "192.154.1.1"; port = 80; }
         { ip = "*"; port = 8080; }
       ];
-      description = ''
+      description = lib.mdDoc ''
         Listen addresses and ports for this virtual host.
-        <note>
-        <para>
-          This option overrides <literal>addSSL</literal>, <literal>forceSSL</literal> and <literal>onlySSL</literal>.
-        </para>
-        <para>
-          If you only want to set the addresses manually and not the ports, take a look at <literal>listenAddresses</literal>.
-        </para>
-        </note>
+
+        ::: {.note}
+        This option overrides `addSSL`, `forceSSL` and `onlySSL`.
+
+        If you only want to set the addresses manually and not the ports, take a look at `listenAddresses`.
+        :::
       '';
     };
 
     listenAddresses = mkOption {
       type = with types; nonEmptyListOf str;
 
-      description = ''
+      description = lib.mdDoc ''
         Listen addresses for this virtual host.
-        Compared to <literal>listen</literal> this only sets the addreses
+        Compared to `listen` this only sets the addreses
         and the ports are chosen automatically.
       '';
       default = [ "*" ];
@@ -79,9 +77,9 @@ in
     addSSL = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable HTTPS in addition to plain HTTP. This will set defaults for
-        <literal>listen</literal> to listen on all interfaces on the respective default
+        `listen` to listen on all interfaces on the respective default
         ports (80, 443).
       '';
     };
@@ -89,19 +87,19 @@ in
     onlySSL = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable HTTPS and reject plain HTTP connections. This will set
-        defaults for <literal>listen</literal> to listen on all interfaces on port 443.
+        defaults for `listen` to listen on all interfaces on port 443.
       '';
     };
 
     forceSSL = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to add a separate nginx server block that permanently redirects (301)
         all plain HTTP traffic to HTTPS. This will set defaults for
-        <literal>listen</literal> to listen on all interfaces on the respective default
+        `listen` to listen on all interfaces on the respective default
         ports (80, 443), where the non-SSL listens are used for the redirect vhosts.
       '';
     };
@@ -109,28 +107,28 @@ in
     enableACME = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to ask Let's Encrypt to sign a certificate for this vhost.
-        Alternately, you can use an existing certificate through <option>useACMEHost</option>.
+        Alternately, you can use an existing certificate through {option}`useACMEHost`.
       '';
     };
 
     useACMEHost = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         A host of an existing Let's Encrypt certificate to use.
         This is useful if you have many subdomains and want to avoid hitting the
-        <link xlink:href="https://letsencrypt.org/docs/rate-limits/">rate limit</link>.
-        Alternately, you can generate a certificate through <option>enableACME</option>.
-        <emphasis>Note that this option does not create any certificates, nor it does add subdomains to existing ones – you will need to create them manually using  <xref linkend="opt-security.acme.certs"/>.</emphasis>
+        [rate limit](https://letsencrypt.org/docs/rate-limits).
+        Alternately, you can generate a certificate through {option}`enableACME`.
+        *Note that this option does not create any certificates, nor it does add subdomains to existing ones – you will need to create them manually using [](#opt-security.acme.certs).*
       '';
     };
 
     acmeRoot = mkOption {
       type = types.nullOr types.str;
       default = "/var/lib/acme/acme-challenge";
-      description = ''
+      description = lib.mdDoc ''
         Directory for the acme challenge which is PUBLIC, don't put certs or keys in here.
         Set to null to inherit from config.security.acme.
       '';
@@ -139,28 +137,28 @@ in
     sslServerCert = mkOption {
       type = types.path;
       example = "/var/host.cert";
-      description = "Path to server SSL certificate.";
+      description = lib.mdDoc "Path to server SSL certificate.";
     };
 
     sslServerKey = mkOption {
       type = types.path;
       example = "/var/host.key";
-      description = "Path to server SSL certificate key.";
+      description = lib.mdDoc "Path to server SSL certificate key.";
     };
 
     sslServerChain = mkOption {
       type = types.nullOr types.path;
       default = null;
       example = "/var/ca.pem";
-      description = "Path to server SSL chain file.";
+      description = lib.mdDoc "Path to server SSL chain file.";
     };
 
     http2 = mkOption {
       type = types.bool;
       default = true;
-      description = ''
-        Whether to enable HTTP 2. HTTP/2 is supported in all multi-processing modules that come with httpd. <emphasis>However, if you use the prefork mpm, there will
-        be severe restrictions.</emphasis> Refer to <link xlink:href="https://httpd.apache.org/docs/2.4/howto/http2.html#mpm-config"/> for details.
+      description = lib.mdDoc ''
+        Whether to enable HTTP 2. HTTP/2 is supported in all multi-processing modules that come with httpd. *However, if you use the prefork mpm, there will
+        be severe restrictions.* Refer to <https://httpd.apache.org/docs/2.4/howto/http2.html#mpm-config> for details.
       '';
     };
 
@@ -168,14 +166,14 @@ in
       type = types.nullOr types.str;
       default = null;
       example = "admin@example.org";
-      description = "E-mail address of the server administrator.";
+      description = lib.mdDoc "E-mail address of the server administrator.";
     };
 
     documentRoot = mkOption {
       type = types.nullOr types.path;
       default = null;
       example = "/data/webserver/docs";
-      description = ''
+      description = lib.mdDoc ''
         The path of Apache's document root directory.  If left undefined,
         an empty directory in the Nix store will be used as root.
       '';
@@ -189,7 +187,7 @@ in
           dir = "/home/eelco/Dev/nix-homepage";
         }
       ];
-      description = ''
+      description = lib.mdDoc ''
         This option provides a simple way to serve static directories.
       '';
     };
@@ -202,14 +200,14 @@ in
           file = "/home/eelco/some-file.png";
         }
       ];
-      description = ''
+      description = lib.mdDoc ''
         This option provides a simple way to serve individual, static files.
 
-        <note><para>
-          This option has been deprecated and will be removed in a future
-          version of NixOS. You can achieve the same result by making use of
-          the <literal>locations.&lt;name&gt;.alias</literal> option.
-        </para></note>
+        ::: {.note}
+        This option has been deprecated and will be removed in a future
+        version of NixOS. You can achieve the same result by making use of
+        the `locations.<name>.alias` option.
+        :::
       '';
     };
 
@@ -222,7 +220,7 @@ in
           AllowOverride All
         </Directory>
       '';
-      description = ''
+      description = lib.mdDoc ''
         These lines go to httpd.conf verbatim. They will go after
         directories and directory aliases defined by default.
       '';
@@ -231,9 +229,9 @@ in
     enableUserDir = mkOption {
       type = types.bool;
       default = false;
-      description = ''
-        Whether to enable serving <filename>~/public_html</filename> as
-        <literal>/~<replaceable>username</replaceable></literal>.
+      description = lib.mdDoc ''
+        Whether to enable serving {file}`~/public_html` as
+        `/~«username»`.
       '';
     };
 
@@ -241,7 +239,7 @@ in
       type = types.nullOr types.str;
       default = null;
       example = "http://newserver.example.org/";
-      description = ''
+      description = lib.mdDoc ''
         If set, all requests for this host are redirected permanently to
         the given URL.
       '';
@@ -251,7 +249,7 @@ in
       type = types.str;
       default = "common";
       example = "combined";
-      description = ''
+      description = lib.mdDoc ''
         Log format for Apache's log files. Possible values are: combined, common, referer, agent.
       '';
     };
@@ -260,9 +258,8 @@ in
       type = types.lines;
       default = "";
       example = "Disallow: /foo/";
-      description = ''
-        Specification of pages to be ignored by web crawlers. See <link
-        xlink:href='http://www.robotstxt.org/'/> for details.
+      description = lib.mdDoc ''
+        Specification of pages to be ignored by web crawlers. See <http://www.robotstxt.org/> for details.
       '';
     };
 
@@ -279,9 +276,8 @@ in
           };
         };
       '';
-      description = ''
-        Declarative location config. See <link
-        xlink:href="https://httpd.apache.org/docs/2.4/mod/core.html#location"/> for details.
+      description = lib.mdDoc ''
+        Declarative location config. See <https://httpd.apache.org/docs/2.4/mod/core.html#location> for details.
       '';
     };
 
diff --git a/nixos/modules/services/web-servers/caddy/default.nix b/nixos/modules/services/web-servers/caddy/default.nix
index 2b8c6f2e308..50213ec252f 100644
--- a/nixos/modules/services/web-servers/caddy/default.nix
+++ b/nixos/modules/services/web-servers/caddy/default.nix
@@ -26,7 +26,7 @@ let
 
   configFile =
     let
-      Caddyfile = pkgs.writeText "Caddyfile" ''
+      Caddyfile = pkgs.writeTextDir "Caddyfile" ''
         {
           ${cfg.globalConfig}
         }
@@ -34,10 +34,11 @@ let
       '';
 
       Caddyfile-formatted = pkgs.runCommand "Caddyfile-formatted" { nativeBuildInputs = [ cfg.package ]; } ''
-        ${cfg.package}/bin/caddy fmt ${Caddyfile} > $out
+        mkdir -p $out
+        ${cfg.package}/bin/caddy fmt ${Caddyfile}/Caddyfile > $out/Caddyfile
       '';
     in
-      if pkgs.stdenv.buildPlatform == pkgs.stdenv.hostPlatform then Caddyfile-formatted else Caddyfile;
+      "${if pkgs.stdenv.buildPlatform == pkgs.stdenv.hostPlatform then Caddyfile-formatted else Caddyfile}/Caddyfile";
 
   acmeHosts = unique (catAttrs "useACMEHost" acmeVHosts);
 
@@ -52,33 +53,33 @@ in
 
   # interface
   options.services.caddy = {
-    enable = mkEnableOption "Caddy web server";
+    enable = mkEnableOption (lib.mdDoc "Caddy web server");
 
     user = mkOption {
       default = "caddy";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         User account under which caddy runs.
 
-        <note><para>
-          If left as the default value this user will automatically be created
-          on system activation, otherwise you are responsible for
-          ensuring the user exists before the Caddy service starts.
-        </para></note>
+        ::: {.note}
+        If left as the default value this user will automatically be created
+        on system activation, otherwise you are responsible for
+        ensuring the user exists before the Caddy service starts.
+        :::
       '';
     };
 
     group = mkOption {
       default = "caddy";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Group account under which caddy runs.
 
-        <note><para>
-          If left as the default value this user will automatically be created
-          on system activation, otherwise you are responsible for
-          ensuring the user exists before the Caddy service starts.
-        </para></note>
+        ::: {.note}
+        If left as the default value this user will automatically be created
+        on system activation, otherwise you are responsible for
+        ensuring the user exists before the Caddy service starts.
+        :::
       '';
     };
 
@@ -86,7 +87,7 @@ in
       default = pkgs.caddy;
       defaultText = literalExpression "pkgs.caddy";
       type = types.package;
-      description = ''
+      description = lib.mdDoc ''
         Caddy package to use.
       '';
     };
@@ -94,34 +95,31 @@ in
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/caddy";
-      description = ''
+      description = lib.mdDoc ''
         The data directory for caddy.
 
-        <note>
-          <para>
-            If left as the default value this directory will automatically be created
-            before the Caddy server starts, otherwise you are responsible for ensuring
-            the directory exists with appropriate ownership and permissions.
-          </para>
-          <para>
-            Caddy v2 replaced <literal>CADDYPATH</literal> with XDG directories.
-            See <link xlink:href="https://caddyserver.com/docs/conventions#file-locations"/>.
-          </para>
-        </note>
+        ::: {.note}
+        If left as the default value this directory will automatically be created
+        before the Caddy server starts, otherwise you are responsible for ensuring
+        the directory exists with appropriate ownership and permissions.
+
+        Caddy v2 replaced `CADDYPATH` with XDG directories.
+        See <https://caddyserver.com/docs/conventions#file-locations>.
+        :::
       '';
     };
 
     logDir = mkOption {
       type = types.path;
       default = "/var/log/caddy";
-      description = ''
+      description = lib.mdDoc ''
         Directory for storing Caddy access logs.
 
-        <note><para>
-          If left as the default value this directory will automatically be created
-          before the Caddy server starts, otherwise the sysadmin is responsible for
-          ensuring the directory exists with appropriate ownership and permissions.
-        </para></note>
+        ::: {.note}
+        If left as the default value this directory will automatically be created
+        before the Caddy server starts, otherwise the sysadmin is responsible for
+        ensuring the directory exists with appropriate ownership and permissions.
+        :::
       '';
     };
 
@@ -133,9 +131,9 @@ in
       example = literalExpression ''
         mkForce "level INFO";
       '';
-      description = ''
+      description = lib.mdDoc ''
         Configuration for the default logger. See
-        <link xlink:href="https://caddyserver.com/docs/caddyfile/options#log"/>
+        <https://caddyserver.com/docs/caddyfile/options#log>
         for details.
       '';
     };
@@ -145,7 +143,7 @@ in
       default = configFile;
       defaultText = "A Caddyfile automatically generated by values from services.caddy.*";
       example = literalExpression ''
-        pkgs.writeText "Caddyfile" '''
+        pkgs.writeTextDir "Caddyfile" '''
           example.com
 
           root * /var/www/wordpress
@@ -153,33 +151,40 @@ in
           file_server
         ''';
       '';
-      description = ''
+      description = lib.mdDoc ''
         Override the configuration file used by Caddy. By default,
         NixOS generates one automatically.
       '';
     };
 
     adapter = mkOption {
-      default = "caddyfile";
-      example = "nginx";
-      type = types.str;
-      description = ''
+      default = null;
+      example = literalExpression "nginx";
+      type = with types; nullOr str;
+      description = lib.mdDoc ''
         Name of the config adapter to use.
-        See <link xlink:href="https://caddyserver.com/docs/config-adapters"/>
+        See <https://caddyserver.com/docs/config-adapters>
         for the full list.
 
-        <note><para>
-          Any value other than <literal>caddyfile</literal> is only valid when
-          providing your own <option>configFile</option>.
-        </para></note>
+        If `null` is specified, the `--adapter` argument is omitted when
+        starting or restarting Caddy. Notably, this allows specification of a
+        configuration file in Caddy's native JSON format, as long as the
+        filename does not start with `Caddyfile` (in which case the `caddyfile`
+        adapter is implicitly enabled). See
+        <https://caddyserver.com/docs/command-line#caddy-run> for details.
+
+        ::: {.note}
+        Any value other than `null` or `caddyfile` is only valid when providing
+        your own `configFile`.
+        :::
       '';
     };
 
     resume = mkOption {
       default = false;
       type = types.bool;
-      description = ''
-        Use saved config, if any (and prefer over any specified configuration passed with <literal>--config</literal>).
+      description = lib.mdDoc ''
+        Use saved config, if any (and prefer over any specified configuration passed with `--config`).
       '';
     };
 
@@ -194,11 +199,11 @@ in
           }
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Additional lines of configuration appended to the global config section
-        of the <literal>Caddyfile</literal>.
+        of the `Caddyfile`.
 
-        Refer to <link xlink:href="https://caddyserver.com/docs/caddyfile/options#global-options"/>
+        Refer to <https://caddyserver.com/docs/caddyfile/options#global-options>
         for details on supported values.
       '';
     };
@@ -213,9 +218,9 @@ in
           root /srv/http
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Additional lines of configuration appended to the automatically
-        generated <literal>Caddyfile</literal>.
+        generated `Caddyfile`.
       '';
     };
 
@@ -233,7 +238,7 @@ in
           };
         };
       '';
-      description = ''
+      description = lib.mdDoc ''
         Declarative specification of virtual hosts served by Caddy.
       '';
     };
@@ -242,11 +247,11 @@ in
       default = "https://acme-v02.api.letsencrypt.org/directory";
       example = "https://acme-staging-v02.api.letsencrypt.org/directory";
       type = with types; nullOr str;
-      description = ''
+      description = lib.mdDoc ''
         The URL to the ACME CA's directory. It is strongly recommended to set
         this to Let's Encrypt's staging endpoint for testing or development.
 
-        Set it to <literal>null</literal> if you want to write a more
+        Set it to `null` if you want to write a more
         fine-grained configuration manually.
       '';
     };
@@ -254,7 +259,7 @@ in
     email = mkOption {
       default = null;
       type = with types; nullOr str;
-      description = ''
+      description = lib.mdDoc ''
         Your email address. Mainly used when creating an ACME account with your
         CA, and is highly recommended in case there are problems with your
         certificates.
@@ -267,8 +272,8 @@ in
   config = mkIf cfg.enable {
 
     assertions = [
-      { assertion = cfg.adapter != "caddyfile" -> cfg.configFile != configFile;
-        message = "Any value other than 'caddyfile' is only valid when providing your own `services.caddy.configFile`";
+      { assertion = cfg.configFile == configFile -> cfg.adapter == "caddyfile" || cfg.adapter == null;
+        message = "To specify an adapter other than 'caddyfile' please provide your own configuration via `services.caddy.configFile`";
       }
     ] ++ map (name: mkCertOwnershipAssertion {
       inherit (cfg) group user;
@@ -285,6 +290,9 @@ in
       }
     '';
 
+    # https://github.com/lucas-clemente/quic-go/wiki/UDP-Receive-Buffer-Size
+    boot.kernel.sysctl."net.core.rmem_max" = mkDefault 2500000;
+
     systemd.packages = [ cfg.package ];
     systemd.services.caddy = {
       wants = map (hostOpts: "acme-finished-${hostOpts.useACMEHost}.target") acmeVHosts;
@@ -298,17 +306,15 @@ in
       serviceConfig = {
         # https://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart=
         # If the empty string is assigned to this option, the list of commands to start is reset, prior assignments of this option will have no effect.
-        ExecStart = [ "" "${cfg.package}/bin/caddy run --config ${cfg.configFile} --adapter ${cfg.adapter} ${optionalString cfg.resume "--resume"}" ];
-        ExecReload = [ "" "${cfg.package}/bin/caddy reload --config ${cfg.configFile} --adapter ${cfg.adapter}" ];
-
-        ExecStartPre = "${cfg.package}/bin/caddy validate --config ${cfg.configFile} --adapter ${cfg.adapter}";
+        ExecStart = [ "" ''${cfg.package}/bin/caddy run --config ${cfg.configFile} ${optionalString (cfg.adapter != null) "--adapter ${cfg.adapter}"} ${optionalString cfg.resume "--resume"}'' ];
+        ExecReload = [ "" ''${cfg.package}/bin/caddy reload --config ${cfg.configFile} ${optionalString (cfg.adapter != null) "--adapter ${cfg.adapter}"} --force'' ];
+        ExecStartPre = ''${cfg.package}/bin/caddy validate --config ${cfg.configFile} ${optionalString (cfg.adapter != null) "--adapter ${cfg.adapter}"}'';
         User = cfg.user;
         Group = cfg.group;
         ReadWriteDirectories = cfg.dataDir;
         StateDirectory = mkIf (cfg.dataDir == "/var/lib/caddy") [ "caddy" ];
         LogsDirectory = mkIf (cfg.logDir == "/var/log/caddy") [ "caddy" ];
         Restart = "on-abnormal";
-        SupplementaryGroups = mkIf (length acmeVHosts != 0) [ "acme" ];
 
         # TODO: attempt to upstream these options
         NoNewPrivileges = true;
@@ -331,9 +337,12 @@ in
 
     security.acme.certs =
       let
-        reloads = map (useACMEHost: nameValuePair useACMEHost { reloadServices = [ "caddy.service" ]; }) acmeHosts;
+        certCfg = map (useACMEHost: nameValuePair useACMEHost {
+          group = mkDefault cfg.group;
+          reloadServices = [ "caddy.service" ];
+        }) acmeHosts;
       in
-        listToAttrs reloads;
+        listToAttrs certCfg;
 
   };
 }
diff --git a/nixos/modules/services/web-servers/caddy/vhost-options.nix b/nixos/modules/services/web-servers/caddy/vhost-options.nix
index f240ec605c2..229b53efb49 100644
--- a/nixos/modules/services/web-servers/caddy/vhost-options.nix
+++ b/nixos/modules/services/web-servers/caddy/vhost-options.nix
@@ -9,21 +9,21 @@ in
     hostName = mkOption {
       type = types.str;
       default = name;
-      description = "Canonical hostname for the server.";
+      description = lib.mdDoc "Canonical hostname for the server.";
     };
 
     serverAliases = mkOption {
       type = with types; listOf str;
       default = [ ];
       example = [ "www.example.org" "example.org" ];
-      description = ''
+      description = lib.mdDoc ''
         Additional names of virtual hosts served by this virtual host configuration.
       '';
     };
 
     listenAddresses = mkOption {
       type = with types; listOf str;
-      description = ''
+      description = lib.mdDoc ''
         A list of host interfaces to bind to for this virtual host.
       '';
       default = [ ];
@@ -33,16 +33,14 @@ in
     useACMEHost = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         A host of an existing Let's Encrypt certificate to use.
         This is mostly useful if you use DNS challenges but Caddy does not
         currently support your provider.
 
-        <emphasis>Note that this option does not create any certificates, nor
+        *Note that this option does not create any certificates, nor
         does it add subdomains to existing ones – you will need to create them
-        manually using <xref linkend="opt-security.acme.certs"/>. Additionally,
-        you should probably add the <literal>caddy</literal> user to the
-        <literal>acme</literal> group to grant access to the certificates.</emphasis>
+        manually using [](#opt-security.acme.certs).*
       '';
     };
 
@@ -59,9 +57,9 @@ in
           output discard
         ''';
       '';
-      description = ''
+      description = lib.mdDoc ''
         Configuration for HTTP request logging (also known as access logs). See
-        <link xlink:href="https://caddyserver.com/docs/caddyfile/directives/log#log"/>
+        <https://caddyserver.com/docs/caddyfile/directives/log#log>
         for details.
       '';
     };
@@ -69,9 +67,9 @@ in
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         Additional lines of configuration appended to this virtual host in the
-        automatically generated <literal>Caddyfile</literal>.
+        automatically generated `Caddyfile`.
       '';
     };
 
diff --git a/nixos/modules/services/web-servers/darkhttpd.nix b/nixos/modules/services/web-servers/darkhttpd.nix
index f6b693139a1..1e3a7166bc4 100644
--- a/nixos/modules/services/web-servers/darkhttpd.nix
+++ b/nixos/modules/services/web-servers/darkhttpd.nix
@@ -15,12 +15,12 @@ let
 
 in {
   options.services.darkhttpd = with types; {
-    enable = mkEnableOption "DarkHTTPd web server";
+    enable = mkEnableOption (lib.mdDoc "DarkHTTPd web server");
 
     port = mkOption {
       default = 80;
       type = types.port;
-      description = ''
+      description = lib.mdDoc ''
         Port to listen on.
         Pass 0 to let the system choose any free port for you.
       '';
@@ -29,7 +29,7 @@ in {
     address = mkOption {
       default = "127.0.0.1";
       type = str;
-      description = ''
+      description = lib.mdDoc ''
         Address to listen on.
         Pass `all` to listen on all interfaces.
       '';
@@ -37,7 +37,7 @@ in {
 
     rootDir = mkOption {
       type = path;
-      description = ''
+      description = lib.mdDoc ''
         Path from which to serve files.
       '';
     };
@@ -45,7 +45,7 @@ in {
     hideServerId = mkOption {
       type = bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Don't identify the server type in headers or directory listings.
       '';
     };
@@ -53,7 +53,7 @@ in {
     extraArgs = mkOption {
       type = listOf str;
       default = [];
-      description = ''
+      description = lib.mdDoc ''
         Additional configuration passed to the executable.
       '';
     };
diff --git a/nixos/modules/services/web-servers/fcgiwrap.nix b/nixos/modules/services/web-servers/fcgiwrap.nix
index a64a187255a..f9c91fb35db 100644
--- a/nixos/modules/services/web-servers/fcgiwrap.nix
+++ b/nixos/modules/services/web-servers/fcgiwrap.nix
@@ -11,38 +11,38 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable fcgiwrap, a server for running CGI applications over FastCGI.";
+        description = lib.mdDoc "Whether to enable fcgiwrap, a server for running CGI applications over FastCGI.";
       };
 
       preforkProcesses = mkOption {
         type = types.int;
         default = 1;
-        description = "Number of processes to prefork.";
+        description = lib.mdDoc "Number of processes to prefork.";
       };
 
       socketType = mkOption {
         type = types.enum [ "unix" "tcp" "tcp6" ];
         default = "unix";
-        description = "Socket type: 'unix', 'tcp' or 'tcp6'.";
+        description = lib.mdDoc "Socket type: 'unix', 'tcp' or 'tcp6'.";
       };
 
       socketAddress = mkOption {
         type = types.str;
         default = "/run/fcgiwrap.sock";
         example = "1.2.3.4:5678";
-        description = "Socket address. In case of a UNIX socket, this should be its filesystem path.";
+        description = lib.mdDoc "Socket address. In case of a UNIX socket, this should be its filesystem path.";
       };
 
       user = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "User permissions for the socket.";
+        description = lib.mdDoc "User permissions for the socket.";
       };
 
       group = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "Group permissions for the socket.";
+        description = lib.mdDoc "Group permissions for the socket.";
       };
     };
   };
diff --git a/nixos/modules/services/web-servers/garage.nix b/nixos/modules/services/web-servers/garage.nix
new file mode 100644
index 00000000000..76ab273483e
--- /dev/null
+++ b/nixos/modules/services/web-servers/garage.nix
@@ -0,0 +1,91 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.garage;
+  toml = pkgs.formats.toml {};
+  configFile = toml.generate "garage.toml" cfg.settings;
+in
+{
+  meta.maintainers = [ maintainers.raitobezarius ];
+
+  options.services.garage = {
+    enable = mkEnableOption (lib.mdDoc "Garage Object Storage (S3 compatible)");
+
+    extraEnvironment = mkOption {
+      type = types.attrsOf types.str;
+      description = lib.mdDoc "Extra environment variables to pass to the Garage server.";
+      default = {};
+      example = { RUST_BACKTRACE="yes"; };
+    };
+
+    logLevel = mkOption {
+      type = types.enum (["info" "debug" "trace"]);
+      default = "info";
+      example = "debug";
+      description = lib.mdDoc "Garage log level, see <https://garagehq.deuxfleurs.fr/documentation/quick-start/#launching-the-garage-server> for examples.";
+    };
+
+    settings = mkOption {
+      type = types.submodule {
+        freeformType = toml.type;
+
+        options = {
+          metadata_dir = mkOption {
+            default = "/var/lib/garage/meta";
+            type = types.path;
+            description = lib.mdDoc "The metadata directory, put this on a fast disk (e.g. SSD) if possible.";
+          };
+
+          data_dir = mkOption {
+            default = "/var/lib/garage/data";
+            type = types.path;
+            description = lib.mdDoc "The main data storage, put this on your large storage (e.g. high capacity HDD)";
+          };
+
+          replication_mode = mkOption {
+            default = "none";
+            type = types.enum ([ "none" "1" "2" "3" 1 2 3 ]);
+            apply = v: toString v;
+            description = lib.mdDoc "Garage replication mode, defaults to none, see: <https://garagehq.deuxfleurs.fr/reference_manual/configuration.html#replication_mode> for reference.";
+          };
+        };
+      };
+      description = lib.mdDoc "Garage configuration, see <https://garagehq.deuxfleurs.fr/reference_manual/configuration.html> for reference.";
+    };
+
+    package = mkOption {
+      default = pkgs.garage;
+      defaultText = literalExpression "pkgs.garage";
+      type = types.package;
+      description = lib.mdDoc "Garage package to use.";
+    };
+  };
+
+  config = mkIf cfg.enable {
+    environment.etc."garage.toml" = {
+      source = configFile;
+    };
+
+    environment.systemPackages = [ cfg.package ]; # For administration
+
+    systemd.services.garage = {
+      description = "Garage Object Storage (S3 compatible)";
+      after = [ "network.target" "network-online.target" ];
+      wants = [ "network.target" "network-online.target" ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        ExecStart = "${cfg.package}/bin/garage server";
+
+        StateDirectory = mkIf (hasPrefix "/var/lib/garage" cfg.settings.data_dir && hasPrefix "/var/lib/garage" cfg.settings.metadata_dir) "garage";
+        DynamicUser = lib.mkDefault true;
+        ProtectHome = true;
+        NoNewPrivileges = true;
+      };
+      environment = {
+        RUST_LOG = lib.mkDefault "garage=${cfg.logLevel}";
+      } // cfg.extraEnvironment;
+    };
+  };
+}
diff --git a/nixos/modules/services/web-servers/hitch/default.nix b/nixos/modules/services/web-servers/hitch/default.nix
index 1812f225b74..6c8b3cda5f7 100644
--- a/nixos/modules/services/web-servers/hitch/default.nix
+++ b/nixos/modules/services/web-servers/hitch/default.nix
@@ -17,11 +17,11 @@ with lib;
 {
   options = {
     services.hitch = {
-      enable = mkEnableOption "Hitch Server";
+      enable = mkEnableOption (lib.mdDoc "Hitch Server");
 
       backend = mkOption {
         type = types.str;
-        description = ''
+        description = lib.mdDoc ''
           The host and port Hitch connects to when receiving
           a connection in the form [HOST]:PORT
         '';
@@ -30,15 +30,15 @@ with lib;
       ciphers = mkOption {
         type = types.str;
         default = "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
-        description = "The list of ciphers to use";
+        description = lib.mdDoc "The list of ciphers to use";
       };
 
       frontend = mkOption {
         type = types.either types.str (types.listOf types.str);
         default = "[127.0.0.1]:443";
-        description = ''
+        description = lib.mdDoc ''
           The port and interface of the listen endpoint in the
-+         form [HOST]:PORT[+CERT].
+          form [HOST]:PORT[+CERT].
         '';
         apply = toList;
       };
@@ -46,33 +46,33 @@ with lib;
       pem-files = mkOption {
         type = types.listOf types.path;
         default = [];
-        description = "PEM files to use";
+        description = lib.mdDoc "PEM files to use";
       };
 
       ocsp-stapling = {
         enabled = mkOption {
           type = types.bool;
           default = true;
-          description = "Whether to enable OCSP Stapling";
+          description = lib.mdDoc "Whether to enable OCSP Stapling";
         };
       };
 
       user = mkOption {
         type = types.str;
         default = "hitch";
-        description = "The user to run as";
+        description = lib.mdDoc "The user to run as";
       };
 
       group = mkOption {
         type = types.str;
         default = "hitch";
-        description = "The group to run as";
+        description = lib.mdDoc "The group to run as";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Additional configuration lines";
+        description = lib.mdDoc "Additional configuration lines";
       };
     };
 
diff --git a/nixos/modules/services/web-servers/hydron.nix b/nixos/modules/services/web-servers/hydron.nix
index a4a5a435b2e..4434965b217 100644
--- a/nixos/modules/services/web-servers/hydron.nix
+++ b/nixos/modules/services/web-servers/hydron.nix
@@ -4,25 +4,24 @@ let
   cfg = config.services.hydron;
 in with lib; {
   options.services.hydron = {
-    enable = mkEnableOption "hydron";
+    enable = mkEnableOption (lib.mdDoc "hydron");
 
     dataDir = mkOption {
       type = types.path;
       default = "/var/lib/hydron";
       example = "/home/okina/hydron";
-      description = "Location where hydron runs and stores data.";
+      description = lib.mdDoc "Location where hydron runs and stores data.";
     };
 
     interval = mkOption {
       type = types.str;
       default = "weekly";
       example = "06:00";
-      description = ''
+      description = lib.mdDoc ''
         How often we run hydron import and possibly fetch tags. Runs by default every week.
 
         The format is described in
-        <citerefentry><refentrytitle>systemd.time</refentrytitle>
-        <manvolnum>7</manvolnum></citerefentry>.
+        {manpage}`systemd.time(7)`.
       '';
     };
 
@@ -30,19 +29,19 @@ in with lib; {
       type = types.str;
       default = "hydron";
       example = "dumbpass";
-      description = "Password for the hydron database.";
+      description = lib.mdDoc "Password for the hydron database.";
     };
 
     passwordFile = mkOption {
       type = types.path;
       default = "/run/keys/hydron-password-file";
       example = "/home/okina/hydron/keys/pass";
-      description = "Password file for the hydron database.";
+      description = lib.mdDoc "Password file for the hydron database.";
     };
 
     postgresArgs = mkOption {
       type = types.str;
-      description = "Postgresql connection arguments.";
+      description = lib.mdDoc "Postgresql connection arguments.";
       example = ''
         {
           "driver": "postgres",
@@ -55,27 +54,27 @@ in with lib; {
       type = types.path;
       default = "/run/keys/hydron-postgres-args";
       example = "/home/okina/hydron/keys/postgres";
-      description = "Postgresql connection arguments file.";
+      description = lib.mdDoc "Postgresql connection arguments file.";
     };
 
     listenAddress = mkOption {
       type = types.nullOr types.str;
       default = null;
       example = "127.0.0.1:8010";
-      description = "Listen on a specific IP address and port.";
+      description = lib.mdDoc "Listen on a specific IP address and port.";
     };
 
     importPaths = mkOption {
       type = types.listOf types.path;
       default = [];
       example = [ "/home/okina/Pictures" ];
-      description = "Paths that hydron will recursively import.";
+      description = lib.mdDoc "Paths that hydron will recursively import.";
     };
 
     fetchTags = mkOption {
       type = types.bool;
       default = true;
-      description = "Fetch tags for imported images and webm from gelbooru.";
+      description = lib.mdDoc "Fetch tags for imported images and webm from gelbooru.";
     };
   };
 
@@ -161,5 +160,5 @@ in with lib; {
     (mkRenamedOptionModule [ "services" "hydron" "baseDir" ] [ "services" "hydron" "dataDir" ])
   ];
 
-  meta.maintainers = with maintainers; [ chiiruno ];
+  meta.maintainers = with maintainers; [ Madouura ];
 }
diff --git a/nixos/modules/services/web-servers/jboss/default.nix b/nixos/modules/services/web-servers/jboss/default.nix
index d243e0f3f1b..05b354d567f 100644
--- a/nixos/modules/services/web-servers/jboss/default.nix
+++ b/nixos/modules/services/web-servers/jboss/default.nix
@@ -26,49 +26,49 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable JBoss. WARNING : this package is outdated and is known to have vulnerabilities.";
+        description = lib.mdDoc "Whether to enable JBoss. WARNING : this package is outdated and is known to have vulnerabilities.";
       };
 
       tempDir = mkOption {
         default = "/tmp";
         type = types.str;
-        description = "Location where JBoss stores its temp files";
+        description = lib.mdDoc "Location where JBoss stores its temp files";
       };
 
       logDir = mkOption {
         default = "/var/log/jboss";
         type = types.str;
-        description = "Location of the logfile directory of JBoss";
+        description = lib.mdDoc "Location of the logfile directory of JBoss";
       };
 
       serverDir = mkOption {
-        description = "Location of the server instance files";
+        description = lib.mdDoc "Location of the server instance files";
         default = "/var/jboss/server";
         type = types.str;
       };
 
       deployDir = mkOption {
-        description = "Location of the deployment files";
+        description = lib.mdDoc "Location of the deployment files";
         default = "/nix/var/nix/profiles/default/server/default/deploy/";
         type = types.str;
       };
 
       libUrl = mkOption {
         default = "file:///nix/var/nix/profiles/default/server/default/lib";
-        description = "Location where the shared library JARs are stored";
+        description = lib.mdDoc "Location where the shared library JARs are stored";
         type = types.str;
       };
 
       user = mkOption {
         default = "nobody";
-        description = "User account under which jboss runs.";
+        description = lib.mdDoc "User account under which jboss runs.";
         type = types.str;
       };
 
       useJK = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to use to connector to the Apache HTTP server";
+        description = lib.mdDoc "Whether to use to connector to the Apache HTTP server";
       };
 
     };
diff --git a/nixos/modules/services/web-servers/keter/bundle.nix b/nixos/modules/services/web-servers/keter/bundle.nix
new file mode 100644
index 00000000000..32b08c3be20
--- /dev/null
+++ b/nixos/modules/services/web-servers/keter/bundle.nix
@@ -0,0 +1,40 @@
+/* This makes a keter bundle as described on the github page:
+  https://github.com/snoyberg/keter#bundling-your-app-for-keter
+*/
+{ keterDomain
+, keterExecutable
+, gnutar
+, writeTextFile
+, lib
+, stdenv
+, ...
+}:
+
+let
+  str.stanzas = [{
+    # we just use nix as an absolute path so we're not bundling any binaries
+    type = "webapp";
+    /* Note that we're not actually putting the executable in the bundle,
+      we already can use the nix store for copying, so we just
+      symlink to the app. */
+    exec = keterExecutable;
+    host = keterDomain;
+  }];
+  configFile = writeTextFile {
+    name = "keter.yml";
+    text = (lib.generators.toYAML { } str);
+  };
+
+in
+stdenv.mkDerivation {
+  name = "keter-bundle";
+  buildCommand = ''
+    mkdir -p config
+    cp ${configFile} config/keter.yaml
+
+    echo 'create a gzipped tarball'
+    mkdir -p $out
+    tar -zcvf $out/bundle.tar.gz.keter ./.
+  '';
+  buildInputs = [ gnutar ];
+}
diff --git a/nixos/modules/services/web-servers/keter/default.nix b/nixos/modules/services/web-servers/keter/default.nix
new file mode 100644
index 00000000000..42ab6640b4c
--- /dev/null
+++ b/nixos/modules/services/web-servers/keter/default.nix
@@ -0,0 +1,162 @@
+{ config, pkgs, lib, ... }:
+let
+  cfg = config.services.keter;
+in
+{
+  meta = {
+    maintainers = with lib.maintainers; [ jappie ];
+  };
+
+  options.services.keter = {
+    enable = lib.mkEnableOption (lib.mdDoc ''keter, a web app deployment manager.
+Note that this module only support loading of webapps:
+Keep an old app running and swap the ports when the new one is booted.
+'');
+
+    keterRoot = lib.mkOption {
+      type = lib.types.str;
+      default = "/var/lib/keter";
+      description = lib.mdDoc "Mutable state folder for keter";
+    };
+
+    keterPackage = lib.mkOption {
+      type = lib.types.package;
+      default = pkgs.haskellPackages.keter;
+      defaultText = lib.literalExpression "pkgs.haskellPackages.keter";
+      description = lib.mdDoc "The keter package to be used";
+    };
+
+    globalKeterConfig = lib.mkOption {
+      type = lib.types.attrs;
+      default = {
+        ip-from-header = true;
+        listeners = [{
+          host = "*4";
+          port = 6981;
+        }];
+      };
+      # You want that ip-from-header in the nginx setup case
+      # so it's not set to 127.0.0.1.
+      # using a port above 1024 allows you to avoid needing CAP_NET_BIND_SERVICE
+      defaultText = lib.literalExpression ''
+        {
+          ip-from-header = true;
+          listeners = [{
+            host = "*4";
+            port = 6981;
+          }];
+        }
+      '';
+      description = lib.mdDoc "Global config for keter";
+    };
+
+    bundle = {
+      appName = lib.mkOption {
+        type = lib.types.str;
+        default = "myapp";
+        description = lib.mdDoc "The name keter assigns to this bundle";
+      };
+
+      executable = lib.mkOption {
+        type = lib.types.path;
+        description = lib.mdDoc "The executable to be run";
+      };
+
+      domain = lib.mkOption {
+        type = lib.types.str;
+        default = "example.com";
+        description = lib.mdDoc "The domain keter will bind to";
+      };
+
+      publicScript = lib.mkOption {
+        type = lib.types.str;
+        default = "";
+        description = lib.mdDoc ''
+          Allows loading of public environment variables,
+          these are emitted to the log so it shouldn't contain secrets.
+        '';
+        example = "ADMIN_EMAIL=hi@example.com";
+      };
+
+      secretScript = lib.mkOption {
+        type = lib.types.str;
+        default = "";
+        description = lib.mdDoc "Allows loading of private environment variables";
+        example = "MY_AWS_KEY=$(cat /run/keys/AWS_ACCESS_KEY_ID)";
+      };
+    };
+
+  };
+
+  config = lib.mkIf cfg.enable (
+    let
+      incoming = "${cfg.keterRoot}/incoming";
+
+
+      globalKeterConfigFile = pkgs.writeTextFile {
+        name = "keter-config.yml";
+        text = (lib.generators.toYAML { } (cfg.globalKeterConfig // { root = cfg.keterRoot; }));
+      };
+
+      # If things are expected to change often, put it in the bundle!
+      bundle = pkgs.callPackage ./bundle.nix
+        (cfg.bundle // { keterExecutable = executable; keterDomain = cfg.bundle.domain; });
+
+      # This indirection is required to ensure the nix path
+      # gets copied over to the target machine in remote deployments.
+      # Furthermore, it's important that we use exec to
+      # run the binary otherwise we get process leakage due to this
+      # being executed on every change.
+      executable = pkgs.writeShellScript "bundle-wrapper" ''
+        set -e
+        ${cfg.bundle.secretScript}
+        set -xe
+        ${cfg.bundle.publicScript}
+        exec ${cfg.bundle.executable}
+      '';
+
+    in
+    {
+      systemd.services.keter = {
+        description = "keter app loader";
+        script = ''
+          set -xe
+          mkdir -p ${incoming}
+          { tail -F ${cfg.keterRoot}/log/keter/current.log -n 0 & ${cfg.keterPackage}/bin/keter ${globalKeterConfigFile}; }
+        '';
+        wantedBy = [ "multi-user.target" "nginx.service" ];
+
+        serviceConfig = {
+          Restart = "always";
+          RestartSec = "10s";
+        };
+
+        after = [
+          "network.target"
+          "local-fs.target"
+          "postgresql.service"
+        ];
+      };
+
+      # On deploy this will load our app, by moving it into the incoming dir
+      # If the bundle content changes, this will run again.
+      # Because the bundle content contains the nix path to the exectuable,
+      # we inherit nix based cache busting.
+      systemd.services.load-keter-bundle = {
+        description = "load keter bundle into incoming folder";
+        after = [ "keter.service" ];
+        wantedBy = [ "multi-user.target" ];
+        # we can't override keter bundles because it'll stop the previous app
+        # https://github.com/snoyberg/keter#deploying
+        script = ''
+          set -xe
+          cp ${bundle}/bundle.tar.gz.keter ${incoming}/${cfg.bundle.appName}.keter
+        '';
+        path = [
+          executable
+          cfg.bundle.executable
+        ]; # this is a hack to get the executable copied over to the machine.
+      };
+    }
+  );
+}
diff --git a/nixos/modules/services/web-servers/lighttpd/cgit.nix b/nixos/modules/services/web-servers/lighttpd/cgit.nix
index 8cd6d020940..5042fbf1f8f 100644
--- a/nixos/modules/services/web-servers/lighttpd/cgit.nix
+++ b/nixos/modules/services/web-servers/lighttpd/cgit.nix
@@ -23,7 +23,7 @@ in
     enable = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         If true, enable cgit (fast web interface for git repositories) as a
         sub-service in lighttpd.
       '';
@@ -33,7 +33,7 @@ in
       default = "cgit";
       example = "";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The subdirectory in which to serve cgit. The web application will be
         accessible at http://yourserver/''${subdir}
       '';
@@ -50,7 +50,7 @@ in
         '''
       '';
       type = types.lines;
-      description = ''
+      description = lib.mdDoc ''
         Verbatim contents of the cgit runtime configuration file. Documentation
         (with cgitrc example file) is available in "man cgitrc". Or online:
         http://git.zx2c4.com/cgit/tree/cgitrc.5.txt
diff --git a/nixos/modules/services/web-servers/lighttpd/collectd.nix b/nixos/modules/services/web-servers/lighttpd/collectd.nix
index 5f091591daf..9a4285e3e2d 100644
--- a/nixos/modules/services/web-servers/lighttpd/collectd.nix
+++ b/nixos/modules/services/web-servers/lighttpd/collectd.nix
@@ -25,15 +25,15 @@ in
 
   options.services.lighttpd.collectd = {
 
-    enable = mkEnableOption "collectd subservice accessible at http://yourserver/collectd";
+    enable = mkEnableOption (lib.mdDoc "collectd subservice accessible at http://yourserver/collectd");
 
     collectionCgi = mkOption {
       type = types.path;
       default = defaultCollectionCgi;
-      defaultText = literalDocBook ''
-        <literal>config.${options.services.collectd.package}</literal> configured for lighttpd
+      defaultText = literalMD ''
+        `config.${options.services.collectd.package}` configured for lighttpd
       '';
-      description = ''
+      description = lib.mdDoc ''
         Path to collection.cgi script from (collectd sources)/contrib/collection.cgi
         This option allows to use a customized version
       '';
diff --git a/nixos/modules/services/web-servers/lighttpd/default.nix b/nixos/modules/services/web-servers/lighttpd/default.nix
index 05e897c8cc9..ec847495d74 100644
--- a/nixos/modules/services/web-servers/lighttpd/default.nix
+++ b/nixos/modules/services/web-servers/lighttpd/default.nix
@@ -130,7 +130,7 @@ in
       enable = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Enable the lighttpd web server.
         '';
       };
@@ -139,7 +139,7 @@ in
         default = pkgs.lighttpd;
         defaultText = "pkgs.lighttpd";
         type = types.package;
-        description = ''
+        description = lib.mdDoc ''
           lighttpd package to use.
         '';
       };
@@ -147,7 +147,7 @@ in
       port = mkOption {
         default = 80;
         type = types.port;
-        description = ''
+        description = lib.mdDoc ''
           TCP port number for lighttpd to bind to.
         '';
       };
@@ -155,7 +155,7 @@ in
       document-root = mkOption {
         default = "/srv/www";
         type = types.path;
-        description = ''
+        description = lib.mdDoc ''
           Document-root of the web server. Must be readable by the "lighttpd" user.
         '';
       };
@@ -163,7 +163,7 @@ in
       mod_userdir = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           If true, requests in the form /~user/page.html are rewritten to take
           the file public_html/page.html from the home directory of the user.
         '';
@@ -173,11 +173,11 @@ in
         type = types.listOf types.str;
         default = [ ];
         example = [ "mod_cgi" "mod_status" ];
-        description = ''
+        description = lib.mdDoc ''
           List of lighttpd modules to enable. Sub-services take care of
           enabling modules as needed, so this option is mainly for when you
           want to add custom stuff to
-          <option>services.lighttpd.extraConfig</option> that depends on a
+          {option}`services.lighttpd.extraConfig` that depends on a
           certain module.
         '';
       };
@@ -185,18 +185,18 @@ in
       enableUpstreamMimeTypes = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to include the list of mime types bundled with lighttpd
           (upstream). If you disable this, no mime types will be added by
           NixOS and you will have to add your own mime types in
-          <option>services.lighttpd.extraConfig</option>.
+          {option}`services.lighttpd.extraConfig`.
         '';
       };
 
       mod_status = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Show server status overview at /server-status, statistics at
           /server-statistics and list of loaded modules at /server-config.
         '';
@@ -206,7 +206,7 @@ in
         default = "";
         type = types.lines;
         example = "...verbatim config file contents...";
-        description = ''
+        description = lib.mdDoc ''
           Overridable config file contents to use for lighttpd. By default, use
           the contents automatically generated by NixOS.
         '';
@@ -215,10 +215,10 @@ in
       extraConfig = mkOption {
         default = "";
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           These configuration lines will be appended to the generated lighttpd
           config file. Note that this mechanism does not work when the manual
-          <option>configText</option> option is used.
+          {option}`configText` option is used.
         '';
       };
 
diff --git a/nixos/modules/services/web-servers/lighttpd/gitweb.nix b/nixos/modules/services/web-servers/lighttpd/gitweb.nix
index c494d6966a7..e129e8bc166 100644
--- a/nixos/modules/services/web-servers/lighttpd/gitweb.nix
+++ b/nixos/modules/services/web-servers/lighttpd/gitweb.nix
@@ -16,7 +16,7 @@ in
     enable = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         If true, enable gitweb in lighttpd. Access it at http://yourserver/gitweb
       '';
     };
diff --git a/nixos/modules/services/web-servers/merecat.nix b/nixos/modules/services/web-servers/merecat.nix
new file mode 100644
index 00000000000..aad93605b71
--- /dev/null
+++ b/nixos/modules/services/web-servers/merecat.nix
@@ -0,0 +1,55 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.merecat;
+  format = pkgs.formats.keyValue {
+    mkKeyValue = generators.mkKeyValueDefault {
+      mkValueString = v:
+        # In merecat.conf, booleans are "true" and "false"
+        if builtins.isBool v
+        then if v then "true" else "false"
+        else generators.mkValueStringDefault {} v;
+    } "=";
+  };
+  configFile = format.generate "merecat.conf" cfg.settings;
+
+in {
+
+  options.services.merecat = {
+
+    enable = mkEnableOption (lib.mdDoc "Merecat HTTP server");
+
+    settings = mkOption {
+      inherit (format) type;
+      default = { };
+      description = lib.mdDoc ''
+        Merecat configuration. Refer to merecat(8) for details on supported values.
+      '';
+      example = {
+        hostname = "localhost";
+        port = 8080;
+        virtual-host = true;
+        directory = "/srv/www";
+      };
+    };
+
+  };
+
+  config = mkIf cfg.enable {
+
+    systemd.services.merecat = {
+      description = "Merecat HTTP server";
+      after = [ "network.target" ];
+      wantedBy = [ "multi-user.target" ];
+      serviceConfig = {
+        DynamicUser = true;
+        ExecStart = "${pkgs.merecat}/bin/merecat -n -f ${configFile}";
+        AmbientCapabilities = lib.mkIf ((cfg.settings.port or 80) < 1024) [ "CAP_NET_BIND_SERVICE" ];
+      };
+    };
+
+  };
+
+}
diff --git a/nixos/modules/services/web-servers/mighttpd2.nix b/nixos/modules/services/web-servers/mighttpd2.nix
index f9b1a8b6ccc..2d887af87c7 100644
--- a/nixos/modules/services/web-servers/mighttpd2.nix
+++ b/nixos/modules/services/web-servers/mighttpd2.nix
@@ -8,7 +8,7 @@ let
   routingFile = pkgs.writeText "mighty-routing" cfg.routing;
 in {
   options.services.mighttpd2 = {
-    enable = mkEnableOption "Mighttpd2 web server";
+    enable = mkEnableOption (lib.mdDoc "Mighttpd2 web server");
 
     config = mkOption {
       default = "";
@@ -42,7 +42,7 @@ in {
         Service: 0 # 0 is HTTP only, 1 is HTTPS only, 2 is both
       '';
       type = types.lines;
-      description = ''
+      description = lib.mdDoc ''
         Verbatim config file to use
         (see http://www.mew.org/~kazu/proj/mighttpd/en/config.html)
       '';
@@ -76,7 +76,7 @@ in {
         /                -> /export/www/
       '';
       type = types.lines;
-      description = ''
+      description = lib.mdDoc ''
         Verbatim routing file to use
         (see http://www.mew.org/~kazu/proj/mighttpd/en/config.html)
       '';
@@ -85,7 +85,7 @@ in {
     cores = mkOption {
       default = null;
       type = types.nullOr types.int;
-      description = ''
+      description = lib.mdDoc ''
         How many cores to use.
         If null it will be determined automatically
       '';
diff --git a/nixos/modules/services/web-servers/minio.nix b/nixos/modules/services/web-servers/minio.nix
index c345e3f2467..1a9eacb431b 100644
--- a/nixos/modules/services/web-servers/minio.nix
+++ b/nixos/modules/services/web-servers/minio.nix
@@ -14,56 +14,56 @@ in
   meta.maintainers = [ maintainers.bachp ];
 
   options.services.minio = {
-    enable = mkEnableOption "Minio Object Storage";
+    enable = mkEnableOption (lib.mdDoc "Minio Object Storage");
 
     listenAddress = mkOption {
       default = ":9000";
       type = types.str;
-      description = "IP address and port of the server.";
+      description = lib.mdDoc "IP address and port of the server.";
     };
 
     consoleAddress = mkOption {
       default = ":9001";
       type = types.str;
-      description = "IP address and port of the web UI (console).";
+      description = lib.mdDoc "IP address and port of the web UI (console).";
     };
 
     dataDir = mkOption {
       default = [ "/var/lib/minio/data" ];
       type = types.listOf types.path;
-      description = "The list of data directories for storing the objects. Use one path for regular operation and the minimum of 4 endpoints for Erasure Code mode.";
+      description = lib.mdDoc "The list of data directories for storing the objects. Use one path for regular operation and the minimum of 4 endpoints for Erasure Code mode.";
     };
 
     configDir = mkOption {
       default = "/var/lib/minio/config";
       type = types.path;
-      description = "The config directory, for the access keys and other settings.";
+      description = lib.mdDoc "The config directory, for the access keys and other settings.";
     };
 
     accessKey = mkOption {
       default = "";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Access key of 5 to 20 characters in length that clients use to access the server.
         This overrides the access key that is generated by minio on first startup and stored inside the
-        <literal>configDir</literal> directory.
+        `configDir` directory.
       '';
     };
 
     secretKey = mkOption {
       default = "";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Specify the Secret key of 8 to 40 characters in length that clients use to access the server.
         This overrides the secret key that is generated by minio on first startup and stored inside the
-        <literal>configDir</literal> directory.
+        `configDir` directory.
       '';
     };
 
     rootCredentialsFile = mkOption  {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         File containing the MINIO_ROOT_USER, default is "minioadmin", and
         MINIO_ROOT_PASSWORD (length >= 8), default is "minioadmin"; in the format of
         an EnvironmentFile=, as described by systemd.exec(5).
@@ -74,7 +74,7 @@ in
     region = mkOption {
       default = "us-east-1";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         The physical location of the server. By default it is set to us-east-1, which is same as AWS S3's and Minio's default region.
       '';
     };
@@ -82,14 +82,14 @@ in
     browser = mkOption {
       default = true;
       type = types.bool;
-      description = "Enable or disable access to web UI.";
+      description = lib.mdDoc "Enable or disable access to web UI.";
     };
 
     package = mkOption {
       default = pkgs.minio;
       defaultText = literalExpression "pkgs.minio";
       type = types.package;
-      description = "Minio package to use.";
+      description = lib.mdDoc "Minio package to use.";
     };
   };
 
@@ -102,7 +102,7 @@ in
 
     systemd.services.minio = {
       description = "Minio Object Storage";
-      after = [ "network.target" ];
+      after = [ "network-online.target" ];
       wantedBy = [ "multi-user.target" ];
       serviceConfig = {
         ExecStart = "${cfg.package}/bin/minio server --json --address ${cfg.listenAddress} --console-address ${cfg.consoleAddress} --config-dir=${cfg.configDir} ${toString cfg.dataDir}";
diff --git a/nixos/modules/services/web-servers/molly-brown.nix b/nixos/modules/services/web-servers/molly-brown.nix
index 0bd8b3316cb..6d7ca0c12ef 100644
--- a/nixos/modules/services/web-servers/molly-brown.nix
+++ b/nixos/modules/services/web-servers/molly-brown.nix
@@ -10,12 +10,12 @@ in {
 
   options.services.molly-brown = {
 
-    enable = mkEnableOption "Molly-Brown Gemini server";
+    enable = mkEnableOption (lib.mdDoc "Molly-Brown Gemini server");
 
     port = mkOption {
       default = 1965;
       type = types.port;
-      description = ''
+      description = lib.mdDoc ''
         TCP port for molly-brown to bind to.
       '';
     };
@@ -24,7 +24,7 @@ in {
       type = types.str;
       default = config.networking.hostName;
       defaultText = literalExpression "config.networking.hostName";
-      description = ''
+      description = lib.mdDoc ''
         The hostname to respond to requests for. Requests for URLs with
         other hosts will result in a status 53 (PROXY REQUEST REFUSED)
         response.
@@ -34,37 +34,37 @@ in {
     certPath = mkOption {
       type = types.path;
       example = "/var/lib/acme/example.com/cert.pem";
-      description = ''
+      description = lib.mdDoc ''
         Path to TLS certificate. An ACME certificate and key may be
         shared with an HTTP server, but only if molly-brown has
         permissions allowing it to read such keys.
 
         As an example:
-        <programlisting>
+        ```
         systemd.services.molly-brown.serviceConfig.SupplementaryGroups =
           [ config.security.acme.certs."example.com".group ];
-        </programlisting>
+        ```
       '';
     };
 
     keyPath = mkOption {
       type = types.path;
       example = "/var/lib/acme/example.com/key.pem";
-      description = "Path to TLS key. See <option>CertPath</option>.";
+      description = lib.mdDoc "Path to TLS key. See {option}`CertPath`.";
     };
 
     docBase = mkOption {
       type = types.path;
       example = "/var/lib/molly-brown";
-      description = "Base directory for Gemini content.";
+      description = lib.mdDoc "Base directory for Gemini content.";
     };
 
     settings = mkOption {
       inherit (settingsFormat) type;
       default = { };
-      description = ''
+      description = lib.mdDoc ''
         molly-brown configuration. Refer to
-        <link xlink:href="https://tildegit.org/solderpunk/molly-brown/src/branch/master/example.conf"/>
+        <https://tildegit.org/solderpunk/molly-brown/src/branch/master/example.conf>
         for details on supported values.
       '';
     };
diff --git a/nixos/modules/services/web-servers/nginx/default.nix b/nixos/modules/services/web-servers/nginx/default.nix
index e046c28dd6b..85c76ed59d6 100644
--- a/nixos/modules/services/web-servers/nginx/default.nix
+++ b/nixos/modules/services/web-servers/nginx/default.nix
@@ -192,14 +192,22 @@ let
 
       server_tokens ${if cfg.serverTokens then "on" else "off"};
 
+      ${optionalString (cfg.proxyCache.enable) ''
+        proxy_cache_path /var/cache/nginx keys_zone=${cfg.proxyCache.keysZoneName}:${cfg.proxyCache.keysZoneSize}
+                                          levels=${cfg.proxyCache.levels}
+                                          use_temp_path=${if cfg.proxyCache.useTempPath then "on" else "off"}
+                                          inactive=${cfg.proxyCache.inactive}
+                                          max_size=${cfg.proxyCache.maxSize};
+      ''}
+
       ${cfg.commonHttpConfig}
 
       ${vhosts}
 
       ${optionalString cfg.statusPage ''
         server {
-          listen 80;
-          ${optionalString enableIPv6 "listen [::]:80;" }
+          listen ${toString cfg.defaultHTTPListenPort};
+          ${optionalString enableIPv6 "listen [::]:${toString cfg.defaultHTTPListenPort};" }
 
           server_name localhost;
 
@@ -246,8 +254,8 @@ let
           if vhost.listen != [] then vhost.listen
           else
             let addrs = if vhost.listenAddresses != [] then vhost.listenAddresses else cfg.defaultListenAddresses;
-            in optionals (hasSSL || vhost.rejectSSL) (map (addr: { inherit addr; port = 443; ssl = true; }) addrs)
-              ++ optionals (!onlySSL) (map (addr: { inherit addr; port = 80; ssl = false; }) addrs);
+            in optionals (hasSSL || vhost.rejectSSL) (map (addr: { inherit addr; port = cfg.defaultSSLListenPort; ssl = true; }) addrs)
+              ++ optionals (!onlySSL) (map (addr: { inherit addr; port = cfg.defaultHTTPListenPort; ssl = false; }) addrs);
 
         hostListen =
           if vhost.forceSSL
@@ -255,25 +263,30 @@ let
             else defaultListen;
 
         listenString = { addr, port, ssl, extraParameters ? [], ... }:
-          "listen ${addr}:${toString port} "
-          + optionalString ssl "ssl "
+          (if ssl && vhost.http3 then "
+          # UDP listener for **QUIC+HTTP/3
+          listen ${addr}:${toString port} http3 "
+          + optionalString vhost.default "default_server "
+          + optionalString vhost.reuseport "reuseport "
+          + optionalString (extraParameters != []) (concatStringsSep " " extraParameters)
+          + ";" else "")
+          + "
+
+            listen ${addr}:${toString port} "
           + optionalString (ssl && vhost.http2) "http2 "
+          + optionalString ssl "ssl "
           + optionalString vhost.default "default_server "
+          + optionalString vhost.reuseport "reuseport "
           + optionalString (extraParameters != []) (concatStringsSep " " extraParameters)
-          + ";"
-          + (if ssl && vhost.http3 then ''
-          # UDP listener for **QUIC+HTTP/3
-          listen ${addr}:${toString port} http3 reuseport;
-          # Advertise that HTTP/3 is available
-          add_header Alt-Svc 'h3=":443"';
-          # Sent when QUIC was used
-          add_header QUIC-Status $quic;
-          '' else "");
+          + ";";
 
         redirectListen = filter (x: !x.ssl) defaultListen;
 
         acmeLocation = optionalString (vhost.enableACME || vhost.useACMEHost != null) ''
-          location /.well-known/acme-challenge {
+          # Rule for legitimate ACME Challenge requests (like /.well-known/acme-challenge/xxxxxxxxx)
+          # We use ^~ here, so that we don't check any regexes (which could
+          # otherwise easily override this intended match accidentally).
+          location ^~ /.well-known/acme-challenge/ {
             ${optionalString (vhost.acmeFallbackHost != null) "try_files $uri @acme-fallback;"}
             ${optionalString (vhost.acmeRoot != null) "root ${vhost.acmeRoot};"}
             auth_basic off;
@@ -321,6 +334,11 @@ let
             ssl_conf_command Options KTLS;
           ''}
 
+          ${optionalString (hasSSL && vhost.http3) ''
+            # Advertise that HTTP/3 is available
+            add_header Alt-Svc 'h3=":443"; ma=86400' always;
+          ''}
+
           ${mkBasicAuth vhostName vhost}
 
           ${mkLocations vhost.locations}
@@ -353,7 +371,7 @@ let
       ${optionalString (config.alias != null) "alias ${config.alias};"}
       ${optionalString (config.return != null) "return ${config.return};"}
       ${config.extraConfig}
-      ${optionalString (config.proxyPass != null && cfg.recommendedProxySettings) "include ${recommendedProxyConfig};"}
+      ${optionalString (config.proxyPass != null && config.recommendedProxySettings) "include ${recommendedProxyConfig};"}
       ${mkBasicAuth "sublocation" config}
     }
   '') (sortProperties (mapAttrsToList (k: v: v // { location = k; }) locations)));
@@ -378,55 +396,55 @@ in
 {
   options = {
     services.nginx = {
-      enable = mkEnableOption "Nginx Web Server";
+      enable = mkEnableOption (lib.mdDoc "Nginx Web Server");
 
       statusPage = mkOption {
         default = false;
         type = types.bool;
-        description = "
+        description = lib.mdDoc ''
           Enable status page reachable from localhost on http://127.0.0.1/nginx_status.
-        ";
+        '';
       };
 
       recommendedTlsSettings = mkOption {
         default = false;
         type = types.bool;
-        description = "
+        description = lib.mdDoc ''
           Enable recommended TLS settings.
-        ";
+        '';
       };
 
       recommendedOptimisation = mkOption {
         default = false;
         type = types.bool;
-        description = "
+        description = lib.mdDoc ''
           Enable recommended optimisation settings.
-        ";
+        '';
       };
 
       recommendedGzipSettings = mkOption {
         default = false;
         type = types.bool;
-        description = "
+        description = lib.mdDoc ''
           Enable recommended gzip settings.
-        ";
+        '';
       };
 
       recommendedProxySettings = mkOption {
         default = false;
         type = types.bool;
-        description = "
-          Enable recommended proxy settings.
-        ";
+        description = lib.mdDoc ''
+          Whether to enable recommended proxy settings if a vhost does not specify the option manually.
+        '';
       };
 
       proxyTimeout = mkOption {
         type = types.str;
         default = "60s";
         example = "20s";
-        description = "
+        description = lib.mdDoc ''
           Change the proxy related timeouts in recommendedProxySettings.
-        ";
+        '';
       };
 
       defaultListenAddresses = mkOption {
@@ -434,9 +452,27 @@ in
         default = [ "0.0.0.0" ] ++ optional enableIPv6 "[::0]";
         defaultText = literalExpression ''[ "0.0.0.0" ] ++ lib.optional config.networking.enableIPv6 "[::0]"'';
         example = literalExpression ''[ "10.0.0.12" "[2002:a00:1::]" ]'';
-        description = "
+        description = lib.mdDoc ''
           If vhosts do not specify listenAddresses, use these addresses by default.
-        ";
+        '';
+      };
+
+      defaultHTTPListenPort = mkOption {
+        type = types.port;
+        default = 80;
+        example = 8080;
+        description = lib.mdDoc ''
+          If vhosts do not specify listen.port, use these ports for HTTP by default.
+        '';
+      };
+
+      defaultSSLListenPort = mkOption {
+        type = types.port;
+        default = 443;
+        example = 8443;
+        description = lib.mdDoc ''
+          If vhosts do not specify listen.port, use these ports for SSL by default.
+        '';
       };
 
       package = mkOption {
@@ -446,28 +482,28 @@ in
         apply = p: p.override {
           modules = p.modules ++ cfg.additionalModules;
         };
-        description = "
+        description = lib.mdDoc ''
           Nginx package to use. This defaults to the stable version. Note
           that the nginx team recommends to use the mainline version which
-          available in nixpkgs as <literal>nginxMainline</literal>.
-        ";
+          available in nixpkgs as `nginxMainline`.
+        '';
       };
 
       additionalModules = mkOption {
         default = [];
         type = types.listOf (types.attrsOf types.anything);
         example = literalExpression "[ pkgs.nginxModules.brotli ]";
-        description = ''
-          Additional <link xlink:href="https://www.nginx.com/resources/wiki/modules/">third-party nginx modules</link>
+        description = lib.mdDoc ''
+          Additional [third-party nginx modules](https://www.nginx.com/resources/wiki/modules/)
           to install. Packaged modules are available in
-          <literal>pkgs.nginxModules</literal>.
+          `pkgs.nginxModules`.
         '';
       };
 
       logError = mkOption {
         default = "stderr";
         type = types.str;
-        description = "
+        description = lib.mdDoc ''
           Configures logging.
           The first parameter defines a file that will store the log. The
           special value stderr selects the standard error file. Logging to
@@ -478,47 +514,42 @@ in
           increasing severity. Setting a certain log level will cause all
           messages of the specified and more severe log levels to be logged.
           If this parameter is omitted then error is used.
-        ";
+        '';
       };
 
       preStart =  mkOption {
         type = types.lines;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Shell commands executed before the service's nginx is started.
-        ";
+        '';
       };
 
       config = mkOption {
         type = types.str;
         default = "";
-        description = ''
-          Verbatim <filename>nginx.conf</filename> configuration.
+        description = lib.mdDoc ''
+          Verbatim {file}`nginx.conf` configuration.
           This is mutually exclusive to any other config option for
-          <filename>nginx.conf</filename> except for
-          <itemizedlist>
-          <listitem><para><xref linkend="opt-services.nginx.appendConfig" />
-          </para></listitem>
-          <listitem><para><xref linkend="opt-services.nginx.httpConfig" />
-          </para></listitem>
-          <listitem><para><xref linkend="opt-services.nginx.logError" />
-          </para></listitem>
-          </itemizedlist>
+          {file}`nginx.conf` except for
+          - [](#opt-services.nginx.appendConfig)
+          - [](#opt-services.nginx.httpConfig)
+          - [](#opt-services.nginx.logError)
 
           If additional verbatim config in addition to other options is needed,
-          <xref linkend="opt-services.nginx.appendConfig" /> should be used instead.
+          [](#opt-services.nginx.appendConfig) should be used instead.
         '';
       };
 
       appendConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Configuration lines appended to the generated Nginx
           configuration file. Commonly used by different modules
-          providing http snippets. <option>appendConfig</option>
+          providing http snippets. {option}`appendConfig`
           can be specified more than once and it's value will be
-          concatenated (contrary to <option>config</option> which
+          concatenated (contrary to {option}`config` which
           can be set only once).
         '';
       };
@@ -533,7 +564,7 @@ in
                               '"$request" $status $body_bytes_sent '
                               '"$http_referer" "$http_user_agent"';
         '';
-        description = ''
+        description = lib.mdDoc ''
           With nginx you must provide common http context definitions before
           they are used, e.g. log_format, resolver, etc. inside of server
           or location contexts. Use this attribute to set these definitions
@@ -544,12 +575,12 @@ in
       httpConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Configuration lines to be set inside the http block.
           This is mutually exclusive with the structured configuration
           via virtualHosts and the recommendedXyzSettings configuration
           options. See appendHttpConfig for appending to the generated http block.
-        ";
+        '';
       };
 
       streamConfig = mkOption {
@@ -562,15 +593,15 @@ in
             proxy_pass 192.168.0.1:53535;
           }
         '';
-        description = "
+        description = lib.mdDoc ''
           Configuration lines to be set inside the stream block.
-        ";
+        '';
       };
 
       eventsConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Configuration lines to be set inside the events block.
         '';
       };
@@ -578,72 +609,72 @@ in
       appendHttpConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Configuration lines to be appended to the generated http block.
           This is mutually exclusive with using config and httpConfig for
           specifying the whole http block verbatim.
-        ";
+        '';
       };
 
       enableReload = mkOption {
         default = false;
         type = types.bool;
-        description = ''
+        description = lib.mdDoc ''
           Reload nginx when configuration file changes (instead of restart).
-          The configuration file is exposed at <filename>/etc/nginx/nginx.conf</filename>.
-          See also <literal>systemd.services.*.restartIfChanged</literal>.
+          The configuration file is exposed at {file}`/etc/nginx/nginx.conf`.
+          See also `systemd.services.*.restartIfChanged`.
         '';
       };
 
       user = mkOption {
         type = types.str;
         default = "nginx";
-        description = "User account under which nginx runs.";
+        description = lib.mdDoc "User account under which nginx runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "nginx";
-        description = "Group account under which nginx runs.";
+        description = lib.mdDoc "Group account under which nginx runs.";
       };
 
       serverTokens = mkOption {
         type = types.bool;
         default = false;
-        description = "Show nginx version in headers and error pages.";
+        description = lib.mdDoc "Show nginx version in headers and error pages.";
       };
 
       clientMaxBodySize = mkOption {
         type = types.str;
         default = "10m";
-        description = "Set nginx global client_max_body_size.";
+        description = lib.mdDoc "Set nginx global client_max_body_size.";
       };
 
       sslCiphers = mkOption {
         type = types.nullOr types.str;
         # Keep in sync with https://ssl-config.mozilla.org/#server=nginx&config=intermediate
         default = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384";
-        description = "Ciphers to choose from when negotiating TLS handshakes.";
+        description = lib.mdDoc "Ciphers to choose from when negotiating TLS handshakes.";
       };
 
       sslProtocols = mkOption {
         type = types.str;
         default = "TLSv1.2 TLSv1.3";
         example = "TLSv1 TLSv1.1 TLSv1.2 TLSv1.3";
-        description = "Allowed TLS protocol versions.";
+        description = lib.mdDoc "Allowed TLS protocol versions.";
       };
 
       sslDhparam = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/path/to/dhparams.pem";
-        description = "Path to DH parameters file.";
+        description = lib.mdDoc "Path to DH parameters file.";
       };
 
       proxyResolveWhileRunning = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Resolves domains of proxyPass targets at runtime
           and not only at start, you have to set
           services.nginx.resolver, too.
@@ -653,7 +684,7 @@ in
       mapHashBucketSize = mkOption {
         type = types.nullOr (types.enum [ 32 64 128 ]);
         default = null;
-        description = ''
+        description = lib.mdDoc ''
             Sets the bucket size for the map variables hash tables. Default
             value depends on the processor’s cache line size.
           '';
@@ -662,7 +693,7 @@ in
       mapHashMaxSize = mkOption {
         type = types.nullOr types.ints.positive;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
             Sets the maximum size of the map variables hash tables.
           '';
       };
@@ -670,7 +701,7 @@ in
       serverNamesHashBucketSize = mkOption {
         type = types.nullOr types.ints.positive;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
             Sets the bucket size for the server names hash tables. Default
             value depends on the processor’s cache line size.
           '';
@@ -679,11 +710,77 @@ in
       serverNamesHashMaxSize = mkOption {
         type = types.nullOr types.ints.positive;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
             Sets the maximum size of the server names hash tables.
           '';
       };
 
+      proxyCache = mkOption {
+        type = types.submodule {
+          options = {
+            enable = mkEnableOption (lib.mdDoc "Enable proxy cache");
+
+            keysZoneName = mkOption {
+              type = types.str;
+              default = "cache";
+              example = "my_cache";
+              description = lib.mdDoc "Set name to shared memory zone.";
+            };
+
+            keysZoneSize = mkOption {
+              type = types.str;
+              default = "10m";
+              example = "32m";
+              description = lib.mdDoc "Set size to shared memory zone.";
+            };
+
+            levels = mkOption {
+              type = types.str;
+              default = "1:2";
+              example = "1:2:2";
+              description = lib.mdDoc ''
+                The levels parameter defines structure of subdirectories in cache: from
+                1 to 3, each level accepts values 1 or 2. Сan be used any combination of
+                1 and 2 in these formats: x, x:x and x:x:x.
+              '';
+            };
+
+            useTempPath = mkOption {
+              type = types.bool;
+              default = false;
+              example = true;
+              description = lib.mdDoc ''
+                Nginx first writes files that are destined for the cache to a temporary
+                storage area, and the use_temp_path=off directive instructs Nginx to
+                write them to the same directories where they will be cached. Recommended
+                that you set this parameter to off to avoid unnecessary copying of data
+                between file systems.
+              '';
+            };
+
+            inactive = mkOption {
+              type = types.str;
+              default = "10m";
+              example = "1d";
+              description = lib.mdDoc ''
+                Cached data that has not been accessed for the time specified by
+                the inactive parameter is removed from the cache, regardless of
+                its freshness.
+              '';
+            };
+
+            maxSize = mkOption {
+              type = types.str;
+              default = "1g";
+              example = "2048m";
+              description = lib.mdDoc "Set maximum cache size";
+            };
+          };
+        };
+        default = {};
+        description = lib.mdDoc "Configure proxy cache";
+      };
+
       resolver = mkOption {
         type = types.submodule {
           options = {
@@ -691,13 +788,13 @@ in
               type = types.listOf types.str;
               default = [];
               example = literalExpression ''[ "[::1]" "127.0.0.1:5353" ]'';
-              description = "List of resolvers to use";
+              description = lib.mdDoc "List of resolvers to use";
             };
             valid = mkOption {
               type = types.str;
               default = "";
               example = "30s";
-              description = ''
+              description = lib.mdDoc ''
                 By default, nginx caches answers using the TTL value of a response.
                 An optional valid parameter allows overriding it
               '';
@@ -705,7 +802,7 @@ in
             ipv6 = mkOption {
               type = types.bool;
               default = true;
-              description = ''
+              description = lib.mdDoc ''
                 By default, nginx will look up both IPv4 and IPv6 addresses while resolving.
                 If looking up of IPv6 addresses is not desired, the ipv6=off parameter can be
                 specified.
@@ -713,7 +810,7 @@ in
             };
           };
         };
-        description = ''
+        description = lib.mdDoc ''
           Configures name servers used to resolve names of upstream servers into addresses
         '';
         default = {};
@@ -728,14 +825,14 @@ in
                   backup = mkOption {
                     type = types.bool;
                     default = false;
-                    description = ''
+                    description = lib.mdDoc ''
                       Marks the server as a backup server. It will be passed
                       requests when the primary servers are unavailable.
                     '';
                   };
                 };
               });
-              description = ''
+              description = lib.mdDoc ''
                 Defines the address and other parameters of the upstream servers.
               '';
               default = {};
@@ -744,13 +841,13 @@ in
             extraConfig = mkOption {
               type = types.lines;
               default = "";
-              description = ''
+              description = lib.mdDoc ''
                 These lines go to the end of the upstream verbatim.
               '';
             };
           };
         });
-        description = ''
+        description = lib.mdDoc ''
           Defines a group of servers to use as proxy target.
         '';
         default = {};
@@ -782,7 +879,7 @@ in
             };
           };
         '';
-        description = "Declarative vhost config";
+        description = lib.mdDoc "Declarative vhost config";
       };
     };
   };
@@ -925,7 +1022,7 @@ in
         # System Call Filtering
         SystemCallArchitectures = "native";
         SystemCallFilter = [ "~@cpu-emulation @debug @keyring @mount @obsolete @privileged @setuid" ]
-          ++ optionals ((cfg.package != pkgs.tengine) && (!lib.any (mod: (mod.disableIPC or false)) cfg.package.modules)) [ "~@ipc" ];
+          ++ optionals ((cfg.package != pkgs.tengine) && (cfg.package != pkgs.openresty) && (!lib.any (mod: (mod.disableIPC or false)) cfg.package.modules)) [ "~@ipc" ];
       };
     };
 
@@ -989,17 +1086,14 @@ in
       nginx.gid = config.ids.gids.nginx;
     };
 
-    services.logrotate.paths.nginx = mapAttrs (_: mkDefault) {
-      path = "/var/log/nginx/*.log";
+    services.logrotate.settings.nginx = mapAttrs (_: mkDefault) {
+      files = "/var/log/nginx/*.log";
       frequency = "weekly";
-      keep = 26;
-      extraConfig = ''
-        compress
-        delaycompress
-        postrotate
-          [ ! -f /var/run/nginx/nginx.pid ] || kill -USR1 `cat /var/run/nginx/nginx.pid`
-        endscript
-      '';
+      su = "${cfg.user} ${cfg.group}";
+      rotate = 26;
+      compress = true;
+      delaycompress = true;
+      postrotate = "[ ! -f /var/run/nginx/nginx.pid ] || kill -USR1 `cat /var/run/nginx/nginx.pid`";
     };
   };
 }
diff --git a/nixos/modules/services/web-servers/nginx/gitweb.nix b/nixos/modules/services/web-servers/nginx/gitweb.nix
index db45577a46d..ec2c432ca57 100644
--- a/nixos/modules/services/web-servers/nginx/gitweb.nix
+++ b/nixos/modules/services/web-servers/nginx/gitweb.nix
@@ -17,7 +17,7 @@ in
     enable = mkOption {
       default = false;
       type = types.bool;
-      description = ''
+      description = lib.mdDoc ''
         If true, enable gitweb in nginx.
       '';
     };
@@ -25,7 +25,7 @@ in
     location = mkOption {
       default = "/gitweb";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Location to serve gitweb on.
       '';
     };
@@ -33,7 +33,7 @@ in
     user = mkOption {
       default = "nginx";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         Existing user that the CGI process will belong to. (Default almost surely will do.)
       '';
     };
@@ -41,15 +41,15 @@ in
     group = mkOption {
       default = "nginx";
       type = types.str;
-      description = ''
-        Group that the CGI process will belong to. (Set to <literal>config.services.gitolite.group</literal> if you are using gitolite.)
+      description = lib.mdDoc ''
+        Group that the CGI process will belong to. (Set to `config.services.gitolite.group` if you are using gitolite.)
       '';
     };
 
     virtualHost = mkOption {
       default = "_";
       type = types.str;
-      description = ''
+      description = lib.mdDoc ''
         VirtualHost to serve gitweb on. Default is catch-all.
       '';
     };
diff --git a/nixos/modules/services/web-servers/nginx/location-options.nix b/nixos/modules/services/web-servers/nginx/location-options.nix
index 6fd00b38697..2728852058e 100644
--- a/nixos/modules/services/web-servers/nginx/location-options.nix
+++ b/nixos/modules/services/web-servers/nginx/location-options.nix
@@ -3,7 +3,7 @@
 # has additional options that affect the web server as a whole, like
 # the user/group to run under.)
 
-{ lib }:
+{ lib, config }:
 
 with lib;
 
@@ -17,7 +17,7 @@ with lib;
           user = "password";
         };
       '';
-      description = ''
+      description = lib.mdDoc ''
         Basic Auth protection for a vhost.
 
         WARNING: This is implemented to store the password in plain text in the
@@ -28,9 +28,9 @@ with lib;
     basicAuthFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Basic Auth password file for a vhost.
-        Can be created via: <command>htpasswd -c &lt;filename&gt; &lt;username&gt;</command>.
+        Can be created via: {command}`htpasswd -c <filename> <username>`.
 
         WARNING: The generate file contains the users' passwords in a
         non-cryptographically-securely hashed way.
@@ -41,7 +41,7 @@ with lib;
       type = types.nullOr types.str;
       default = null;
       example = "http://www.example.org/";
-      description = ''
+      description = lib.mdDoc ''
         Adds proxy_pass directive and sets recommended proxy headers if
         recommendedProxySettings is enabled.
       '';
@@ -51,7 +51,7 @@ with lib;
       type = types.bool;
       default = false;
       example = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to support proxying websocket connections with HTTP/1.1.
       '';
     };
@@ -60,7 +60,7 @@ with lib;
       type = types.nullOr types.str;
       default = null;
       example = "index.php index.html";
-      description = ''
+      description = lib.mdDoc ''
         Adds index directive.
       '';
     };
@@ -69,7 +69,7 @@ with lib;
       type = types.nullOr types.str;
       default = null;
       example = "$uri =404";
-      description = ''
+      description = lib.mdDoc ''
         Adds try_files directive.
       '';
     };
@@ -78,7 +78,7 @@ with lib;
       type = types.nullOr types.path;
       default = null;
       example = "/your/root/directory";
-      description = ''
+      description = lib.mdDoc ''
         Root directory for requests.
       '';
     };
@@ -87,7 +87,7 @@ with lib;
       type = types.nullOr types.path;
       default = null;
       example = "/your/alias/directory";
-      description = ''
+      description = lib.mdDoc ''
         Alias directory for requests.
       '';
     };
@@ -96,7 +96,7 @@ with lib;
       type = types.nullOr types.str;
       default = null;
       example = "301 http://example.com$request_uri";
-      description = ''
+      description = lib.mdDoc ''
         Adds a return directive, for e.g. redirections.
       '';
     };
@@ -104,7 +104,7 @@ with lib;
     fastcgiParams = mkOption {
       type = types.attrsOf (types.either types.str types.path);
       default = {};
-      description = ''
+      description = lib.mdDoc ''
         FastCGI parameters to override.  Unlike in the Nginx
         configuration file, overriding only some default parameters
         won't unset the default values for other parameters.
@@ -114,7 +114,7 @@ with lib;
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         These lines go to the end of the location verbatim.
       '';
     };
@@ -122,11 +122,20 @@ with lib;
     priority = mkOption {
       type = types.int;
       default = 1000;
-      description = ''
+      description = lib.mdDoc ''
         Order of this location block in relation to the others in the vhost.
         The semantics are the same as with `lib.mkOrder`. Smaller values have
         a greater priority.
       '';
     };
+
+    recommendedProxySettings = mkOption {
+      type = types.bool;
+      default = config.services.nginx.recommendedProxySettings;
+      defaultText = literalExpression "config.services.nginx.recommendedProxySettings";
+      description = lib.mdDoc ''
+        Enable recommended proxy settings.
+      '';
+    };
   };
 }
diff --git a/nixos/modules/services/web-servers/nginx/vhost-options.nix b/nixos/modules/services/web-servers/nginx/vhost-options.nix
index c4e8285dc48..e3d4afc074c 100644
--- a/nixos/modules/services/web-servers/nginx/vhost-options.nix
+++ b/nixos/modules/services/web-servers/nginx/vhost-options.nix
@@ -11,7 +11,7 @@ with lib;
     serverName = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Name of this virtual host. Defaults to attribute name in virtualHosts.
       '';
       example = "example.org";
@@ -20,75 +20,75 @@ with lib;
     serverAliases = mkOption {
       type = types.listOf types.str;
       default = [];
-      example = ["www.example.org" "example.org"];
-      description = ''
+      example = [ "www.example.org" "example.org" ];
+      description = lib.mdDoc ''
         Additional names of virtual hosts served by this virtual host configuration.
       '';
     };
 
     listen = mkOption {
       type = with types; listOf (submodule { options = {
-        addr = mkOption { type = str;  description = "IP address.";  };
-        port = mkOption { type = int;  description = "Port number."; default = 80; };
-        ssl  = mkOption { type = bool; description = "Enable SSL.";  default = false; };
-        extraParameters = mkOption { type = listOf str; description = "Extra parameters of this listen directive."; default = []; example = [ "reuseport" "deferred" ]; };
+        addr = mkOption { type = str;  description = lib.mdDoc "IP address.";  };
+        port = mkOption { type = int;  description = lib.mdDoc "Port number."; default = 80; };
+        ssl  = mkOption { type = bool; description = lib.mdDoc "Enable SSL.";  default = false; };
+        extraParameters = mkOption { type = listOf str; description = lib.mdDoc "Extra parameters of this listen directive."; default = []; example = [ "backlog=1024" "deferred" ]; };
       }; });
       default = [];
       example = [
-        { addr = "195.154.1.1"; port = 443; ssl = true;}
+        { addr = "195.154.1.1"; port = 443; ssl = true; }
         { addr = "192.154.1.1"; port = 80; }
       ];
-      description = ''
+      description = lib.mdDoc ''
         Listen addresses and ports for this virtual host.
         IPv6 addresses must be enclosed in square brackets.
-        Note: this option overrides <literal>addSSL</literal>
-        and <literal>onlySSL</literal>.
+        Note: this option overrides `addSSL`
+        and `onlySSL`.
 
         If you only want to set the addresses manually and not
-        the ports, take a look at <literal>listenAddresses</literal>
+        the ports, take a look at `listenAddresses`
       '';
     };
 
     listenAddresses = mkOption {
       type = with types; listOf str;
 
-      description = ''
+      description = lib.mdDoc ''
         Listen addresses for this virtual host.
-        Compared to <literal>listen</literal> this only sets the addreses
+        Compared to `listen` this only sets the addreses
         and the ports are choosen automatically.
 
-        Note: This option overrides <literal>enableIPv6</literal>
+        Note: This option overrides `enableIPv6`
       '';
       default = [];
-      example = [ "127.0.0.1" "::1" ];
+      example = [ "127.0.0.1" "[::1]" ];
     };
 
     enableACME = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to ask Let's Encrypt to sign a certificate for this vhost.
-        Alternately, you can use an existing certificate through <option>useACMEHost</option>.
+        Alternately, you can use an existing certificate through {option}`useACMEHost`.
       '';
     };
 
     useACMEHost = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         A host of an existing Let's Encrypt certificate to use.
         This is useful if you have many subdomains and want to avoid hitting the
-        <link xlink:href="https://letsencrypt.org/docs/rate-limits/">rate limit</link>.
-        Alternately, you can generate a certificate through <option>enableACME</option>.
-        <emphasis>Note that this option does not create any certificates, nor it does add subdomains to existing ones – you will need to create them manually using  <xref linkend="opt-security.acme.certs"/>.</emphasis>
+        [rate limit](https://letsencrypt.org/docs/rate-limits).
+        Alternately, you can generate a certificate through {option}`enableACME`.
+        *Note that this option does not create any certificates, nor it does add subdomains to existing ones – you will need to create them manually using [](#opt-security.acme.certs).*
       '';
     };
 
     acmeRoot = mkOption {
       type = types.nullOr types.str;
       default = "/var/lib/acme/acme-challenge";
-      description = ''
-        Directory for the acme challenge which is PUBLIC, don't put certs or keys in here.
+      description = lib.mdDoc ''
+        Directory for the ACME challenge, which is **public**. Don't put certs or keys in here.
         Set to null to inherit from config.security.acme.
       '';
     };
@@ -96,18 +96,22 @@ with lib;
     acmeFallbackHost = mkOption {
       type = types.nullOr types.str;
       default = null;
-      description = ''
-        Host which to proxy requests to if acme challenge is not found. Useful
+      description = lib.mdDoc ''
+        Host which to proxy requests to if ACME challenge is not found. Useful
         if you want multiple hosts to be able to verify the same domain name.
+
+        With this option, you could request certificates for the present domain
+        with an ACME client that is running on another host, which you would
+        specify here.
       '';
     };
 
     addSSL = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable HTTPS in addition to plain HTTP. This will set defaults for
-        <literal>listen</literal> to listen on all interfaces on the respective default
+        `listen` to listen on all interfaces on the respective default
         ports (80, 443).
       '';
     };
@@ -115,9 +119,9 @@ with lib;
     onlySSL = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable HTTPS and reject plain HTTP connections. This will set
-        defaults for <literal>listen</literal> to listen on all interfaces on port 443.
+        defaults for `listen` to listen on all interfaces on port 443.
       '';
     };
 
@@ -130,10 +134,10 @@ with lib;
     forceSSL = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to add a separate nginx server block that permanently redirects (301)
         all plain HTTP traffic to HTTPS. This will set defaults for
-        <literal>listen</literal> to listen on all interfaces on the respective default
+        `listen` to listen on all interfaces on the respective default
         ports (80, 443), where the non-SSL listens are used for the redirect vhosts.
       '';
     };
@@ -141,11 +145,11 @@ with lib;
     rejectSSL = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to listen for and reject all HTTPS connections to this vhost. Useful in
-        <link linkend="opt-services.nginx.virtualHosts._name_.default">default</link>
+        [default](#opt-services.nginx.virtualHosts._name_.default)
         server blocks to avoid serving the certificate for another vhost. Uses the
-        <literal>ssl_reject_handshake</literal> directive available in nginx versions
+        `ssl_reject_handshake` directive available in nginx versions
         1.19.4 and above.
       '';
     };
@@ -153,7 +157,7 @@ with lib;
     kTLS = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable kTLS support.
         Implementing TLS in the kernel (kTLS) improves performance by significantly
         reducing the need for copying operations between user space and the kernel.
@@ -164,26 +168,26 @@ with lib;
     sslCertificate = mkOption {
       type = types.path;
       example = "/var/host.cert";
-      description = "Path to server SSL certificate.";
+      description = lib.mdDoc "Path to server SSL certificate.";
     };
 
     sslCertificateKey = mkOption {
       type = types.path;
       example = "/var/host.key";
-      description = "Path to server SSL certificate key.";
+      description = lib.mdDoc "Path to server SSL certificate key.";
     };
 
     sslTrustedCertificate = mkOption {
       type = types.nullOr types.path;
       default = null;
       example = literalExpression ''"''${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"'';
-      description = "Path to root SSL certificate for stapling and client certificates.";
+      description = lib.mdDoc "Path to root SSL certificate for stapling and client certificates.";
     };
 
     http2 = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable HTTP 2.
         Note that (as of writing) due to nginx's implementation, to disable
         HTTP 2 you have to disable it on all vhosts that use a given
@@ -197,21 +201,30 @@ with lib;
     http3 = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether to enable HTTP 3.
-        This requires using <literal>pkgs.nginxQuic</literal> package
-        which can be achieved by setting <literal>services.nginx.package = pkgs.nginxQuic;</literal>.
+        This requires using `pkgs.nginxQuic` package
+        which can be achieved by setting `services.nginx.package = pkgs.nginxQuic;`.
         Note that HTTP 3 support is experimental and
         *not* yet recommended for production.
         Read more at https://quic.nginx.org/
       '';
     };
 
+    reuseport = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Create an individual listening socket .
+        It is required to specify only once on one of the hosts.
+      '';
+    };
+
     root = mkOption {
       type = types.nullOr types.path;
       default = null;
       example = "/data/webserver/docs";
-      description = ''
+      description = lib.mdDoc ''
         The path of the web root directory.
       '';
     };
@@ -219,7 +232,7 @@ with lib;
     default = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Makes this vhost the default.
       '';
     };
@@ -227,7 +240,7 @@ with lib;
     extraConfig = mkOption {
       type = types.lines;
       default = "";
-      description = ''
+      description = lib.mdDoc ''
         These lines go to the end of the vhost verbatim.
       '';
     };
@@ -236,7 +249,7 @@ with lib;
       type = types.nullOr types.str;
       default = null;
       example = "newserver.example.org";
-      description = ''
+      description = lib.mdDoc ''
         If set, all requests for this host are redirected permanently to
         the given hostname.
       '';
@@ -250,7 +263,7 @@ with lib;
           user = "password";
         };
       '';
-      description = ''
+      description = lib.mdDoc ''
         Basic Auth protection for a vhost.
 
         WARNING: This is implemented to store the password in plain text in the
@@ -261,9 +274,9 @@ with lib;
     basicAuthFile = mkOption {
       type = types.nullOr types.path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Basic Auth password file for a vhost.
-        Can be created via: <command>htpasswd -c &lt;filename&gt; &lt;username&gt;</command>.
+        Can be created via: {command}`htpasswd -c <filename> <username>`.
 
         WARNING: The generate file contains the users' passwords in a
         non-cryptographically-securely hashed way.
@@ -272,7 +285,7 @@ with lib;
 
     locations = mkOption {
       type = types.attrsOf (types.submodule (import ./location-options.nix {
-        inherit lib;
+        inherit lib config;
       }));
       default = {};
       example = literalExpression ''
@@ -282,7 +295,7 @@ with lib;
           };
         };
       '';
-      description = "Declarative location config";
+      description = lib.mdDoc "Declarative location config";
     };
   };
 }
diff --git a/nixos/modules/services/web-servers/phpfpm/default.nix b/nixos/modules/services/web-servers/phpfpm/default.nix
index 87c68fa074a..0bd1d5b29b3 100644
--- a/nixos/modules/services/web-servers/phpfpm/default.nix
+++ b/nixos/modules/services/web-servers/phpfpm/default.nix
@@ -40,9 +40,12 @@ let
         socket = mkOption {
           type = types.str;
           readOnly = true;
-          description = ''
+          description = lib.mdDoc ''
             Path to the unix socket file on which to accept FastCGI requests.
-            <note><para>This option is read-only and managed by NixOS.</para></note>
+
+            ::: {.note}
+            This option is read-only and managed by NixOS.
+            :::
           '';
           example = "${runtimeDir}/<name>.sock";
         };
@@ -51,7 +54,7 @@ let
           type = types.str;
           default = "";
           example = "/path/to/unix/socket";
-          description = ''
+          description = lib.mdDoc ''
             The address on which to accept FastCGI requests.
           '';
         };
@@ -60,22 +63,22 @@ let
           type = types.package;
           default = cfg.phpPackage;
           defaultText = literalExpression "config.services.phpfpm.phpPackage";
-          description = ''
+          description = lib.mdDoc ''
             The PHP package to use for running this PHP-FPM pool.
           '';
         };
 
         phpOptions = mkOption {
           type = types.lines;
-          description = ''
-            "Options appended to the PHP configuration file <filename>php.ini</filename> used for this PHP-FPM pool."
+          description = lib.mdDoc ''
+            "Options appended to the PHP configuration file {file}`php.ini` used for this PHP-FPM pool."
           '';
         };
 
         phpEnv = lib.mkOption {
           type = with types; attrsOf str;
           default = {};
-          description = ''
+          description = lib.mdDoc ''
             Environment variables used for this PHP-FPM pool.
           '';
           example = literalExpression ''
@@ -90,22 +93,22 @@ let
 
         user = mkOption {
           type = types.str;
-          description = "User account under which this pool runs.";
+          description = lib.mdDoc "User account under which this pool runs.";
         };
 
         group = mkOption {
           type = types.str;
-          description = "Group account under which this pool runs.";
+          description = lib.mdDoc "Group account under which this pool runs.";
         };
 
         settings = mkOption {
           type = with types; attrsOf (oneOf [ str int bool ]);
           default = {};
-          description = ''
+          description = lib.mdDoc ''
             PHP-FPM pool directives. Refer to the "List of pool directives" section of
-            <link xlink:href="https://www.php.net/manual/en/install.fpm.configuration.php"/>
+            <https://www.php.net/manual/en/install.fpm.configuration.php>
             for details. Note that settings names must be enclosed in quotes (e.g.
-            <literal>"pm.max_children"</literal> instead of <literal>pm.max_children</literal>).
+            `"pm.max_children"` instead of `pm.max_children`).
           '';
           example = literalExpression ''
             {
@@ -122,9 +125,9 @@ let
         extraConfig = mkOption {
           type = with types; nullOr lines;
           default = null;
-          description = ''
+          description = lib.mdDoc ''
             Extra lines that go into the pool configuration.
-            See the documentation on <literal>php-fpm.conf</literal> for
+            See the documentation on `php-fpm.conf` for
             details on configuration directives.
           '';
         };
@@ -154,24 +157,24 @@ in {
       settings = mkOption {
         type = with types; attrsOf (oneOf [ str int bool ]);
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           PHP-FPM global directives. Refer to the "List of global php-fpm.conf directives" section of
-          <link xlink:href="https://www.php.net/manual/en/install.fpm.configuration.php"/>
+          <https://www.php.net/manual/en/install.fpm.configuration.php>
           for details. Note that settings names must be enclosed in quotes (e.g.
-          <literal>"pm.max_children"</literal> instead of <literal>pm.max_children</literal>).
-          You need not specify the options <literal>error_log</literal> or
-          <literal>daemonize</literal> here, since they are generated by NixOS.
+          `"pm.max_children"` instead of `pm.max_children`).
+          You need not specify the options `error_log` or
+          `daemonize` here, since they are generated by NixOS.
         '';
       };
 
       extraConfig = mkOption {
         type = with types; nullOr lines;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration that should be put in the global section of
           the PHP-FPM configuration file. Do not specify the options
-          <literal>error_log</literal> or
-          <literal>daemonize</literal> here, since they are generated by
+          `error_log` or
+          `daemonize` here, since they are generated by
           NixOS.
         '';
       };
@@ -180,7 +183,7 @@ in {
         type = types.package;
         default = pkgs.php;
         defaultText = literalExpression "pkgs.php";
-        description = ''
+        description = lib.mdDoc ''
           The PHP package to use for running the PHP-FPM service.
         '';
       };
@@ -192,8 +195,8 @@ in {
           ''
             date.timezone = "CET"
           '';
-        description = ''
-          Options appended to the PHP configuration file <filename>php.ini</filename>.
+        description = lib.mdDoc ''
+          Options appended to the PHP configuration file {file}`php.ini`.
         '';
       };
 
@@ -216,7 +219,7 @@ in {
              };
            }
          }'';
-        description = ''
+        description = lib.mdDoc ''
           PHP-FPM pools. If no pools are defined, the PHP-FPM
           service is disabled.
         '';
diff --git a/nixos/modules/services/web-servers/pomerium.nix b/nixos/modules/services/web-servers/pomerium.nix
index 0b460755f50..90748f74d24 100644
--- a/nixos/modules/services/web-servers/pomerium.nix
+++ b/nixos/modules/services/web-servers/pomerium.nix
@@ -7,18 +7,18 @@ let
 in
 {
   options.services.pomerium = {
-    enable = mkEnableOption "the Pomerium authenticating reverse proxy";
+    enable = mkEnableOption (lib.mdDoc "the Pomerium authenticating reverse proxy");
 
     configFile = mkOption {
       type = with types; nullOr path;
       default = null;
-      description = "Path to Pomerium config YAML. If set, overrides services.pomerium.settings.";
+      description = lib.mdDoc "Path to Pomerium config YAML. If set, overrides services.pomerium.settings.";
     };
 
     useACMEHost = mkOption {
       type = with types; nullOr str;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         If set, use a NixOS-generated ACME certificate with the specified name.
 
         Note that this will require you to use a non-HTTP-based challenge, or
@@ -32,13 +32,13 @@ in
     };
 
     settings = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         The contents of Pomerium's config.yaml, in Nix expressions.
 
         Specifying configFile will override this in its entirety.
 
-        See <link xlink:href="https://pomerium.io/reference/">the Pomerium
-        configuration reference</link> for more information about what to put
+        See [the Pomerium
+        configuration reference](https://pomerium.io/reference/) for more information about what to put
         here.
       '';
       default = {};
@@ -48,7 +48,7 @@ in
     secretsFile = mkOption {
       type = with types; nullOr path;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Path to file containing secrets for Pomerium, in systemd
         EnvironmentFile format. See the systemd.exec(5) man page.
       '';
diff --git a/nixos/modules/services/web-servers/tomcat.nix b/nixos/modules/services/web-servers/tomcat.nix
index 877097cf378..d8bfee547c7 100644
--- a/nixos/modules/services/web-servers/tomcat.nix
+++ b/nixos/modules/services/web-servers/tomcat.nix
@@ -19,14 +19,14 @@ in
   options = {
 
     services.tomcat = {
-      enable = mkEnableOption "Apache Tomcat";
+      enable = mkEnableOption (lib.mdDoc "Apache Tomcat");
 
       package = mkOption {
         type = types.package;
         default = pkgs.tomcat9;
         defaultText = literalExpression "pkgs.tomcat9";
         example = lib.literalExpression "pkgs.tomcat9";
-        description = ''
+        description = lib.mdDoc ''
           Which tomcat package to use.
         '';
       };
@@ -34,7 +34,7 @@ in
       purifyOnStart = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           On startup, the `baseDir` directory is populated with various files,
           subdirectories and symlinks. If this option is enabled, these items
           (except for the `logs` and `work` subdirectories) are first removed.
@@ -46,7 +46,7 @@ in
       baseDir = mkOption {
         type = lib.types.path;
         default = "/var/tomcat";
-        description = ''
+        description = lib.mdDoc ''
           Location where Tomcat stores configuration files, web applications
           and logfiles. Note that it is partially cleared on each service startup
           if `purifyOnStart` is enabled.
@@ -56,79 +56,79 @@ in
       logDirs = mkOption {
         default = [];
         type = types.listOf types.path;
-        description = "Directories to create in baseDir/logs/";
+        description = lib.mdDoc "Directories to create in baseDir/logs/";
       };
 
       extraConfigFiles = mkOption {
         default = [];
         type = types.listOf types.path;
-        description = "Extra configuration files to pull into the tomcat conf directory";
+        description = lib.mdDoc "Extra configuration files to pull into the tomcat conf directory";
       };
 
       extraEnvironment = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "ENVIRONMENT=production" ];
-        description = "Environment Variables to pass to the tomcat service";
+        description = lib.mdDoc "Environment Variables to pass to the tomcat service";
       };
 
       extraGroups = mkOption {
         default = [];
         type = types.listOf types.str;
         example = [ "users" ];
-        description = "Defines extra groups to which the tomcat user belongs.";
+        description = lib.mdDoc "Defines extra groups to which the tomcat user belongs.";
       };
 
       user = mkOption {
         type = types.str;
         default = "tomcat";
-        description = "User account under which Apache Tomcat runs.";
+        description = lib.mdDoc "User account under which Apache Tomcat runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "tomcat";
-        description = "Group account under which Apache Tomcat runs.";
+        description = lib.mdDoc "Group account under which Apache Tomcat runs.";
       };
 
       javaOpts = mkOption {
         type = types.either (types.listOf types.str) types.str;
         default = "";
-        description = "Parameters to pass to the Java Virtual Machine which spawns Apache Tomcat";
+        description = lib.mdDoc "Parameters to pass to the Java Virtual Machine which spawns Apache Tomcat";
       };
 
       catalinaOpts = mkOption {
         type = types.either (types.listOf types.str) types.str;
         default = "";
-        description = "Parameters to pass to the Java Virtual Machine which spawns the Catalina servlet container";
+        description = lib.mdDoc "Parameters to pass to the Java Virtual Machine which spawns the Catalina servlet container";
       };
 
       sharedLibs = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "List containing JAR files or directories with JAR files which are libraries shared by the web applications";
+        description = lib.mdDoc "List containing JAR files or directories with JAR files which are libraries shared by the web applications";
       };
 
       serverXml = mkOption {
         type = types.lines;
         default = "";
-        description = "
+        description = lib.mdDoc ''
           Verbatim server.xml configuration.
           This is mutually exclusive with the virtualHosts options.
-        ";
+        '';
       };
 
       commonLibs = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "List containing JAR files or directories with JAR files which are libraries shared by the web applications and the servlet container";
+        description = lib.mdDoc "List containing JAR files or directories with JAR files which are libraries shared by the web applications and the servlet container";
       };
 
       webapps = mkOption {
         type = types.listOf types.path;
         default = [ tomcat.webapps ];
         defaultText = literalExpression "[ config.services.tomcat.package.webapps ]";
-        description = "List containing WAR files or directories with WAR files which are web applications to be deployed on Tomcat";
+        description = lib.mdDoc "List containing WAR files or directories with WAR files which are web applications to be deployed on Tomcat";
       };
 
       virtualHosts = mkOption {
@@ -136,16 +136,16 @@ in
           options = {
             name = mkOption {
               type = types.str;
-              description = "name of the virtualhost";
+              description = lib.mdDoc "name of the virtualhost";
             };
             aliases = mkOption {
               type = types.listOf types.str;
-              description = "aliases of the virtualhost";
+              description = lib.mdDoc "aliases of the virtualhost";
               default = [];
             };
             webapps = mkOption {
               type = types.listOf types.path;
-              description = ''
+              description = lib.mdDoc ''
                 List containing web application WAR files and/or directories containing
                 web applications and configuration files for the virtual host.
               '';
@@ -154,20 +154,20 @@ in
           };
         });
         default = [];
-        description = "List consisting of a virtual host name and a list of web applications to deploy on each virtual host";
+        description = lib.mdDoc "List consisting of a virtual host name and a list of web applications to deploy on each virtual host";
       };
 
       logPerVirtualHost = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable logging per virtual host.";
+        description = lib.mdDoc "Whether to enable logging per virtual host.";
       };
 
       jdk = mkOption {
         type = types.package;
         default = pkgs.jdk;
         defaultText = literalExpression "pkgs.jdk";
-        description = "Which JDK to use.";
+        description = lib.mdDoc "Which JDK to use.";
       };
 
       axis2 = {
@@ -175,13 +175,13 @@ in
         enable = mkOption {
           default = false;
           type = types.bool;
-          description = "Whether to enable an Apache Axis2 container";
+          description = lib.mdDoc "Whether to enable an Apache Axis2 container";
         };
 
         services = mkOption {
           default = [];
           type = types.listOf types.str;
-          description = "List containing AAR files or directories with AAR files which are web services to be deployed on Axis2";
+          description = lib.mdDoc "List containing AAR files or directories with AAR files which are web services to be deployed on Axis2";
         };
 
       };
diff --git a/nixos/modules/services/web-servers/traefik.nix b/nixos/modules/services/web-servers/traefik.nix
index eb7fd0995de..9e5603e0edc 100644
--- a/nixos/modules/services/web-servers/traefik.nix
+++ b/nixos/modules/services/web-servers/traefik.nix
@@ -50,20 +50,20 @@ let
     cfg.staticConfigFile;
 in {
   options.services.traefik = {
-    enable = mkEnableOption "Traefik web server";
+    enable = mkEnableOption (lib.mdDoc "Traefik web server");
 
     staticConfigFile = mkOption {
       default = null;
       example = literalExpression "/path/to/static_config.toml";
       type = types.nullOr types.path;
-      description = ''
+      description = lib.mdDoc ''
         Path to traefik's static configuration to use.
-        (Using that option has precedence over <literal>staticConfigOptions</literal> and <literal>dynamicConfigOptions</literal>)
+        (Using that option has precedence over `staticConfigOptions` and `dynamicConfigOptions`)
       '';
     };
 
     staticConfigOptions = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Static configuration for Traefik.
       '';
       type = jsonValue;
@@ -80,14 +80,14 @@ in {
       default = null;
       example = literalExpression "/path/to/dynamic_config.toml";
       type = types.nullOr types.path;
-      description = ''
+      description = lib.mdDoc ''
         Path to traefik's dynamic configuration to use.
-        (Using that option has precedence over <literal>dynamicConfigOptions</literal>)
+        (Using that option has precedence over `dynamicConfigOptions`)
       '';
     };
 
     dynamicConfigOptions = mkOption {
-      description = ''
+      description = lib.mdDoc ''
         Dynamic configuration for Traefik.
       '';
       type = jsonValue;
@@ -106,7 +106,7 @@ in {
     dataDir = mkOption {
       default = "/var/lib/traefik";
       type = types.path;
-      description = ''
+      description = lib.mdDoc ''
         Location for any persistent data traefik creates, ie. acme
       '';
     };
@@ -115,9 +115,9 @@ in {
       default = "traefik";
       type = types.str;
       example = "docker";
-      description = ''
+      description = lib.mdDoc ''
         Set the group that traefik runs under.
-        For the docker backend this needs to be set to <literal>docker</literal> instead.
+        For the docker backend this needs to be set to `docker` instead.
       '';
     };
 
@@ -125,7 +125,7 @@ in {
       default = pkgs.traefik;
       defaultText = literalExpression "pkgs.traefik";
       type = types.package;
-      description = "Traefik package to use.";
+      description = lib.mdDoc "Traefik package to use.";
     };
   };
 
diff --git a/nixos/modules/services/web-servers/trafficserver/default.nix b/nixos/modules/services/web-servers/trafficserver/default.nix
index b52087fa038..17dece8746a 100644
--- a/nixos/modules/services/web-servers/trafficserver/default.nix
+++ b/nixos/modules/services/web-servers/trafficserver/default.nix
@@ -33,17 +33,17 @@ let
 in
 {
   options.services.trafficserver = {
-    enable = mkEnableOption "Apache Traffic Server";
+    enable = mkEnableOption (lib.mdDoc "Apache Traffic Server");
 
     cache = mkOption {
       type = types.lines;
       default = "";
       example = "dest_domain=example.com suffix=js action=never-cache";
-      description = ''
+      description = lib.mdDoc ''
         Caching rules that overrule the origin's caching policy.
 
-        Consult the <link xlink:href="${getManualUrl "cache.config"}">upstream
-        documentation</link> for more details.
+        Consult the [upstream
+        documentation](${getManualUrl "cache.config"}) for more details.
       '';
     };
 
@@ -51,18 +51,18 @@ in
       type = types.lines;
       default = "";
       example = "domain=example.com volume=1";
-      description = ''
+      description = lib.mdDoc ''
         Partition the cache according to origin server or domain
 
-        Consult the <link xlink:href="${getManualUrl "hosting.config"}">
-        upstream documentation</link> for more details.
+        Consult the [
+        upstream documentation](${getManualUrl "hosting.config"}) for more details.
       '';
     };
 
     ipAllow = mkOption {
       type = types.nullOr yaml.type;
       default = lib.importJSON ./ip_allow.json;
-      defaultText = literalDocBook "upstream defaults";
+      defaultText = literalMD "upstream defaults";
       example = literalExpression ''
         {
           ip_allow = [{
@@ -73,25 +73,25 @@ in
           }];
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Control client access to Traffic Server and Traffic Server connections
         to upstream servers.
 
-        Consult the <link xlink:href="${getManualUrl "ip_allow.yaml"}">upstream
-        documentation</link> for more details.
+        Consult the [upstream
+        documentation](${getManualUrl "ip_allow.yaml"}) for more details.
       '';
     };
 
     logging = mkOption {
       type = types.nullOr yaml.type;
       default = lib.importJSON ./logging.json;
-      defaultText = literalDocBook "upstream defaults";
+      defaultText = literalMD "upstream defaults";
       example = { };
-      description = ''
+      description = lib.mdDoc ''
         Configure logs.
 
-        Consult the <link xlink:href="${getManualUrl "logging.yaml"}">upstream
-        documentation</link> for more details.
+        Consult the [upstream
+        documentation](${getManualUrl "logging.yaml"}) for more details.
       '';
     };
 
@@ -101,23 +101,23 @@ in
       example = ''
         dest_domain=. method=get parent="p1.example:8080; p2.example:8080" round_robin=true
       '';
-      description = ''
+      description = lib.mdDoc ''
         Identify the parent proxies used in an cache hierarchy.
 
-        Consult the <link xlink:href="${getManualUrl "parent.config"}">upstream
-        documentation</link> for more details.
+        Consult the [upstream
+        documentation](${getManualUrl "parent.config"}) for more details.
       '';
     };
 
     plugins = mkOption {
       default = [ ];
 
-      description = ''
+      description = lib.mdDoc ''
         Controls run-time loadable plugins available to Traffic Server, as
         well as their configuration.
 
-        Consult the <link xlink:href="${getManualUrl "plugin.config"}">upstream
-        documentation</link> for more details.
+        Consult the [upstream
+        documentation](${getManualUrl "plugin.config"}) for more details.
       '';
 
       type = with types;
@@ -125,7 +125,7 @@ in
           options.path = mkOption {
             type = str;
             example = "xdebug.so";
-            description = ''
+            description = lib.mdDoc ''
               Path to plugin. The path can either be absolute, or relative to
               the plugin directory.
             '';
@@ -134,7 +134,7 @@ in
             type = str;
             default = "";
             example = "--header=ATS-My-Debug";
-            description = "arguments to pass to the plugin";
+            description = lib.mdDoc "arguments to pass to the plugin";
           };
         });
     };
@@ -148,11 +148,11 @@ in
         valueType;
       default = { };
       example = { proxy.config.proxy_name = "my_server"; };
-      description = ''
+      description = lib.mdDoc ''
         List of configurable variables used by Traffic Server.
 
-        Consult the <link xlink:href="${getManualUrl "records.config"}">
-        upstream documentation</link> for more details.
+        Consult the [
+        upstream documentation](${getManualUrl "records.config"}) for more details.
       '';
     };
 
@@ -160,11 +160,11 @@ in
       type = types.lines;
       default = "";
       example = "map http://from.example http://origin.example";
-      description = ''
+      description = lib.mdDoc ''
         URL remapping rules used by Traffic Server.
 
-        Consult the <link xlink:href="${getManualUrl "remap.config"}">
-        upstream documentation</link> for more details.
+        Consult the [
+        upstream documentation](${getManualUrl "remap.config"}) for more details.
       '';
     };
 
@@ -175,12 +175,12 @@ in
         dest_domain=internal.corp.example named="255.255.255.255:212 255.255.255.254" def_domain=corp.example search_list="corp.example corp1.example"
         dest_domain=!internal.corp.example named=255.255.255.253
       '';
-      description = ''
+      description = lib.mdDoc ''
         Specify the DNS server that Traffic Server should use under specific
         conditions.
 
-        Consult the <link xlink:href="${getManualUrl "splitdns.config"}">
-        upstream documentation</link> for more details.
+        Consult the [
+        upstream documentation](${getManualUrl "splitdns.config"}) for more details.
       '';
     };
 
@@ -188,11 +188,11 @@ in
       type = types.lines;
       default = "";
       example = "dest_ip=* ssl_cert_name=default.pem";
-      description = ''
+      description = lib.mdDoc ''
         Configure SSL server certificates to terminate the SSL sessions.
 
-        Consult the <link xlink:href="${getManualUrl "ssl_multicert.config"}">
-        upstream documentation</link> for more details.
+        Consult the [
+        upstream documentation](${getManualUrl "ssl_multicert.config"}) for more details.
       '';
     };
 
@@ -207,12 +207,12 @@ in
           }];
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Configure aspects of TLS connection handling for both inbound and
         outbound connections.
 
-        Consult the <link xlink:href="${getManualUrl "sni.yaml"}">upstream
-        documentation</link> for more details.
+        Consult the [upstream
+        documentation](${getManualUrl "sni.yaml"}) for more details.
       '';
     };
 
@@ -220,23 +220,23 @@ in
       type = types.lines;
       default = "/var/cache/trafficserver 256M";
       example = "/dev/disk/by-id/XXXXX volume=1";
-      description = ''
+      description = lib.mdDoc ''
         List all the storage that make up the Traffic Server cache.
 
-        Consult the <link xlink:href="${getManualUrl "storage.config"}">
-        upstream documentation</link> for more details.
+        Consult the [
+        upstream documentation](${getManualUrl "storage.config"}) for more details.
       '';
     };
 
     strategies = mkOption {
       type = types.nullOr yaml.type;
       default = null;
-      description = ''
+      description = lib.mdDoc ''
         Specify the next hop proxies used in an cache hierarchy and the
         algorithms used to select the next proxy.
 
-        Consult the <link xlink:href="${getManualUrl "strategies.yaml"}">
-        upstream documentation</link> for more details.
+        Consult the [
+        upstream documentation](${getManualUrl "strategies.yaml"}) for more details.
       '';
     };
 
@@ -244,12 +244,12 @@ in
       type = types.nullOr yaml.type;
       default = "";
       example = "volume=1 scheme=http size=20%";
-      description = ''
+      description = lib.mdDoc ''
         Manage cache space more efficiently and restrict disk usage by
         creating cache volumes of different sizes.
 
-        Consult the <link xlink:href="${getManualUrl "volume.config"}">
-        upstream documentation</link> for more details.
+        Consult the [
+        upstream documentation](${getManualUrl "volume.config"}) for more details.
       '';
     };
   };
diff --git a/nixos/modules/services/web-servers/ttyd.nix b/nixos/modules/services/web-servers/ttyd.nix
index 431509f7fd5..affd5bbeea3 100644
--- a/nixos/modules/services/web-servers/ttyd.nix
+++ b/nixos/modules/services/web-servers/ttyd.nix
@@ -30,49 +30,49 @@ in
 
   options = {
     services.ttyd = {
-      enable = mkEnableOption "ttyd daemon";
+      enable = mkEnableOption (lib.mdDoc "ttyd daemon");
 
       port = mkOption {
         type = types.port;
         default = 7681;
-        description = "Port to listen on (use 0 for random port)";
+        description = lib.mdDoc "Port to listen on (use 0 for random port)";
       };
 
       socket = mkOption {
         type = types.nullOr types.path;
         default = null;
         example = "/var/run/ttyd.sock";
-        description = "UNIX domain socket path to bind.";
+        description = lib.mdDoc "UNIX domain socket path to bind.";
       };
 
       interface = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "eth0";
-        description = "Network interface to bind.";
+        description = lib.mdDoc "Network interface to bind.";
       };
 
       username = mkOption {
         type = types.nullOr types.str;
         default = null;
-        description = "Username for basic authentication.";
+        description = lib.mdDoc "Username for basic authentication.";
       };
 
       passwordFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         apply = value: if value == null then null else toString value;
-        description = ''
+        description = lib.mdDoc ''
           File containing the password to use for basic authentication.
           For insecurely putting the password in the globally readable store use
-          <literal>pkgs.writeText "ttydpw" "MyPassword"</literal>.
+          `pkgs.writeText "ttydpw" "MyPassword"`.
         '';
       };
 
       signal = mkOption {
         type = types.ints.u8;
         default = 1;
-        description = "Signal to send to the command on session close.";
+        description = lib.mdDoc "Signal to send to the command on session close.";
       };
 
       clientOptions = mkOption {
@@ -83,75 +83,75 @@ in
           fontFamily = "Fira Code";
 
         }'';
-        description = ''
+        description = lib.mdDoc ''
           Attribute set of client options for xtermjs.
-          <link xlink:href="https://xtermjs.org/docs/api/terminal/interfaces/iterminaloptions/"/>
+          <https://xtermjs.org/docs/api/terminal/interfaces/iterminaloptions/>
         '';
       };
 
       terminalType = mkOption {
         type = types.str;
         default = "xterm-256color";
-        description = "Terminal type to report.";
+        description = lib.mdDoc "Terminal type to report.";
       };
 
       checkOrigin = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to allow a websocket connection from a different origin.";
+        description = lib.mdDoc "Whether to allow a websocket connection from a different origin.";
       };
 
       maxClients = mkOption {
         type = types.int;
         default = 0;
-        description = "Maximum clients to support (0, no limit)";
+        description = lib.mdDoc "Maximum clients to support (0, no limit)";
       };
 
       indexFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "Custom index.html path";
+        description = lib.mdDoc "Custom index.html path";
       };
 
       enableIPv6 = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether or not to enable IPv6 support.";
+        description = lib.mdDoc "Whether or not to enable IPv6 support.";
       };
 
       enableSSL = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether or not to enable SSL (https) support.";
+        description = lib.mdDoc "Whether or not to enable SSL (https) support.";
       };
 
       certFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "SSL certificate file path.";
+        description = lib.mdDoc "SSL certificate file path.";
       };
 
       keyFile = mkOption {
         type = types.nullOr types.path;
         default = null;
         apply = value: if value == null then null else toString value;
-        description = ''
+        description = lib.mdDoc ''
           SSL key file path.
           For insecurely putting the keyFile in the globally readable store use
-          <literal>pkgs.writeText "ttydKeyFile" "SSLKEY"</literal>.
+          `pkgs.writeText "ttydKeyFile" "SSLKEY"`.
         '';
       };
 
       caFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = "SSL CA file path for client certificate verification.";
+        description = lib.mdDoc "SSL CA file path for client certificate verification.";
       };
 
       logLevel = mkOption {
         type = types.int;
         default = 7;
-        description = "Set log level.";
+        description = lib.mdDoc "Set log level.";
       };
     };
   };
diff --git a/nixos/modules/services/web-servers/unit/default.nix b/nixos/modules/services/web-servers/unit/default.nix
index b2eecdbb53e..0aaac8a14e4 100644
--- a/nixos/modules/services/web-servers/unit/default.nix
+++ b/nixos/modules/services/web-servers/unit/default.nix
@@ -10,32 +10,32 @@ let
 in {
   options = {
     services.unit = {
-      enable = mkEnableOption "Unit App Server";
+      enable = mkEnableOption (lib.mdDoc "Unit App Server");
       package = mkOption {
         type = types.package;
         default = pkgs.unit;
         defaultText = literalExpression "pkgs.unit";
-        description = "Unit package to use.";
+        description = lib.mdDoc "Unit package to use.";
       };
       user = mkOption {
         type = types.str;
         default = "unit";
-        description = "User account under which unit runs.";
+        description = lib.mdDoc "User account under which unit runs.";
       };
       group = mkOption {
         type = types.str;
         default = "unit";
-        description = "Group account under which unit runs.";
+        description = lib.mdDoc "Group account under which unit runs.";
       };
       stateDir = mkOption {
         type = types.path;
         default = "/var/spool/unit";
-        description = "Unit data directory.";
+        description = lib.mdDoc "Unit data directory.";
       };
       logDir = mkOption {
         type = types.path;
         default = "/var/log/unit";
-        description = "Unit log directory.";
+        description = lib.mdDoc "Unit log directory.";
       };
       config = mkOption {
         type = types.str;
@@ -75,7 +75,7 @@ in {
             }
           }
         '';
-        description = "Unit configuration in JSON format. More details here https://unit.nginx.org/configuration";
+        description = lib.mdDoc "Unit configuration in JSON format. More details here https://unit.nginx.org/configuration";
       };
     };
   };
diff --git a/nixos/modules/services/web-servers/uwsgi.nix b/nixos/modules/services/web-servers/uwsgi.nix
index 1b3474f2f52..510582feaae 100644
--- a/nixos/modules/services/web-servers/uwsgi.nix
+++ b/nixos/modules/services/web-servers/uwsgi.nix
@@ -75,13 +75,13 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable uWSGI";
+        description = lib.mdDoc "Enable uWSGI";
       };
 
       runDir = mkOption {
         type = types.path;
         default = "/run/uwsgi";
-        description = "Where uWSGI communication sockets can live";
+        description = lib.mdDoc "Where uWSGI communication sockets can live";
       };
 
       package = mkOption {
@@ -124,37 +124,37 @@ in {
             };
           }
         '';
-        description = ''
-          uWSGI configuration. It awaits an attribute <literal>type</literal> inside which can be either
-          <literal>normal</literal> or <literal>emperor</literal>.
+        description = lib.mdDoc ''
+          uWSGI configuration. It awaits an attribute `type` inside which can be either
+          `normal` or `emperor`.
 
-          For <literal>normal</literal> mode you can specify <literal>pythonPackages</literal> as a function
-          from libraries set into a list of libraries. <literal>pythonpath</literal> will be set accordingly.
+          For `normal` mode you can specify `pythonPackages` as a function
+          from libraries set into a list of libraries. `pythonpath` will be set accordingly.
 
-          For <literal>emperor</literal> mode, you should use <literal>vassals</literal> attribute
+          For `emperor` mode, you should use `vassals` attribute
           which should be either a set of names and configurations or a path to a directory.
 
           Other attributes will be used in configuration file as-is. Notice that you can redefine
-          <literal>plugins</literal> setting here.
+          `plugins` setting here.
         '';
       };
 
       plugins = mkOption {
         type = types.listOf types.str;
         default = [];
-        description = "Plugins used with uWSGI";
+        description = lib.mdDoc "Plugins used with uWSGI";
       };
 
       user = mkOption {
         type = types.str;
         default = "uwsgi";
-        description = "User account under which uWSGI runs.";
+        description = lib.mdDoc "User account under which uWSGI runs.";
       };
 
       group = mkOption {
         type = types.str;
         default = "uwsgi";
-        description = "Group account under which uWSGI runs.";
+        description = lib.mdDoc "Group account under which uWSGI runs.";
       };
 
       capabilities = mkOption {
@@ -167,23 +167,20 @@ in {
             "CAP_NET_RAW"          # open raw sockets
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Grant capabilities to the uWSGI instance. See the
-          <literal>capabilities(7)</literal> for available values.
-          <note>
-            <para>
-              uWSGI runs as an unprivileged user (even as Emperor) with the minimal
-              capabilities required. This option can be used to add fine-grained
-              permissions without running the service as root.
-            </para>
-            <para>
-              When in Emperor mode, any capability to be inherited by a vassal must
-              be specified again in the vassal configuration using <literal>cap</literal>.
-              See the uWSGI <link
-              xlink:href="https://uwsgi-docs.readthedocs.io/en/latest/Capabilities.html">docs</link>
-              for more information.
-            </para>
-          </note>
+          `capabilities(7)` for available values.
+
+          ::: {.note}
+          uWSGI runs as an unprivileged user (even as Emperor) with the minimal
+          capabilities required. This option can be used to add fine-grained
+          permissions without running the service as root.
+
+          When in Emperor mode, any capability to be inherited by a vassal must
+          be specified again in the vassal configuration using `cap`.
+          See the uWSGI [docs](https://uwsgi-docs.readthedocs.io/en/latest/Capabilities.html)
+          for more information.
+          :::
         '';
       };
     };
diff --git a/nixos/modules/services/web-servers/varnish/default.nix b/nixos/modules/services/web-servers/varnish/default.nix
index fe817313a99..e34c22d2868 100644
--- a/nixos/modules/services/web-servers/varnish/default.nix
+++ b/nixos/modules/services/web-servers/varnish/default.nix
@@ -11,15 +11,15 @@ in
 {
   options = {
     services.varnish = {
-      enable = mkEnableOption "Varnish Server";
+      enable = mkEnableOption (lib.mdDoc "Varnish Server");
 
-      enableConfigCheck = mkEnableOption "checking the config during build time" // { default = true; };
+      enableConfigCheck = mkEnableOption (lib.mdDoc "checking the config during build time") // { default = true; };
 
       package = mkOption {
         type = types.package;
         default = pkgs.varnish;
         defaultText = literalExpression "pkgs.varnish";
-        description = ''
+        description = lib.mdDoc ''
           The package to use
         '';
       };
@@ -27,43 +27,43 @@ in
       http_address = mkOption {
         type = types.str;
         default = "*:6081";
-        description = "
+        description = lib.mdDoc ''
           HTTP listen address and port.
-        ";
+        '';
       };
 
       config = mkOption {
         type = types.lines;
-        description = "
+        description = lib.mdDoc ''
           Verbatim default.vcl configuration.
-        ";
+        '';
       };
 
       stateDir = mkOption {
         type = types.path;
         default = "/var/spool/varnish/${config.networking.hostName}";
         defaultText = literalExpression ''"/var/spool/varnish/''${config.networking.hostName}"'';
-        description = "
+        description = lib.mdDoc ''
           Directory holding all state for Varnish to run.
-        ";
+        '';
       };
 
       extraModules = mkOption {
         type = types.listOf types.package;
         default = [];
         example = literalExpression "[ pkgs.varnishPackages.geoip ]";
-        description = "
+        description = lib.mdDoc ''
           Varnish modules (except 'std').
-        ";
+        '';
       };
 
       extraCommandLine = mkOption {
         type = types.str;
         default = "";
         example = "-s malloc,256M";
-        description = "
+        description = lib.mdDoc ''
           Command line switches for varnishd (run 'varnishd -?' to get list of options)
-        ";
+        '';
       };
     };
 
diff --git a/nixos/modules/services/web-servers/zope2.nix b/nixos/modules/services/web-servers/zope2.nix
index 92210916022..a80fe882f1a 100644
--- a/nixos/modules/services/web-servers/zope2.nix
+++ b/nixos/modules/services/web-servers/zope2.nix
@@ -12,31 +12,31 @@ let
       name = mkOption {
         default = "${name}";
         type = types.str;
-        description = "The name of the zope2 instance. If undefined, the name of the attribute set will be used.";
+        description = lib.mdDoc "The name of the zope2 instance. If undefined, the name of the attribute set will be used.";
       };
 
       threads = mkOption {
         default = 2;
         type = types.int;
-        description = "Specify the number of threads that Zope's ZServer web server will use to service requests. ";
+        description = lib.mdDoc "Specify the number of threads that Zope's ZServer web server will use to service requests. ";
       };
 
       http_address = mkOption {
         default = "localhost:8080";
         type = types.str;
-        description = "Give a port and address for the HTTP server.";
+        description = lib.mdDoc "Give a port and address for the HTTP server.";
       };
 
       user = mkOption {
         default = "zope2";
         type = types.str;
-        description = "The name of the effective user for the Zope process.";
+        description = lib.mdDoc "The name of the effective user for the Zope process.";
       };
 
       clientHome = mkOption {
         default = "/var/lib/zope2/${name}";
         type = types.path;
-        description = "Home directory of zope2 instance.";
+        description = lib.mdDoc "Home directory of zope2 instance.";
       };
       extra = mkOption {
         default =
@@ -53,12 +53,12 @@ let
           </zodb_db>
           '';
         type = types.lines;
-        description = "Extra zope.conf";
+        description = lib.mdDoc "Extra zope.conf";
       };
 
       packages = mkOption {
         type = types.listOf types.package;
-        description = "The list of packages you want to make available to the zope2 instance.";
+        description = lib.mdDoc "The list of packages you want to make available to the zope2 instance.";
       };
 
     };
@@ -95,7 +95,7 @@ in
           };
         }
       '';
-      description = "zope2 instances to be created automaticaly by the system.";
+      description = lib.mdDoc "zope2 instances to be created automaticaly by the system.";
     };
   };
 
diff --git a/nixos/modules/services/x11/clight.nix b/nixos/modules/services/x11/clight.nix
index d994a658cba..0f66e191fe2 100644
--- a/nixos/modules/services/x11/clight.nix
+++ b/nixos/modules/services/x11/clight.nix
@@ -28,29 +28,23 @@ let
       cfg.settings));
 in {
   options.services.clight = {
-    enable = mkOption {
-      type = types.bool;
-      default = false;
-      description = ''
-        Whether to enable clight or not.
-      '';
-    };
+    enable = mkEnableOption (lib.mdDoc "clight");
 
     temperature = {
       day = mkOption {
         type = types.int;
         default = 5500;
-        description = ''
+        description = lib.mdDoc ''
           Colour temperature to use during the day, between
-          <literal>1000</literal> and <literal>25000</literal> K.
+          `1000` and `25000` K.
         '';
       };
       night = mkOption {
         type = types.int;
         default = 3700;
-        description = ''
+        description = lib.mdDoc ''
           Colour temperature to use at night, between
-          <literal>1000</literal> and <literal>25000</literal> K.
+          `1000` and `25000` K.
         '';
       };
     };
@@ -62,9 +56,9 @@ in {
       type = with types; attrsOf (nullOr (either collectionTypes (attrsOf collectionTypes)));
       default = {};
       example = { captures = 20; gamma_long_transition = true; ac_capture_timeouts = [ 120 300 60 ]; };
-      description = ''
+      description = lib.mdDoc ''
         Additional configuration to extend clight.conf. See
-        <link xlink:href="https://github.com/FedeDP/Clight/blob/master/Extra/clight.conf"/> for a
+        <https://github.com/FedeDP/Clight/blob/master/Extra/clight.conf> for a
         sample configuration file.
       '';
     };
diff --git a/nixos/modules/services/x11/colord.nix b/nixos/modules/services/x11/colord.nix
index 31ccee6aa33..cb7b9096e5d 100644
--- a/nixos/modules/services/x11/colord.nix
+++ b/nixos/modules/services/x11/colord.nix
@@ -11,7 +11,7 @@ in {
   options = {
 
     services.colord = {
-      enable = mkEnableOption "colord, the color management daemon";
+      enable = mkEnableOption (lib.mdDoc "colord, the color management daemon");
     };
 
   };
diff --git a/nixos/modules/services/x11/desktop-managers/cde.nix b/nixos/modules/services/x11/desktop-managers/cde.nix
index 6c7105729cf..e0b4fb0e7bf 100644
--- a/nixos/modules/services/x11/desktop-managers/cde.nix
+++ b/nixos/modules/services/x11/desktop-managers/cde.nix
@@ -7,7 +7,7 @@ let
   cfg = xcfg.desktopManager.cde;
 in {
   options.services.xserver.desktopManager.cde = {
-    enable = mkEnableOption "Common Desktop Environment";
+    enable = mkEnableOption (lib.mdDoc "Common Desktop Environment");
 
     extraPackages = mkOption {
       type = with types; listOf package;
@@ -19,7 +19,7 @@ in {
           xclock bitmap xlsfonts xfd xrefresh xload xwininfo xdpyinfo xwd xwud
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         Extra packages to be installed system wide.
       '';
     };
diff --git a/nixos/modules/services/x11/desktop-managers/cinnamon.nix b/nixos/modules/services/x11/desktop-managers/cinnamon.nix
index 3a78a526460..25de29554b1 100644
--- a/nixos/modules/services/x11/desktop-managers/cinnamon.nix
+++ b/nixos/modules/services/x11/desktop-managers/cinnamon.nix
@@ -1,4 +1,4 @@
-{ config, lib, pkgs, ... }:
+{ config, lib, pkgs, utils, ... }:
 
 with lib;
 
@@ -12,22 +12,23 @@ let
     extraGSettingsOverrides = cfg.extraGSettingsOverrides;
   };
 
+  notExcluded = pkg: (!(lib.elem pkg config.environment.cinnamon.excludePackages));
 in
 
 {
   options = {
     services.cinnamon = {
-      apps.enable = mkEnableOption "Cinnamon default applications";
+      apps.enable = mkEnableOption (lib.mdDoc "Cinnamon default applications");
     };
 
     services.xserver.desktopManager.cinnamon = {
-      enable = mkEnableOption "the cinnamon desktop manager";
+      enable = mkEnableOption (lib.mdDoc "the cinnamon desktop manager");
 
       sessionPath = mkOption {
         default = [];
         type = types.listOf types.package;
         example = literalExpression "[ pkgs.gnome.gpaste ]";
-        description = ''
+        description = lib.mdDoc ''
           Additional list of packages to be added to the session search path.
           Useful for GSettings-conditional autostart.
 
@@ -38,13 +39,13 @@ in
       extraGSettingsOverrides = mkOption {
         default = "";
         type = types.lines;
-        description = "Additional gsettings overrides.";
+        description = lib.mdDoc "Additional gsettings overrides.";
       };
 
       extraGSettingsOverridePackages = mkOption {
         default = [];
         type = types.listOf types.path;
-        description = "List of packages for which gsettings are overridden.";
+        description = lib.mdDoc "List of packages for which gsettings are overridden.";
       };
     };
 
@@ -52,19 +53,28 @@ in
       default = [];
       example = literalExpression "[ pkgs.cinnamon.blueberry ]";
       type = types.listOf types.package;
-      description = "Which packages cinnamon should exclude from the default environment";
+      description = lib.mdDoc "Which packages cinnamon should exclude from the default environment";
     };
 
   };
 
   config = mkMerge [
-    (mkIf (cfg.enable && config.services.xserver.displayManager.lightdm.enable && config.services.xserver.displayManager.lightdm.greeters.gtk.enable) {
-      services.xserver.displayManager.lightdm.greeters.gtk.extraConfig = mkDefault (builtins.readFile "${pkgs.cinnamon.mint-artwork}/etc/lightdm/lightdm-gtk-greeter.conf.d/99_linuxmint.conf");
-      })
-
     (mkIf cfg.enable {
       services.xserver.displayManager.sessionPackages = [ pkgs.cinnamon.cinnamon-common ];
 
+      services.xserver.displayManager.lightdm.greeters.slick = {
+        enable = mkDefault true;
+
+        # Taken from mint-artwork.gschema.override
+        theme = mkIf (notExcluded pkgs.cinnamon.mint-themes) {
+          name = mkDefault "Mint-X";
+          package = mkDefault pkgs.cinnamon.mint-themes;
+        };
+        iconTheme = mkIf (notExcluded pkgs.cinnamon.mint-x-icons) {
+          name = mkDefault "Mint-X-Dark";
+          package = mkDefault pkgs.cinnamon.mint-x-icons;
+        };
+      };
       services.xserver.displayManager.sessionCommands = ''
         if test "$XDG_CURRENT_DESKTOP" = "Cinnamon"; then
             true
@@ -82,6 +92,7 @@ in
       '';
 
       # Default services
+      services.blueman.enable = mkDefault true;
       hardware.bluetooth.enable = mkDefault true;
       hardware.pulseaudio.enable = mkDefault true;
       security.polkit.enable = true;
@@ -91,7 +102,7 @@ in
         cinnamon-common
         cinnamon-screensaver
         nemo
-        xapps
+        xapp
       ];
       services.cinnamon.apps.enable = mkDefault true;
       services.gnome.glib-networking.enable = true;
@@ -117,11 +128,8 @@ in
         cinnamon-screensaver = {};
       };
 
-      environment.systemPackages = with pkgs.cinnamon // pkgs; [
+      environment.systemPackages = with pkgs.cinnamon // pkgs; ([
         desktop-file-utils
-        nixos-artwork.wallpapers.simple-dark-gray
-        onboard
-        sound-theme-freedesktop
 
         # common-files
         cinnamon-common
@@ -146,24 +154,32 @@ in
         cinnamon-control-center
         cinnamon-settings-daemon
         libgnomekbd
-        orca
 
         # theme
         gnome.adwaita-icon-theme
-        hicolor-icon-theme
         gnome.gnome-themes-extra
         gtk3.out
+
+        # other
+        glib # for gsettings
+        xdg-user-dirs
+      ] ++ utils.removePackagesByName [
+        # accessibility
+        onboard
+        orca
+
+        # theme
+        sound-theme-freedesktop
+        nixos-artwork.wallpapers.simple-dark-gray
         mint-artwork
+        mint-cursor-themes
         mint-themes
         mint-x-icons
         mint-y-icons
-        vanilla-dmz
+      ] config.environment.cinnamon.excludePackages);
 
-        # other
-        glib # for gsettings
-        shared-mime-info # for update-mime-database
-        xdg-user-dirs
-      ];
+      xdg.mime.enable = true;
+      xdg.icons.enable = true;
 
       # Override GSettings schemas
       environment.sessionVariables.NIX_GSETTINGS_OVERRIDES_DIR = "${nixos-gsettings-overrides}/share/gsettings-schemas/nixos-gsettings-overrides/glib-2.0/schemas";
@@ -177,7 +193,7 @@ in
       programs.bash.vteIntegration = mkDefault true;
       programs.zsh.vteIntegration = mkDefault true;
 
-      # Harmonize Qt5 applications under Pantheon
+      # Harmonize Qt5 applications under Cinnamon
       qt5.enable = true;
       qt5.platformTheme = "gnome";
       qt5.style = "adwaita";
@@ -196,23 +212,23 @@ in
       programs.evince.enable = mkDefault true;
       programs.file-roller.enable = mkDefault true;
 
-      environment.systemPackages = (with pkgs // pkgs.gnome // pkgs.cinnamon; pkgs.gnome.removePackagesByName [
+      environment.systemPackages = with pkgs // pkgs.gnome // pkgs.cinnamon; utils.removePackagesByName [
         # cinnamon team apps
         bulky
-        blueberry
         warpinator
 
-        # cinnamon xapps
+        # cinnamon xapp
         xviewer
         xreader
-        xed
+        xed-editor
         xplayer
         pix
 
         # external apps shipped with linux-mint
         hexchat
         gnome-calculator
-      ] config.environment.cinnamon.excludePackages);
+        gnome-screenshot
+      ] config.environment.cinnamon.excludePackages;
     })
   ];
 }
diff --git a/nixos/modules/services/x11/desktop-managers/default.nix b/nixos/modules/services/x11/desktop-managers/default.nix
index 8247a7e381c..510561246a2 100644
--- a/nixos/modules/services/x11/desktop-managers/default.nix
+++ b/nixos/modules/services/x11/desktop-managers/default.nix
@@ -18,7 +18,7 @@ in
   # determines the default: later modules (if enabled) are preferred.
   # E.g., if Plasma 5 is enabled, it supersedes xterm.
   imports = [
-    ./none.nix ./xterm.nix ./xfce.nix ./plasma5.nix ./lumina.nix
+    ./none.nix ./xterm.nix ./phosh.nix ./xfce.nix ./plasma5.nix ./lumina.nix
     ./lxqt.nix ./enlightenment.nix ./gnome.nix ./retroarch.nix ./kodi.nix
     ./mate.nix ./pantheon.nix ./surf-display.nix ./cde.nix
     ./cinnamon.nix
@@ -33,25 +33,25 @@ in
           type = types.enum [ "center" "fill" "max" "scale" "tile" ];
           default = "scale";
           example = "fill";
-          description = ''
-            The file <filename>~/.background-image</filename> is used as a background image.
+          description = lib.mdDoc ''
+            The file {file}`~/.background-image` is used as a background image.
             This option specifies the placement of this image onto your desktop.
 
             Possible values:
-            <literal>center</literal>: Center the image on the background. If it is too small, it will be surrounded by a black border.
-            <literal>fill</literal>: Like <literal>scale</literal>, but preserves aspect ratio by zooming the image until it fits. Either a horizontal or a vertical part of the image will be cut off.
-            <literal>max</literal>: Like <literal>fill</literal>, but scale the image to the maximum size that fits the screen with black borders on one side.
-            <literal>scale</literal>: Fit the file into the background without repeating it, cutting off stuff or using borders. But the aspect ratio is not preserved either.
-            <literal>tile</literal>: Tile (repeat) the image in case it is too small for the screen.
+            `center`: Center the image on the background. If it is too small, it will be surrounded by a black border.
+            `fill`: Like `scale`, but preserves aspect ratio by zooming the image until it fits. Either a horizontal or a vertical part of the image will be cut off.
+            `max`: Like `fill`, but scale the image to the maximum size that fits the screen with black borders on one side.
+            `scale`: Fit the file into the background without repeating it, cutting off stuff or using borders. But the aspect ratio is not preserved either.
+            `tile`: Tile (repeat) the image in case it is too small for the screen.
           '';
         };
 
         combineScreens = mkOption {
           type = types.bool;
           default = false;
-          description = ''
-            When set to <literal>true</literal> the wallpaper will stretch across all screens.
-            When set to <literal>false</literal> the wallpaper is duplicated to all screens.
+          description = lib.mdDoc ''
+            When set to `true` the wallpaper will stretch across all screens.
+            When set to `false` the wallpaper is duplicated to all screens.
           '';
         };
       };
@@ -64,15 +64,17 @@ in
             bgSupport = true;
             start = "...";
           };
-        description = ''
+        description = lib.mdDoc ''
           Internal option used to add some common line to desktop manager
           scripts before forwarding the value to the
-          <varname>displayManager</varname>.
+          `displayManager`.
         '';
         apply = map (d: d // {
           manage = "desktop";
           start = d.start
+          # literal newline to ensure d.start's last line is not appended to
           + optionalString (needBGCond d) ''
+
             if [ -e $HOME/.background-image ]; then
               ${pkgs.feh}/bin/feh --bg-${cfg.wallpaper.mode} ${optionalString cfg.wallpaper.combineScreens "--no-xinerama"} $HOME/.background-image
             fi
@@ -84,8 +86,8 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "none";
-        description = ''
-          <emphasis role="strong">Deprecated</emphasis>, please use <xref linkend="opt-services.xserver.displayManager.defaultSession"/> instead.
+        description = lib.mdDoc ''
+          **Deprecated**, please use [](#opt-services.xserver.displayManager.defaultSession) instead.
 
           Default desktop manager loaded if none have been chosen.
         '';
diff --git a/nixos/modules/services/x11/desktop-managers/enlightenment.nix b/nixos/modules/services/x11/desktop-managers/enlightenment.nix
index d1513a596b9..2de5d845d68 100644
--- a/nixos/modules/services/x11/desktop-managers/enlightenment.nix
+++ b/nixos/modules/services/x11/desktop-managers/enlightenment.nix
@@ -16,6 +16,10 @@ let
 in
 
 {
+  meta = {
+    maintainers = teams.enlightenment.members;
+  };
+
   imports = [
     (mkRenamedOptionModule [ "services" "xserver" "desktopManager" "e19" "enable" ] [ "services" "xserver" "desktopManager" "enlightenment" "enable" ])
   ];
@@ -25,7 +29,7 @@ in
     services.xserver.desktopManager.enlightenment.enable = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable the Enlightenment desktop environment.";
+      description = lib.mdDoc "Enable the Enlightenment desktop environment.";
     };
 
   };
@@ -92,6 +96,7 @@ in
 
     services.udisks2.enable = true;
     services.upower.enable = config.powerManagement.enable;
+    services.xserver.libinput.enable = mkDefault true;
 
     services.dbus.packages = [ e.efl ];
 
diff --git a/nixos/modules/services/x11/desktop-managers/gnome.nix b/nixos/modules/services/x11/desktop-managers/gnome.nix
index b308ed736ff..9c1978e362b 100644
--- a/nixos/modules/services/x11/desktop-managers/gnome.nix
+++ b/nixos/modules/services/x11/desktop-managers/gnome.nix
@@ -1,4 +1,4 @@
-{ config, lib, pkgs, ... }:
+{ config, lib, pkgs, utils, ... }:
 
 with lib;
 
@@ -22,38 +22,34 @@ let
     favorite-apps=[ 'org.gnome.Epiphany.desktop', 'org.gnome.Geary.desktop', 'org.gnome.Calendar.desktop', 'org.gnome.Music.desktop', 'org.gnome.Photos.desktop', 'org.gnome.Nautilus.desktop' ]
   '';
 
-  nixos-gsettings-desktop-schemas = let
-    defaultPackages = with pkgs; [ gsettings-desktop-schemas gnome.gnome-shell ];
-  in
-  pkgs.runCommand "nixos-gsettings-desktop-schemas" { preferLocalBuild = true; }
-    ''
-     mkdir -p $out/share/gsettings-schemas/nixos-gsettings-overrides/glib-2.0/schemas
+  nixos-background-light = pkgs.nixos-artwork.wallpapers.simple-blue;
+  nixos-background-dark = pkgs.nixos-artwork.wallpapers.simple-dark-gray;
 
-     ${concatMapStrings
-        (pkg: "cp -rf ${pkg}/share/gsettings-schemas/*/glib-2.0/schemas/*.xml $out/share/gsettings-schemas/nixos-gsettings-overrides/glib-2.0/schemas\n")
-        (defaultPackages ++ cfg.extraGSettingsOverridePackages)}
-
-     cp -f ${pkgs.gnome.gnome-shell}/share/gsettings-schemas/*/glib-2.0/schemas/*.gschema.override $out/share/gsettings-schemas/nixos-gsettings-overrides/glib-2.0/schemas
-
-     ${optionalString flashbackEnabled ''
-       cp -f ${pkgs.gnome.gnome-flashback}/share/gsettings-schemas/*/glib-2.0/schemas/*.gschema.override $out/share/gsettings-schemas/nixos-gsettings-overrides/glib-2.0/schemas
-     ''}
-
-     chmod -R a+w $out/share/gsettings-schemas/nixos-gsettings-overrides
-     cat - > $out/share/gsettings-schemas/nixos-gsettings-overrides/glib-2.0/schemas/nixos-defaults.gschema.override <<- EOF
-       [org.gnome.desktop.background]
-       picture-uri='file://${pkgs.nixos-artwork.wallpapers.simple-dark-gray.gnomeFilePath}'
-
-       [org.gnome.desktop.screensaver]
-       picture-uri='file://${pkgs.nixos-artwork.wallpapers.simple-dark-gray-bottom.gnomeFilePath}'
-
-       ${cfg.favoriteAppsOverride}
-
-       ${cfg.extraGSettingsOverrides}
-     EOF
+  # TODO: Having https://github.com/NixOS/nixpkgs/issues/54150 would supersede this
+  nixos-gsettings-desktop-schemas = pkgs.gnome.nixos-gsettings-overrides.override {
+    inherit (cfg) extraGSettingsOverrides extraGSettingsOverridePackages favoriteAppsOverride;
+    inherit flashbackEnabled nixos-background-dark nixos-background-light;
+  };
 
-     ${pkgs.glib.dev}/bin/glib-compile-schemas $out/share/gsettings-schemas/nixos-gsettings-overrides/glib-2.0/schemas/
+  nixos-background-info = pkgs.writeTextFile rec {
+    name = "nixos-background-info";
+    text = ''
+      <?xml version="1.0"?>
+      <!DOCTYPE wallpapers SYSTEM "gnome-wp-list.dtd">
+      <wallpapers>
+        <wallpaper deleted="false">
+          <name>Blobs</name>
+          <filename>${nixos-background-light.gnomeFilePath}</filename>
+          <filename-dark>${nixos-background-dark.gnomeFilePath}</filename-dark>
+          <options>zoom</options>
+          <shade_type>solid</shade_type>
+          <pcolor>#3a4ba0</pcolor>
+          <scolor>#2f302f</scolor>
+        </wallpaper>
+      </wallpapers>
     '';
+    destination = "/share/gnome-background-properties/nixos.xml";
+  };
 
   flashbackEnabled = cfg.flashback.enableMetacity || length cfg.flashback.customSessions > 0;
   flashbackWms = optional cfg.flashback.enableMetacity {
@@ -141,31 +137,30 @@ in
   options = {
 
     services.gnome = {
-      core-os-services.enable = mkEnableOption "essential services for GNOME3";
-      core-shell.enable = mkEnableOption "GNOME Shell services";
-      core-utilities.enable = mkEnableOption "GNOME core utilities";
-      core-developer-tools.enable = mkEnableOption "GNOME core developer tools";
-      games.enable = mkEnableOption "GNOME games";
+      core-os-services.enable = mkEnableOption (lib.mdDoc "essential services for GNOME3");
+      core-shell.enable = mkEnableOption (lib.mdDoc "GNOME Shell services");
+      core-utilities.enable = mkEnableOption (lib.mdDoc "GNOME core utilities");
+      core-developer-tools.enable = mkEnableOption (lib.mdDoc "GNOME core developer tools");
+      games.enable = mkEnableOption (lib.mdDoc "GNOME games");
     };
 
     services.xserver.desktopManager.gnome = {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable GNOME desktop manager.";
+        description = lib.mdDoc "Enable GNOME desktop manager.";
       };
 
       sessionPath = mkOption {
         default = [];
         type = types.listOf types.package;
         example = literalExpression "[ pkgs.gnome.gpaste ]";
-        description = ''
+        description = lib.mdDoc ''
           Additional list of packages to be added to the session search path.
           Useful for GNOME Shell extensions or GSettings-conditional autostart.
 
           Note that this should be a last resort; patching the package is preferred (see GPaste).
         '';
-        apply = list: list ++ [ pkgs.gnome.gnome-shell pkgs.gnome.gnome-shell-extensions ];
       };
 
       favoriteAppsOverride = mkOption {
@@ -178,44 +173,44 @@ in
             favorite-apps=[ 'firefox.desktop', 'org.gnome.Calendar.desktop' ]
           '''
         '';
-        description = "List of desktop files to put as favorite apps into gnome-shell. These need to be installed somehow globally.";
+        description = lib.mdDoc "List of desktop files to put as favorite apps into gnome-shell. These need to be installed somehow globally.";
       };
 
       extraGSettingsOverrides = mkOption {
         default = "";
         type = types.lines;
-        description = "Additional gsettings overrides.";
+        description = lib.mdDoc "Additional gsettings overrides.";
       };
 
       extraGSettingsOverridePackages = mkOption {
         default = [];
         type = types.listOf types.path;
-        description = "List of packages for which gsettings are overridden.";
+        description = lib.mdDoc "List of packages for which gsettings are overridden.";
       };
 
-      debug = mkEnableOption "gnome-session debug messages";
+      debug = mkEnableOption (lib.mdDoc "gnome-session debug messages");
 
       flashback = {
-        enableMetacity = mkEnableOption "the standard GNOME Flashback session with Metacity";
+        enableMetacity = mkEnableOption (lib.mdDoc "the standard GNOME Flashback session with Metacity");
 
         customSessions = mkOption {
           type = types.listOf (types.submodule {
             options = {
               wmName = mkOption {
                 type = types.strMatching "[a-zA-Z0-9_-]+";
-                description = "A unique identifier for the window manager.";
+                description = lib.mdDoc "A unique identifier for the window manager.";
                 example = "xmonad";
               };
 
               wmLabel = mkOption {
                 type = types.str;
-                description = "The name of the window manager to show in the session chooser.";
+                description = lib.mdDoc "The name of the window manager to show in the session chooser.";
                 example = "XMonad";
               };
 
               wmCommand = mkOption {
                 type = types.str;
-                description = "The executable of the window manager to use.";
+                description = lib.mdDoc "The executable of the window manager to use.";
                 example = literalExpression ''"''${pkgs.haskellPackages.xmonad}/bin/xmonad"'';
               };
 
@@ -223,22 +218,22 @@ in
                 type = types.bool;
                 default = true;
                 example = false;
-                description = "Whether to enable the GNOME panel in this session.";
+                description = lib.mdDoc "Whether to enable the GNOME panel in this session.";
               };
             };
           });
           default = [];
-          description = "Other GNOME Flashback sessions to enable.";
+          description = lib.mdDoc "Other GNOME Flashback sessions to enable.";
         };
 
         panelModulePackages = mkOption {
           default = [ pkgs.gnome.gnome-applets ];
           defaultText = literalExpression "[ pkgs.gnome.gnome-applets ]";
           type = types.listOf types.path;
-          description = ''
-            Packages containing modules that should be made available to <literal>gnome-panel</literal> (usually for applets).
+          description = lib.mdDoc ''
+            Packages containing modules that should be made available to `gnome-panel` (usually for applets).
 
-            If you're packaging something to use here, please install the modules in <literal>$out/lib/gnome-panel/modules</literal>.
+            If you're packaging something to use here, please install the modules in `$out/lib/gnome-panel/modules`.
           '';
         };
       };
@@ -248,7 +243,7 @@ in
       default = [];
       example = literalExpression "[ pkgs.gnome.totem ]";
       type = types.listOf types.package;
-      description = "Which packages gnome should exclude from the default environment";
+      description = lib.mdDoc "Which packages gnome should exclude from the default environment";
     };
 
   };
@@ -338,11 +333,16 @@ in
       services.gnome.tracker-miners.enable = mkDefault true;
       services.gnome.tracker.enable = mkDefault true;
       services.hardware.bolt.enable = mkDefault true;
-      services.packagekit.enable = mkDefault true;
+      # TODO: Enable once #177946 is resolved
+      # services.packagekit.enable = mkDefault true;
       services.udisks2.enable = true;
       services.upower.enable = config.powerManagement.enable;
       services.xserver.libinput.enable = mkDefault true; # for controlling touchpad settings via gnome control center
 
+      # Explicitly enabled since GNOME will be severely broken without these.
+      xdg.mime.enable = true;
+      xdg.icons.enable = true;
+
       xdg.portal.enable = true;
       xdg.portal.extraPortals = [
         pkgs.xdg-desktop-portal-gnome
@@ -376,9 +376,21 @@ in
     })
 
     (mkIf serviceCfg.core-shell.enable {
+      services.xserver.desktopManager.gnome.sessionPath =
+        let
+          mandatoryPackages = [
+            pkgs.gnome.gnome-shell
+          ];
+          optionalPackages = [
+            pkgs.gnome.gnome-shell-extensions
+          ];
+        in
+        mandatoryPackages
+        ++ utils.removePackagesByName optionalPackages config.environment.gnome.excludePackages;
+
       services.colord.enable = mkDefault true;
-      services.gnome.chrome-gnome-shell.enable = mkDefault true;
       services.gnome.glib-networking.enable = true;
+      services.gnome.gnome-browser-connector.enable = mkDefault true;
       services.gnome.gnome-initial-setup.enable = mkDefault true;
       services.gnome.gnome-remote-desktop.enable = mkDefault true;
       services.gnome.gnome-settings-daemon.enable = true;
@@ -428,34 +440,38 @@ in
       ];
 
       # Adapt from https://gitlab.gnome.org/GNOME/gnome-build-meta/blob/gnome-3-38/elements/core/meta-gnome-core-shell.bst
-      environment.systemPackages = with pkgs.gnome; [
-        adwaita-icon-theme
-        gnome-backgrounds
-        gnome-bluetooth
-        gnome-color-manager
-        gnome-control-center
-        gnome-shell
-        gnome-shell-extensions
-        gnome-themes-extra
-        pkgs.gnome-tour # GNOME Shell detects the .desktop file on first log-in.
-        pkgs.nixos-artwork.wallpapers.simple-dark-gray
-        pkgs.nixos-artwork.wallpapers.simple-dark-gray-bottom
-        pkgs.gnome-user-docs
-        pkgs.orca
-        pkgs.glib # for gsettings
-        pkgs.gnome-menus
-        pkgs.gtk3.out # for gtk-launch
-        pkgs.hicolor-icon-theme
-        pkgs.shared-mime-info # for update-mime-database
-        pkgs.xdg-user-dirs # Update user dirs as described in http://freedesktop.org/wiki/Software/xdg-user-dirs/
-      ];
+      environment.systemPackages =
+        let
+          mandatoryPackages = with pkgs.gnome; [
+            gnome-shell
+          ];
+          optionalPackages = with pkgs.gnome; [
+            adwaita-icon-theme
+            nixos-background-info
+            gnome-backgrounds
+            gnome-bluetooth
+            gnome-color-manager
+            gnome-control-center
+            gnome-shell-extensions
+            gnome-themes-extra
+            pkgs.gnome-tour # GNOME Shell detects the .desktop file on first log-in.
+            pkgs.gnome-user-docs
+            pkgs.orca
+            pkgs.glib # for gsettings program
+            pkgs.gnome-menus
+            pkgs.gtk3.out # for gtk-launch program
+            pkgs.xdg-user-dirs # Update user dirs as described in http://freedesktop.org/wiki/Software/xdg-user-dirs/
+          ];
+        in
+        mandatoryPackages
+        ++ utils.removePackagesByName optionalPackages config.environment.gnome.excludePackages;
     })
 
     # Adapt from https://gitlab.gnome.org/GNOME/gnome-build-meta/blob/gnome-3-38/elements/core/meta-gnome-core-utilities.bst
     (mkIf serviceCfg.core-utilities.enable {
       environment.systemPackages =
         with pkgs.gnome;
-        removePackagesByName
+        utils.removePackagesByName
           ([
             baobab
             cheese
@@ -498,9 +514,13 @@ in
       programs.seahorse.enable = notExcluded pkgs.gnome.seahorse;
       services.gnome.sushi.enable = notExcluded pkgs.gnome.sushi;
 
+      # VTE shell integration for gnome-console
+      programs.bash.vteIntegration = mkDefault true;
+      programs.zsh.vteIntegration = mkDefault true;
+
       # Let nautilus find extensions
       # TODO: Create nautilus-with-extensions package
-      environment.sessionVariables.NAUTILUS_EXTENSION_DIR = "${config.system.path}/lib/nautilus/extensions-3.0";
+      environment.sessionVariables.NAUTILUS_4_EXTENSION_DIR = "${config.system.path}/lib/nautilus/extensions-4";
 
       # Override default mimeapps for nautilus
       environment.sessionVariables.XDG_DATA_DIRS = [ "${mimeAppsList}/share" ];
@@ -511,7 +531,7 @@ in
     })
 
     (mkIf serviceCfg.games.enable {
-      environment.systemPackages = (with pkgs.gnome; removePackagesByName [
+      environment.systemPackages = with pkgs.gnome; utils.removePackagesByName [
         aisleriot
         atomix
         five-or-more
@@ -532,12 +552,12 @@ in
         quadrapassel
         swell-foop
         tali
-      ] config.environment.gnome.excludePackages);
+      ] config.environment.gnome.excludePackages;
     })
 
     # Adapt from https://gitlab.gnome.org/GNOME/gnome-build-meta/-/blob/3.38.0/elements/core/meta-gnome-core-developer-tools.bst
     (mkIf serviceCfg.core-developer-tools.enable {
-      environment.systemPackages = (with pkgs.gnome; removePackagesByName [
+      environment.systemPackages = with pkgs.gnome; utils.removePackagesByName [
         dconf-editor
         devhelp
         pkgs.gnome-builder
@@ -546,7 +566,7 @@ in
         # in default configurations.
         # https://github.com/NixOS/nixpkgs/issues/60908
         /* gnome-boxes */
-      ] config.environment.gnome.excludePackages);
+      ] config.environment.gnome.excludePackages;
 
       services.sysprof.enable = notExcluded pkgs.sysprof;
     })
diff --git a/nixos/modules/services/x11/desktop-managers/kodi.nix b/nixos/modules/services/x11/desktop-managers/kodi.nix
index b853c94d6fd..43904cd00e8 100644
--- a/nixos/modules/services/x11/desktop-managers/kodi.nix
+++ b/nixos/modules/services/x11/desktop-managers/kodi.nix
@@ -12,7 +12,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable the kodi multimedia center.";
+        description = lib.mdDoc "Enable the kodi multimedia center.";
       };
 
       package = mkOption {
@@ -20,7 +20,7 @@ in
         default = pkgs.kodi;
         defaultText = literalExpression "pkgs.kodi";
         example = literalExpression "pkgs.kodi.withPackages (p: with p; [ jellyfin pvr-iptvsimple vfs-sftp ])";
-        description = ''
+        description = lib.mdDoc ''
           Package that should be used for Kodi.
         '';
       };
diff --git a/nixos/modules/services/x11/desktop-managers/lumina.nix b/nixos/modules/services/x11/desktop-managers/lumina.nix
index 419f5055d8b..7b694106bf7 100644
--- a/nixos/modules/services/x11/desktop-managers/lumina.nix
+++ b/nixos/modules/services/x11/desktop-managers/lumina.nix
@@ -10,12 +10,16 @@ let
 in
 
 {
+  meta = {
+    maintainers = teams.lumina.members;
+  };
+
   options = {
 
     services.xserver.desktopManager.lumina.enable = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable the Lumina desktop manager";
+      description = lib.mdDoc "Enable the Lumina desktop manager";
     };
 
   };
diff --git a/nixos/modules/services/x11/desktop-managers/lxqt.nix b/nixos/modules/services/x11/desktop-managers/lxqt.nix
index 720985ba0d9..b69da41c9fc 100644
--- a/nixos/modules/services/x11/desktop-managers/lxqt.nix
+++ b/nixos/modules/services/x11/desktop-managers/lxqt.nix
@@ -1,4 +1,4 @@
-{ config, lib, pkgs, ... }:
+{ config, lib, pkgs, utils, ... }:
 
 with lib;
 
@@ -9,19 +9,23 @@ let
 in
 
 {
+  meta = {
+    maintainers = teams.lxqt.members;
+  };
+
   options = {
 
     services.xserver.desktopManager.lxqt.enable = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable the LXQt desktop manager";
+      description = lib.mdDoc "Enable the LXQt desktop manager";
     };
 
     environment.lxqt.excludePackages = mkOption {
       default = [];
       example = literalExpression "[ pkgs.lxqt.qterminal ]";
       type = types.listOf types.package;
-      description = "Which LXQt packages to exclude from the default environment";
+      description = lib.mdDoc "Which LXQt packages to exclude from the default environment";
     };
 
   };
@@ -51,7 +55,7 @@ in
     environment.systemPackages =
       pkgs.lxqt.preRequisitePackages ++
       pkgs.lxqt.corePackages ++
-      (pkgs.gnome.removePackagesByName
+      (utils.removePackagesByName
         pkgs.lxqt.optionalPackages
         config.environment.lxqt.excludePackages);
 
@@ -62,6 +66,10 @@ in
     services.gvfs.enable = true;
 
     services.upower.enable = config.powerManagement.enable;
+
+    services.xserver.libinput.enable = mkDefault true;
+
+    xdg.portal.lxqt.enable = true;
   };
 
 }
diff --git a/nixos/modules/services/x11/desktop-managers/mate.nix b/nixos/modules/services/x11/desktop-managers/mate.nix
index a7fda4be979..c93f120bed7 100644
--- a/nixos/modules/services/x11/desktop-managers/mate.nix
+++ b/nixos/modules/services/x11/desktop-managers/mate.nix
@@ -1,20 +1,9 @@
-{ config, lib, pkgs, ... }:
+{ config, lib, pkgs, utils, ... }:
 
 with lib;
 
 let
 
-  addToXDGDirs = p: ''
-    if [ -d "${p}/share/gsettings-schemas/${p.name}" ]; then
-      export XDG_DATA_DIRS=$XDG_DATA_DIRS''${XDG_DATA_DIRS:+:}${p}/share/gsettings-schemas/${p.name}
-    fi
-
-    if [ -d "${p}/lib/girepository-1.0" ]; then
-      export GI_TYPELIB_PATH=$GI_TYPELIB_PATH''${GI_TYPELIB_PATH:+:}${p}/lib/girepository-1.0
-      export LD_LIBRARY_PATH=$LD_LIBRARY_PATH''${LD_LIBRARY_PATH:+:}${p}/lib
-    fi
-  '';
-
   xcfg = config.services.xserver;
   cfg = xcfg.desktopManager.mate;
 
@@ -27,17 +16,17 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable the MATE desktop environment";
+        description = lib.mdDoc "Enable the MATE desktop environment";
       };
 
-      debug = mkEnableOption "mate-session debug messages";
+      debug = mkEnableOption (lib.mdDoc "mate-session debug messages");
     };
 
     environment.mate.excludePackages = mkOption {
       default = [];
       example = literalExpression "[ pkgs.mate.mate-terminal pkgs.mate.pluma ]";
       type = types.listOf types.package;
-      description = "Which MATE packages to exclude from the default environment";
+      description = lib.mdDoc "Which MATE packages to exclude from the default environment";
     };
 
   };
@@ -48,24 +37,8 @@ in
       pkgs.mate.mate-session-manager
     ];
 
-    services.xserver.displayManager.sessionCommands = ''
-      if test "$XDG_CURRENT_DESKTOP" = "MATE"; then
-          export XDG_MENU_PREFIX=mate-
-
-          # Let caja find extensions
-          export CAJA_EXTENSION_DIRS=$CAJA_EXTENSION_DIRS''${CAJA_EXTENSION_DIRS:+:}${config.system.path}/lib/caja/extensions-2.0
-
-          # Let caja extensions find gsettings schemas
-          ${concatMapStrings (p: ''
-          if [ -d "${p}/lib/caja/extensions-2.0" ]; then
-              ${addToXDGDirs p}
-          fi
-          '') config.environment.systemPackages}
-
-          # Add mate-control-center paths to some XDG variables because its schemas are needed by mate-settings-daemon, and mate-settings-daemon is a dependency for mate-control-center (that is, they are mutually recursive)
-          ${addToXDGDirs pkgs.mate.mate-control-center}
-      fi
-    '';
+    # Let caja find extensions
+    environment.sessionVariables.CAJA_EXTENSION_DIRS = [ "${config.system.path}/lib/caja/extensions-2.0" ];
 
     # Let mate-panel find applets
     environment.sessionVariables."MATE_PANEL_APPLETS_DIR" = "${config.system.path}/share/mate-panel/applets";
@@ -74,7 +47,7 @@ in
     # Debugging
     environment.sessionVariables.MATE_SESSION_DEBUG = mkIf cfg.debug "1";
 
-    environment.systemPackages = pkgs.gnome.removePackagesByName
+    environment.systemPackages = utils.removePackagesByName
       (pkgs.mate.basePackages ++
       pkgs.mate.extraPackages ++
       [
@@ -83,7 +56,6 @@ in
         pkgs.gtk3.out
         pkgs.shared-mime-info
         pkgs.xdg-user-dirs # Update user dirs as described in https://freedesktop.org/wiki/Software/xdg-user-dirs/
-        pkgs.mate.mate-settings-daemon
         pkgs.yelp # for 'Contents' in 'Help' menus
       ])
       config.environment.mate.excludePackages;
@@ -101,6 +73,7 @@ in
     services.udev.packages = [ pkgs.mate.mate-settings-daemon ];
     services.gvfs.enable = true;
     services.upower.enable = config.powerManagement.enable;
+    services.xserver.libinput.enable = mkDefault true;
 
     security.pam.services.mate-screensaver.unixAuth = true;
 
diff --git a/nixos/modules/services/x11/desktop-managers/none.nix b/nixos/modules/services/x11/desktop-managers/none.nix
index af7a376ae02..074b729cc3f 100644
--- a/nixos/modules/services/x11/desktop-managers/none.nix
+++ b/nixos/modules/services/x11/desktop-managers/none.nix
@@ -1,7 +1,46 @@
+{ config, lib, pkgs, ... }:
+with lib;
+let
+  runXdgAutostart = config.services.xserver.desktopManager.runXdgAutostartIfNone;
+in
 {
-  services.xserver.desktopManager.session =
-    [ { name = "none";
-        start = "";
-      }
-    ];
+  options = {
+    services.xserver.desktopManager.runXdgAutostartIfNone = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Whether to run XDG autostart files for sessions without a desktop manager
+        (with only a window manager), these sessions usually don't handle XDG
+        autostart files by default.
+
+        Some services like {option}`i18n.inputMethod` and
+        {option}`service.earlyoom` use XDG autostart files to start.
+        If this option is not set to `true` and you are using
+        a window manager without a desktop manager, you need to manually start
+        them or running `dex` somewhere.
+      '';
+    };
+  };
+
+  config = mkMerge [
+    {
+      services.xserver.desktopManager.session = [
+        {
+          name = "none";
+          start = optionalString runXdgAutostart ''
+            /run/current-system/systemd/bin/systemctl --user start xdg-autostart-if-no-desktop-manager.target
+          '';
+        }
+      ];
+    }
+    (mkIf runXdgAutostart {
+      systemd.user.targets.xdg-autostart-if-no-desktop-manager = {
+        description = "Run XDG autostart files";
+        # From `plasma-workspace`, `share/systemd/user/plasma-workspace@.target`.
+        requires = [ "xdg-desktop-autostart.target" "graphical-session.target" ];
+        before = [ "xdg-desktop-autostart.target" "graphical-session.target" ];
+        bindsTo = [ "graphical-session.target" ];
+      };
+    })
+  ];
 }
diff --git a/nixos/modules/services/x11/desktop-managers/pantheon.nix b/nixos/modules/services/x11/desktop-managers/pantheon.nix
index 48e119a8618..5c0203224e1 100644
--- a/nixos/modules/services/x11/desktop-managers/pantheon.nix
+++ b/nixos/modules/services/x11/desktop-managers/pantheon.nix
@@ -1,4 +1,4 @@
-{ config, lib, pkgs, ... }:
+{ config, lib, utils, pkgs, ... }:
 
 with lib;
 
@@ -26,10 +26,10 @@ in
     services.pantheon = {
 
       contractor = {
-         enable = mkEnableOption "contractor, a desktop-wide extension service used by Pantheon";
+         enable = mkEnableOption (lib.mdDoc "contractor, a desktop-wide extension service used by Pantheon");
       };
 
-      apps.enable = mkEnableOption "Pantheon default applications";
+      apps.enable = mkEnableOption (lib.mdDoc "Pantheon default applications");
 
     };
 
@@ -37,50 +37,46 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable the pantheon desktop manager";
+        description = lib.mdDoc "Enable the pantheon desktop manager";
       };
 
       sessionPath = mkOption {
         default = [];
         type = types.listOf types.package;
         example = literalExpression "[ pkgs.gnome.gpaste ]";
-        description = ''
+        description = lib.mdDoc ''
           Additional list of packages to be added to the session search path.
           Useful for GSettings-conditional autostart.
 
           Note that this should be a last resort; patching the package is preferred (see GPaste).
         '';
-        apply = list: list ++
-        [
-          pkgs.pantheon.pantheon-agent-geoclue2
-        ];
       };
 
       extraWingpanelIndicators = mkOption {
         default = null;
         type = with types; nullOr (listOf package);
-        description = "Indicators to add to Wingpanel.";
+        description = lib.mdDoc "Indicators to add to Wingpanel.";
       };
 
       extraSwitchboardPlugs = mkOption {
         default = null;
         type = with types; nullOr (listOf package);
-        description = "Plugs to add to Switchboard.";
+        description = lib.mdDoc "Plugs to add to Switchboard.";
       };
 
       extraGSettingsOverrides = mkOption {
         default = "";
         type = types.lines;
-        description = "Additional gsettings overrides.";
+        description = lib.mdDoc "Additional gsettings overrides.";
       };
 
       extraGSettingsOverridePackages = mkOption {
         default = [];
         type = types.listOf types.path;
-        description = "List of packages for which gsettings are overridden.";
+        description = lib.mdDoc "List of packages for which gsettings are overridden.";
       };
 
-      debug = mkEnableOption "gnome-session debug messages";
+      debug = mkEnableOption (lib.mdDoc "gnome-session debug messages");
 
     };
 
@@ -88,7 +84,7 @@ in
       default = [];
       example = literalExpression "[ pkgs.pantheon.elementary-camera ]";
       type = types.listOf types.package;
-      description = "Which packages pantheon should exclude from the default environment";
+      description = lib.mdDoc "Which packages pantheon should exclude from the default environment";
     };
 
   };
@@ -96,6 +92,9 @@ in
 
   config = mkMerge [
     (mkIf cfg.enable {
+      services.xserver.desktopManager.pantheon.sessionPath = utils.removePackagesByName [
+        pkgs.pantheon.pantheon-agent-geoclue2
+      ] config.environment.pantheon.excludePackages;
 
       services.xserver.displayManager.sessionPackages = [ pkgs.pantheon.elementary-session-settings ];
 
@@ -135,7 +134,9 @@ in
       services.bamf.enable = true;
       services.colord.enable = mkDefault true;
       services.fwupd.enable = mkDefault true;
-      services.packagekit.enable = mkDefault true;
+      # TODO: Enable once #177946 is resolved
+      # services.packagekit.enable = mkDefault true;
+      services.power-profiles-daemon.enable = mkDefault true;
       services.touchegg.enable = mkDefault true;
       services.touchegg.package = pkgs.pantheon.touchegg;
       services.tumbler.enable = mkDefault true;
@@ -167,28 +168,37 @@ in
         isSystem = true;
       };
       services.udev.packages = [
-        pkgs.gnome.gnome-settings-daemon338
+        pkgs.pantheon.gnome-settings-daemon
       ];
       systemd.packages = [
-        pkgs.gnome.gnome-settings-daemon338
+        pkgs.pantheon.gnome-settings-daemon
       ];
       programs.dconf.enable = true;
       networking.networkmanager.enable = mkDefault true;
 
       # Global environment
-      environment.systemPackages = with pkgs; [
+      environment.systemPackages = (with pkgs.pantheon; [
+        elementary-session-settings
+        elementary-settings-daemon
+        gala
+        gnome-settings-daemon
+        (switchboard-with-plugs.override {
+          plugs = cfg.extraSwitchboardPlugs;
+        })
+        (wingpanel-with-indicators.override {
+          indicators = cfg.extraWingpanelIndicators;
+        })
+      ]) ++ utils.removePackagesByName ((with pkgs; [
         desktop-file-utils
-        glib
+        glib # for gsettings program
         gnome-menus
         gnome.adwaita-icon-theme
-        gtk3.out
-        hicolor-icon-theme
+        gtk3.out # for gtk-launch program
         onboard
         qgnomeplatform
-        shared-mime-info
         sound-theme-freedesktop
-        xdg-user-dirs
-      ] ++ (with pkgs.pantheon; [
+        xdg-user-dirs # Update user dirs as described in http://freedesktop.org/wiki/Software/xdg-user-dirs/
+      ]) ++ (with pkgs.pantheon; [
         # Artwork
         elementary-gtk-theme
         elementary-icon-theme
@@ -198,33 +208,21 @@ in
         # Desktop
         elementary-default-settings
         elementary-dock
-        elementary-session-settings
         elementary-shortcut-overlay
-        gala
-        (switchboard-with-plugs.override {
-          plugs = cfg.extraSwitchboardPlugs;
-        })
-        (wingpanel-with-indicators.override {
-          indicators = cfg.extraWingpanelIndicators;
-        })
 
         # Services
         elementary-capnet-assist
         elementary-notifications
-        elementary-settings-daemon
         pantheon-agent-geoclue2
         pantheon-agent-polkit
-      ]) ++ (gnome.removePackagesByName [
-        gnome.gnome-font-viewer
-        gnome.gnome-settings-daemon338
-      ] config.environment.pantheon.excludePackages);
-
-      programs.evince.enable = mkDefault true;
-      programs.file-roller.enable = mkDefault true;
+      ])) config.environment.pantheon.excludePackages;
 
       # Settings from elementary-default-settings
       environment.etc."gtk-3.0/settings.ini".source = "${pkgs.pantheon.elementary-default-settings}/etc/gtk-3.0/settings.ini";
 
+      xdg.mime.enable = true;
+      xdg.icons.enable = true;
+
       xdg.portal.enable = true;
       xdg.portal.extraPortals = with pkgs.pantheon; [
         elementary-files
@@ -272,7 +270,12 @@ in
     })
 
     (mkIf serviceCfg.apps.enable {
-      environment.systemPackages = with pkgs.pantheon; pkgs.gnome.removePackagesByName ([
+      programs.evince.enable = mkDefault true;
+      programs.file-roller.enable = mkDefault true;
+
+      environment.systemPackages = utils.removePackagesByName ([
+        pkgs.gnome.gnome-font-viewer
+      ] ++ (with pkgs.pantheon; [
         elementary-calculator
         elementary-calendar
         elementary-camera
@@ -282,7 +285,7 @@ in
         elementary-music
         elementary-photos
         elementary-screenshot
-        elementary-tasks
+        # elementary-tasks
         elementary-terminal
         elementary-videos
         epiphany
@@ -290,7 +293,8 @@ in
         # Only install appcenter if flatpak is enabled before
         # https://github.com/NixOS/nixpkgs/issues/15932 is resolved.
         appcenter
-      ]) config.environment.pantheon.excludePackages;
+        sideload
+      ])) config.environment.pantheon.excludePackages;
 
       # needed by screenshot
       fonts.fonts = [
@@ -302,6 +306,7 @@ in
       environment.systemPackages = with pkgs.pantheon; [
         contractor
         file-roller-contract
+        gnome-bluetooth-contract
       ];
 
       environment.pathsToLink = [
diff --git a/nixos/modules/services/x11/desktop-managers/pantheon.xml b/nixos/modules/services/x11/desktop-managers/pantheon.xml
index 202909d398f..6226f8f6a27 100644
--- a/nixos/modules/services/x11/desktop-managers/pantheon.xml
+++ b/nixos/modules/services/x11/desktop-managers/pantheon.xml
@@ -3,7 +3,7 @@
          xml:id="chap-pantheon">
  <title>Pantheon Desktop</title>
  <para>
-  Pantheon is the desktop environment created for the elementary OS distribution. It is written from scratch in Vala, utilizing GNOME technologies with GTK 3 and Granite.
+  Pantheon is the desktop environment created for the elementary OS distribution. It is written from scratch in Vala, utilizing GNOME technologies with GTK and Granite.
  </para>
  <section xml:id="sec-pantheon-enable">
   <title>Enabling Pantheon</title>
@@ -89,9 +89,9 @@ switchboard-with-plugs.override {
      </para>
     </listitem>
    </varlistentry>
-   <varlistentry xml:id="sec-pantheon-faq-gnome3-and-pantheon">
+   <varlistentry xml:id="sec-pantheon-faq-gnome-and-pantheon">
     <term>
-     I cannot enable both GNOME 3 and Pantheon.
+     I cannot enable both GNOME and Pantheon.
     </term>
     <listitem>
      <para>
diff --git a/nixos/modules/services/x11/desktop-managers/phosh.nix b/nixos/modules/services/x11/desktop-managers/phosh.nix
new file mode 100644
index 00000000000..e889c0e34e7
--- /dev/null
+++ b/nixos/modules/services/x11/desktop-managers/phosh.nix
@@ -0,0 +1,223 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.xserver.desktopManager.phosh;
+
+  # Based on https://source.puri.sm/Librem5/librem5-base/-/blob/4596c1056dd75ac7f043aede07887990fd46f572/default/sm.puri.OSK0.desktop
+  oskItem = pkgs.makeDesktopItem {
+    name = "sm.puri.OSK0";
+    desktopName = "On-screen keyboard";
+    exec = "${pkgs.squeekboard}/bin/squeekboard";
+    categories = [ "GNOME" "Core" ];
+    onlyShowIn = [ "GNOME" ];
+    noDisplay = true;
+    extraConfig = {
+      X-GNOME-Autostart-Phase = "Panel";
+      X-GNOME-Provides = "inputmethod";
+      X-GNOME-Autostart-Notify = "true";
+      X-GNOME-AutoRestart = "true";
+    };
+  };
+
+  phocConfigType = types.submodule {
+    options = {
+      xwayland = mkOption {
+        description = lib.mdDoc ''
+          Whether to enable XWayland support.
+
+          To start XWayland immediately, use `immediate`.
+        '';
+        type = types.enum [ "true" "false" "immediate" ];
+        default = "false";
+      };
+      cursorTheme = mkOption {
+        description = lib.mdDoc ''
+          Cursor theme to use in Phosh.
+        '';
+        type = types.str;
+        default = "default";
+      };
+      outputs = mkOption {
+        description = lib.mdDoc ''
+          Output configurations.
+        '';
+        type = types.attrsOf phocOutputType;
+        default = {
+          DSI-1 = {
+            scale = 2;
+          };
+        };
+      };
+    };
+  };
+
+  phocOutputType = types.submodule {
+    options = {
+      modeline = mkOption {
+        description = lib.mdDoc ''
+          One or more modelines.
+        '';
+        type = types.either types.str (types.listOf types.str);
+        default = [];
+        example = [
+          "87.25 720 776 848  976 1440 1443 1453 1493 -hsync +vsync"
+          "65.13 768 816 896 1024 1024 1025 1028 1060 -HSync +VSync"
+        ];
+      };
+      mode = mkOption {
+        description = lib.mdDoc ''
+          Default video mode.
+        '';
+        type = types.nullOr types.str;
+        default = null;
+        example = "768x1024";
+      };
+      scale = mkOption {
+        description = lib.mdDoc ''
+          Display scaling factor.
+        '';
+        type = types.nullOr (
+          types.addCheck
+          (types.either types.int types.float)
+          (x : x > 0)
+        ) // {
+          description = "null or positive integer or float";
+        };
+        default = null;
+        example = 2;
+      };
+      rotate = mkOption {
+        description = lib.mdDoc ''
+          Screen transformation.
+        '';
+        type = types.enum [
+          "90" "180" "270" "flipped" "flipped-90" "flipped-180" "flipped-270" null
+        ];
+        default = null;
+      };
+    };
+  };
+
+  optionalKV = k: v: if v == null then "" else "${k} = ${builtins.toString v}";
+
+  renderPhocOutput = name: output: let
+    modelines = if builtins.isList output.modeline
+      then output.modeline
+      else [ output.modeline ];
+    renderModeline = l: "modeline = ${l}";
+  in ''
+    [output:${name}]
+    ${concatStringsSep "\n" (map renderModeline modelines)}
+    ${optionalKV "mode" output.mode}
+    ${optionalKV "scale" output.scale}
+    ${optionalKV "rotate" output.rotate}
+  '';
+
+  renderPhocConfig = phoc: let
+    outputs = mapAttrsToList renderPhocOutput phoc.outputs;
+  in ''
+    [core]
+    xwayland = ${phoc.xwayland}
+    ${concatStringsSep "\n" outputs}
+    [cursor]
+    theme = ${phoc.cursorTheme}
+  '';
+in
+
+{
+  options = {
+    services.xserver.desktopManager.phosh = {
+      enable = mkOption {
+        type = types.bool;
+        default = false;
+        description = lib.mdDoc "Enable the Phone Shell.";
+      };
+
+      package = mkOption {
+        type = types.package;
+        default = pkgs.phosh;
+        defaultText = literalExpression "pkgs.phosh";
+        example = literalExpression "pkgs.phosh";
+        description = lib.mdDoc ''
+          Package that should be used for Phosh.
+        '';
+      };
+
+      user = mkOption {
+        description = lib.mdDoc "The user to run the Phosh service.";
+        type = types.str;
+        example = "alice";
+      };
+
+      group = mkOption {
+        description = lib.mdDoc "The group to run the Phosh service.";
+        type = types.str;
+        example = "users";
+      };
+
+      phocConfig = mkOption {
+        description = lib.mdDoc ''
+          Configurations for the Phoc compositor.
+        '';
+        type = types.oneOf [ types.lines types.path phocConfigType ];
+        default = {};
+      };
+    };
+  };
+
+  config = mkIf cfg.enable {
+    systemd.defaultUnit = "graphical.target";
+    # Inspired by https://gitlab.gnome.org/World/Phosh/phosh/-/blob/main/data/phosh.service
+    systemd.services.phosh = {
+      wantedBy = [ "graphical.target" ];
+      serviceConfig = {
+        ExecStart = "${cfg.package}/bin/phosh";
+        User = cfg.user;
+        Group = cfg.group;
+        PAMName = "login";
+        WorkingDirectory = "~";
+        Restart = "always";
+
+        TTYPath = "/dev/tty7";
+        TTYReset = "yes";
+        TTYVHangup = "yes";
+        TTYVTDisallocate = "yes";
+
+        # Fail to start if not controlling the tty.
+        StandardInput = "tty-fail";
+        StandardOutput = "journal";
+        StandardError = "journal";
+
+        # Log this user with utmp, letting it show up with commands 'w' and 'who'.
+        UtmpIdentifier = "tty7";
+        UtmpMode = "user";
+      };
+    };
+
+    environment.systemPackages = [
+      pkgs.phoc
+      cfg.package
+      pkgs.squeekboard
+      oskItem
+    ];
+
+    systemd.packages = [ cfg.package ];
+
+    programs.feedbackd.enable = true;
+
+    security.pam.services.phosh = {};
+
+    hardware.opengl.enable = mkDefault true;
+
+    services.gnome.core-shell.enable = true;
+    services.gnome.core-os-services.enable = true;
+    services.xserver.displayManager.sessionPackages = [ cfg.package ];
+
+    environment.etc."phosh/phoc.ini".source =
+      if builtins.isPath cfg.phocConfig then cfg.phocConfig
+      else if builtins.isString cfg.phocConfig then pkgs.writeText "phoc.ini" cfg.phocConfig
+      else pkgs.writeText "phoc.ini" (renderPhocConfig cfg.phocConfig);
+  };
+}
diff --git a/nixos/modules/services/x11/desktop-managers/plasma5.nix b/nixos/modules/services/x11/desktop-managers/plasma5.nix
index 3ca044ad5bc..a6ab3053087 100644
--- a/nixos/modules/services/x11/desktop-managers/plasma5.nix
+++ b/nixos/modules/services/x11/desktop-managers/plasma5.nix
@@ -1,4 +1,4 @@
-{ config, lib, pkgs, ... }:
+{ config, lib, pkgs, utils, ... }:
 
 let
   xcfg = config.services.xserver;
@@ -30,7 +30,7 @@ let
   inherit (libsForQt5) kdeGear kdeFrameworks plasma5;
   inherit (pkgs) writeText;
   inherit (lib)
-    getBin optionalString
+    getBin optionalString literalExpression
     mkRemovedOptionModule mkRenamedOptionModule
     mkDefault mkIf mkMerge mkOption types;
 
@@ -157,23 +157,22 @@ in
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable the Plasma 5 (KDE 5) desktop environment.";
+      description = lib.mdDoc "Enable the Plasma 5 (KDE 5) desktop environment.";
     };
 
     phononBackend = mkOption {
       type = types.enum [ "gstreamer" "vlc" ];
       default = "gstreamer";
       example = "vlc";
-      description = "Phonon audio backend to install.";
+      description = lib.mdDoc "Phonon audio backend to install.";
     };
 
     supportDDC = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Support setting monitor brightness via DDC.
-        </para>
-        <para>
+
         This is not needed for controlling brightness of the internal monitor
         of a laptop and as it is considered experimental by upstream, it is
         disabled by default.
@@ -183,13 +182,20 @@ in
     useQtScaling = mkOption {
       type = types.bool;
       default = false;
-      description = "Enable HiDPI scaling in Qt.";
+      description = lib.mdDoc "Enable HiDPI scaling in Qt.";
     };
 
     runUsingSystemd = mkOption {
-      description = "Use systemd to manage the Plasma session";
+      description = lib.mdDoc "Use systemd to manage the Plasma session";
       type = types.bool;
-      default = false;
+      default = true;
+    };
+
+    excludePackages = mkOption {
+      description = lib.mdDoc "List of default packages to exclude from the configuration";
+      type = types.listOf types.package;
+      default = [];
+      example = literalExpression "[ pkgs.plasma5Packages.oxygen ]";
     };
 
     # Internally allows configuring kdeglobals globally
@@ -209,7 +215,7 @@ in
     mobile.enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable support for running the Plasma Mobile shell.
       '';
     };
@@ -217,11 +223,19 @@ in
     mobile.installRecommendedSoftware = mkOption {
       type = types.bool;
       default = true;
-      description = ''
+      description = lib.mdDoc ''
         Installs software recommended for use with Plasma Mobile, but which
         is not strictly required for Plasma Mobile to run.
       '';
     };
+
+    bigscreen.enable = mkOption {
+      type = types.bool;
+      default = false;
+      description = lib.mdDoc ''
+        Enable support for running the Plasma Bigscreen session.
+      '';
+    };
   };
 
   imports = [
@@ -231,14 +245,14 @@ in
 
   config = mkMerge [
     # Common Plasma dependencies
-    (mkIf (cfg.enable || cfg.mobile.enable) {
+    (mkIf (cfg.enable || cfg.mobile.enable || cfg.bigscreen.enable) {
 
       security.wrappers = {
-        kcheckpass = {
+        kscreenlocker_greet = {
           setuid = true;
           owner = "root";
           group = "root";
-          source = "${getBin libsForQt5.kscreenlocker}/libexec/kcheckpass";
+          source = "${getBin libsForQt5.kscreenlocker}/libexec/kscreenlocker_greet";
         };
         start_kdeinit = {
           setuid = true;
@@ -263,89 +277,97 @@ in
       environment.systemPackages =
         with libsForQt5;
         with plasma5; with kdeGear; with kdeFrameworks;
-        [
-          frameworkintegration
-          kactivities
-          kauth
-          kcmutils
-          kconfig
-          kconfigwidgets
-          kcoreaddons
-          kdoctools
-          kdbusaddons
-          kdeclarative
-          kded
-          kdesu
-          kdnssd
-          kemoticons
-          kfilemetadata
-          kglobalaccel
-          kguiaddons
-          kiconthemes
-          kidletime
-          kimageformats
-          kinit
-          kirigami2 # In system profile for SDDM theme. TODO: wrapper.
-          kio
-          kjobwidgets
-          knewstuff
-          knotifications
-          knotifyconfig
-          kpackage
-          kparts
-          kpeople
-          krunner
-          kservice
-          ktextwidgets
-          kwallet
-          kwallet-pam
-          kwalletmanager
-          kwayland
-          kwayland-integration
-          kwidgetsaddons
-          kxmlgui
-          kxmlrpcclient
-          plasma-framework
-          solid
-          sonnet
-          threadweaver
-
-          breeze-qt5
-          kactivitymanagerd
-          kde-cli-tools
-          kdecoration
-          kdeplasma-addons
-          kgamma5
-          khotkeys
-          kscreen
-          kscreenlocker
-          kwayland
-          kwin
-          kwrited
-          libkscreen
-          libksysguard
-          milou
-          plasma-browser-integration
-          plasma-integration
-          polkit-kde-agent
-
-          plasma-desktop
-          plasma-workspace
-          plasma-workspace-wallpapers
-
-          konsole
-          oxygen
-
-          breeze-icons
-          pkgs.hicolor-icon-theme
-
-          kde-gtk-config
-          breeze-gtk
-
-          qtvirtualkeyboard
-
-          pkgs.xdg-user-dirs # Update user dirs as described in https://freedesktop.org/wiki/Software/xdg-user-dirs/
-        ]
+        let
+          requiredPackages = [
+            frameworkintegration
+            kactivities
+            kauth
+            kcmutils
+            kconfig
+            kconfigwidgets
+            kcoreaddons
+            kdoctools
+            kdbusaddons
+            kdeclarative
+            kded
+            kdesu
+            kdnssd
+            kemoticons
+            kfilemetadata
+            kglobalaccel
+            kguiaddons
+            kiconthemes
+            kidletime
+            kimageformats
+            kinit
+            kirigami2 # In system profile for SDDM theme. TODO: wrapper.
+            kio
+            kjobwidgets
+            knewstuff
+            knotifications
+            knotifyconfig
+            kpackage
+            kparts
+            kpeople
+            krunner
+            kservice
+            ktextwidgets
+            kwallet
+            kwallet-pam
+            kwalletmanager
+            kwayland
+            kwayland-integration
+            kwidgetsaddons
+            kxmlgui
+            kxmlrpcclient
+            plasma-framework
+            solid
+            sonnet
+            threadweaver
+
+            breeze-qt5
+            kactivitymanagerd
+            kde-cli-tools
+            kdecoration
+            kdeplasma-addons
+            kgamma5
+            khotkeys
+            kscreen
+            kscreenlocker
+            kwayland
+            kwin
+            kwrited
+            libkscreen
+            libksysguard
+            milou
+            plasma-integration
+            polkit-kde-agent
+
+            plasma-desktop
+            plasma-workspace
+            plasma-workspace-wallpapers
+
+            oxygen-sounds
+
+            breeze-icons
+            pkgs.hicolor-icon-theme
+
+            kde-gtk-config
+            breeze-gtk
+
+            qtvirtualkeyboard
+
+            pkgs.xdg-user-dirs # Update user dirs as described in https://freedesktop.org/wiki/Software/xdg-user-dirs/
+          ];
+          optionalPackages = [
+            plasma-browser-integration
+            konsole
+            oxygen
+            (lib.getBin qttools) # Expose qdbus in PATH
+          ];
+        in
+        requiredPackages
+        ++ utils.removePackagesByName optionalPackages cfg.excludePackages
 
         # Phonon audio backend
         ++ lib.optional (cfg.phononBackend == "gstreamer") libsForQt5.phonon-backend-gstreamer
@@ -387,9 +409,10 @@ in
       services.accounts-daemon.enable = true;
       # when changing an account picture the accounts-daemon reads a temporary file containing the image which systemsettings5 may place under /tmp
       systemd.services.accounts-daemon.serviceConfig.PrivateTmp = false;
+      services.power-profiles-daemon.enable = mkDefault true;
+      services.system-config-printer.enable = mkIf config.services.printing.enable (mkDefault true);
       services.udisks2.enable = true;
       services.upower.enable = config.powerManagement.enable;
-      services.system-config-printer.enable = mkIf config.services.printing.enable (mkDefault true);
       services.xserver.libinput.enable = mkDefault true;
 
       # Extra UDEV rules used by Solid
@@ -429,11 +452,14 @@ in
       services.xserver.displayManager.setupCommands = startplasma;
 
       nixpkgs.config.firefox.enablePlasmaBrowserIntegration = true;
+    })
 
-      environment.etc = {
-        "xdg/kwinrc".text     = lib.generators.toINI {} cfg.kwinrc;
-        "xdg/kdeglobals".text = lib.generators.toINI {} cfg.kdeglobals;
-      };
+    (mkIf (cfg.kwinrc != {}) {
+      environment.etc."xdg/kwinrc".text = lib.generators.toINI {} cfg.kwinrc;
+    })
+
+    (mkIf (cfg.kdeglobals != {}) {
+      environment.etc."xdg/kdeglobals".text = lib.generators.toINI {} cfg.kdeglobals;
     })
 
     # Plasma Desktop
@@ -457,27 +483,29 @@ in
       environment.systemPackages =
         with libsForQt5;
         with plasma5; with kdeGear; with kdeFrameworks;
-        [
-          ksystemstats
-          kinfocenter
-          kmenuedit
-          plasma-systemmonitor
-          spectacle
-          systemsettings
-
-          dolphin
-          dolphin-plugins
-          ffmpegthumbs
-          kdegraphics-thumbnailers
-          khelpcenter
-          kio-extras
-          print-manager
-
-          elisa
-          gwenview
-          okular
-        ]
-      ;
+        let
+          requiredPackages = [
+            ksystemstats
+            kinfocenter
+            kmenuedit
+            plasma-systemmonitor
+            spectacle
+            systemsettings
+
+            dolphin
+            dolphin-plugins
+            ffmpegthumbs
+            kdegraphics-thumbnailers
+            kio-extras
+          ];
+          optionalPackages = [
+            elisa
+            gwenview
+            okular
+            khelpcenter
+            print-manager
+          ];
+      in requiredPackages ++ utils.removePackagesByName optionalPackages cfg.excludePackages;
 
       systemd.user.services = {
         plasma-run-with-systemd = {
@@ -562,9 +590,9 @@ in
           };
         };
         kwinrc = {
-          Windows = {
-            # Forces windows to be maximized
-            Placement = lib.mkDefault "Maximizing";
+          "Wayland" = {
+            "InputMethod[$e]" = "/run/current-system/sw/share/applications/com.github.maliit.keyboard.desktop";
+            "VirtualKeyboardEnabled" = "true";
           };
           "org.kde.kdecoration2" = {
             # No decorations (title bar)
@@ -575,5 +603,29 @@ in
 
       services.xserver.displayManager.sessionPackages = [ pkgs.libsForQt5.plasma5.plasma-mobile ];
     })
+
+    # Plasma Bigscreen
+    (mkIf cfg.bigscreen.enable {
+      environment.systemPackages =
+        with pkgs.plasma5Packages;
+        [
+          plasma-nano
+          plasma-settings
+          plasma-bigscreen
+          plasma-remotecontrollers
+
+          aura-browser
+          plank-player
+
+          plasma-pa
+          plasma-nm
+          kdeconnect-kde
+        ];
+
+      services.xserver.displayManager.sessionPackages = [ pkgs.plasma5Packages.plasma-bigscreen ];
+
+      # required for plasma-remotecontrollers to work correctly
+      hardware.uinput.enable = true;
+    })
   ];
 }
diff --git a/nixos/modules/services/x11/desktop-managers/retroarch.nix b/nixos/modules/services/x11/desktop-managers/retroarch.nix
index d471673d452..5552f37612a 100644
--- a/nixos/modules/services/x11/desktop-managers/retroarch.nix
+++ b/nixos/modules/services/x11/desktop-managers/retroarch.nix
@@ -6,21 +6,21 @@ let cfg = config.services.xserver.desktopManager.retroarch;
 
 in {
   options.services.xserver.desktopManager.retroarch = {
-    enable = mkEnableOption "RetroArch";
+    enable = mkEnableOption (lib.mdDoc "RetroArch");
 
     package = mkOption {
       type = types.package;
       default = pkgs.retroarch;
       defaultText = literalExpression "pkgs.retroarch";
       example = literalExpression "pkgs.retroarch-full";
-      description = "RetroArch package to use.";
+      description = lib.mdDoc "RetroArch package to use.";
     };
 
     extraArgs = mkOption {
       type = types.listOf types.str;
       default = [ ];
       example = [ "--verbose" "--host" ];
-      description = "Extra arguments to pass to RetroArch.";
+      description = lib.mdDoc "Extra arguments to pass to RetroArch.";
     };
   };
 
diff --git a/nixos/modules/services/x11/desktop-managers/surf-display.nix b/nixos/modules/services/x11/desktop-managers/surf-display.nix
index 4b5a04f988b..38ebb9d02b4 100644
--- a/nixos/modules/services/x11/desktop-managers/surf-display.nix
+++ b/nixos/modules/services/x11/desktop-managers/surf-display.nix
@@ -45,21 +45,21 @@ let
 in {
   options = {
     services.xserver.desktopManager.surf-display = {
-      enable = mkEnableOption "surf-display as a kiosk browser session";
+      enable = mkEnableOption (lib.mdDoc "surf-display as a kiosk browser session");
 
       defaultWwwUri = mkOption {
         type = types.str;
         default = "${pkgs.surf-display}/share/surf-display/empty-page.html";
         defaultText = literalExpression ''"''${pkgs.surf-display}/share/surf-display/empty-page.html"'';
         example = "https://www.example.com/";
-        description = "Default URI to display.";
+        description = lib.mdDoc "Default URI to display.";
       };
 
       inactivityInterval = mkOption {
         type = types.int;
         default = 300;
         example = 0;
-        description = ''
+        description = lib.mdDoc ''
           Setting for internal inactivity timer to restart surf-display if the
           user goes inactive/idle to get a fresh session for the next user of
           the kiosk.
@@ -72,18 +72,18 @@ in {
       screensaverSettings = mkOption {
         type = types.separatedString " ";
         default = "";
-        description = ''
-          Screensaver settings, see <literal>man 1 xset</literal> for possible options.
+        description = lib.mdDoc ''
+          Screensaver settings, see `man 1 xset` for possible options.
         '';
       };
 
       pointerButtonMap = mkOption {
         type = types.str;
         default = "1 0 0 4 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0";
-        description = ''
+        description = lib.mdDoc ''
           Disable right and middle pointer device click in browser sessions
           while keeping scrolling wheels' functionality intact. See pointer
-          subcommand on <literal>man xmodmap</literal> for details.
+          subcommand on `man xmodmap` for details.
         '';
       };
 
@@ -91,7 +91,7 @@ in {
         type = types.str;
         default = "yes";
         example = "no";
-        description = "Hide idle mouse pointer.";
+        description = lib.mdDoc "Hide idle mouse pointer.";
       };
 
       extraConfig = mkOption {
@@ -111,8 +111,8 @@ in {
           DISPLAYS['display-host-3']="www_uri=https://www.displayserver.comany.net/display-4/index.html"|res=1280x1024"
           DISPLAYS['display-host-local-file']="www_uri=file:///usr/share/doc/surf-display/empty-page.html"
         '';
-        description = ''
-          Extra configuration options to append to <literal>/etc/default/surf-display</literal>.
+        description = lib.mdDoc ''
+          Extra configuration options to append to `/etc/default/surf-display`.
         '';
       };
     };
diff --git a/nixos/modules/services/x11/desktop-managers/xfce.nix b/nixos/modules/services/x11/desktop-managers/xfce.nix
index 3cf92f98c56..eee1f63ebdc 100644
--- a/nixos/modules/services/x11/desktop-managers/xfce.nix
+++ b/nixos/modules/services/x11/desktop-managers/xfce.nix
@@ -4,10 +4,9 @@ with lib;
 
 let
   cfg = config.services.xserver.desktopManager.xfce;
-in
 
+in
 {
-
   meta = {
     maintainers = teams.xfce.members;
   };
@@ -36,6 +35,12 @@ in
       [ "services" "xserver" "desktopManager" "xfce" "extraSessionCommands" ]
       [ "services" "xserver" "displayManager" "sessionCommands" ])
     (mkRemovedOptionModule [ "services" "xserver" "desktopManager" "xfce" "screenLock" ] "")
+
+    # added 2022-06-26
+    # thunar has its own module
+    (mkRenamedOptionModule
+      [ "services" "xserver" "desktopManager" "xfce" "thunarPlugins" ]
+      [ "programs" "thunar" "plugins" ])
   ];
 
   options = {
@@ -43,28 +48,25 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable the Xfce desktop environment.";
-      };
-
-      thunarPlugins = mkOption {
-        default = [];
-        type = types.listOf types.package;
-        example = literalExpression "[ pkgs.xfce.thunar-archive-plugin ]";
-        description = ''
-          A list of plugin that should be installed with Thunar.
-        '';
+        description = lib.mdDoc "Enable the Xfce desktop environment.";
       };
 
       noDesktop = mkOption {
         type = types.bool;
         default = false;
-        description = "Don't install XFCE desktop components (xfdesktop and panel).";
+        description = lib.mdDoc "Don't install XFCE desktop components (xfdesktop and panel).";
       };
 
       enableXfwm = mkOption {
         type = types.bool;
         default = true;
-        description = "Enable the XFWM (default) window manager.";
+        description = lib.mdDoc "Enable the XFWM (default) window manager.";
+      };
+
+      enableScreensaver = mkOption {
+        type = types.bool;
+        default = true;
+        description = lib.mdDoc "Enable the XFCE screensaver.";
       };
     };
   };
@@ -92,7 +94,6 @@ in
       exo
       garcon
       libxfce4ui
-      xfconf
 
       mousepad
       parole
@@ -104,8 +105,6 @@ in
       xfce4-settings
       xfce4-taskmanager
       xfce4-terminal
-
-      (thunar.override { thunarPlugins = cfg.thunarPlugins; })
     ] # TODO: NetworkManager doesn't belong here
       ++ optional config.networking.networkmanager.enable networkmanagerapplet
       ++ optional config.powerManagement.enable xfce4-power-manager
@@ -122,7 +121,10 @@ in
       ] ++ optionals (!cfg.noDesktop) [
         xfce4-panel
         xfdesktop
-      ];
+      ] ++ optional cfg.enableScreensaver xfce4-screensaver;
+
+    programs.xfconf.enable = true;
+    programs.thunar.enable = true;
 
     environment.pathsToLink = [
       "/share/xfce4"
@@ -164,9 +166,9 @@ in
 
     # Systemd services
     systemd.packages = with pkgs.xfce; [
-      (thunar.override { thunarPlugins = cfg.thunarPlugins; })
       xfce4-notifyd
     ];
 
+    security.pam.services.xfce4-screensaver.unixAuth = cfg.enableScreensaver;
   };
 }
diff --git a/nixos/modules/services/x11/desktop-managers/xterm.nix b/nixos/modules/services/x11/desktop-managers/xterm.nix
index 3424ee1b0e1..2b439effabe 100644
--- a/nixos/modules/services/x11/desktop-managers/xterm.nix
+++ b/nixos/modules/services/x11/desktop-managers/xterm.nix
@@ -16,7 +16,7 @@ in
       type = types.bool;
       default = versionOlder config.system.stateVersion "19.09" && xSessionEnabled;
       defaultText = literalExpression ''versionOlder config.system.stateVersion "19.09" && config.services.xserver.enable;'';
-      description = "Enable a xterm terminal as a desktop manager.";
+      description = lib.mdDoc "Enable a xterm terminal as a desktop manager.";
     };
 
   };
diff --git a/nixos/modules/services/x11/display-managers/default.nix b/nixos/modules/services/x11/display-managers/default.nix
index a5db3dd5dd4..995ecd231c4 100644
--- a/nixos/modules/services/x11/display-managers/default.nix
+++ b/nixos/modules/services/x11/display-managers/default.nix
@@ -24,7 +24,7 @@ let
     Xft.lcdfilter: lcd${fontconfig.subpixel.lcdfilter}
     Xft.hinting: ${if fontconfig.hinting.enable then "1" else "0"}
     Xft.autohint: ${if fontconfig.hinting.autohint then "1" else "0"}
-    Xft.hintstyle: hintslight
+    Xft.hintstyle: ${fontconfig.hinting.style}
   '';
 
   # file provided by services.xserver.displayManager.sessionData.wrapper
@@ -35,6 +35,10 @@ let
       # Shared environment setup for graphical sessions.
 
       . /etc/profile
+      if test -f ~/.profile; then
+          source ~/.profile
+      fi
+
       cd "$HOME"
 
       # Allow the user to execute commands at the beginning of the X session.
@@ -149,25 +153,25 @@ in
         internal = true;
         default = "${xorg.xauth}/bin/xauth";
         defaultText = literalExpression ''"''${pkgs.xorg.xauth}/bin/xauth"'';
-        description = "Path to the <command>xauth</command> program used by display managers.";
+        description = lib.mdDoc "Path to the {command}`xauth` program used by display managers.";
       };
 
       xserverBin = mkOption {
         type = types.path;
-        description = "Path to the X server used by display managers.";
+        description = lib.mdDoc "Path to the X server used by display managers.";
       };
 
       xserverArgs = mkOption {
         type = types.listOf types.str;
         default = [];
         example = [ "-ac" "-logverbose" "-verbose" "-nolisten tcp" ];
-        description = "List of arguments for the X server.";
+        description = lib.mdDoc "List of arguments for the X server.";
       };
 
       setupCommands = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Shell commands executed just after the X server has started.
 
           This option is only effective for display managers for which this feature
@@ -182,7 +186,7 @@ in
           ''
             xmessage "Hello World!" &
           '';
-        description = ''
+        description = lib.mdDoc ''
           Shell commands executed just before the window or desktop manager is
           started. These commands are not currently sourced for Wayland sessions.
         '';
@@ -191,7 +195,7 @@ in
       hiddenUsers = mkOption {
         type = types.listOf types.str;
         default = [ "nobody" ];
-        description = ''
+        description = lib.mdDoc ''
           A list of users which will not be shown in the display manager.
         '';
       };
@@ -212,7 +216,7 @@ in
            '';
         });
         default = [];
-        description = ''
+        description = lib.mdDoc ''
           A list of packages containing x11 or wayland session files to be passed to the display manager.
         '';
       };
@@ -231,15 +235,15 @@ in
               }
             ]
           '';
-        description = ''
+        description = lib.mdDoc ''
           List of sessions supported with the command used to start each
           session.  Each session script can set the
-          <varname>waitPID</varname> shell variable to make this script
+          {var}`waitPID` shell variable to make this script
           wait until the end of the user session.  Each script is used
           to define either a window manager or a desktop manager.  These
           can be differentiated by setting the attribute
-          <varname>manage</varname> either to <literal>"window"</literal>
-          or <literal>"desktop"</literal>.
+          {var}`manage` either to `"window"`
+          or `"desktop"`.
 
           The list of desktop manager and window manager should appear
           inside the display manager with the desktop manager name
@@ -248,7 +252,7 @@ in
       };
 
       sessionData = mkOption {
-        description = "Data exported for display managers’ convenience";
+        description = lib.mdDoc "Data exported for display managers’ convenience";
         internal = true;
         default = {};
         apply = val: {
@@ -281,11 +285,11 @@ in
             defaultSessionFromLegacyOptions
           else
             null;
-        defaultText = literalDocBook ''
+        defaultText = literalMD ''
           Taken from display manager settings or window manager settings, if either is set.
         '';
         example = "gnome";
-        description = ''
+        description = lib.mdDoc ''
           Graphical session to pre-select in the session chooser (only effective for GDM, LightDM and SDDM).
 
           On GDM, LightDM and SDDM, it will also be used as a session for auto-login.
@@ -295,7 +299,7 @@ in
       importedVariables = mkOption {
         type = types.listOf (types.strMatching "[a-zA-Z_][a-zA-Z0-9_]*");
         visible = false;
-        description = ''
+        description = lib.mdDoc ''
           Environment variables to import into the systemd user environment.
         '';
       };
@@ -306,34 +310,34 @@ in
           type = types.lines;
           default = "";
           example = "rm -f /var/log/my-display-manager.log";
-          description = "Script executed before the display manager is started.";
+          description = lib.mdDoc "Script executed before the display manager is started.";
         };
 
         execCmd = mkOption {
           type = types.str;
           example = literalExpression ''"''${pkgs.lightdm}/bin/lightdm"'';
-          description = "Command to start the display manager.";
+          description = lib.mdDoc "Command to start the display manager.";
         };
 
         environment = mkOption {
           type = types.attrsOf types.unspecified;
           default = {};
-          description = "Additional environment variables needed by the display manager.";
+          description = lib.mdDoc "Additional environment variables needed by the display manager.";
         };
 
         logToFile = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             Whether the display manager redirects the output of the
-            session script to <filename>~/.xsession-errors</filename>.
+            session script to {file}`~/.xsession-errors`.
           '';
         };
 
         logToJournal = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             Whether the display manager redirects the output of the
             session script to the systemd journal.
           '';
@@ -349,15 +353,15 @@ in
               type = types.bool;
               default = config.user != null;
               defaultText = literalExpression "config.${options.user} != null";
-              description = ''
-                Automatically log in as <option>autoLogin.user</option>.
+              description = lib.mdDoc ''
+                Automatically log in as {option}`autoLogin.user`.
               '';
             };
 
             user = mkOption {
               type = types.nullOr types.str;
               default = null;
-              description = ''
+              description = lib.mdDoc ''
                 User to be used for the automatic login.
               '';
             };
@@ -365,7 +369,7 @@ in
         });
 
         default = {};
-        description = ''
+        description = lib.mdDoc ''
           Auto login configuration attrset.
         '';
       };
diff --git a/nixos/modules/services/x11/display-managers/gdm.nix b/nixos/modules/services/x11/display-managers/gdm.nix
index 70ae6b8978d..1c3881bef2d 100644
--- a/nixos/modules/services/x11/display-managers/gdm.nix
+++ b/nixos/modules/services/x11/display-managers/gdm.nix
@@ -67,15 +67,15 @@ in
 
     services.xserver.displayManager.gdm = {
 
-      enable = mkEnableOption "GDM, the GNOME Display Manager";
+      enable = mkEnableOption (lib.mdDoc "GDM, the GNOME Display Manager");
 
-      debug = mkEnableOption "debugging messages in GDM";
+      debug = mkEnableOption (lib.mdDoc "debugging messages in GDM");
 
       # Auto login options specific to GDM
       autoLogin.delay = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Seconds of inactivity after which the autologin will be performed.
         '';
       };
@@ -83,14 +83,14 @@ in
       wayland = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Allow GDM to run on Wayland instead of Xserver.
         '';
       };
 
       autoSuspend = mkOption {
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           On the GNOME Display Manager login screen, suspend the machine after inactivity.
           (Does not affect automatic suspend while logged in, or at lock screen.)
         '';
@@ -103,9 +103,9 @@ in
         example = {
           debug.enable = true;
         };
-        description = ''
+        description = lib.mdDoc ''
           Options passed to the gdm daemon.
-          See <link xlink:href="https://help.gnome.org/admin/gdm/stable/configuration.html.en#daemonconfig">here</link> for supported options.
+          See [here](https://help.gnome.org/admin/gdm/stable/configuration.html.en#daemonconfig) for supported options.
         '';
       };
 
@@ -140,8 +140,13 @@ in
         environment = {
           GDM_X_SERVER_EXTRA_ARGS = toString
             (filter (arg: arg != "-terminate") cfg.xserverArgs);
-          # GDM is needed for gnome-login.session
-          XDG_DATA_DIRS = "${gdm}/share:${cfg.sessionData.desktops}/share:${pkgs.gnome.gnome-control-center}/share";
+          XDG_DATA_DIRS = lib.makeSearchPath "share" [
+            gdm # for gnome-login.session
+            cfg.sessionData.desktops
+            pkgs.gnome.gnome-control-center # for accessibility icon
+            pkgs.gnome.adwaita-icon-theme
+            pkgs.hicolor-icon-theme # empty icon theme as a base
+          ];
         } // optionalAttrs (xSessionWrapper != null) {
           # Make GDM use this wrapper before running the session, which runs the
           # configured setupCommands. This relies on a patched GDM which supports
@@ -298,7 +303,7 @@ in
 
         session  required       pam_succeed_if.so audit quiet_success user = gdm
         session  required       pam_env.so conffile=/etc/pam/environment readenv=0
-        session  optional       ${pkgs.systemd}/lib/security/pam_systemd.so
+        session  optional       ${config.systemd.package}/lib/security/pam_systemd.so
         session  optional       pam_keyinit.so force revoke
         session  optional       pam_permit.so
       '';
diff --git a/nixos/modules/services/x11/display-managers/lightdm-greeters/enso-os.nix b/nixos/modules/services/x11/display-managers/lightdm-greeters/enso-os.nix
index 930ee96b384..412bcc4091b 100644
--- a/nixos/modules/services/x11/display-managers/lightdm-greeters/enso-os.nix
+++ b/nixos/modules/services/x11/display-managers/lightdm-greeters/enso-os.nix
@@ -26,7 +26,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable enso-os-greeter as the lightdm greeter
         '';
       };
@@ -36,7 +36,7 @@ in {
           type = types.package;
           default = pkgs.gnome.gnome-themes-extra;
           defaultText = literalExpression "pkgs.gnome.gnome-themes-extra";
-          description = ''
+          description = lib.mdDoc ''
             The package path that contains the theme given in the name option.
           '';
         };
@@ -44,7 +44,7 @@ in {
         name = mkOption {
           type = types.str;
           default = "Adwaita";
-          description = ''
+          description = lib.mdDoc ''
             Name of the theme to use for the lightdm-enso-os-greeter
           '';
         };
@@ -55,7 +55,7 @@ in {
           type = types.package;
           default = pkgs.papirus-icon-theme;
           defaultText = literalExpression "pkgs.papirus-icon-theme";
-          description = ''
+          description = lib.mdDoc ''
             The package path that contains the icon theme given in the name option.
           '';
         };
@@ -63,7 +63,7 @@ in {
         name = mkOption {
           type = types.str;
           default = "ePapirus";
-          description = ''
+          description = lib.mdDoc ''
             Name of the icon theme to use for the lightdm-enso-os-greeter
           '';
         };
@@ -74,7 +74,7 @@ in {
           type = types.package;
           default = pkgs.capitaine-cursors;
           defaultText = literalExpression "pkgs.capitaine-cursors";
-          description = ''
+          description = lib.mdDoc ''
             The package path that contains the cursor theme given in the name option.
           '';
         };
@@ -82,7 +82,7 @@ in {
         name = mkOption {
           type = types.str;
           default = "capitane-cursors";
-          description = ''
+          description = lib.mdDoc ''
             Name of the cursor theme to use for the lightdm-enso-os-greeter
           '';
         };
@@ -91,7 +91,7 @@ in {
       blur = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether or not to enable blur
         '';
       };
@@ -99,7 +99,7 @@ in {
       brightness = mkOption {
         type = types.int;
         default = 7;
-        description = ''
+        description = lib.mdDoc ''
           Brightness
         '';
       };
@@ -107,7 +107,7 @@ in {
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration that should be put in the greeter.conf
           configuration file
         '';
diff --git a/nixos/modules/services/x11/display-managers/lightdm-greeters/gtk.nix b/nixos/modules/services/x11/display-managers/lightdm-greeters/gtk.nix
index debd4b568bf..c050367e74d 100644
--- a/nixos/modules/services/x11/display-managers/lightdm-greeters/gtk.nix
+++ b/nixos/modules/services/x11/display-managers/lightdm-greeters/gtk.nix
@@ -38,7 +38,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable lightdm-gtk-greeter as the lightdm greeter.
         '';
       };
@@ -49,7 +49,7 @@ in
           type = types.package;
           default = pkgs.gnome.gnome-themes-extra;
           defaultText = literalExpression "pkgs.gnome.gnome-themes-extra";
-          description = ''
+          description = lib.mdDoc ''
             The package path that contains the theme given in the name option.
           '';
         };
@@ -57,7 +57,7 @@ in
         name = mkOption {
           type = types.str;
           default = "Adwaita";
-          description = ''
+          description = lib.mdDoc ''
             Name of the theme to use for the lightdm-gtk-greeter.
           '';
         };
@@ -70,7 +70,7 @@ in
           type = types.package;
           default = pkgs.gnome.adwaita-icon-theme;
           defaultText = literalExpression "pkgs.gnome.adwaita-icon-theme";
-          description = ''
+          description = lib.mdDoc ''
             The package path that contains the icon theme given in the name option.
           '';
         };
@@ -78,7 +78,7 @@ in
         name = mkOption {
           type = types.str;
           default = "Adwaita";
-          description = ''
+          description = lib.mdDoc ''
             Name of the icon theme to use for the lightdm-gtk-greeter.
           '';
         };
@@ -91,7 +91,7 @@ in
           type = types.package;
           default = pkgs.gnome.adwaita-icon-theme;
           defaultText = literalExpression "pkgs.gnome.adwaita-icon-theme";
-          description = ''
+          description = lib.mdDoc ''
             The package path that contains the cursor theme given in the name option.
           '';
         };
@@ -99,7 +99,7 @@ in
         name = mkOption {
           type = types.str;
           default = "Adwaita";
-          description = ''
+          description = lib.mdDoc ''
             Name of the cursor theme to use for the lightdm-gtk-greeter.
           '';
         };
@@ -107,7 +107,7 @@ in
         size = mkOption {
           type = types.int;
           default = 16;
-          description = ''
+          description = lib.mdDoc ''
             Size of the cursor theme to use for the lightdm-gtk-greeter.
           '';
         };
@@ -117,7 +117,7 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "%F";
-        description = ''
+        description = lib.mdDoc ''
           Clock format string (as expected by strftime, e.g. "%H:%M")
           to use with the lightdm gtk greeter panel.
 
@@ -129,7 +129,7 @@ in
         type = types.nullOr (types.listOf types.str);
         default = null;
         example = [ "~host" "~spacer" "~clock" "~spacer" "~session" "~language" "~a11y" "~power" ];
-        description = ''
+        description = lib.mdDoc ''
           List of allowed indicator modules to use for the lightdm gtk
           greeter panel.
 
@@ -145,7 +145,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration that should be put in the lightdm-gtk-greeter.conf
           configuration file.
         '';
@@ -158,7 +158,7 @@ in
   config = mkIf (ldmcfg.enable && cfg.enable) {
 
     services.xserver.displayManager.lightdm.greeter = mkDefault {
-      package = pkgs.lightdm_gtk_greeter.xgreeters;
+      package = pkgs.lightdm-gtk-greeter.xgreeters;
       name = "lightdm-gtk-greeter";
     };
 
diff --git a/nixos/modules/services/x11/display-managers/lightdm-greeters/mini.nix b/nixos/modules/services/x11/display-managers/lightdm-greeters/mini.nix
index 16d7fdf15cf..f4195c4c2dc 100644
--- a/nixos/modules/services/x11/display-managers/lightdm-greeters/mini.nix
+++ b/nixos/modules/services/x11/display-managers/lightdm-greeters/mini.nix
@@ -55,19 +55,19 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable lightdm-mini-greeter as the lightdm greeter.
 
           Note that this greeter starts only the default X session.
           You can configure the default X session using
-          <xref linkend="opt-services.xserver.displayManager.defaultSession"/>.
+          [](#opt-services.xserver.displayManager.defaultSession).
         '';
       };
 
       user = mkOption {
         type = types.str;
         default = "root";
-        description = ''
+        description = lib.mdDoc ''
           The user to login as.
         '';
       };
@@ -75,7 +75,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Extra configuration that should be put in the lightdm-mini-greeter.conf
           configuration file.
         '';
diff --git a/nixos/modules/services/x11/display-managers/lightdm-greeters/mobile.nix b/nixos/modules/services/x11/display-managers/lightdm-greeters/mobile.nix
new file mode 100644
index 00000000000..31cc9b3deaa
--- /dev/null
+++ b/nixos/modules/services/x11/display-managers/lightdm-greeters/mobile.nix
@@ -0,0 +1,26 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+let
+  dmcfg = config.services.xserver.displayManager;
+  ldmcfg = dmcfg.lightdm;
+  cfg = ldmcfg.greeters.mobile;
+in
+{
+  options = {
+    services.xserver.displayManager.lightdm.greeters.mobile = {
+      enable = mkEnableOption (lib.mdDoc
+        "lightdm-mobile-greeter as the lightdm greeter"
+      );
+    };
+  };
+
+  config = mkIf (ldmcfg.enable && cfg.enable) {
+    services.xserver.displayManager.lightdm.greeters.gtk.enable = false;
+
+    services.xserver.displayManager.lightdm.greeter = mkDefault {
+      package = pkgs.lightdm-mobile-greeter.xgreeters;
+      name = "lightdm-mobile-greeter";
+    };
+  };
+}
diff --git a/nixos/modules/services/x11/display-managers/lightdm-greeters/pantheon.nix b/nixos/modules/services/x11/display-managers/lightdm-greeters/pantheon.nix
index f18e4a914e5..10707e001e8 100644
--- a/nixos/modules/services/x11/display-managers/lightdm-greeters/pantheon.nix
+++ b/nixos/modules/services/x11/display-managers/lightdm-greeters/pantheon.nix
@@ -21,7 +21,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable elementary-greeter as the lightdm greeter.
         '';
       };
diff --git a/nixos/modules/services/x11/display-managers/lightdm-greeters/slick.nix b/nixos/modules/services/x11/display-managers/lightdm-greeters/slick.nix
new file mode 100644
index 00000000000..00fa8af71dc
--- /dev/null
+++ b/nixos/modules/services/x11/display-managers/lightdm-greeters/slick.nix
@@ -0,0 +1,118 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  ldmcfg = config.services.xserver.displayManager.lightdm;
+  cfg = ldmcfg.greeters.slick;
+
+  inherit (pkgs) writeText;
+
+  theme = cfg.theme.package;
+  icons = cfg.iconTheme.package;
+  font = cfg.font.package;
+
+  slickGreeterConf = writeText "slick-greeter.conf" ''
+    [Greeter]
+    background=${ldmcfg.background}
+    theme-name=${cfg.theme.name}
+    icon-theme-name=${cfg.iconTheme.name}
+    font-name=${cfg.font.name}
+    draw-user-backgrounds=${boolToString cfg.draw-user-backgrounds}
+    ${cfg.extraConfig}
+  '';
+in
+{
+  options = {
+    services.xserver.displayManager.lightdm.greeters.slick = {
+      enable = mkEnableOption (lib.mdDoc "lightdm-slick-greeter as the lightdm greeter");
+
+      theme = {
+        package = mkOption {
+          type = types.package;
+          default = pkgs.gnome.gnome-themes-extra;
+          defaultText = literalExpression "pkgs.gnome.gnome-themes-extra";
+          description = lib.mdDoc ''
+            The package path that contains the theme given in the name option.
+          '';
+        };
+
+        name = mkOption {
+          type = types.str;
+          default = "Adwaita";
+          description = lib.mdDoc ''
+            Name of the theme to use for the lightdm-slick-greeter.
+          '';
+        };
+      };
+
+      iconTheme = {
+        package = mkOption {
+          type = types.package;
+          default = pkgs.gnome.adwaita-icon-theme;
+          defaultText = literalExpression "pkgs.gnome.adwaita-icon-theme";
+          description = lib.mdDoc ''
+            The package path that contains the icon theme given in the name option.
+          '';
+        };
+
+        name = mkOption {
+          type = types.str;
+          default = "Adwaita";
+          description = lib.mdDoc ''
+            Name of the icon theme to use for the lightdm-slick-greeter.
+          '';
+        };
+      };
+
+      font = {
+        package = mkOption {
+          type = types.package;
+          default = pkgs.ubuntu_font_family;
+          defaultText = literalExpression "pkgs.ubuntu_font_family";
+          description = lib.mdDoc ''
+            The package path that contains the font given in the name option.
+          '';
+        };
+
+        name = mkOption {
+          type = types.str;
+          default = "Ubuntu 11";
+          description = lib.mdDoc ''
+            Name of the font to use.
+          '';
+        };
+      };
+
+      draw-user-backgrounds = mkEnableOption (lib.mdDoc "draw user backgrounds");
+
+      extraConfig = mkOption {
+        type = types.lines;
+        default = "";
+        description = lib.mdDoc ''
+          Extra configuration that should be put in the lightdm-slick-greeter.conf
+          configuration file.
+        '';
+      };
+    };
+  };
+
+  config = mkIf (ldmcfg.enable && cfg.enable) {
+    services.xserver.displayManager.lightdm = {
+      greeters.gtk.enable = false;
+      greeter = mkDefault {
+        package = pkgs.lightdm-slick-greeter.xgreeters;
+        name = "lightdm-slick-greeter";
+      };
+    };
+
+    environment.systemPackages = [
+      icons
+      theme
+    ];
+
+    fonts.fonts = [ font ];
+
+    environment.etc."lightdm/slick-greeter.conf".source = slickGreeterConf;
+  };
+}
diff --git a/nixos/modules/services/x11/display-managers/lightdm-greeters/tiny.nix b/nixos/modules/services/x11/display-managers/lightdm-greeters/tiny.nix
index a9ba8e6280d..8d6bfa98a7e 100644
--- a/nixos/modules/services/x11/display-managers/lightdm-greeters/tiny.nix
+++ b/nixos/modules/services/x11/display-managers/lightdm-greeters/tiny.nix
@@ -17,12 +17,12 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable lightdm-tiny-greeter as the lightdm greeter.
 
           Note that this greeter starts only the default X session.
           You can configure the default X session using
-          <xref linkend="opt-services.xserver.displayManager.defaultSession"/>.
+          [](#opt-services.xserver.displayManager.defaultSession).
         '';
       };
 
@@ -30,7 +30,7 @@ in
         user = mkOption {
           type = types.str;
           default = "Username";
-          description = ''
+          description = lib.mdDoc ''
             The string to represent the user_text label.
           '';
         };
@@ -38,7 +38,7 @@ in
         pass = mkOption {
           type = types.str;
           default = "Password";
-          description = ''
+          description = lib.mdDoc ''
             The string to represent the pass_text label.
           '';
         };
@@ -48,7 +48,7 @@ in
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Section to describe style and ui.
         '';
       };
diff --git a/nixos/modules/services/x11/display-managers/lightdm.nix b/nixos/modules/services/x11/display-managers/lightdm.nix
index 27dfed3cc14..f74e8efb8f6 100644
--- a/nixos/modules/services/x11/display-managers/lightdm.nix
+++ b/nixos/modules/services/x11/display-managers/lightdm.nix
@@ -82,6 +82,8 @@ in
     ./lightdm-greeters/enso-os.nix
     ./lightdm-greeters/pantheon.nix
     ./lightdm-greeters/tiny.nix
+    ./lightdm-greeters/slick.nix
+    ./lightdm-greeters/mobile.nix
     (mkRenamedOptionModule [ "services" "xserver" "displayManager" "lightdm" "autoLogin" "enable" ] [
       "services"
       "xserver"
@@ -105,7 +107,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable lightdm as the display manager.
         '';
       };
@@ -114,14 +116,14 @@ in
         enable = mkOption {
           type = types.bool;
           default = true;
-          description = ''
+          description = lib.mdDoc ''
             If set to false, run lightdm in greeterless mode. This only works if autologin
             is enabled and autoLogin.timeout is zero.
           '';
         };
         package = mkOption {
           type = types.package;
-          description = ''
+          description = lib.mdDoc ''
             The LightDM greeter to login via. The package should be a directory
             containing a .desktop file matching the name in the 'name' option.
           '';
@@ -129,7 +131,7 @@ in
         };
         name = mkOption {
           type = types.str;
-          description = ''
+          description = lib.mdDoc ''
             The name of a .desktop file in the directory specified
             in the 'package' option.
           '';
@@ -142,14 +144,14 @@ in
         example = ''
           user-authority-in-system-dir = true
         '';
-        description = "Extra lines to append to LightDM section.";
+        description = lib.mdDoc "Extra lines to append to LightDM section.";
       };
 
       background = mkOption {
         type = types.either types.path (types.strMatching "^#[0-9]\{6\}$");
         # Manual cannot depend on packages, we are actually setting the default in config below.
         defaultText = literalExpression "pkgs.nixos-artwork.wallpapers.simple-dark-gray-bottom.gnomeFilePath";
-        description = ''
+        description = lib.mdDoc ''
           The background image or color to use.
         '';
       };
@@ -160,14 +162,14 @@ in
         example = ''
           greeter-show-manual-login=true
         '';
-        description = "Extra lines to append to SeatDefaults section.";
+        description = lib.mdDoc "Extra lines to append to SeatDefaults section.";
       };
 
       # Configuration for automatic login specific to LightDM
       autoLogin.timeout = mkOption {
         type = types.int;
         default = 0;
-        description = ''
+        description = lib.mdDoc ''
           Show the greeter for this many seconds before automatic login occurs.
         '';
       };
@@ -287,7 +289,7 @@ in
 
         session  required       pam_succeed_if.so audit quiet_success user = lightdm
         session  required       pam_env.so conffile=/etc/pam/environment readenv=0
-        session  optional       ${pkgs.systemd}/lib/security/pam_systemd.so
+        session  optional       ${config.systemd.package}/lib/security/pam_systemd.so
         session  optional       pam_keyinit.so force revoke
         session  optional       pam_permit.so
     '';
@@ -310,7 +312,6 @@ in
       home = "/var/lib/lightdm";
       group = "lightdm";
       uid = config.ids.uids.lightdm;
-      shell = pkgs.bash;
     };
 
     systemd.tmpfiles.rules = [
diff --git a/nixos/modules/services/x11/display-managers/sddm.nix b/nixos/modules/services/x11/display-managers/sddm.nix
index 529a086381f..e86a18ff618 100644
--- a/nixos/modules/services/x11/display-managers/sddm.nix
+++ b/nixos/modules/services/x11/display-managers/sddm.nix
@@ -100,7 +100,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable sddm as the display manager.
         '';
       };
@@ -108,7 +108,7 @@ in
       enableHidpi = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable automatic HiDPI mode.
         '';
       };
@@ -122,7 +122,7 @@ in
             Session = "plasma.desktop";
           };
         };
-        description = ''
+        description = lib.mdDoc ''
           Extra settings merged in and overwritting defaults in sddm.conf.
         '';
       };
@@ -130,7 +130,7 @@ in
       theme = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           Greeter theme to use.
         '';
       };
@@ -138,7 +138,7 @@ in
       autoNumlock = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Enable numlock at login.
         '';
       };
@@ -151,16 +151,16 @@ in
           xrandr --setprovideroutputsource modesetting NVIDIA-0
           xrandr --auto
         '';
-        description = ''
+        description = lib.mdDoc ''
           A script to execute when starting the display server. DEPRECATED, please
-          use <option>services.xserver.displayManager.setupCommands</option>.
+          use {option}`services.xserver.displayManager.setupCommands`.
         '';
       };
 
       stopScript = mkOption {
         type = types.str;
         default = "";
-        description = ''
+        description = lib.mdDoc ''
           A script to execute when stopping the display server.
         '';
       };
@@ -170,7 +170,7 @@ in
         relogin = mkOption {
           type = types.bool;
           default = false;
-          description = ''
+          description = lib.mdDoc ''
             If true automatic login will kick in again on session exit (logout), otherwise it
             will only log in automatically when the display-manager is started.
           '';
@@ -179,7 +179,7 @@ in
         minimumUid = mkOption {
           type = types.ints.u16;
           default = 1000;
-          description = ''
+          description = lib.mdDoc ''
             Minimum user ID for auto-login user.
           '';
         };
@@ -231,7 +231,7 @@ in
 
         session  required       pam_succeed_if.so audit quiet_success user = sddm
         session  required       pam_env.so conffile=/etc/pam/environment readenv=0
-        session  optional       ${pkgs.systemd}/lib/security/pam_systemd.so
+        session  optional       ${config.systemd.package}/lib/security/pam_systemd.so
         session  optional       pam_keyinit.so force revoke
         session  optional       pam_permit.so
       '';
@@ -269,20 +269,5 @@ in
     # To enable user switching, allow sddm to allocate TTYs/displays dynamically.
     services.xserver.tty = null;
     services.xserver.display = null;
-
-    systemd.tmpfiles.rules = [
-      # Prior to Qt 5.9.2, there is a QML cache invalidation bug which sometimes
-      # strikes new Plasma 5 releases. If the QML cache is not invalidated, SDDM
-      # will segfault without explanation. We really tore our hair out for awhile
-      # before finding the bug:
-      # https://bugreports.qt.io/browse/QTBUG-62302
-      # We work around the problem by deleting the QML cache before startup.
-      # This was supposedly fixed in Qt 5.9.2 however it has been reported with
-      # 5.10 and 5.11 as well. The initial workaround was to delete the directory
-      # in the Xsetup script but that doesn't do anything.
-      # Instead we use tmpfiles.d to ensure it gets wiped.
-      # This causes a small but perceptible delay when SDDM starts.
-      "e ${config.users.users.sddm.home}/.cache - - - 0"
-    ];
   };
 }
diff --git a/nixos/modules/services/x11/display-managers/startx.nix b/nixos/modules/services/x11/display-managers/startx.nix
index a48566ae068..f4bb7a89d03 100644
--- a/nixos/modules/services/x11/display-managers/startx.nix
+++ b/nixos/modules/services/x11/display-managers/startx.nix
@@ -17,7 +17,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the dummy "startx" pseudo-display manager,
           which allows users to start X manually via the "startx" command
           from a vt shell. The X server runs under the user's id, not as root.
diff --git a/nixos/modules/services/x11/display-managers/sx.nix b/nixos/modules/services/x11/display-managers/sx.nix
index e3097736430..6a7fc1a040e 100644
--- a/nixos/modules/services/x11/display-managers/sx.nix
+++ b/nixos/modules/services/x11/display-managers/sx.nix
@@ -7,8 +7,8 @@ let cfg = config.services.xserver.displayManager.sx;
 in {
   options = {
     services.xserver.displayManager.sx = {
-      enable = mkEnableOption "sx pseudo-display manager" // {
-        description = ''
+      enable = mkEnableOption (lib.mdDoc "sx pseudo-display manager") // {
+        description = lib.mdDoc ''
           Whether to enable the "sx" pseudo-display manager, which allows users
           to start manually via the "sx" command from a vt shell. The X server
           runs under the user's id, not as root. The user must provide a
diff --git a/nixos/modules/services/x11/display-managers/xpra.nix b/nixos/modules/services/x11/display-managers/xpra.nix
index c23e479140f..cb78f52d9b6 100644
--- a/nixos/modules/services/x11/display-managers/xpra.nix
+++ b/nixos/modules/services/x11/display-managers/xpra.nix
@@ -16,27 +16,34 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable xpra as display manager.";
+        description = lib.mdDoc "Whether to enable xpra as display manager.";
       };
 
       bindTcp = mkOption {
         default = "127.0.0.1:10000";
         example = "0.0.0.0:10000";
         type = types.nullOr types.str;
-        description = "Bind xpra to TCP";
+        description = lib.mdDoc "Bind xpra to TCP";
+      };
+
+      desktop = mkOption {
+        type = types.nullOr types.str;
+        default = null;
+        example = "gnome-shell";
+        description = lib.mdDoc "Start a desktop environment instead of seamless mode";
       };
 
       auth = mkOption {
         type = types.str;
         default = "pam";
         example = "password:value=mysecret";
-        description = "Authentication to use when connecting to xpra";
+        description = lib.mdDoc "Authentication to use when connecting to xpra";
       };
 
-      pulseaudio = mkEnableOption "pulseaudio audio streaming";
+      pulseaudio = mkEnableOption (lib.mdDoc "pulseaudio audio streaming");
 
       extraOptions = mkOption {
-        description = "Extra xpra options";
+        description = lib.mdDoc "Extra xpra options";
         default = [];
         type = types.listOf types.str;
       };
@@ -222,7 +229,7 @@ in
     services.xserver.displayManager.job.execCmd = ''
       ${optionalString (cfg.pulseaudio)
         "export PULSE_COOKIE=/run/pulse/.config/pulse/cookie"}
-      exec ${pkgs.xpra}/bin/xpra start \
+      exec ${pkgs.xpra}/bin/xpra ${if cfg.desktop == null then "start" else "start-desktop --start=${cfg.desktop}"} \
         --daemon=off \
         --log-dir=/var/log \
         --log-file=xpra.log \
diff --git a/nixos/modules/services/x11/extra-layouts.nix b/nixos/modules/services/x11/extra-layouts.nix
index 159bed63e13..574657a50c8 100644
--- a/nixos/modules/services/x11/extra-layouts.nix
+++ b/nixos/modules/services/x11/extra-layouts.nix
@@ -9,13 +9,13 @@ let
     options = {
       description = mkOption {
         type = types.str;
-        description = "A short description of the layout.";
+        description = lib.mdDoc "A short description of the layout.";
       };
 
       languages = mkOption {
         type = types.listOf types.str;
         description =
-        ''
+        lib.mdDoc ''
           A list of languages provided by the layout.
           (Use ISO 639-2 codes, for example: "eng" for english)
         '';
@@ -24,55 +24,55 @@ let
       compatFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The path to the xkb compat file.
           This file sets the compatibility state, used to preserve
           compatibility with xkb-unaware programs.
-          It must contain a <literal>xkb_compat "name" { ... }</literal> block.
+          It must contain a `xkb_compat "name" { ... }` block.
         '';
       };
 
       geometryFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The path to the xkb geometry file.
           This (completely optional) file describes the physical layout of
           keyboard, which maybe be used by programs to depict it.
-          It must contain a <literal>xkb_geometry "name" { ... }</literal> block.
+          It must contain a `xkb_geometry "name" { ... }` block.
         '';
       };
 
       keycodesFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The path to the xkb keycodes file.
           This file specifies the range and the interpretation of the raw
           keycodes sent by the keyboard.
-          It must contain a <literal>xkb_keycodes "name" { ... }</literal> block.
+          It must contain a `xkb_keycodes "name" { ... }` block.
         '';
       };
 
       symbolsFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The path to the xkb symbols file.
           This is the most important file: it defines which symbol or action
           maps to each key and must contain a
-          <literal>xkb_symbols "name" { ... }</literal> block.
+          `xkb_symbols "name" { ... }` block.
         '';
       };
 
       typesFile = mkOption {
         type = types.nullOr types.path;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           The path to the xkb types file.
           This file specifies the key types that can be associated with
           the various keyboard keys.
-          It must contain a <literal>xkb_types "name" { ... }</literal> block.
+          It must contain a `xkb_types "name" { ... }` block.
         '';
       };
 
@@ -103,12 +103,12 @@ in
           };
         }
       '';
-      description = ''
+      description = lib.mdDoc ''
         Extra custom layouts that will be included in the xkb configuration.
         Information on how to create a new layout can be found here:
-        <link xlink:href="https://www.x.org/releases/current/doc/xorg-docs/input/XKB-Enhancing.html#Defining_New_Layouts"></link>.
+        [](https://www.x.org/releases/current/doc/xorg-docs/input/XKB-Enhancing.html#Defining_New_Layouts).
         For more examples see
-        <link xlink:href="https://wiki.archlinux.org/index.php/X_KeyBoard_extension#Basic_examples"></link>
+        [](https://wiki.archlinux.org/index.php/X_KeyBoard_extension#Basic_examples)
       '';
     };
 
diff --git a/nixos/modules/services/x11/fractalart.nix b/nixos/modules/services/x11/fractalart.nix
index 448248a5879..f7fc1ec9622 100644
--- a/nixos/modules/services/x11/fractalart.nix
+++ b/nixos/modules/services/x11/fractalart.nix
@@ -8,21 +8,21 @@ in {
       type = types.bool;
       default = false;
       example = true;
-      description = "Enable FractalArt for generating colorful wallpapers on login";
+      description = lib.mdDoc "Enable FractalArt for generating colorful wallpapers on login";
     };
 
     width = mkOption {
       type = types.nullOr types.int;
       default = null;
       example = 1920;
-      description = "Screen width";
+      description = lib.mdDoc "Screen width";
     };
 
     height = mkOption {
       type = types.nullOr types.int;
       default = null;
       example = 1080;
-      description = "Screen height";
+      description = lib.mdDoc "Screen height";
     };
   };
 
diff --git a/nixos/modules/services/x11/gdk-pixbuf.nix b/nixos/modules/services/x11/gdk-pixbuf.nix
index 3fd6fed91e1..2105224f92f 100644
--- a/nixos/modules/services/x11/gdk-pixbuf.nix
+++ b/nixos/modules/services/x11/gdk-pixbuf.nix
@@ -1,43 +1,26 @@
 { config, lib, pkgs, ... }:
 
-with lib;
-
 let
   cfg = config.services.xserver.gdk-pixbuf;
 
-  # Get packages to generate the cache for. We always include gdk-pixbuf.
-  effectivePackages = unique ([pkgs.gdk-pixbuf] ++ cfg.modulePackages);
-
-  # Generate the cache file by running gdk-pixbuf-query-loaders for each
-  # package and concatenating the results.
-  loadersCache = pkgs.runCommand "gdk-pixbuf-loaders.cache" { preferLocalBuild = true; } ''
-    (
-      for package in ${concatStringsSep " " effectivePackages}; do
-        module_dir="$package/${pkgs.gdk-pixbuf.moduleDir}"
-        if [[ ! -d $module_dir ]]; then
-          echo "Warning (services.xserver.gdk-pixbuf): missing module directory $module_dir" 1>&2
-          continue
-        fi
-        GDK_PIXBUF_MODULEDIR="$module_dir" \
-          ${pkgs.stdenv.hostPlatform.emulator pkgs.buildPackages} ${pkgs.gdk-pixbuf.dev}/bin/gdk-pixbuf-query-loaders
-      done
-    ) > "$out"
-  '';
+  loadersCache = pkgs.gnome._gdkPixbufCacheBuilder_DO_NOT_USE {
+    extraLoaders = lib.unique (cfg.modulePackages);
+  };
 in
 
 {
   options = {
-    services.xserver.gdk-pixbuf.modulePackages = mkOption {
-      type = types.listOf types.package;
+    services.xserver.gdk-pixbuf.modulePackages = lib.mkOption {
+      type = lib.types.listOf lib.types.package;
       default = [ ];
-      description = "Packages providing GDK-Pixbuf modules, for cache generation.";
+      description = lib.mdDoc "Packages providing GDK-Pixbuf modules, for cache generation.";
     };
   };
 
   # If there is any package configured in modulePackages, we generate the
   # loaders.cache based on that and set the environment variable
   # GDK_PIXBUF_MODULE_FILE to point to it.
-  config = mkIf (cfg.modulePackages != []) {
+  config = lib.mkIf (cfg.modulePackages != []) {
     environment.variables = {
       GDK_PIXBUF_MODULE_FILE = "${loadersCache}";
     };
diff --git a/nixos/modules/services/x11/hardware/cmt.nix b/nixos/modules/services/x11/hardware/cmt.nix
index 5ac824c5e41..a44221141c3 100644
--- a/nixos/modules/services/x11/hardware/cmt.nix
+++ b/nixos/modules/services/x11/hardware/cmt.nix
@@ -15,14 +15,14 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Enable chrome multitouch input (cmt). Touchpad drivers that are configured for chromebooks.";
+        description = lib.mdDoc "Enable chrome multitouch input (cmt). Touchpad drivers that are configured for chromebooks.";
       };
       models = mkOption {
         type = types.enum [ "atlas" "banjo" "candy" "caroline" "cave" "celes" "clapper" "cyan" "daisy" "elan" "elm" "enguarde" "eve" "expresso" "falco" "gandof" "glimmer" "gnawty" "heli" "kevin" "kip" "leon" "lulu" "orco" "pbody" "peppy" "pi" "pit" "puppy" "quawks" "rambi" "samus" "snappy" "spring" "squawks" "swanky" "winky" "wolf" "auron_paine" "auron_yuna" "daisy_skate" "nyan_big" "nyan_blaze" "veyron_jaq" "veyron_jerry" "veyron_mighty" "veyron_minnie" "veyron_speedy" ];
         example = "banjo";
-        description = ''
+        description = lib.mdDoc ''
           Which models to enable cmt for. Enter the Code Name for your Chromebook.
-          Code Name can be found at <link xlink:href="https://www.chromium.org/chromium-os/developer-information-for-chrome-os-devices" />.
+          Code Name can be found at <https://www.chromium.org/chromium-os/developer-information-for-chrome-os-devices>.
         '';
       };
     }; #closes services
diff --git a/nixos/modules/services/x11/hardware/digimend.nix b/nixos/modules/services/x11/hardware/digimend.nix
index b1b1682f00b..f82aac41a32 100644
--- a/nixos/modules/services/x11/hardware/digimend.nix
+++ b/nixos/modules/services/x11/hardware/digimend.nix
@@ -16,7 +16,7 @@ in
 
     services.xserver.digimend = {
 
-      enable = mkEnableOption "the digimend drivers for Huion/XP-Pen/etc. tablets";
+      enable = mkEnableOption (lib.mdDoc "the digimend drivers for Huion/XP-Pen/etc. tablets");
 
     };
 
diff --git a/nixos/modules/services/x11/hardware/libinput.nix b/nixos/modules/services/x11/hardware/libinput.nix
index efdb7c61dfa..0d30b9b5e68 100644
--- a/nixos/modules/services/x11/hardware/libinput.nix
+++ b/nixos/modules/services/x11/hardware/libinput.nix
@@ -12,8 +12,8 @@ let cfg = config.services.xserver.libinput;
         default = null;
         example = "/dev/input/event0";
         description =
-          ''
-            Path for ${deviceType} device.  Set to <literal>null</literal> to apply to any
+          lib.mdDoc ''
+            Path for ${deviceType} device.  Set to `null` to apply to any
             auto-detected ${deviceType}.
           '';
       };
@@ -23,14 +23,14 @@ let cfg = config.services.xserver.libinput;
         default = "adaptive";
         example = "flat";
         description =
-          ''
+          lib.mdDoc ''
             Sets the pointer acceleration profile to the given profile.
-            Permitted values are <literal>adaptive</literal>, <literal>flat</literal>.
+            Permitted values are `adaptive`, `flat`.
             Not all devices support this option or all profiles.
             If a profile is unsupported, the default profile for this is used.
-            <literal>flat</literal>: Pointer motion is accelerated by a constant
+            `flat`: Pointer motion is accelerated by a constant
             (device-specific) factor, depending on the current speed.
-            <literal>adaptive</literal>: Pointer acceleration depends on the input speed.
+            `adaptive`: Pointer acceleration depends on the input speed.
             This is the default profile for most devices.
           '';
       };
@@ -39,7 +39,7 @@ let cfg = config.services.xserver.libinput;
         type = types.nullOr types.str;
         default = null;
         example = "-0.5";
-        description = "Cursor acceleration (how fast speed increases from minSpeed to maxSpeed).";
+        description = lib.mdDoc "Cursor acceleration (how fast speed increases from minSpeed to maxSpeed).";
       };
 
       buttonMapping = mkOption {
@@ -47,7 +47,7 @@ let cfg = config.services.xserver.libinput;
         default = null;
         example = "1 6 3 4 5 0 7";
         description =
-          ''
+          lib.mdDoc ''
             Sets the logical button mapping for this device, see XSetPointerMapping(3). The string  must
             be  a  space-separated  list  of  button mappings in the order of the logical buttons on the
             device, starting with button 1.  The default mapping is "1 2 3 ... 32". A mapping of 0 deac‐
@@ -62,7 +62,7 @@ let cfg = config.services.xserver.libinput;
         default = null;
         example = "0.5 0 0 0 0.8 0.1 0 0 1";
         description =
-          ''
+          lib.mdDoc ''
             A string of 9 space-separated floating point numbers. Sets the calibration matrix to the
             3x3 matrix where the first row is (abc), the second row is (def) and the third row is (ghi).
           '';
@@ -73,9 +73,9 @@ let cfg = config.services.xserver.libinput;
         default = null;
         example = "buttonareas";
         description =
-          ''
-            Enables a click method. Permitted values are <literal>none</literal>,
-            <literal>buttonareas</literal>, <literal>clickfinger</literal>.
+          lib.mdDoc ''
+            Enables a click method. Permitted values are `none`,
+            `buttonareas`, `clickfinger`.
             Not all devices support all methods, if an option is unsupported,
             the default click method for this device is used.
           '';
@@ -84,14 +84,14 @@ let cfg = config.services.xserver.libinput;
       leftHanded = mkOption {
         type = types.bool;
         default = false;
-        description = "Enables left-handed button orientation, i.e. swapping left and right buttons.";
+        description = lib.mdDoc "Enables left-handed button orientation, i.e. swapping left and right buttons.";
       };
 
       middleEmulation = mkOption {
         type = types.bool;
         default = true;
         description =
-          ''
+          lib.mdDoc ''
             Enables middle button emulation. When enabled, pressing the left and right buttons
             simultaneously produces a middle mouse button click.
           '';
@@ -100,7 +100,7 @@ let cfg = config.services.xserver.libinput;
       naturalScrolling = mkOption {
         type = types.bool;
         default = false;
-        description = "Enables or disables natural scrolling behavior.";
+        description = lib.mdDoc "Enables or disables natural scrolling behavior.";
       };
 
       scrollButton = mkOption {
@@ -108,7 +108,7 @@ let cfg = config.services.xserver.libinput;
         default = null;
         example = 1;
         description =
-          ''
+          lib.mdDoc ''
             Designates a button as scroll button. If the ScrollMethod is button and the button is logically
             held down, x/y axis movement is converted into scroll events.
           '';
@@ -119,9 +119,9 @@ let cfg = config.services.xserver.libinput;
         default = "twofinger";
         example = "edge";
         description =
-          ''
-            Specify the scrolling method: <literal>twofinger</literal>, <literal>edge</literal>,
-            <literal>button</literal>, or <literal>none</literal>
+          lib.mdDoc ''
+            Specify the scrolling method: `twofinger`, `edge`,
+            `button`, or `none`
           '';
       };
 
@@ -129,7 +129,7 @@ let cfg = config.services.xserver.libinput;
         type = types.bool;
         default = true;
         description =
-          ''
+          lib.mdDoc ''
             Disables horizontal scrolling. When disabled, this driver will discard any horizontal scroll
             events from libinput. Note that this does not disable horizontal scrolling, it merely
             discards the horizontal axis from any scroll events.
@@ -141,9 +141,9 @@ let cfg = config.services.xserver.libinput;
         default = "enabled";
         example = "disabled";
         description =
-          ''
-            Sets the send events mode to <literal>disabled</literal>, <literal>enabled</literal>,
-            or <literal>disabled-on-external-mouse</literal>
+          lib.mdDoc ''
+            Sets the send events mode to `disabled`, `enabled`,
+            or `disabled-on-external-mouse`
           '';
       };
 
@@ -151,16 +151,24 @@ let cfg = config.services.xserver.libinput;
         type = types.bool;
         default = true;
         description =
-          ''
+          lib.mdDoc ''
             Enables or disables tap-to-click behavior.
           '';
       };
 
+      tappingButtonMap = mkOption {
+        type = types.nullOr (types.enum [ "lrm" "lmr" ]);
+        default = null;
+        description = lib.mdDoc ''
+          Set the button mapping for 1/2/3-finger taps to left/right/middle or left/middle/right, respectively.
+        '';
+      };
+
       tappingDragLock = mkOption {
         type = types.bool;
         default = true;
         description =
-          ''
+          lib.mdDoc ''
             Enables or disables drag lock during tapping behavior. When enabled, a finger up during tap-
             and-drag will not immediately release the button. If the finger is set down again within the
             timeout, the draging process continues.
@@ -171,7 +179,7 @@ let cfg = config.services.xserver.libinput;
         type = types.nullOr types.str;
         default = null;
         example = "0.5 0 0 0 0.8 0.1 0 0 1";
-        description = ''
+        description = lib.mdDoc ''
           A string of 9 space-separated floating point numbers. Sets the transformation matrix to
           the 3x3 matrix where the first row is (abc), the second row is (def) and the third row is (ghi).
         '';
@@ -181,7 +189,7 @@ let cfg = config.services.xserver.libinput;
         type = types.bool;
         default = false;
         description =
-          ''
+          lib.mdDoc ''
             Disable input method while typing.
           '';
       };
@@ -193,9 +201,9 @@ let cfg = config.services.xserver.libinput;
         ''
           Option "DragLockButtons" "L1 B1 L2 B2"
         '';
-        description = ''
+        description = lib.mdDoc ''
           Additional options for libinput ${deviceType} driver. See
-          <citerefentry><refentrytitle>libinput</refentrytitle><manvolnum>4</manvolnum></citerefentry>
+          {manpage}`libinput(4)`
           for available options.";
         '';
       };
@@ -220,6 +228,7 @@ let cfg = config.services.xserver.libinput;
       Option "HorizontalScrolling" "${xorgBool cfg.${deviceType}.horizontalScrolling}"
       Option "SendEventsMode" "${cfg.${deviceType}.sendEventsMode}"
       Option "Tapping" "${xorgBool cfg.${deviceType}.tapping}"
+      ${optionalString (cfg.${deviceType}.tappingButtonMap != null) ''Option "TappingButtonMap" "${cfg.${deviceType}.tappingButtonMap}"''}
       Option "TappingDragLock" "${xorgBool cfg.${deviceType}.tappingDragLock}"
       Option "DisableWhileTyping" "${xorgBool cfg.${deviceType}.disableWhileTyping}"
       ${cfg.${deviceType}.additionalOptions}
@@ -241,6 +250,7 @@ in {
       "horizontalScrolling"
       "sendEventsMode"
       "tapping"
+      "tappingButtonMap"
       "tappingDragLock"
       "transformationMatrix"
       "disableWhileTyping"
@@ -250,7 +260,7 @@ in {
   options = {
 
     services.xserver.libinput = {
-      enable = mkEnableOption "libinput";
+      enable = mkEnableOption (lib.mdDoc "libinput");
       mouse = mkConfigForDevice "mouse";
       touchpad = mkConfigForDevice "touchpad";
     };
diff --git a/nixos/modules/services/x11/hardware/synaptics.nix b/nixos/modules/services/x11/hardware/synaptics.nix
index 93dd560bca4..7b45222ac64 100644
--- a/nixos/modules/services/x11/hardware/synaptics.nix
+++ b/nixos/modules/services/x11/hardware/synaptics.nix
@@ -30,7 +30,7 @@ in {
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable touchpad support. Deprecated: Consider services.xserver.libinput.enable.";
+        description = lib.mdDoc "Whether to enable touchpad support. Deprecated: Consider services.xserver.libinput.enable.";
       };
 
       dev = mkOption {
@@ -38,7 +38,7 @@ in {
         default = null;
         example = "/dev/input/event0";
         description =
-          ''
+          lib.mdDoc ''
             Path for touchpad device.  Set to null to apply to any
             auto-detected touchpad.
           '';
@@ -47,73 +47,73 @@ in {
       accelFactor = mkOption {
         type = types.nullOr types.str;
         default = "0.001";
-        description = "Cursor acceleration (how fast speed increases from minSpeed to maxSpeed).";
+        description = lib.mdDoc "Cursor acceleration (how fast speed increases from minSpeed to maxSpeed).";
       };
 
       minSpeed = mkOption {
         type = types.nullOr types.str;
         default = "0.6";
-        description = "Cursor speed factor for precision finger motion.";
+        description = lib.mdDoc "Cursor speed factor for precision finger motion.";
       };
 
       maxSpeed = mkOption {
         type = types.nullOr types.str;
         default = "1.0";
-        description = "Cursor speed factor for highest-speed finger motion.";
+        description = lib.mdDoc "Cursor speed factor for highest-speed finger motion.";
       };
 
       scrollDelta = mkOption {
         type = types.nullOr types.int;
         default = null;
         example = 75;
-        description = "Move distance of the finger for a scroll event.";
+        description = lib.mdDoc "Move distance of the finger for a scroll event.";
       };
 
       twoFingerScroll = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable two-finger drag-scrolling. Overridden by horizTwoFingerScroll and vertTwoFingerScroll.";
+        description = lib.mdDoc "Whether to enable two-finger drag-scrolling. Overridden by horizTwoFingerScroll and vertTwoFingerScroll.";
       };
 
       horizTwoFingerScroll = mkOption {
         type = types.bool;
         default = cfg.twoFingerScroll;
         defaultText = literalExpression "config.${opt.twoFingerScroll}";
-        description = "Whether to enable horizontal two-finger drag-scrolling.";
+        description = lib.mdDoc "Whether to enable horizontal two-finger drag-scrolling.";
       };
 
       vertTwoFingerScroll = mkOption {
         type = types.bool;
         default = cfg.twoFingerScroll;
         defaultText = literalExpression "config.${opt.twoFingerScroll}";
-        description = "Whether to enable vertical two-finger drag-scrolling.";
+        description = lib.mdDoc "Whether to enable vertical two-finger drag-scrolling.";
       };
 
       horizEdgeScroll = mkOption {
         type = types.bool;
         default = ! cfg.horizTwoFingerScroll;
         defaultText = literalExpression "! config.${opt.horizTwoFingerScroll}";
-        description = "Whether to enable horizontal edge drag-scrolling.";
+        description = lib.mdDoc "Whether to enable horizontal edge drag-scrolling.";
       };
 
       vertEdgeScroll = mkOption {
         type = types.bool;
         default = ! cfg.vertTwoFingerScroll;
         defaultText = literalExpression "! config.${opt.vertTwoFingerScroll}";
-        description = "Whether to enable vertical edge drag-scrolling.";
+        description = lib.mdDoc "Whether to enable vertical edge drag-scrolling.";
       };
 
       tapButtons = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable tap buttons.";
+        description = lib.mdDoc "Whether to enable tap buttons.";
       };
 
       buttonsMap = mkOption {
         type = types.listOf types.int;
         default = [1 2 3];
         example = [1 3 2];
-        description = "Remap touchpad buttons.";
+        description = lib.mdDoc "Remap touchpad buttons.";
         apply = map toString;
       };
 
@@ -121,34 +121,34 @@ in {
         type = types.listOf types.int;
         default = [1 2 3];
         example = [1 3 2];
-        description = "Remap several-fingers taps.";
+        description = lib.mdDoc "Remap several-fingers taps.";
         apply = map toString;
       };
 
       palmDetect = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable palm detection (hardware support required)";
+        description = lib.mdDoc "Whether to enable palm detection (hardware support required)";
       };
 
       palmMinWidth = mkOption {
         type = types.nullOr types.int;
         default = null;
         example = 5;
-        description = "Minimum finger width at which touch is considered a palm";
+        description = lib.mdDoc "Minimum finger width at which touch is considered a palm";
       };
 
       palmMinZ = mkOption {
         type = types.nullOr types.int;
         default = null;
         example = 20;
-        description = "Minimum finger pressure at which touch is considered a palm";
+        description = lib.mdDoc "Minimum finger pressure at which touch is considered a palm";
       };
 
       horizontalScroll = mkOption {
         type = types.bool;
         default = true;
-        description = "Whether to enable horizontal scrolling (on touchpad)";
+        description = lib.mdDoc "Whether to enable horizontal scrolling (on touchpad)";
       };
 
       additionalOptions = mkOption {
@@ -158,7 +158,7 @@ in {
           Option "RTCornerButton" "2"
           Option "RBCornerButton" "3"
         '';
-        description = ''
+        description = lib.mdDoc ''
           Additional options for synaptics touchpad driver.
         '';
       };
diff --git a/nixos/modules/services/x11/hardware/wacom.nix b/nixos/modules/services/x11/hardware/wacom.nix
index dad2b308d1b..4994e5c1a2c 100644
--- a/nixos/modules/services/x11/hardware/wacom.nix
+++ b/nixos/modules/services/x11/hardware/wacom.nix
@@ -17,13 +17,13 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the Wacom touchscreen/digitizer/tablet.
           If you ever have any issues such as, try switching to terminal (ctrl-alt-F1) and back
           which will make Xorg reconfigure the device ?
 
           If you're not satisfied by the default behaviour you can override
-          <option>environment.etc."X11/xorg.conf.d/70-wacom.conf"</option> in
+          {option}`environment.etc."X11/xorg.conf.d/70-wacom.conf"` in
           configuration.nix easily.
         '';
       };
diff --git a/nixos/modules/services/x11/imwheel.nix b/nixos/modules/services/x11/imwheel.nix
index ae990141a50..03cbdbfb09a 100644
--- a/nixos/modules/services/x11/imwheel.nix
+++ b/nixos/modules/services/x11/imwheel.nix
@@ -6,15 +6,15 @@ in
   {
     options = {
       services.xserver.imwheel = {
-        enable = mkEnableOption "IMWheel service";
+        enable = mkEnableOption (lib.mdDoc "IMWheel service");
 
         extraOptions = mkOption {
           type = types.listOf types.str;
           default = [ "--buttons=45" ];
           example = [ "--debug" ];
-          description = ''
+          description = lib.mdDoc ''
             Additional command-line arguments to pass to
-            <command>imwheel</command>.
+            {command}`imwheel`.
           '';
         };
 
@@ -33,11 +33,11 @@ in
               ''';
             }
           '';
-          description = ''
+          description = lib.mdDoc ''
             Window class translation rules.
             /etc/X11/imwheelrc is generated based on this config
             which means this config is global for all users.
-            See <link xlink:href="http://imwheel.sourceforge.net/imwheel.1.html">offical man pages</link>
+            See [offical man pages](http://imwheel.sourceforge.net/imwheel.1.html)
             for more informations.
           '';
         };
diff --git a/nixos/modules/services/x11/picom.nix b/nixos/modules/services/x11/picom.nix
index b40e20bcd35..4a0578de09c 100644
--- a/nixos/modules/services/x11/picom.nix
+++ b/nixos/modules/services/x11/picom.nix
@@ -11,15 +11,6 @@ let
     addCheck (listOf x) (y: length y == 2)
     // { description = "pair of ${x.description}"; };
 
-  floatBetween = a: b: with types;
-    let
-      # toString prints floats with hardcoded high precision
-      floatToString = f: builtins.toJSON f;
-    in
-      addCheck float (x: x <= b && x >= a)
-      // { description = "a floating point number in " +
-                         "range [${floatToString a}, ${floatToString b}]"; };
-
   mkDefaultAttrs = mapAttrs (n: v: mkDefault v);
 
   # Basically a tinkered lib.generators.mkKeyValueDefault
@@ -51,29 +42,29 @@ in {
 
   imports = [
     (mkAliasOptionModule [ "services" "compton" ] [ "services" "picom" ])
+    (mkRemovedOptionModule [ "services" "picom" "refreshRate" ] ''
+      This option corresponds to `refresh-rate`, which has been unused
+      since picom v6 and was subsequently removed by upstream.
+      See https://github.com/yshui/picom/commit/bcbc410
+    '')
+    (mkRemovedOptionModule [ "services" "picom" "experimentalBackends" ] ''
+      This option was removed by upstream since picom v10.
+    '')
   ];
 
   options.services.picom = {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether or not to enable Picom as the X.org composite manager.
       '';
     };
 
-    experimentalBackends = mkOption {
-      type = types.bool;
-      default = false;
-      description = ''
-        Whether to use the unstable new reimplementation of the backends.
-      '';
-    };
-
     fade = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Fade windows in and out.
       '';
     };
@@ -82,16 +73,16 @@ in {
       type = types.ints.positive;
       default = 10;
       example = 5;
-      description = ''
+      description = lib.mdDoc ''
         Time between fade animation step (in ms).
       '';
     };
 
     fadeSteps = mkOption {
-      type = pairOf (floatBetween 0.01 1);
+      type = pairOf (types.numbers.between 0.01 1);
       default = [ 0.028 0.03 ];
       example = [ 0.04 0.04 ];
-      description = ''
+      description = lib.mdDoc ''
         Opacity change between fade steps (in and out).
       '';
     };
@@ -104,16 +95,16 @@ in {
         "name ~= 'Firefox$'"
         "focused = 1"
       ];
-      description = ''
+      description = lib.mdDoc ''
         List of conditions of windows that should not be faded.
-        See <literal>picom(1)</literal> man page for more examples.
+        See `picom(1)` man page for more examples.
       '';
     };
 
     shadow = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Draw window shadows.
       '';
     };
@@ -122,16 +113,16 @@ in {
       type = pairOf types.int;
       default = [ (-15) (-15) ];
       example = [ (-10) (-15) ];
-      description = ''
+      description = lib.mdDoc ''
         Left and right offset for shadows (in pixels).
       '';
     };
 
     shadowOpacity = mkOption {
-      type = floatBetween 0 1;
+      type = types.numbers.between 0 1;
       default = 0.75;
       example = 0.8;
-      description = ''
+      description = lib.mdDoc ''
         Window shadows opacity.
       '';
     };
@@ -144,35 +135,35 @@ in {
         "name ~= 'Firefox$'"
         "focused = 1"
       ];
-      description = ''
+      description = lib.mdDoc ''
         List of conditions of windows that should have no shadow.
-        See <literal>picom(1)</literal> man page for more examples.
+        See `picom(1)` man page for more examples.
       '';
     };
 
     activeOpacity = mkOption {
-      type = floatBetween 0 1;
+      type = types.numbers.between 0 1;
       default = 1.0;
       example = 0.8;
-      description = ''
+      description = lib.mdDoc ''
         Opacity of active windows.
       '';
     };
 
     inactiveOpacity = mkOption {
-      type = floatBetween 0.1 1;
+      type = types.numbers.between 0.1 1;
       default = 1.0;
       example = 0.8;
-      description = ''
+      description = lib.mdDoc ''
         Opacity of inactive windows.
       '';
     };
 
     menuOpacity = mkOption {
-      type = floatBetween 0 1;
+      type = types.numbers.between 0 1;
       default = 1.0;
       example = 0.8;
-      description = ''
+      description = lib.mdDoc ''
         Opacity of dropdown and popup menu.
       '';
     };
@@ -190,7 +181,7 @@ in {
         }
       '';
       example = {};
-      description = ''
+      description = lib.mdDoc ''
         Rules for specific window types.
       '';
     };
@@ -202,16 +193,16 @@ in {
         "95:class_g = 'URxvt' && !_NET_WM_STATE@:32a"
         "0:_NET_WM_STATE@:32a *= '_NET_WM_STATE_HIDDEN'"
       ];
-      description = ''
+      description = lib.mdDoc ''
         Rules that control the opacity of windows, in format PERCENT:PATTERN.
       '';
     };
 
     backend = mkOption {
-      type = types.enum [ "glx" "xrender" "xr_glx_hybrid" ];
+      type = types.enum [ "egl" "glx" "xrender" "xr_glx_hybrid" ];
       default = "xrender";
-      description = ''
-        Backend to use: <literal>glx</literal>, <literal>xrender</literal> or <literal>xr_glx_hybrid</literal>.
+      description = lib.mdDoc ''
+        Backend to use: `egl`, `glx`, `xrender` or `xr_glx_hybrid`.
       '';
     };
 
@@ -228,22 +219,13 @@ in {
           if isBool x then x
           else warn msg res;
 
-      description = ''
+      description = lib.mdDoc ''
         Enable vertical synchronization. Chooses the best method
         (drm, opengl, opengl-oml, opengl-swc, opengl-mswc) automatically.
         The bool value should be used, the others are just for backwards compatibility.
       '';
     };
 
-    refreshRate = mkOption {
-      type = types.ints.unsigned;
-      default = 0;
-      example = 60;
-      description = ''
-       Screen refresh rate (0 = automatically detect).
-      '';
-    };
-
     settings = with types;
     let
       scalar = oneOf [ bool int float str ]
@@ -271,10 +253,10 @@ in {
             deviation = 5.0;
           };
       '';
-      description = ''
+      description = lib.mdDoc ''
         Picom settings. Use this option to configure Picom settings not exposed
         in a NixOS option or to bypass one.  For the available options see the
-        CONFIGURATION FILES section at <literal>picom(1)</literal>.
+        CONFIGURATION FILES section at `picom(1)`.
       '';
     };
   };
@@ -306,7 +288,6 @@ in {
       # other options
       backend          = cfg.backend;
       vsync            = cfg.vSync;
-      refresh-rate     = cfg.refreshRate;
     };
 
     systemd.user.services.picom = {
@@ -320,8 +301,7 @@ in {
       };
 
       serviceConfig = {
-        ExecStart = "${pkgs.picom}/bin/picom --config ${configFile}"
-          + (optionalString cfg.experimentalBackends " --experimental-backends");
+        ExecStart = "${pkgs.picom}/bin/picom --config ${configFile}";
         RestartSec = 3;
         Restart = "always";
       };
diff --git a/nixos/modules/services/x11/redshift.nix b/nixos/modules/services/x11/redshift.nix
index cc9f964754f..3eb9e28edae 100644
--- a/nixos/modules/services/x11/redshift.nix
+++ b/nixos/modules/services/x11/redshift.nix
@@ -29,7 +29,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable Redshift to change your screen's colour temperature depending on
         the time of day.
       '';
@@ -39,17 +39,17 @@ in {
       day = mkOption {
         type = types.int;
         default = 5500;
-        description = ''
+        description = lib.mdDoc ''
           Colour temperature to use during the day, between
-          <literal>1000</literal> and <literal>25000</literal> K.
+          `1000` and `25000` K.
         '';
       };
       night = mkOption {
         type = types.int;
         default = 3700;
-        description = ''
+        description = lib.mdDoc ''
           Colour temperature to use at night, between
-          <literal>1000</literal> and <literal>25000</literal> K.
+          `1000` and `25000` K.
         '';
       };
     };
@@ -58,17 +58,17 @@ in {
       day = mkOption {
         type = types.str;
         default = "1";
-        description = ''
+        description = lib.mdDoc ''
           Screen brightness to apply during the day,
-          between <literal>0.1</literal> and <literal>1.0</literal>.
+          between `0.1` and `1.0`.
         '';
       };
       night = mkOption {
         type = types.str;
         default = "1";
-        description = ''
+        description = lib.mdDoc ''
           Screen brightness to apply during the night,
-          between <literal>0.1</literal> and <literal>1.0</literal>.
+          between `0.1` and `1.0`.
         '';
       };
     };
@@ -77,7 +77,7 @@ in {
       type = types.package;
       default = pkgs.redshift;
       defaultText = literalExpression "pkgs.redshift";
-      description = ''
+      description = lib.mdDoc ''
         redshift derivation to use.
       '';
     };
@@ -86,7 +86,7 @@ in {
       type = types.str;
       default = "/bin/redshift";
       example = "/bin/redshift-gtk";
-      description = ''
+      description = lib.mdDoc ''
         Redshift executable to use within the package.
       '';
     };
@@ -95,9 +95,9 @@ in {
       type = types.listOf types.str;
       default = [];
       example = [ "-v" "-m randr" ];
-      description = ''
+      description = lib.mdDoc ''
         Additional command-line arguments to pass to
-        <command>redshift</command>.
+        {command}`redshift`.
       '';
     };
   };
diff --git a/nixos/modules/services/x11/touchegg.nix b/nixos/modules/services/x11/touchegg.nix
index 9d3678e7696..f1103c054c5 100644
--- a/nixos/modules/services/x11/touchegg.nix
+++ b/nixos/modules/services/x11/touchegg.nix
@@ -11,13 +11,13 @@ in {
 
   ###### interface
   options.services.touchegg = {
-    enable = mkEnableOption "touchegg, a multi-touch gesture recognizer";
+    enable = mkEnableOption (lib.mdDoc "touchegg, a multi-touch gesture recognizer");
 
     package = mkOption {
       type = types.package;
       default = pkgs.touchegg;
       defaultText = literalExpression "pkgs.touchegg";
-      description = "touchegg derivation to use.";
+      description = lib.mdDoc "touchegg derivation to use.";
     };
   };
 
diff --git a/nixos/modules/services/x11/unclutter-xfixes.nix b/nixos/modules/services/x11/unclutter-xfixes.nix
index 0b4d06f640d..4a35176c583 100644
--- a/nixos/modules/services/x11/unclutter-xfixes.nix
+++ b/nixos/modules/services/x11/unclutter-xfixes.nix
@@ -8,32 +8,32 @@ in {
   options.services.unclutter-xfixes = {
 
     enable = mkOption {
-      description = "Enable unclutter-xfixes to hide your mouse cursor when inactive.";
+      description = lib.mdDoc "Enable unclutter-xfixes to hide your mouse cursor when inactive.";
       type = types.bool;
       default = false;
     };
 
     package = mkOption {
-      description = "unclutter-xfixes derivation to use.";
+      description = lib.mdDoc "unclutter-xfixes derivation to use.";
       type = types.package;
       default = pkgs.unclutter-xfixes;
       defaultText = literalExpression "pkgs.unclutter-xfixes";
     };
 
     timeout = mkOption {
-      description = "Number of seconds before the cursor is marked inactive.";
+      description = lib.mdDoc "Number of seconds before the cursor is marked inactive.";
       type = types.int;
       default = 1;
     };
 
     threshold = mkOption {
-      description = "Minimum number of pixels considered cursor movement.";
+      description = lib.mdDoc "Minimum number of pixels considered cursor movement.";
       type = types.int;
       default = 1;
     };
 
     extraOptions = mkOption {
-      description = "More arguments to pass to the unclutter-xfixes command.";
+      description = lib.mdDoc "More arguments to pass to the unclutter-xfixes command.";
       type = types.listOf types.str;
       default = [];
       example = [ "exclude-root" "ignore-scrolling" "fork" ];
diff --git a/nixos/modules/services/x11/unclutter.nix b/nixos/modules/services/x11/unclutter.nix
index bdb5fa7b50c..039214a575a 100644
--- a/nixos/modules/services/x11/unclutter.nix
+++ b/nixos/modules/services/x11/unclutter.nix
@@ -8,7 +8,7 @@ in {
   options.services.unclutter = {
 
     enable = mkOption {
-      description = "Enable unclutter to hide your mouse cursor when inactive";
+      description = lib.mdDoc "Enable unclutter to hide your mouse cursor when inactive";
       type = types.bool;
       default = false;
     };
@@ -17,36 +17,36 @@ in {
       type = types.package;
       default = pkgs.unclutter;
       defaultText = literalExpression "pkgs.unclutter";
-      description = "unclutter derivation to use.";
+      description = lib.mdDoc "unclutter derivation to use.";
     };
 
     keystroke = mkOption {
-      description = "Wait for a keystroke before hiding the cursor";
+      description = lib.mdDoc "Wait for a keystroke before hiding the cursor";
       type = types.bool;
       default = false;
     };
 
     timeout = mkOption {
-      description = "Number of seconds before the cursor is marked inactive";
+      description = lib.mdDoc "Number of seconds before the cursor is marked inactive";
       type = types.int;
       default = 1;
     };
 
     threshold = mkOption {
-      description = "Minimum number of pixels considered cursor movement";
+      description = lib.mdDoc "Minimum number of pixels considered cursor movement";
       type = types.int;
       default = 1;
     };
 
     excluded = mkOption {
-      description = "Names of windows where unclutter should not apply";
+      description = lib.mdDoc "Names of windows where unclutter should not apply";
       type = types.listOf types.str;
       default = [];
       example = [ "" ];
     };
 
     extraOptions = mkOption {
-      description = "More arguments to pass to the unclutter command";
+      description = lib.mdDoc "More arguments to pass to the unclutter command";
       type = types.listOf types.str;
       default = [];
       example = [ "noevent" "grab" ];
diff --git a/nixos/modules/services/x11/urserver.nix b/nixos/modules/services/x11/urserver.nix
index 0beb62eb766..d0b6e0775e5 100644
--- a/nixos/modules/services/x11/urserver.nix
+++ b/nixos/modules/services/x11/urserver.nix
@@ -5,7 +5,7 @@ let
   cfg = config.services.urserver;
 in {
 
-  options.services.urserver.enable = lib.mkEnableOption "urserver";
+  options.services.urserver.enable = lib.mkEnableOption (lib.mdDoc "urserver");
 
   config = lib.mkIf cfg.enable {
 
diff --git a/nixos/modules/services/x11/urxvtd.nix b/nixos/modules/services/x11/urxvtd.nix
index 0a0df447f4e..fedcb6c7293 100644
--- a/nixos/modules/services/x11/urxvtd.nix
+++ b/nixos/modules/services/x11/urxvtd.nix
@@ -11,7 +11,7 @@ in {
     enable = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Enable urxvtd, the urxvt terminal daemon. To use urxvtd, run
         "urxvtc".
       '';
@@ -20,7 +20,7 @@ in {
     package = mkOption {
       default = pkgs.rxvt-unicode;
       defaultText = literalExpression "pkgs.rxvt-unicode";
-      description = ''
+      description = lib.mdDoc ''
         Package to install. Usually pkgs.rxvt-unicode.
       '';
       type = types.package;
diff --git a/nixos/modules/services/x11/window-managers/2bwm.nix b/nixos/modules/services/x11/window-managers/2bwm.nix
index fdbdf35b0f5..8483a74b9f6 100644
--- a/nixos/modules/services/x11/window-managers/2bwm.nix
+++ b/nixos/modules/services/x11/window-managers/2bwm.nix
@@ -13,7 +13,7 @@ in
   ###### interface
 
   options = {
-    services.xserver.windowManager."2bwm".enable = mkEnableOption "2bwm";
+    services.xserver.windowManager."2bwm".enable = mkEnableOption (lib.mdDoc "2bwm");
   };
 
 
diff --git a/nixos/modules/services/x11/window-managers/afterstep.nix b/nixos/modules/services/x11/window-managers/afterstep.nix
index ba88a64c702..a0606359797 100644
--- a/nixos/modules/services/x11/window-managers/afterstep.nix
+++ b/nixos/modules/services/x11/window-managers/afterstep.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.afterstep.enable = mkEnableOption "afterstep";
+    services.xserver.windowManager.afterstep.enable = mkEnableOption (lib.mdDoc "afterstep");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/awesome.nix b/nixos/modules/services/x11/window-managers/awesome.nix
index c6c0c934f9a..c1231d3fbf3 100644
--- a/nixos/modules/services/x11/window-managers/awesome.nix
+++ b/nixos/modules/services/x11/window-managers/awesome.nix
@@ -6,7 +6,7 @@ let
 
   cfg = config.services.xserver.windowManager.awesome;
   awesome = cfg.package;
-  getLuaPath = lib : dir : "${lib}/${dir}/lua/${pkgs.luaPackages.lua.luaversion}";
+  getLuaPath = lib: dir: "${lib}/${dir}/lua/${awesome.lua.luaversion}";
   makeSearchPath = lib.concatMapStrings (path:
     " --search " + (getLuaPath path "share") +
     " --search " + (getLuaPath path "lib")
@@ -21,26 +21,26 @@ in
 
     services.xserver.windowManager.awesome = {
 
-      enable = mkEnableOption "Awesome window manager";
+      enable = mkEnableOption (lib.mdDoc "Awesome window manager");
 
       luaModules = mkOption {
         default = [];
         type = types.listOf types.package;
-        description = "List of lua packages available for being used in the Awesome configuration.";
+        description = lib.mdDoc "List of lua packages available for being used in the Awesome configuration.";
         example = literalExpression "[ pkgs.luaPackages.vicious ]";
       };
 
       package = mkOption {
         default = null;
         type = types.nullOr types.package;
-        description = "Package to use for running the Awesome WM.";
+        description = lib.mdDoc "Package to use for running the Awesome WM.";
         apply = pkg: if pkg == null then pkgs.awesome else pkg;
       };
 
       noArgb = mkOption {
         default = false;
         type = types.bool;
-        description = "Disable client transparency support, which can be greatly detrimental to performance in some setups";
+        description = lib.mdDoc "Disable client transparency support, which can be greatly detrimental to performance in some setups";
       };
     };
 
diff --git a/nixos/modules/services/x11/window-managers/berry.nix b/nixos/modules/services/x11/window-managers/berry.nix
index 0d2285e7a60..eb552860267 100644
--- a/nixos/modules/services/x11/window-managers/berry.nix
+++ b/nixos/modules/services/x11/window-managers/berry.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.berry.enable = mkEnableOption "berry";
+    services.xserver.windowManager.berry.enable = mkEnableOption (lib.mdDoc "berry");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/bspwm.nix b/nixos/modules/services/x11/window-managers/bspwm.nix
index ade24061a06..c403f744cd4 100644
--- a/nixos/modules/services/x11/window-managers/bspwm.nix
+++ b/nixos/modules/services/x11/window-managers/bspwm.nix
@@ -9,14 +9,14 @@ in
 {
   options = {
     services.xserver.windowManager.bspwm = {
-      enable = mkEnableOption "bspwm";
+      enable = mkEnableOption (lib.mdDoc "bspwm");
 
       package = mkOption {
         type        = types.package;
         default     = pkgs.bspwm;
         defaultText = literalExpression "pkgs.bspwm";
         example     = literalExpression "pkgs.bspwm-unstable";
-        description = ''
+        description = lib.mdDoc ''
           bspwm package to use.
         '';
       };
@@ -24,7 +24,7 @@ in
         type        = with types; nullOr path;
         example     = literalExpression ''"''${pkgs.bspwm}/share/doc/bspwm/examples/bspwmrc"'';
         default     = null;
-        description = ''
+        description = lib.mdDoc ''
           Path to the bspwm configuration file.
           If null, $HOME/.config/bspwm/bspwmrc will be used.
         '';
@@ -36,7 +36,7 @@ in
           default     = pkgs.sxhkd;
           defaultText = literalExpression "pkgs.sxhkd";
           example     = literalExpression "pkgs.sxhkd-unstable";
-          description = ''
+          description = lib.mdDoc ''
             sxhkd package to use.
           '';
         };
@@ -44,7 +44,7 @@ in
           type        = with types; nullOr path;
           example     = literalExpression ''"''${pkgs.bspwm}/share/doc/bspwm/examples/sxhkdrc"'';
           default     = null;
-          description = ''
+          description = lib.mdDoc ''
             Path to the sxhkd configuration file.
             If null, $HOME/.config/sxhkd/sxhkdrc will be used.
           '';
diff --git a/nixos/modules/services/x11/window-managers/clfswm.nix b/nixos/modules/services/x11/window-managers/clfswm.nix
index 78772c79974..f2e4c2f91c9 100644
--- a/nixos/modules/services/x11/window-managers/clfswm.nix
+++ b/nixos/modules/services/x11/window-managers/clfswm.nix
@@ -9,12 +9,12 @@ in
 {
   options = {
     services.xserver.windowManager.clfswm = {
-      enable = mkEnableOption "clfswm";
+      enable = mkEnableOption (lib.mdDoc "clfswm");
       package = mkOption {
         type        = types.package;
         default     = pkgs.lispPackages.clfswm;
         defaultText = literalExpression "pkgs.lispPackages.clfswm";
-        description = ''
+        description = lib.mdDoc ''
           clfswm package to use.
         '';
       };
diff --git a/nixos/modules/services/x11/window-managers/cwm.nix b/nixos/modules/services/x11/window-managers/cwm.nix
index 03375a226bb..9a143e7bccc 100644
--- a/nixos/modules/services/x11/window-managers/cwm.nix
+++ b/nixos/modules/services/x11/window-managers/cwm.nix
@@ -7,7 +7,7 @@ let
 in
 {
   options = {
-    services.xserver.windowManager.cwm.enable = mkEnableOption "cwm";
+    services.xserver.windowManager.cwm.enable = mkEnableOption (lib.mdDoc "cwm");
   };
   config = mkIf cfg.enable {
     services.xserver.windowManager.session = singleton
diff --git a/nixos/modules/services/x11/window-managers/default.nix b/nixos/modules/services/x11/window-managers/default.nix
index d71738ea633..48b413beaa8 100644
--- a/nixos/modules/services/x11/window-managers/default.nix
+++ b/nixos/modules/services/x11/window-managers/default.nix
@@ -19,8 +19,11 @@ in
     ./evilwm.nix
     ./exwm.nix
     ./fluxbox.nix
-    ./fvwm.nix
+    ./fvwm2.nix
+    ./fvwm3.nix
+    ./hackedbox.nix
     ./herbstluftwm.nix
+    ./hypr.nix
     ./i3.nix
     ./jwm.nix
     ./leftwm.nix
@@ -57,10 +60,10 @@ in
           name = "wmii";
           start = "...";
         }];
-        description = ''
+        description = lib.mdDoc ''
           Internal option used to add some common line to window manager
           scripts before forwarding the value to the
-          <varname>displayManager</varname>.
+          `displayManager`.
         '';
         apply = map (d: d // {
           manage = "window";
@@ -71,8 +74,8 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "wmii";
-        description = ''
-          <emphasis role="strong">Deprecated</emphasis>, please use <xref linkend="opt-services.xserver.displayManager.defaultSession"/> instead.
+        description = lib.mdDoc ''
+          **Deprecated**, please use [](#opt-services.xserver.displayManager.defaultSession) instead.
 
           Default window manager loaded if none have been chosen.
         '';
diff --git a/nixos/modules/services/x11/window-managers/dwm.nix b/nixos/modules/services/x11/window-managers/dwm.nix
index 7777913ce1e..1881826944a 100644
--- a/nixos/modules/services/x11/window-managers/dwm.nix
+++ b/nixos/modules/services/x11/window-managers/dwm.nix
@@ -13,7 +13,27 @@ in
   ###### interface
 
   options = {
-    services.xserver.windowManager.dwm.enable = mkEnableOption "dwm";
+    services.xserver.windowManager.dwm = {
+      enable = mkEnableOption (lib.mdDoc "dwm");
+      package = mkOption {
+        type        = types.package;
+        default     = pkgs.dwm;
+        defaultText = literalExpression "pkgs.dwm";
+        example     = literalExpression ''
+          pkgs.dwm.overrideAttrs (oldAttrs: rec {
+            patches = [
+              (super.fetchpatch {
+                url = "https://dwm.suckless.org/patches/steam/dwm-steam-6.2.diff";
+                sha256 = "1ld1z3fh6p5f8gr62zknx3axsinraayzxw3rz1qwg73mx2zk5y1f";
+              })
+            ];
+          })
+        '';
+        description = lib.mdDoc ''
+          dwm package to use.
+        '';
+      };
+    };
   };
 
 
@@ -30,7 +50,7 @@ in
           '';
       };
 
-    environment.systemPackages = [ pkgs.dwm ];
+    environment.systemPackages = [ cfg.package ];
 
   };
 
diff --git a/nixos/modules/services/x11/window-managers/e16.nix b/nixos/modules/services/x11/window-managers/e16.nix
index 3e1a22c4dab..000feea12c2 100644
--- a/nixos/modules/services/x11/window-managers/e16.nix
+++ b/nixos/modules/services/x11/window-managers/e16.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.e16.enable = mkEnableOption "e16";
+    services.xserver.windowManager.e16.enable = mkEnableOption (lib.mdDoc "e16");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/evilwm.nix b/nixos/modules/services/x11/window-managers/evilwm.nix
index 6f1db2110f8..842f84c2cfb 100644
--- a/nixos/modules/services/x11/window-managers/evilwm.nix
+++ b/nixos/modules/services/x11/window-managers/evilwm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.evilwm.enable = mkEnableOption "evilwm";
+    services.xserver.windowManager.evilwm.enable = mkEnableOption (lib.mdDoc "evilwm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/exwm.nix b/nixos/modules/services/x11/window-managers/exwm.nix
index b505f720f04..a97ed74ae88 100644
--- a/nixos/modules/services/x11/window-managers/exwm.nix
+++ b/nixos/modules/services/x11/window-managers/exwm.nix
@@ -18,7 +18,7 @@ in
 {
   options = {
     services.xserver.windowManager.exwm = {
-      enable = mkEnableOption "exwm";
+      enable = mkEnableOption (lib.mdDoc "exwm");
       loadScript = mkOption {
         default = "(require 'exwm)";
         type = types.lines;
@@ -26,7 +26,7 @@ in
           (require 'exwm)
           (exwm-enable)
         '';
-        description = ''
+        description = lib.mdDoc ''
           Emacs lisp code to be run after loading the user's init
           file. If enableDefaultConfig is true, this will be run
           before loading the default config.
@@ -35,7 +35,7 @@ in
       enableDefaultConfig = mkOption {
         default = true;
         type = lib.types.bool;
-        description = "Enable an uncustomised exwm configuration.";
+        description = lib.mdDoc "Enable an uncustomised exwm configuration.";
       };
       extraPackages = mkOption {
         type = types.functionTo (types.listOf types.package);
@@ -48,10 +48,10 @@ in
             epkgs.proofgeneral
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra packages available to Emacs. The value must be a
           function which receives the attrset defined in
-          <varname>emacs.pkgs</varname> as the sole argument.
+          {var}`emacs.pkgs` as the sole argument.
         '';
       };
     };
diff --git a/nixos/modules/services/x11/window-managers/fluxbox.nix b/nixos/modules/services/x11/window-managers/fluxbox.nix
index b409335702a..24165fb6fb0 100644
--- a/nixos/modules/services/x11/window-managers/fluxbox.nix
+++ b/nixos/modules/services/x11/window-managers/fluxbox.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.fluxbox.enable = mkEnableOption "fluxbox";
+    services.xserver.windowManager.fluxbox.enable = mkEnableOption (lib.mdDoc "fluxbox");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/fvwm.nix b/nixos/modules/services/x11/window-managers/fvwm.nix
deleted file mode 100644
index e283886ecc4..00000000000
--- a/nixos/modules/services/x11/window-managers/fvwm.nix
+++ /dev/null
@@ -1,41 +0,0 @@
-{ config, lib, pkgs, ... }:
-
-with lib;
-
-let
-  cfg = config.services.xserver.windowManager.fvwm;
-  fvwm = pkgs.fvwm.override { enableGestures = cfg.gestures; };
-in
-
-{
-
-  ###### interface
-
-  options = {
-    services.xserver.windowManager.fvwm = {
-      enable = mkEnableOption "Fvwm window manager";
-
-      gestures = mkOption {
-        default = false;
-        type = types.bool;
-        description = "Whether or not to enable libstroke for gesture support";
-      };
-    };
-  };
-
-
-  ###### implementation
-
-  config = mkIf cfg.enable {
-    services.xserver.windowManager.session = singleton
-      { name = "fvwm";
-        start =
-          ''
-            ${fvwm}/bin/fvwm &
-            waitPID=$!
-          '';
-      };
-
-    environment.systemPackages = [ fvwm ];
-  };
-}
diff --git a/nixos/modules/services/x11/window-managers/fvwm2.nix b/nixos/modules/services/x11/window-managers/fvwm2.nix
new file mode 100644
index 00000000000..aaf3c5c4690
--- /dev/null
+++ b/nixos/modules/services/x11/window-managers/fvwm2.nix
@@ -0,0 +1,47 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.xserver.windowManager.fvwm2;
+  fvwm2 = pkgs.fvwm2.override { enableGestures = cfg.gestures; };
+in
+
+{
+
+  imports = [
+    (mkRenamedOptionModule
+      [ "services" "xserver" "windowManager" "fvwm" ]
+      [ "services" "xserver" "windowManager" "fvwm2" ])
+  ];
+
+  ###### interface
+
+  options = {
+    services.xserver.windowManager.fvwm2 = {
+      enable = mkEnableOption (lib.mdDoc "Fvwm2 window manager");
+
+      gestures = mkOption {
+        default = false;
+        type = types.bool;
+        description = lib.mdDoc "Whether or not to enable libstroke for gesture support";
+      };
+    };
+  };
+
+
+  ###### implementation
+
+  config = mkIf cfg.enable {
+    services.xserver.windowManager.session = singleton
+      { name = "fvwm2";
+        start =
+          ''
+            ${fvwm2}/bin/fvwm &
+            waitPID=$!
+          '';
+      };
+
+    environment.systemPackages = [ fvwm2 ];
+  };
+}
diff --git a/nixos/modules/services/x11/window-managers/fvwm3.nix b/nixos/modules/services/x11/window-managers/fvwm3.nix
new file mode 100644
index 00000000000..50c76b67eea
--- /dev/null
+++ b/nixos/modules/services/x11/window-managers/fvwm3.nix
@@ -0,0 +1,35 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.xserver.windowManager.fvwm3;
+  inherit (pkgs) fvwm3;
+in
+
+{
+
+  ###### interface
+
+  options = {
+    services.xserver.windowManager.fvwm3 = {
+      enable = mkEnableOption (lib.mdDoc "Fvwm3 window manager");
+    };
+  };
+
+
+  ###### implementation
+
+  config = mkIf cfg.enable {
+    services.xserver.windowManager.session = singleton
+      { name = "fvwm3";
+        start =
+          ''
+            ${fvwm3}/bin/fvwm3 &
+            waitPID=$!
+          '';
+      };
+
+    environment.systemPackages = [ fvwm3 ];
+  };
+}
diff --git a/nixos/modules/services/x11/window-managers/hackedbox.nix b/nixos/modules/services/x11/window-managers/hackedbox.nix
new file mode 100644
index 00000000000..61e911961f5
--- /dev/null
+++ b/nixos/modules/services/x11/window-managers/hackedbox.nix
@@ -0,0 +1,25 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.xserver.windowManager.hackedbox;
+in
+{
+  ###### interface
+  options = {
+    services.xserver.windowManager.hackedbox.enable = mkEnableOption (lib.mdDoc "hackedbox");
+  };
+
+  ###### implementation
+  config = mkIf cfg.enable {
+    services.xserver.windowManager.session = singleton {
+      name = "hackedbox";
+      start = ''
+        ${pkgs.hackedbox}/bin/hackedbox &
+        waitPID=$!
+      '';
+    };
+    environment.systemPackages = [ pkgs.hackedbox ];
+  };
+}
diff --git a/nixos/modules/services/x11/window-managers/herbstluftwm.nix b/nixos/modules/services/x11/window-managers/herbstluftwm.nix
index 354d70c695c..816cbb36caf 100644
--- a/nixos/modules/services/x11/window-managers/herbstluftwm.nix
+++ b/nixos/modules/services/x11/window-managers/herbstluftwm.nix
@@ -9,13 +9,13 @@ in
 {
   options = {
     services.xserver.windowManager.herbstluftwm = {
-      enable = mkEnableOption "herbstluftwm";
+      enable = mkEnableOption (lib.mdDoc "herbstluftwm");
 
       package = mkOption {
         type = types.package;
         default = pkgs.herbstluftwm;
         defaultText = literalExpression "pkgs.herbstluftwm";
-        description = ''
+        description = lib.mdDoc ''
           Herbstluftwm package to use.
         '';
       };
@@ -23,7 +23,7 @@ in
       configFile = mkOption {
         default     = null;
         type        = with types; nullOr path;
-        description = ''
+        description = lib.mdDoc ''
           Path to the herbstluftwm configuration file.  If left at the
           default value, $XDG_CONFIG_HOME/herbstluftwm/autostart will
           be used.
diff --git a/nixos/modules/services/x11/window-managers/hypr.nix b/nixos/modules/services/x11/window-managers/hypr.nix
new file mode 100644
index 00000000000..4c1fea71f93
--- /dev/null
+++ b/nixos/modules/services/x11/window-managers/hypr.nix
@@ -0,0 +1,25 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+  cfg = config.services.xserver.windowManager.hypr;
+in
+{
+  ###### interface
+  options = {
+    services.xserver.windowManager.hypr.enable = mkEnableOption (lib.mdDoc "hypr");
+  };
+
+  ###### implementation
+  config = mkIf cfg.enable {
+    services.xserver.windowManager.session = singleton {
+      name = "hypr";
+      start = ''
+        ${pkgs.hypr}/bin/Hypr &
+        waitPID=$!
+      '';
+    };
+    environment.systemPackages = [ pkgs.hypr ];
+  };
+}
diff --git a/nixos/modules/services/x11/window-managers/i3.nix b/nixos/modules/services/x11/window-managers/i3.nix
index 99f9997024f..64109e0c39f 100644
--- a/nixos/modules/services/x11/window-managers/i3.nix
+++ b/nixos/modules/services/x11/window-managers/i3.nix
@@ -8,12 +8,12 @@ in
 
 {
   options.services.xserver.windowManager.i3 = {
-    enable = mkEnableOption "i3 window manager";
+    enable = mkEnableOption (lib.mdDoc "i3 window manager");
 
     configFile = mkOption {
       default     = null;
       type        = with types; nullOr path;
-      description = ''
+      description = lib.mdDoc ''
         Path to the i3 configuration file.
         If left at the default value, $HOME/.i3/config will be used.
       '';
@@ -22,7 +22,7 @@ in
     extraSessionCommands = mkOption {
       default     = "";
       type        = types.lines;
-      description = ''
+      description = lib.mdDoc ''
         Shell commands executed just before i3 is started.
       '';
     };
@@ -32,7 +32,7 @@ in
       default     = pkgs.i3;
       defaultText = literalExpression "pkgs.i3";
       example     = literalExpression "pkgs.i3-gaps";
-      description = ''
+      description = lib.mdDoc ''
         i3 package to use.
       '';
     };
@@ -47,7 +47,7 @@ in
           i3lock
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         Extra packages to be installed system wide.
       '';
     };
diff --git a/nixos/modules/services/x11/window-managers/icewm.nix b/nixos/modules/services/x11/window-managers/icewm.nix
index f4ae9222df6..48741aa41d8 100644
--- a/nixos/modules/services/x11/window-managers/icewm.nix
+++ b/nixos/modules/services/x11/window-managers/icewm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.icewm.enable = mkEnableOption "icewm";
+    services.xserver.windowManager.icewm.enable = mkEnableOption (lib.mdDoc "icewm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/jwm.nix b/nixos/modules/services/x11/window-managers/jwm.nix
index 0e8dab2e922..40758029bc6 100644
--- a/nixos/modules/services/x11/window-managers/jwm.nix
+++ b/nixos/modules/services/x11/window-managers/jwm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.jwm.enable = mkEnableOption "jwm";
+    services.xserver.windowManager.jwm.enable = mkEnableOption (lib.mdDoc "jwm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/leftwm.nix b/nixos/modules/services/x11/window-managers/leftwm.nix
index 3ef40df95df..2571735ba8b 100644
--- a/nixos/modules/services/x11/window-managers/leftwm.nix
+++ b/nixos/modules/services/x11/window-managers/leftwm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.leftwm.enable = mkEnableOption "leftwm";
+    services.xserver.windowManager.leftwm.enable = mkEnableOption (lib.mdDoc "leftwm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/lwm.nix b/nixos/modules/services/x11/window-managers/lwm.nix
index e2aa062fd13..517abb23d4a 100644
--- a/nixos/modules/services/x11/window-managers/lwm.nix
+++ b/nixos/modules/services/x11/window-managers/lwm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.lwm.enable = mkEnableOption "lwm";
+    services.xserver.windowManager.lwm.enable = mkEnableOption (lib.mdDoc "lwm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/metacity.nix b/nixos/modules/services/x11/window-managers/metacity.nix
index 600afe759b2..1f69147af5b 100644
--- a/nixos/modules/services/x11/window-managers/metacity.nix
+++ b/nixos/modules/services/x11/window-managers/metacity.nix
@@ -10,7 +10,7 @@ in
 
 {
   options = {
-    services.xserver.windowManager.metacity.enable = mkEnableOption "metacity";
+    services.xserver.windowManager.metacity.enable = mkEnableOption (lib.mdDoc "metacity");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/x11/window-managers/mlvwm.nix b/nixos/modules/services/x11/window-managers/mlvwm.nix
index 08dd0402029..fe0433c24b6 100644
--- a/nixos/modules/services/x11/window-managers/mlvwm.nix
+++ b/nixos/modules/services/x11/window-managers/mlvwm.nix
@@ -8,12 +8,12 @@ in
 {
 
   options.services.xserver.windowManager.mlvwm = {
-    enable = mkEnableOption "Macintosh-like Virtual Window Manager";
+    enable = mkEnableOption (lib.mdDoc "Macintosh-like Virtual Window Manager");
 
     configFile = mkOption {
       default = null;
       type = with types; nullOr path;
-      description = ''
+      description = lib.mdDoc ''
         Path to the mlvwm configuration file.
         If left at the default value, $HOME/.mlvwmrc will be used.
       '';
diff --git a/nixos/modules/services/x11/window-managers/mwm.nix b/nixos/modules/services/x11/window-managers/mwm.nix
index 31f7b725f74..9f8dc0939e5 100644
--- a/nixos/modules/services/x11/window-managers/mwm.nix
+++ b/nixos/modules/services/x11/window-managers/mwm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.mwm.enable = mkEnableOption "mwm";
+    services.xserver.windowManager.mwm.enable = mkEnableOption (lib.mdDoc "mwm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/notion.nix b/nixos/modules/services/x11/window-managers/notion.nix
index 4ece0d241c9..0015e90a41c 100644
--- a/nixos/modules/services/x11/window-managers/notion.nix
+++ b/nixos/modules/services/x11/window-managers/notion.nix
@@ -8,7 +8,7 @@ in
 
 {
   options = {
-    services.xserver.windowManager.notion.enable = mkEnableOption "notion";
+    services.xserver.windowManager.notion.enable = mkEnableOption (lib.mdDoc "notion");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/x11/window-managers/openbox.nix b/nixos/modules/services/x11/window-managers/openbox.nix
index 165772d1aa0..bf5a500f431 100644
--- a/nixos/modules/services/x11/window-managers/openbox.nix
+++ b/nixos/modules/services/x11/window-managers/openbox.nix
@@ -7,7 +7,7 @@ in
 
 {
   options = {
-    services.xserver.windowManager.openbox.enable = mkEnableOption "openbox";
+    services.xserver.windowManager.openbox.enable = mkEnableOption (lib.mdDoc "openbox");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/x11/window-managers/oroborus.nix b/nixos/modules/services/x11/window-managers/oroborus.nix
index bd7e3396864..654b8708e48 100644
--- a/nixos/modules/services/x11/window-managers/oroborus.nix
+++ b/nixos/modules/services/x11/window-managers/oroborus.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.oroborus.enable = mkEnableOption "oroborus";
+    services.xserver.windowManager.oroborus.enable = mkEnableOption (lib.mdDoc "oroborus");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/pekwm.nix b/nixos/modules/services/x11/window-managers/pekwm.nix
index 850335ce7dd..8818f568647 100644
--- a/nixos/modules/services/x11/window-managers/pekwm.nix
+++ b/nixos/modules/services/x11/window-managers/pekwm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.pekwm.enable = mkEnableOption "pekwm";
+    services.xserver.windowManager.pekwm.enable = mkEnableOption (lib.mdDoc "pekwm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/qtile.nix b/nixos/modules/services/x11/window-managers/qtile.nix
index 835b41d4ada..523642591d9 100644
--- a/nixos/modules/services/x11/window-managers/qtile.nix
+++ b/nixos/modules/services/x11/window-managers/qtile.nix
@@ -7,19 +7,26 @@ let
 in
 
 {
-  options = {
-    services.xserver.windowManager.qtile.enable = mkEnableOption "qtile";
+  options.services.xserver.windowManager.qtile = {
+    enable = mkEnableOption (lib.mdDoc "qtile");
+
+    package = mkPackageOption pkgs "qtile" { };
   };
 
   config = mkIf cfg.enable {
     services.xserver.windowManager.session = [{
       name = "qtile";
       start = ''
-        ${pkgs.qtile}/bin/qtile start &
+        ${cfg.package}/bin/qtile start &
         waitPID=$!
       '';
     }];
 
-    environment.systemPackages = [ pkgs.qtile ];
+    environment.systemPackages = [
+      # pkgs.qtile is currently a buildenv of qtile and its dependencies.
+      # For userland commands, we want the underlying package so that
+      # packages such as python don't bleed into userland and overwrite intended behavior.
+      (cfg.package.unwrapped or cfg.package)
+    ];
   };
 }
diff --git a/nixos/modules/services/x11/window-managers/ratpoison.nix b/nixos/modules/services/x11/window-managers/ratpoison.nix
index 0d58481d457..1de0fad3e54 100644
--- a/nixos/modules/services/x11/window-managers/ratpoison.nix
+++ b/nixos/modules/services/x11/window-managers/ratpoison.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.ratpoison.enable = mkEnableOption "ratpoison";
+    services.xserver.windowManager.ratpoison.enable = mkEnableOption (lib.mdDoc "ratpoison");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/sawfish.nix b/nixos/modules/services/x11/window-managers/sawfish.nix
index b988b5e1829..1945a1af676 100644
--- a/nixos/modules/services/x11/window-managers/sawfish.nix
+++ b/nixos/modules/services/x11/window-managers/sawfish.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.sawfish.enable = mkEnableOption "sawfish";
+    services.xserver.windowManager.sawfish.enable = mkEnableOption (lib.mdDoc "sawfish");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/smallwm.nix b/nixos/modules/services/x11/window-managers/smallwm.nix
index 091ba4f92b9..e92b18690d8 100644
--- a/nixos/modules/services/x11/window-managers/smallwm.nix
+++ b/nixos/modules/services/x11/window-managers/smallwm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.smallwm.enable = mkEnableOption "smallwm";
+    services.xserver.windowManager.smallwm.enable = mkEnableOption (lib.mdDoc "smallwm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/spectrwm.nix b/nixos/modules/services/x11/window-managers/spectrwm.nix
index a1dc298d242..c464803a0b6 100644
--- a/nixos/modules/services/x11/window-managers/spectrwm.nix
+++ b/nixos/modules/services/x11/window-managers/spectrwm.nix
@@ -9,7 +9,7 @@ in
 
 {
   options = {
-    services.xserver.windowManager.spectrwm.enable = mkEnableOption "spectrwm";
+    services.xserver.windowManager.spectrwm.enable = mkEnableOption (lib.mdDoc "spectrwm");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/x11/window-managers/stumpwm.nix b/nixos/modules/services/x11/window-managers/stumpwm.nix
index 27a17178476..162af689dbb 100644
--- a/nixos/modules/services/x11/window-managers/stumpwm.nix
+++ b/nixos/modules/services/x11/window-managers/stumpwm.nix
@@ -8,7 +8,7 @@ in
 
 {
   options = {
-    services.xserver.windowManager.stumpwm.enable = mkEnableOption "stumpwm";
+    services.xserver.windowManager.stumpwm.enable = mkEnableOption (lib.mdDoc "stumpwm");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/x11/window-managers/tinywm.nix b/nixos/modules/services/x11/window-managers/tinywm.nix
index 8e5d9b9170c..7418a6ddc76 100644
--- a/nixos/modules/services/x11/window-managers/tinywm.nix
+++ b/nixos/modules/services/x11/window-managers/tinywm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.tinywm.enable = mkEnableOption "tinywm";
+    services.xserver.windowManager.tinywm.enable = mkEnableOption (lib.mdDoc "tinywm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/twm.nix b/nixos/modules/services/x11/window-managers/twm.nix
index fc09901aae3..231817a26e6 100644
--- a/nixos/modules/services/x11/window-managers/twm.nix
+++ b/nixos/modules/services/x11/window-managers/twm.nix
@@ -13,7 +13,7 @@ in
   ###### interface
 
   options = {
-    services.xserver.windowManager.twm.enable = mkEnableOption "twm";
+    services.xserver.windowManager.twm.enable = mkEnableOption (lib.mdDoc "twm");
   };
 
 
diff --git a/nixos/modules/services/x11/window-managers/windowlab.nix b/nixos/modules/services/x11/window-managers/windowlab.nix
index fb891a39fa4..9a0646b6ee7 100644
--- a/nixos/modules/services/x11/window-managers/windowlab.nix
+++ b/nixos/modules/services/x11/window-managers/windowlab.nix
@@ -7,7 +7,7 @@ in
 {
   options = {
     services.xserver.windowManager.windowlab.enable =
-      lib.mkEnableOption "windowlab";
+      lib.mkEnableOption (lib.mdDoc "windowlab");
   };
 
   config = lib.mkIf cfg.enable {
diff --git a/nixos/modules/services/x11/window-managers/windowmaker.nix b/nixos/modules/services/x11/window-managers/windowmaker.nix
index b6272375805..a679e2b5bc8 100644
--- a/nixos/modules/services/x11/window-managers/windowmaker.nix
+++ b/nixos/modules/services/x11/window-managers/windowmaker.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.windowmaker.enable = mkEnableOption "windowmaker";
+    services.xserver.windowManager.windowmaker.enable = mkEnableOption (lib.mdDoc "windowmaker");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/window-managers/wmderland.nix b/nixos/modules/services/x11/window-managers/wmderland.nix
index 56b69220965..ed515741f62 100644
--- a/nixos/modules/services/x11/window-managers/wmderland.nix
+++ b/nixos/modules/services/x11/window-managers/wmderland.nix
@@ -8,12 +8,12 @@ in
 
 {
   options.services.xserver.windowManager.wmderland = {
-    enable = mkEnableOption "wmderland";
+    enable = mkEnableOption (lib.mdDoc "wmderland");
 
     extraSessionCommands = mkOption {
       default = "";
       type = types.lines;
-      description = ''
+      description = lib.mdDoc ''
         Shell commands executed just before wmderland is started.
       '';
     };
@@ -38,7 +38,7 @@ in
           rxvt-unicode
         ]
       '';
-      description = ''
+      description = lib.mdDoc ''
         Extra packages to be installed system wide.
       '';
     };
diff --git a/nixos/modules/services/x11/window-managers/wmii.nix b/nixos/modules/services/x11/window-managers/wmii.nix
index 9b50a99bf23..090aa31610a 100644
--- a/nixos/modules/services/x11/window-managers/wmii.nix
+++ b/nixos/modules/services/x11/window-managers/wmii.nix
@@ -7,7 +7,7 @@ let
 in
 {
   options = {
-    services.xserver.windowManager.wmii.enable = mkEnableOption "wmii";
+    services.xserver.windowManager.wmii.enable = mkEnableOption (lib.mdDoc "wmii");
   };
 
   config = mkIf cfg.enable {
diff --git a/nixos/modules/services/x11/window-managers/xmonad.nix b/nixos/modules/services/x11/window-managers/xmonad.nix
index 68f97c2f504..c35446bf405 100644
--- a/nixos/modules/services/x11/window-managers/xmonad.nix
+++ b/nixos/modules/services/x11/window-managers/xmonad.nix
@@ -30,7 +30,7 @@ let
         install -D ${xmonadEnv}/share/man/man1/xmonad.1.gz $out/share/man/man1/xmonad.1.gz
         makeWrapper ${configured}/bin/xmonad $out/bin/xmonad \
       '' + optionalString cfg.enableConfiguredRecompile ''
-          --set NIX_GHC "${xmonadEnv}/bin/ghc" \
+          --set XMONAD_GHC "${xmonadEnv}/bin/ghc" \
       '' + ''
           --set XMONAD_XMESSAGE "${pkgs.xorg.xmessage}/bin/xmessage"
       '');
@@ -41,18 +41,18 @@ in {
 
   options = {
     services.xserver.windowManager.xmonad = {
-      enable = mkEnableOption "xmonad";
+      enable = mkEnableOption (lib.mdDoc "xmonad");
 
       haskellPackages = mkOption {
         default = pkgs.haskellPackages;
         defaultText = literalExpression "pkgs.haskellPackages";
-        example = literalExpression "pkgs.haskell.packages.ghc784";
+        example = literalExpression "pkgs.haskell.packages.ghc810";
         type = types.attrs;
-        description = ''
+        description = lib.mdDoc ''
           haskellPackages used to build Xmonad and other packages.
           This can be used to change the GHC version used to build
           Xmonad and the packages listed in
-          <varname>extraPackages</varname>.
+          {var}`extraPackages`.
         '';
       };
 
@@ -66,23 +66,23 @@ in {
             haskellPackages.monad-logger
           ]
         '';
-        description = ''
+        description = lib.mdDoc ''
           Extra packages available to ghc when rebuilding Xmonad. The
           value must be a function which receives the attrset defined
-          in <varname>haskellPackages</varname> as the sole argument.
+          in {var}`haskellPackages` as the sole argument.
         '';
       };
 
       enableContribAndExtras = mkOption {
         default = false;
         type = lib.types.bool;
-        description = "Enable xmonad-{contrib,extras} in Xmonad.";
+        description = lib.mdDoc "Enable xmonad-{contrib,extras} in Xmonad.";
       };
 
       config = mkOption {
         default = null;
         type = with lib.types; nullOr (either path str);
-        description = ''
+        description = lib.mdDoc ''
           Configuration from which XMonad gets compiled. If no value is
           specified, a vanilla xmonad binary is put in PATH, which will
           attempt to recompile and exec your xmonad config from $HOME/.xmonad.
@@ -94,17 +94,17 @@ in {
           "mod+q" restart key binding dysfunctional though, because that attempts
           to call your binary with the "--restart" command line option, unless
           you implement that yourself. You way mant to bind "mod+q" to
-          <literal>(restart "xmonad" True)</literal> instead, which will just restart
+          `(restart "xmonad" True)` instead, which will just restart
           xmonad from PATH. This allows e.g. switching to the new xmonad binary
           after rebuilding your system with nixos-rebuild.
           For the same reason, ghc is not added to the environment when this
-          option is set, unless <option>enableConfiguredRecompile</option> is
-          set to <literal>true</literal>.
+          option is set, unless {option}`enableConfiguredRecompile` is
+          set to `true`.
 
           If you actually want to run xmonad with a config specified here, but
           also be able to recompile and restart it from a copy of that source in
-          $HOME/.xmonad on the fly, set <option>enableConfiguredRecompile</option>
-          to <literal>true</literal> and implement something like "compileRestart"
+          $HOME/.xmonad on the fly, set {option}`enableConfiguredRecompile`
+          to `true` and implement something like "compileRestart"
           from the example.
           This should allow you to switch at will between the local xmonad and
           the one NixOS puts in your PATH.
@@ -128,41 +128,42 @@ in {
             [ ( (mod4Mask,xK_r), compileRestart True)
             , ( (mod4Mask,xK_q), restart "xmonad" True ) ]
 
+          compileRestart resume = do
+            dirs  <- asks directories
+            whenX (recompile dirs True) $ do
+              when resume writeStateToFile
+              catchIO
+                  ( do
+                      args <- getArgs
+                      executeFile (cacheDir dirs </> compiledConfig) False args Nothing
+                  )
+
+          main = getDirectories >>= launch myConfig
+
           --------------------------------------------
-          {- version 0.17.0 -}
+          {- For versions before 0.17.0 use this instead -}
           --------------------------------------------
           -- compileRestart resume =
-          --   dirs <- io getDirectories
-          --   whenX (recompile dirs True) $
+          --   whenX (recompile True) $
           --     when resume writeStateToFile
           --       *> catchIO
           --         ( do
+          --             dir <- getXMonadDataDir
           --             args <- getArgs
-          --             executeFile (cacheDir dirs </> compiledConfig) False args Nothing
+          --             executeFile (dir </> compiledConfig) False args Nothing
           --         )
           --
-          -- main = getDirectories >>= launch myConfig
+          -- main = launch myConfig
           --------------------------------------------
 
-          compileRestart resume =
-            whenX (recompile True) $
-              when resume writeStateToFile
-                *> catchIO
-                  ( do
-                      dir <- getXMonadDataDir
-                      args <- getArgs
-                      executeFile (dir </> compiledConfig) False args Nothing
-                  )
-
-          main = launch myConfig
         '';
       };
 
       enableConfiguredRecompile = mkOption {
         default = false;
         type = lib.types.bool;
-        description = ''
-          Enable recompilation even if <option>config</option> is set to a
+        description = lib.mdDoc ''
+          Enable recompilation even if {option}`config` is set to a
           non-null value. This adds the necessary Haskell dependencies (GHC with
           packages) to the xmonad binary's environment.
         '';
@@ -171,7 +172,7 @@ in {
       xmonadCliArgs = mkOption {
         default = [];
         type = with lib.types; listOf str;
-        description = ''
+        description = lib.mdDoc ''
           Command line arguments passed to the xmonad binary.
         '';
       };
@@ -179,7 +180,7 @@ in {
       ghcArgs = mkOption {
         default = [];
         type = with lib.types; listOf str;
-        description = ''
+        description = lib.mdDoc ''
           Command line arguments passed to the compiler (ghc)
           invocation when xmonad.config is set.
         '';
diff --git a/nixos/modules/services/x11/window-managers/yeahwm.nix b/nixos/modules/services/x11/window-managers/yeahwm.nix
index 351bd7dfe48..9b40cecace2 100644
--- a/nixos/modules/services/x11/window-managers/yeahwm.nix
+++ b/nixos/modules/services/x11/window-managers/yeahwm.nix
@@ -8,7 +8,7 @@ in
 {
   ###### interface
   options = {
-    services.xserver.windowManager.yeahwm.enable = mkEnableOption "yeahwm";
+    services.xserver.windowManager.yeahwm.enable = mkEnableOption (lib.mdDoc "yeahwm");
   };
 
   ###### implementation
diff --git a/nixos/modules/services/x11/xautolock.nix b/nixos/modules/services/x11/xautolock.nix
index 947d8f4edfb..8200057660e 100644
--- a/nixos/modules/services/x11/xautolock.nix
+++ b/nixos/modules/services/x11/xautolock.nix
@@ -8,9 +8,9 @@ in
   {
     options = {
       services.xserver.xautolock = {
-        enable = mkEnableOption "xautolock";
-        enableNotifier = mkEnableOption "xautolock.notify" // {
-          description = ''
+        enable = mkEnableOption (lib.mdDoc "xautolock");
+        enableNotifier = mkEnableOption (lib.mdDoc "xautolock.notify") // {
+          description = lib.mdDoc ''
             Whether to enable the notifier feature of xautolock.
             This publishes a notification before the autolock.
           '';
@@ -20,7 +20,7 @@ in
           default = 15;
           type = types.int;
 
-          description = ''
+          description = lib.mdDoc ''
             Idle time (in minutes) to wait until xautolock locks the computer.
           '';
         };
@@ -31,7 +31,7 @@ in
           example = literalExpression ''"''${pkgs.i3lock}/bin/i3lock -i /path/to/img"'';
           type = types.str;
 
-          description = ''
+          description = lib.mdDoc ''
             The script to use when automatically locking the computer.
           '';
         };
@@ -41,8 +41,8 @@ in
           example = literalExpression ''"''${pkgs.i3lock}/bin/i3lock -i /path/to/img"'';
           type = types.nullOr types.str;
 
-          description = ''
-            The script to use when manually locking the computer with <command>xautolock -locknow</command>.
+          description = lib.mdDoc ''
+            The script to use when manually locking the computer with {command}`xautolock -locknow`.
           '';
         };
 
@@ -50,7 +50,7 @@ in
           default = 10;
           type = types.int;
 
-          description = ''
+          description = lib.mdDoc ''
             Time (in seconds) before the actual lock when the notification about the pending lock should be published.
           '';
         };
@@ -60,7 +60,7 @@ in
           example = literalExpression ''"''${pkgs.libnotify}/bin/notify-send 'Locking in 10 seconds'"'';
           type = types.nullOr types.str;
 
-          description = ''
+          description = lib.mdDoc ''
             Notification script to be used to warn about the pending autolock.
           '';
         };
@@ -70,8 +70,8 @@ in
           example = "/run/current-system/systemd/bin/systemctl suspend";
           type = types.nullOr types.str;
 
-          description = ''
-            The script to use when nothing has happend for as long as <option>killtime</option>
+          description = lib.mdDoc ''
+            The script to use when nothing has happend for as long as {option}`killtime`
           '';
         };
 
@@ -79,8 +79,8 @@ in
           default = 20; # default according to `man xautolock`
           type = types.int;
 
-          description = ''
-            Minutes xautolock waits until it executes the script specified in <option>killer</option>
+          description = lib.mdDoc ''
+            Minutes xautolock waits until it executes the script specified in {option}`killer`
             (Has to be at least 10 minutes)
           '';
         };
@@ -89,9 +89,9 @@ in
           type = types.listOf types.str;
           default = [ ];
           example = [ "-detectsleep" ];
-          description = ''
+          description = lib.mdDoc ''
             Additional command-line arguments to pass to
-            <command>xautolock</command>.
+            {command}`xautolock`.
           '';
         };
       };
diff --git a/nixos/modules/services/x11/xbanish.nix b/nixos/modules/services/x11/xbanish.nix
index b95fac68f16..de893fae75a 100644
--- a/nixos/modules/services/x11/xbanish.nix
+++ b/nixos/modules/services/x11/xbanish.nix
@@ -7,10 +7,10 @@ let cfg = config.services.xbanish;
 in {
   options.services.xbanish = {
 
-    enable = mkEnableOption "xbanish";
+    enable = mkEnableOption (lib.mdDoc "xbanish");
 
     arguments = mkOption {
-      description = "Arguments to pass to xbanish command";
+      description = lib.mdDoc "Arguments to pass to xbanish command";
       default = "";
       example = "-d -i shift";
       type = types.str;
diff --git a/nixos/modules/services/x11/xfs.nix b/nixos/modules/services/x11/xfs.nix
index ea7cfa1aa43..591bf461496 100644
--- a/nixos/modules/services/x11/xfs.nix
+++ b/nixos/modules/services/x11/xfs.nix
@@ -19,7 +19,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = "Whether to enable the X Font Server.";
+        description = lib.mdDoc "Whether to enable the X Font Server.";
       };
 
     };
diff --git a/nixos/modules/services/x11/xserver.nix b/nixos/modules/services/x11/xserver.nix
index 0c50d82b23b..83a71dcf23e 100644
--- a/nixos/modules/services/x11/xserver.nix
+++ b/nixos/modules/services/x11/xserver.nix
@@ -1,4 +1,4 @@
-{ config, lib, pkgs, ... }:
+{ config, lib, utils, pkgs, ... }:
 
 with lib;
 
@@ -37,18 +37,16 @@ let
     output = mkOption {
       type = types.str;
       example = "DVI-0";
-      description = ''
-        The output name of the monitor, as shown by <citerefentry>
-          <refentrytitle>xrandr</refentrytitle>
-          <manvolnum>1</manvolnum>
-        </citerefentry> invoked without arguments.
+      description = lib.mdDoc ''
+        The output name of the monitor, as shown by
+        {manpage}`xrandr(1)` invoked without arguments.
       '';
     };
 
     primary = mkOption {
       type = types.bool;
       default = false;
-      description = ''
+      description = lib.mdDoc ''
         Whether this head is treated as the primary monitor,
       '';
     };
@@ -60,11 +58,10 @@ let
         DisplaySize 408 306
         Option "DPMS" "false"
       '';
-      description = ''
-        Extra lines to append to the <literal>Monitor</literal> section
+      description = lib.mdDoc ''
+        Extra lines to append to the `Monitor` section
         verbatim. Available options are documented in the MONITOR section in
-        <citerefentry><refentrytitle>xorg.conf</refentrytitle>
-        <manvolnum>5</manvolnum></citerefentry>.
+        {manpage}`xorg.conf(5)`.
       '';
     };
   };
@@ -154,8 +151,10 @@ in
       (mkRemovedOptionModule
         [ "services" "xserver" "startDbusSession" ]
         "The user D-Bus session is now always socket activated and this option can safely be removed.")
-      (mkRemovedOptionModule ["services" "xserver" "useXFS" ]
+      (mkRemovedOptionModule [ "services" "xserver" "useXFS" ]
         "Use services.xserver.fontPath instead of useXFS")
+      (mkRemovedOptionModule [ "services" "xserver" "useGlamor" ]
+        "Option services.xserver.useGlamor was removed because it is unnecessary. Drivers that uses Glamor will use it automatically.")
     ];
 
 
@@ -168,7 +167,7 @@ in
       enable = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the X server.
         '';
       };
@@ -176,24 +175,31 @@ in
       autorun = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to start the X server automatically.
         '';
       };
 
+      excludePackages = mkOption {
+        default = [];
+        example = literalExpression "[ pkgs.xterm ]";
+        type = types.listOf types.package;
+        description = lib.mdDoc "Which X11 packages to exclude from the default environment";
+      };
+
       exportConfiguration = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to symlink the X server configuration under
-          <filename>/etc/X11/xorg.conf</filename>.
+          {file}`/etc/X11/xorg.conf`.
         '';
       };
 
       enableTCP = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to allow the X server to accept TCP connections.
         '';
       };
@@ -201,7 +207,7 @@ in
       autoRepeatDelay = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Sets the autorepeat delay (length of time in milliseconds that a key must be depressed before autorepeat starts).
         '';
       };
@@ -209,7 +215,7 @@ in
       autoRepeatInterval = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Sets the autorepeat interval (length of time in milliseconds that should elapse between autorepeat-generated keystrokes).
         '';
       };
@@ -227,21 +233,21 @@ in
             '''
           ]
         '';
-        description = "Content of additional InputClass sections of the X server configuration file.";
+        description = lib.mdDoc "Content of additional InputClass sections of the X server configuration file.";
       };
 
       modules = mkOption {
         type = types.listOf types.path;
         default = [];
         example = literalExpression "[ pkgs.xf86_input_wacom ]";
-        description = "Packages to be added to the module search path of the X server.";
+        description = lib.mdDoc "Packages to be added to the module search path of the X server.";
       };
 
       resolutions = mkOption {
         type = types.listOf types.attrs;
         default = [];
         example = [ { x = 1600; y = 1200; } { x = 1024; y = 786; } ];
-        description = ''
+        description = lib.mdDoc ''
           The screen resolutions for the X server.  The first element
           is the default resolution.  If this list is empty, the X
           server will automatically configure the resolution.
@@ -262,7 +268,7 @@ in
               path  = [ "xorg" n ];
               title = removePrefix "xf86video" n;
             }) pkgs.xorg);
-        description = ''
+        description = lib.mdDoc ''
           The names of the video drivers the configuration
           supports. They will be tried in order until one that
           supports your card is found.
@@ -278,17 +284,17 @@ in
         type = types.nullOr types.str;
         default = null;
         example = "i810";
-        description = ''
+        description = lib.mdDoc ''
           The name of the video driver for your graphics card.  This
           option is obsolete; please set the
-          <option>services.xserver.videoDrivers</option> instead.
+          {option}`services.xserver.videoDrivers` instead.
         '';
       };
 
       drivers = mkOption {
         type = types.listOf types.attrs;
         internal = true;
-        description = ''
+        description = lib.mdDoc ''
           A list of attribute sets specifying drivers to be loaded by
           the X11 server.
         '';
@@ -297,17 +303,17 @@ in
       dpi = mkOption {
         type = types.nullOr types.int;
         default = null;
-        description = ''
+        description = lib.mdDoc ''
           Force global DPI resolution to use for X server. It's recommended to
           use this only when DPI is detected incorrectly; also consider using
-          <literal>Monitor</literal> section in configuration file instead.
+          `Monitor` section in configuration file instead.
         '';
       };
 
       updateDbusEnvironment = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to update the DBus activation environment after launching the
           desktop manager.
         '';
@@ -316,7 +322,7 @@ in
       layout = mkOption {
         type = types.str;
         default = "us";
-        description = ''
+        description = lib.mdDoc ''
           Keyboard layout, or multiple keyboard layouts separated by commas.
         '';
       };
@@ -325,7 +331,7 @@ in
         type = types.str;
         default = "pc104";
         example = "presario";
-        description = ''
+        description = lib.mdDoc ''
           Keyboard model.
         '';
       };
@@ -334,7 +340,7 @@ in
         type = types.commas;
         default = "terminate:ctrl_alt_bksp";
         example = "grp:caps_toggle,grp_led:scroll";
-        description = ''
+        description = lib.mdDoc ''
           X keyboard options; layout switching goes here.
         '';
       };
@@ -343,7 +349,7 @@ in
         type = types.str;
         default = "";
         example = "colemak";
-        description = ''
+        description = lib.mdDoc ''
           X keyboard variant.
         '';
       };
@@ -352,22 +358,22 @@ in
         type = types.path;
         default = "${pkgs.xkeyboard_config}/etc/X11/xkb";
         defaultText = literalExpression ''"''${pkgs.xkeyboard_config}/etc/X11/xkb"'';
-        description = ''
+        description = lib.mdDoc ''
           Path used for -xkbdir xserver parameter.
         '';
       };
 
       config = mkOption {
         type = types.lines;
-        description = ''
+        description = lib.mdDoc ''
           The contents of the configuration file of the X server
-          (<filename>xorg.conf</filename>).
+          ({file}`xorg.conf`).
 
           This option is set by multiple modules, and the configs are
           concatenated together.
 
           In Xorg configs the last config entries take precedence,
-          so you may want to use <literal>lib.mkAfter</literal> on this option
+          so you may want to use `lib.mkAfter` on this option
           to override NixOS's defaults.
         '';
       };
@@ -376,14 +382,14 @@ in
         type = types.lines;
         default = "";
         example = ''FontPath "/path/to/my/fonts"'';
-        description = "Contents of the first <literal>Files</literal> section of the X server configuration file.";
+        description = lib.mdDoc "Contents of the first `Files` section of the X server configuration file.";
       };
 
       deviceSection = mkOption {
         type = types.lines;
         default = "";
         example = "VideoRAM 131072";
-        description = "Contents of the first Device section of the X server configuration file.";
+        description = lib.mdDoc "Contents of the first Device section of the X server configuration file.";
       };
 
       screenSection = mkOption {
@@ -392,20 +398,20 @@ in
         example = ''
           Option "RandRRotation" "on"
         '';
-        description = "Contents of the first Screen section of the X server configuration file.";
+        description = lib.mdDoc "Contents of the first Screen section of the X server configuration file.";
       };
 
       monitorSection = mkOption {
         type = types.lines;
         default = "";
         example = "HorizSync 28-49";
-        description = "Contents of the first Monitor section of the X server configuration file.";
+        description = lib.mdDoc "Contents of the first Monitor section of the X server configuration file.";
       };
 
       extraConfig = mkOption {
         type = types.lines;
         default = "";
-        description = "Additional contents (sections) included in the X server configuration file";
+        description = lib.mdDoc "Additional contents (sections) included in the X server configuration file";
       };
 
       xrandrHeads = mkOption {
@@ -425,23 +431,25 @@ in
           firstPrimary = head heads // { primary = true; };
           newHeads = singleton firstPrimary ++ tail heads;
         in if heads != [] && !hasPrimary then newHeads else heads;
-        description = ''
+        description = lib.mdDoc ''
           Multiple monitor configuration, just specify a list of XRandR
           outputs. The individual elements should be either simple strings or
           an attribute set of output options.
 
           If the element is a string, it is denoting the physical output for a
           monitor, if it's an attribute set, you must at least provide the
-          <option>output</option> option.
+          {option}`output` option.
 
           The monitors will be mapped from left to right in the order of the
           list.
 
           By default, the first monitor will be set as the primary monitor if
           none of the elements contain an option that has set
-          <option>primary</option> to <literal>true</literal>.
+          {option}`primary` to `true`.
 
-          <note><para>Only one monitor is allowed to be primary.</para></note>
+          ::: {.note}
+          Only one monitor is allowed to be primary.
+          :::
 
           Be careful using this option with multiple graphic adapters or with
           drivers that have poor support for XRandR, unexpected things might
@@ -459,7 +467,7 @@ in
           Option "SuspendTime" "0"
           Option "OffTime" "0"
           '';
-        description = "Contents of the ServerFlags section of the X server configuration file.";
+        description = lib.mdDoc "Contents of the ServerFlags section of the X server configuration file.";
       };
 
       moduleSection = mkOption {
@@ -470,7 +478,7 @@ in
             SubSection "extmod"
             EndSubsection
           '';
-        description = "Contents of the Module section of the X server configuration file.";
+        description = lib.mdDoc "Contents of the Module section of the X server configuration file.";
       };
 
       serverLayoutSection = mkOption {
@@ -480,28 +488,28 @@ in
           ''
             Option "AIGLX" "true"
           '';
-        description = "Contents of the ServerLayout section of the X server configuration file.";
+        description = lib.mdDoc "Contents of the ServerLayout section of the X server configuration file.";
       };
 
       extraDisplaySettings = mkOption {
         type = types.lines;
         default = "";
         example = "Virtual 2048 2048";
-        description = "Lines to be added to every Display subsection of the Screen section.";
+        description = lib.mdDoc "Lines to be added to every Display subsection of the Screen section.";
       };
 
       defaultDepth = mkOption {
         type = types.int;
         default = 0;
         example = 8;
-        description = "Default colour depth.";
+        description = lib.mdDoc "Default colour depth.";
       };
 
       fontPath = mkOption {
         type = types.nullOr types.str;
         default = null;
         example = "unix/:7100";
-        description = ''
+        description = lib.mdDoc ''
           Set the X server FontPath. Defaults to null, which
           means the compiled in defaults will be used. See
           man xorg.conf for details.
@@ -511,20 +519,20 @@ in
       tty = mkOption {
         type = types.nullOr types.int;
         default = 7;
-        description = "Virtual console for the X server.";
+        description = lib.mdDoc "Virtual console for the X server.";
       };
 
       display = mkOption {
         type = types.nullOr types.int;
         default = 0;
-        description = "Display number for the X server.";
+        description = lib.mdDoc "Display number for the X server.";
       };
 
       virtualScreen = mkOption {
         type = types.nullOr types.attrs;
         default = null;
         example = { x = 2048; y = 2048; };
-        description = ''
+        description = lib.mdDoc ''
           Virtual screen size for Xrandr.
         '';
       };
@@ -533,12 +541,12 @@ in
         type = types.nullOr types.str;
         default = "/dev/null";
         example = "/var/log/Xorg.0.log";
-        description = ''
+        description = lib.mdDoc ''
           Controls the file Xorg logs to.
 
-          The default of <literal>/dev/null</literal> is set so that systemd services (like <literal>displayManagers</literal>) only log to the journal and don't create their own log files.
+          The default of `/dev/null` is set so that systemd services (like `displayManagers`) only log to the journal and don't create their own log files.
 
-          Setting this to <literal>null</literal> will not pass the <literal>-logfile</literal> argument to Xorg which allows it to log to its default logfile locations instead (see <literal>man Xorg</literal>). You probably only want this behaviour when running Xorg manually (e.g. via <literal>startx</literal>).
+          Setting this to `null` will not pass the `-logfile` argument to Xorg which allows it to log to its default logfile locations instead (see `man Xorg`). You probably only want this behaviour when running Xorg manually (e.g. via `startx`).
         '';
       };
 
@@ -546,24 +554,15 @@ in
         type = types.nullOr types.int;
         default = 3;
         example = 7;
-        description = ''
+        description = lib.mdDoc ''
           Controls verbosity of X logging.
         '';
       };
 
-      useGlamor = mkOption {
-        type = types.bool;
-        default = false;
-        description = ''
-          Whether to use the Glamor module for 2D acceleration,
-          if possible.
-        '';
-      };
-
       enableCtrlAltBackspace = mkOption {
         type = types.bool;
         default = false;
-        description = ''
+        description = lib.mdDoc ''
           Whether to enable the DontZap option, which binds Ctrl+Alt+Backspace
           to forcefully kill X. This can lead to data loss and is disabled
           by default.
@@ -573,7 +572,7 @@ in
       terminateOnReset = mkOption {
         type = types.bool;
         default = true;
-        description = ''
+        description = lib.mdDoc ''
           Whether to terminate X upon server reset.
         '';
       };
@@ -655,7 +654,7 @@ in
           ${cfgPath}.source = xorg.xf86inputevdev.out + "/share" + cfgPath;
         });
 
-    environment.systemPackages =
+    environment.systemPackages = utils.removePackagesByName
       [ xorg.xorgserver.out
         xorg.xrandr
         xorg.xrdb
@@ -671,7 +670,7 @@ in
         pkgs.xdg-utils
         xorg.xf86inputevdev.out # get evdev.4 man page
         pkgs.nixos-icons # needed for gnome and pantheon about dialog, nixos-manual and maybe more
-      ]
+      ] config.services.xserver.excludePackages
       ++ optional (elem "virtualbox" cfg.videoDrivers) xorg.xrefresh;
 
     environment.pathsToLink = [ "/share/X11" ];
@@ -790,13 +789,6 @@ in
           '')}
         EndSection
 
-        ${if cfg.useGlamor then ''
-          Section "Module"
-            Load "dri2"
-            Load "glamoregl"
-          EndSection
-        '' else ""}
-
         # For each supported driver, add a "Device" and "Screen"
         # section.
         ${flip concatMapStrings cfg.drivers (driver: ''
@@ -804,7 +796,6 @@ in
           Section "Device"
             Identifier "Device-${driver.name}[0]"
             Driver "${driver.driverName or driver.name}"
-            ${if cfg.useGlamor then ''Option "AccelMethod" "glamor"'' else ""}
           ${indent cfg.deviceSection}
           ${indent (driver.deviceSection or "")}
           ${indent xrandrDeviceSection}