feat(ntfy-sh): Self-host ntfy-sh

This commit is contained in:
Tristan Daniël Maat 2025-11-29 21:02:10 +08:00
parent 59fdb37222
commit 342b6c756a
Signed by: tlater
GPG key ID: 02E935006CF2E8E7
6 changed files with 281 additions and 18 deletions

View file

@ -8,6 +8,7 @@
./gitea.nix
./immich.nix
./metrics
./ntfy-sh
./minecraft.nix
./nextcloud.nix
./postgres.nix

View file

@ -0,0 +1,189 @@
{
pkgs,
config,
flake-inputs,
...
}:
let
domain = "ntfy.${config.services.nginx.domain}";
in
{
imports = [ ./downstream-module.nix ];
networking.firewall.allowedTCPPorts = [
80
443
];
services.ntfy-sh = {
enable = true;
package = flake-inputs.nixpkgs-unstable.legacyPackages.${pkgs.system}.ntfy-sh;
environmentFile = config.sops.secrets."ntfy/users".path;
settings = {
base-url = "https://${domain}";
listen-http = "127.0.0.1:2586";
behind-proxy = true;
# Paths
attachment-cache-dir = "/var/lib/ntfy-sh/attachments";
cache-file = "/var/lib/ntfy-sh/cache-file.db";
auth-file = "/var/lib/ntfy-sh/user.db";
auth-default-access = "deny-all";
auth-access = [ "*:local-*:wo" ];
# Don't want to host the front-end
web-root = "disable";
};
};
services.nginx.virtualHosts."ntfy.${config.services.nginx.domain}" = {
forceSSL = true;
useACMEHost = "tlater.net";
enableHSTS = true;
locations."/" = {
proxyWebsockets = true;
proxyPass = "http://${config.services.ntfy-sh.settings.listen-http}";
extraConfig = ''
client_max_body_size 0; # Stream request body to backend
'';
};
# Don't allow writing to topics with the local prefix, *including*
# webhook writes, since they are set to write-only access from
# anyone.
locations."/local" = {
proxyWebsockets = true;
proxyPass = "http://${config.services.ntfy-sh.settings.listen-http}";
extraConfig = ''
client_max_body_size 0; # Stream request body to backend
limit_except GET OPTIONS {
deny all;
}
location ~ /trigger$ {
deny all;
}
'';
};
};
sops.secrets."ntfy/users" = { };
serviceTests = {
testNtfyConfig = pkgs.testers.runNixOSTest {
name = "test-ntfy-config";
node.specialArgs = { inherit flake-inputs; };
nodes = {
testHost =
{ lib, ... }:
{
imports = [
./.
../../nginx
../../../modules/serviceTests/mocks.nix
];
services.nginx.domain = "testHost";
# Don't care for testing SSL here
services.nginx.virtualHosts."ntfy.testHost" = {
forceSSL = lib.mkForce false;
enableHSTS = lib.mkForce false;
};
};
client =
{ pkgs, ... }:
{
environment.systemPackages = [ pkgs.curl ];
networking.hosts."192.168.1.2" = [ "ntfy.testHost" ];
};
};
testScript = ''
import json
import time
from contextlib import contextmanager
def read_client_messages():
client.wait_for_unit("messages.service")
messages = [json.loads(line) for line in client.succeed("cat messages").split()]
client.succeed("systemctl stop messages.service")
client.succeed("rm messages")
print(messages)
return messages
@contextmanager
def client_subscribe(topic: str, timeout: int = 2):
systemd_invocation = [
"systemd-run",
"--unit messages",
"--property=Type=oneshot",
"--property=SuccessExitStatus=28",
"--remain-after-exit",
"--setenv=PATH=$PATH",
"--same-dir",
"--no-block",
"/bin/sh -c"
]
curl = [
"curl",
"--silent",
"--show-error",
f"--max-time {timeout}",
"-u tlater:insecure",
f"http://ntfy.testHost/{topic}/json",
"> messages"
]
client.succeed(f'{" ".join(systemd_invocation)} "{" ".join(curl)}"')
# Give some slack so the host doesn't send messages before
# we're listening
time.sleep(1)
yield
start_all()
testHost.wait_for_unit("ntfy-sh.service")
client.wait_until_succeeds("curl http://ntfy.testHost")
with subtest("subscribing and writing to local topics works"):
with client_subscribe("local-test"):
testHost.succeed("curl --fail --silent --show-error --data test http://127.0.0.1:2586/local-test")
messages = read_client_messages()
t.assertEqual(len(messages), 2)
t.assertEqual(messages[1].get("message"), "test")
with subtest("writing to non-local topics without auth fails"):
testHost.fail("curl --fail --silent --show-error --data test http://127.0.0.1:2586/test")
with subtest("writing to *any* topics from outside localhost fails"):
client.fail("curl --fail --silent --show-error --data test http://ntfy.testHost/test")
client.fail("curl --fail --silent --show-error --data test http://ntfy.testHost/local-test")
# GET requests work by default because websocket shenanigans
client.fail("curl --fail --silent --show-error http://ntfy.testHost/local-test/trigger?message=test")
with subtest("authenticated messaging works from outside localhost"):
with client_subscribe("test", 10):
client.succeed("curl -u tlater:insecure --fail --silent --show-error --data test http://ntfy.testHost/test")
client.succeed("curl -u tlater:insecure --fail --silent --show-error http://ntfy.testHost/test/trigger?message=test2")
messages = read_client_messages()
t.assertEqual(len(messages), 3)
t.assertEqual(messages[1].get("message"), "test")
t.assertEqual(messages[2].get("message"), "test2")
'';
};
};
}

