summaryrefslogtreecommitdiff
path: root/sys/web/sites/matrix.nix
blob: d27c00cea7bf73f5446ec6d59d5dc06bfc469b79 (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
{ config, lib, ... }:
with lib; let
  cfg = config.local.web.sites.matrix;
  inherit (config.local) domains;
in
{
  options.local.web.sites.matrix = {
    enable = mkEnableOption "matrix proxy site";

    proxyUrl = mkOption {
      type = types.str;
    };
  };

  config = mkIf cfg.enable {
    local.web = {
      enable = mkDefault true;
      ownedCerts = [ "matrix" ];

      sites.portal.enable = true;
    };

    services.nginx.virtualHosts = {
      ${domains.exdev.www}.locations =
        let
          serverConfig."m.server" = "${domains.matrix.main}:443";
          clientConfig."m.homeserver".base_url = "https://${domains.matrix.main}";

          mkWellKnown = data: ''
            default_type application/json;
            add_header Access-Control-Allow-Origin *;
            return 200 '${builtins.toJSON data}';
          '';
        in
        {
          "= /.well-known/matrix/server".extraConfig = mkWellKnown serverConfig;
          "= /.well-known/matrix/client".extraConfig = mkWellKnown clientConfig;
        };

      ${domains.matrix.main} = {
        forceSSL = true;
        useACMEHost = domains.matrix.main;

        locations =
          let
            proxyLocation =
              throwIf (hasSuffix "/" cfg.proxyUrl)
                "matrix site: a trailing slash *must not* be used here"
                cfg.proxyUrl;
          in
          {
            "/".extraConfig = ''
              return 403;
            '';

            # Forward all Matrix API calls to the synapse Matrix homeserver. A trailing slash
            # *must not* be used here.
            "/_matrix".proxyPass = proxyLocation;

            # Forward requests for e.g. SSO and password-resets.
            "/_synapse/client".proxyPass = proxyLocation;
          };
      };
    };
  };
}