about summary refs log tree commit diff
path: root/modules/services/dendrite.nix
blob: 70f9db88903a8d87b7cd2baf44eef5f3f22ea195 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
{ config, lib, ... }:

with lib;
let
  cfg = config.modules.services.dendrite;

  database = {
    connection_string = "postgres:///dendrite?host=/run/postgresql";
    max_open_conns = 100;
    max_idle_conns = 5;
    conn_max_lifetime = -1;
  };
in
{
  imports = [
    ../../overlays/sliding-sync-module.nix
  ];

  options.modules.services.dendrite = {
    enable = mkEnableOption "dendrite instance";
    domain = mkOption { type = types.str; };
    realHost = mkOption { type = types.str; default = "matrix.${cfg.domain}"; };
    slidingSyncHost = mkOption { type = types.str; default = "slidingsync.${cfg.domain}"; };
    turn = {
      enable = mkEnableOption "VOIP suing TURN";
      domain = mkOption { type = types.str; default = "turn.${cfg.domain}"; };
      shared_secret = mkOption { type = types.str; };
    };
    secrets = {
      matrix-server-key = mkOption { type = types.str; description = "path to the server key"; };
      dendrite-envs = mkOption { type = types.nullOr types.str; description = "path for the environment file to source"; };
      sliding-sync-secret = mkOption { type = types.nullOr types.str; description = "path to the sliding sync secret"; };
    };
  };

  config = mkIf cfg.enable {
    # Adapted from Mic92/dotfiles, (C) 2021 Jörg Thalheim (MIT)
    services.dendrite = {
      enable = true;
      settings = {
        global = {
          server_name = cfg.domain;
          # `private_key` has the type `path`
          # prefix a `/` to make `path` happy
          private_key = "/$CREDENTIALS_DIRECTORY/matrix-server-key";
          jetstream.storage_path = "/var/lib/dendrite/jetstream";
          trusted_third_party_id_servers = [
            "matrix.org"
            "vector.im"
          ];
          metrics.enabled = true;
        };
        logging = [
          {
            type = "std";
            level = "info"; # "warn" on public release
          }
        ];
        app_service_api = {
          inherit database;
          config_files = [ ];
        };
        client_api = {
          registration_disabled = true;
          rate_limiting.enabled = false;
          rate_limiting.exempt_user_ids = [
            "@abuse:${cfg.domain}"
          ];
          # registration_shared_secret = ""; # Initially set this option to configure the admin user.
        } // optionalAttrs cfg.turn.enable {
          turn = {
            turn_user_lifetime = "24h";
            turn_uris = [
              "turns:${cfg.turn.domain}?transport=udp"
              "turns:${cfg.turn.domain}?transport=tcp"
              "turn:${cfg.turn.domain}?transport=udp"
              "turn:${cfg.turn.domain}?transport=tcp"
            ];
            turn_shared_secret = cfg.turn.shared_secret;
          };
        };
        media_api = {
          inherit database;
          dynamic_thumbnails = true;
        };
        room_server = {
          inherit database;
        };
        push_server = {
          inherit database;
        };
        mscs = {
          inherit database;
          mscs = [ "msc2836" "msc2946" ];
        };
        sync_api = {
          inherit database;
          real_ip_header = "X-Real-IP";
          # The NixOS option is 'enable', which doesn't exist in Dendrite.
          search.enabled = true;
        };
        key_server = {
          inherit database;
        };
        federation_api = {
          inherit database;
          key_perspectives = [
            {
              server_name = "matrix.org";
              keys = [
                {
                  key_id = "ed25519:auto";
                  public_key = "Noi6WqcDj0QmPxCNQqgezwTlBKrfqehY1u2FyWP9uYw";
                }
                {
                  key_id = "ed25519:a_RXGa";
                  public_key = "l8Hft5qXKn1vfHrg3p4+W8gELQVo8N13JkluMfmn2sQ";
                }
              ];
            }
          ];
          prefer_direct_fetch = false;
        };
        user_api = {
          account_database = database;
          device_database = database;
        };
      };
      loadCredential = [ "matrix-server-key:${cfg.secrets.matrix-server-key}" ];
    } // optionalAttrs (cfg.secrets.dendrite-envs != null) {
      environmentFile = cfg.secrets.dendrite-envs;
    };

    services.prometheus.scrapeConfigs = [
      {
        job_name = "dendrite";
        static_configs = [{
          targets = [ "127.0.0.1:${toString config.services.dendrite.httpPort}" ];
        }];
      }
    ];

    systemd.services.dendrite = {
      after = [ "postgresql.service" ];
    };

    environment.persistence."/persist".directories = [
      "/var/lib/private/dendrite"
    ];

    services.sliding-sync = {
      enable = true;
      server = "https://${cfg.realHost}";
      bindAddr = "[::1]:8009";
      db = "postgres:///syncv3?host=/run/postgresql";
      secret = cfg.secrets.sliding-sync-secret;
    };

    services.postgresql.enable = true;
    services.postgresql.ensureDatabases = [ "dendrite" "syncv3" ];
    services.postgresql.ensureUsers = [
      {
        name = "dendrite";
        ensurePermissions."DATABASE dendrite" = "ALL PRIVILEGES";
      }
      {
        name = "sliding-sync";
        ensurePermissions."DATABASE syncv3" = "ALL PRIVILEGES";
      }
    ];

    services.nginx.virtualHosts.${cfg.realHost} = {
      forceSSL = true;
      useACMEHost = cfg.domain;
      listen = [
        { addr = "0.0.0.0"; port = 443; ssl = true; }
        { addr = "[::]"; port = 443; ssl = true; }
        { addr = "0.0.0.0"; port = 8448; ssl = true; }
        { addr = "[::]"; port = 8448; ssl = true; }

      ];
      extraConfig = ''
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_read_timeout 600;
        client_max_body_size 50M;
      '';
      locations."/_matrix".proxyPass = "http://[::1]:${toString config.services.dendrite.httpPort}";
      locations."/_dendrite".proxyPass = "http://[::1]:${toString config.services.dendrite.httpPort}";
      locations."/_synapse".proxyPass = "http://[::1]:${toString config.services.dendrite.httpPort}";
    };

    services.nginx.virtualHosts.${cfg.domain} =
      let
        server-hello = { "m.server" = "${cfg.realHost}:443"; };
        client-hello = {
          "m.homeserver"."base_url" = "https://${cfg.realHost}";
          "m.identity_server"."base_url" = "https://vector.im";
          "org.matrix.msc3575.proxy"."url" = "https://${cfg.slidingSyncHost}";
        };
      in
      {
        forceSSL = true;
        useACMEHost = cfg.domain;
        locations = {
          "/.well-known/matrix/server" = {
            extraConfig = ''
              add_header Content-Type application/json;
              return 200 '${builtins.toJSON server-hello}';
            '';
          };
          "/.well-known/matrix/client" = {
            extraConfig = ''
              add_header Content-Type application/json;
              add_header Access-Control-Allow-Origin *;
              return 200 '${builtins.toJSON client-hello}';
            '';
          };
        };
      };

    services.nginx.virtualHosts.${cfg.slidingSyncHost} = {
      forceSSL = true;
      useACMEHost = cfg.domain;
      locations."/".proxyPass = "http://${config.services.sliding-sync.bindAddr}";
    };

    networking.firewall.allowedTCPPorts = [ 443 8448 ];
  };
}