View file

@ -0,0 +1,70 @@
{
pkgs,
lib,
config,
...
}:
let
cfg = config.services.ntfy-sh;
settingsFormat = pkgs.formats.yaml { };
configFile = settingsFormat.generate "server.yml" cfg.settings;
in
{
# We don't use the upstream module because it's stupid; the author
# doesn't seem to understand `DynamicUser` (or at least be unaware of
# systemd credentials).
disabledModules = [ "services/misc/ntfy-sh.nix" ];
options.services.ntfy-sh = {
enable = lib.mkEnableOption "[ntfy-sh](https://ntfy.sh), a push notification service";
package = lib.mkPackageOption pkgs "ntfy-sh" { };
environmentFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = ''
Environment file; intended to be used for user provisioning.
'';
};
settings = lib.mkOption {
inherit (settingsFormat) type;
default = { };
description = ''
Configuration for ntfy.sh, supported values are [here](https://ntfy.sh/docs/config/#config-options).
'';
};
};
config.systemd.services.ntfy-sh = {
description = "Push notifications server";
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
serviceConfig = {
Type = "exec";
ExecReload = "kill --signal HUP $MAINPID";
ExecStart = "${lib.getExe' cfg.package "ntfy"} serve -c ${configFile}";
EnvironmentFile = cfg.environmentFile;
StateDirectory = "ntfy-sh";
DynamicUser = true;
PrivateTmp = true;
NoNewPrivileges = true;
ProtectSystem = "full";
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectKernelLogs = true;
ProtectControlGroups = true;
PrivateDevices = true;
RestrictSUIDSGID = true;
RestrictNamespaces = true;
RestrictRealtime = true;
MemoryDenyWriteExecute = true;
# Upstream Recommandation
LimitNOFILE = 20500;
};
};
}

View file

