summaryrefslogtreecommitdiff
path: root/modules/nixos/matrix/synapse.nix
blob: 1117f23c179219d56bf761a6283465f30de2dd1a (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
{
  config,
  lib,
  ...
}:
with lib; let
  cfg = config.nixfiles.modules.matrix.synapse;
in {
  options.nixfiles.modules.matrix.synapse = {
    enable = mkEnableOption "Synapse Matrix server";

    domain = mkOption {
      description = "Domain name sans protocol scheme.";
      type = with types; str;
      default = config.networking.domain;
    };
  };

  config = let
    bind_address = "127.0.0.1";
    port = 8448;
  in
    mkIf cfg.enable {
      nixfiles.modules = {
        nginx = {
          enable = true;
          upstreams.synapse.servers."${bind_address}:${toString port}" = {};
          virtualHosts.${cfg.domain}.locations = {
            "~ ^(/_matrix|/_synapse/client)".proxyPass = "http://synapse";
            "= /.well-known/matrix/server" = {
              extraConfig = ''
                add_header Content-Type application/json;
              '';
              return = "200 '${
                generators.toJSON {} {"m.server" = "${cfg.domain}:443";}
              }'";
            };
            "= /.well-known/matrix/client" = {
              extraConfig = ''
                add_header Content-Type application/json;
                add_header Access-Control-Allow-Origin *;
              '';
              return = "200 '${
                generators.toJSON {} {
                  "m.homeserver".base_url = "https://${cfg.domain}";
                }
              }'";
            };
          };
        };
        postgresql.enable = true;
      };

      services = let
        db = "synapse";
      in {
        matrix-synapse = {
          enable = true;
          server_name = config.networking.domain;

          database_type = "psycopg2";
          database_name = db;
          database_user = db;

          listeners = [
            {
              inherit bind_address port;
              type = "http";
              tls = false;
              x_forwarded = true;
              resources = [
                {
                  names = ["client" "federation"];
                  compress = false;
                }
              ];
            }
          ];
        };

        postgresql = {
          ensureDatabases = [db];
          ensureUsers = [
            {
              name = db;
              ensurePermissions."DATABASE \"${db}\"" = "ALL";
            }
          ];
        };
      };
    };
}