@ -24,7 +24,7 @@ in
'';
environment = {
TLATERNET_NTFY_INSTANCE = "https://tlater.net";
TLATERNET_NTFY_INSTANCE = "http://${config.services.ntfy-sh.settings.listen-http}";
LEPTOS_SITE_ADDR = "127.0.0.1:8000";
};
@ -62,20 +62,16 @@ in
};
# Set up SSL
services.nginx.virtualHosts."${domain}" =
let
inherit (config.services.tlaternet-webserver.listen) addr port;
in
{
serverAliases = [ "www.${domain}" ];
services.nginx.virtualHosts."${domain}" = {
serverAliases = [ "www.${domain}" ];
forceSSL = true;
useACMEHost = "tlater.net";
enableHSTS = true;
forceSSL = true;
useACMEHost = "tlater.net";
enableHSTS = true;
locations."/".proxyPass =
"http://${config.systemd.services.tlaternet-webserver.environment.LEPTOS_SITE_ADDR}";
};
locations."/".proxyPass =
"http://${config.systemd.services.tlaternet-webserver.environment.LEPTOS_SITE_ADDR}";
};
sops.secrets = {
"tlaternet/ntfy-topic" = { };

View file

@ -1,3 +1,7 @@
tlaternet:
ntfy-topic: ENC[AES256_GCM,data:1mlcrb4uOkwyB5pwTbIv,iv:Ba6k9HV4ze9cftbSE8ns2+j2ebi4cqmHa5UwM1YR6W8=,tag:Ksf840uCOQdoVasORjUdcQ==,type:str]
ntfy:
users: ENC[AES256_GCM,data:7vZx2jIXsEMT0LhPKis7oiaq8YGgGnW3M6L9Aq0qlaNzpF31sAAZHMYPMJDG0Z09gvQ60kRVxgggHYx8TlaD/ZxLhFVfKgUcQaiRRxyAFIKFVqVNRQaiykQcFzw=,iv:HefHN4rkVKg43Ery0QW2Mg74tIwsM0OvsluXFIWVCVM=,tag:WM8uW4bV9nHuwWYaH+mmUw==,type:str]
porkbun:
api-key: ENC[AES256_GCM,data:p3lqvGc8m2U/12rBPjoNR7hxQyD52CyEen/V8q59k5CSJZSqzZS8M5vEXFBsUMjz2lrmKM4pgtz4wa2fWK6Ty4LJCaI=,iv:OQC3FpwTtPmqHvDbA41mWF7LGYwC/jD2ZMBsE8ktNOg=,tag:kq5hUR7TBgczuGcXpsdu2A==,type:str]
secret-api-key: ENC[AES256_GCM,data:zV5PTKf45Zab8uW8mbuXmPNzciq6tV9OF0wUND7YnRk/DjZneYWItAsNBVoM+iHA+XsUPDoeKo6hoJiGkH/cCQ8WvuM=,iv:yr1M5DlgI8k6BgzNz3HRnqspHOrQuf2PmoZS1HGp0v8=,tag:JkNNziMMfKFZV2hnx5lXRg==,type:str]
@ -28,8 +32,8 @@ turn:
env: ENC[AES256_GCM,data:kt5nhVo9pb/ZbPUEcqSYXxN9YMgQKnFb5VRfFFS/qoIaJ73uD2fuJKqcxAyVRrdLqnSAWSQBgTgunBzdP7xqLAK2qt8DYAQWHkIe9uxFbSXZpdmw,iv:9lq6SFwTFN4GGm6gPiJpUMasMdnHVF6XLGYrsyG3kjU=,tag:428Qf9DOiiHt/Wjb188b8g==,type:str]
secret: ENC[AES256_GCM,data:si7ee6Xfhdgdyzbp6aQpF7pz3TmTBb7iQ82lRPVXNDg9JfHI+lbmgAsSnRLX5qMCA6P9R045sSMosqidL8QwRg==,iv:SrhpZKK8D45yxCEfDb9P3TwtA14+qEI+wcRqcN/a6pw=,tag:PiwV+mOL9xHJgJft6sc61g==,type:str]
sops:
lastmodified: "2025-11-22T11:12:58Z"
mac: ENC[AES256_GCM,data:KWc1yNxHQa7MKV/3iXaGOz+RQnHoF4cPumhdoY9zMzWsF1UV0FcR9xCF8KB40elHd4/7uz0stKiSiHhLvtSBW6KjMj0N5JSFknXKxGJWf8XA6ZJrvHhWamXX/ZVbdpvgwh6LzluzogjlCWatWYcr6svDoSEm0gL+Aynudyrx75I=,iv:gPXZpMs0TOvY6cpQJ4MprGlS8jleuO+vWwmJ0F6G+3s=,tag:BfhXRv+mANrBVASc8Edu8A==,type:str]
lastmodified: "2025-11-29T14:52:24Z"
mac: ENC[AES256_GCM,data:RC18s48jxRFQMtbmu74P7G4uhm2yHk9TB0wN7z4g8SNE3nfkYMvHAJqPr3A3dO+T33zkTFcSRm7fhWItUahTCW3fO10u6kDvWbnyjlSuAy86Tkz2iqeW4iSOzKswDptAgb/B+juAHhEMxDnkG5vpPlIcD0SVP89NlflXftogOqw=,iv:2vN2TJvzePzBJfUeBxvGXwGmRsB5sopqyWm9uUv/rzA=,tag:C6UOWrUxVsRMFncL1y1eTQ==,type:str]
pgp:
- created_at: "2025-10-03T21:38:48Z"
enc: |-

View file

@ -1,5 +1,8 @@
tlaternet:
ntfy-topic: ENC[AES256_GCM,data:T0wEsXso0uJD4KDe8qv8d24+vaouDrpDFxpSROn5kiYnqa1w6BSy3VrFdqFy17s7mzlAsZtN7gfDZDFjIo1S3Q==,iv:evWlOBgdnVdprzrTy5m+rcRo0OkFEIX+lCgfwLyfw4I=,tag:iq4B6VLWy0nm80ezqJ+rgw==,type:str]
ntfy-topic: ENC[AES256_GCM,data:BSNLP9hLQKufDf3STknQ,iv:4WeYARwDEg84fh8qMa4szssQeK2orBl72oiIRywXCi8=,tag:GtS7YAlQiuGAWaUn+JxaYg==,type:str]
ntfy:
#ENC[AES256_GCM,data:B5sUuCWTheo/Lz5kAN5/8NeiT7ohQ6IRYjD7k/c0,iv:E85yGjNcd9RGOgBKFPxRB6LqdqISNcjlvp/pqpR7VPg=,tag:1NrwtWyoVp4qDWiqAt/few==,type:comment]
users: ENC[AES256_GCM,data:zW02xRlLvqJ0/rLJMX9/LSW7CQ26nIyifOLYba4AkstQcrVMOIV1Je4QwaKoy2TPhDcVcjLg6Ce2/0qxpO7Q3rqoXqACbPAUwcxzn14KOt7tEb3IE2S//0Y/law=,iv:sV5Dvplr6A5ivrI/+Cyl6mC+Zxo8NORxfuhEZ/75JbU=,tag:NzqxoN3Hr0YO2CXiVdEo+A==,type:str]
porkbun:
api-key: ENC[AES256_GCM,data:A5J1sqwq6hs=,iv:77Mar3IX7mq7z7x6s9sSeGNVYc1Wv78HptJElEC7z3Q=,tag:eM/EF9TxKu+zcbJ1SYXiuA==,type:str]
secret-api-key: ENC[AES256_GCM,data:8Xv+jWYaWMI=,iv:li4tdY0pch5lksftMmfMVS729caAwfaacoztaQ49az0=,tag:KhfElBGzVH4ByFPfuQsdhw==,type:str]
@ -30,8 +33,8 @@ turn:
env: ENC[AES256_GCM,data:xjIz/AY109lyiL5N01p5T3HcYco/rM5CJSRTtg==,iv:16bW6OpyOK/QL0QPGQp/Baa9xyT8E3ZsYkwqmjuofk0=,tag:J5re3uKxIykw3YunvQWBgg==,type:str]
secret: ENC[AES256_GCM,data:eQ7dAocoZtg=,iv:fgzjTPv30WqTKlLy+yMn5MsKQgjhPnwlGFFwYEg3gWs=,tag:1ze33U1NBkgMX/9SiaBNQg==,type:str]
sops:
lastmodified: "2025-11-27T19:00:56Z"
mac: ENC[AES256_GCM,data:Q8ATaYVuToQaToVgT5JNP6NGipLnu8JifBivD5jG0h/Xb82ObkMHYejy7tcir600+XgC2UJgfRBgEtYbhjK+SQcyvyBpmPWyv1cKfcidwnfDqRMbc8/1LLl/3mK1losv7/51aZDqvu7GuIvOwXh6IyDQldSuyyPf+wcmCCENiLY=,iv:zDGmnEL2659W7JPRG9dlLjtvDtCgz+iXjJt4EPx/OCM=,tag:3X69zX1sZqrZujB7En8jqA==,type:str]
lastmodified: "2025-11-29T11:54:33Z"
mac: ENC[AES256_GCM,data:SaTvwxfARVou/ZjrWfdC8J6je8l89Zuumdz7PkmY2Tl2CQVxZmEt4AyV4bWiCtWhJmfH1Qa8m4Q+DyqimjapgYT5cUB1yxlknp233bB/+5C5k3KozU2hmh80KYgR496FtQvI74p0qw/lw00CGCR3WHNcIc0dbTiDzC90HlOpafg=,iv:vxMCAjpgyWvxk18LalmFhwOb5b2ThCDq1KTaX2OPvpM=,tag:QMA+tC4hs/FBnuVDye38Vg==,type:str]
pgp:
- created_at: "2025-10-03T21:38:26Z"
enc: |-