about summary refs log tree commit diff stats
path: root/modules/by-name/sh/sharkey/module.nix
blob: a2f54451df5e0890bfb5270f617659c2ac6ee29a (plain) (blame)
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# Source: https://github.com/sodiboo/system/blob/b63c7b27f49043e8701b3ff5e1441cd27d5a2fff/sharkey/module.nix
{
  config,
  lib,
  pkgs,
  vhackPackages,
  ...
}: let
  cfg = config.vhack.sharkey;

  createDB = cfg.database.host == "127.0.0.1" && cfg.database.createLocally;

  settingsFormat = pkgs.formats.yaml {};
  configFile = settingsFormat.generate "sharkey-config.yml" cfg.settings;
in {
  options.vhack.sharkey = {
    enable = lib.mkEnableOption "sharkey";

    fqdn = lib.mkOption {
      description = "The fully qualified domain name of this instance.";
      type = lib.types.str;
      example = "sharkey.shonk.social";
    };

    package = lib.mkOption {
      type = lib.types.package;
      default = vhackPackages.sharkey;
      defaultText = lib.literalExpression "vhackPackages.sharkey";
      description = "Sharkey package to use.";
    };

    dataDirectory = lib.mkOption {
      type = lib.types.path;
      default = "/var/lib/sharkey";
      description = "The directory where sharkey stores it's data.";

      # This is already set in the package.
      readOnly = true;
    };

    database = {
      createLocally = lib.mkOption {
        description = "Whether to enable local db creation.";
        type = lib.types.bool;
        default = true;
      };

      host = lib.mkOption {
        type = lib.types.str;
        default = "127.0.0.1";
        description = "The database host.";
      };

      port = lib.mkOption {
        type = lib.types.port;
        default = 5432;
        description = "The database port.";
      };

      name = lib.mkOption {
        type = lib.types.str;
        default = "sharkey";
        description = "The database name in postgresql.";
      };
    };

    settings = lib.mkOption {
      inherit (settingsFormat) type;
      default = {};
      description = ''
        Configuration for Sharkey, see
        <link xlink:href="https://activitypub.software/TransFem-org/Sharkey/-/blob/develop/.config/example.yml"/>
        for supported settings.
      '';
    };
  };

  config = lib.mkIf cfg.enable {
    environment.systemPackages = [cfg.package];

    vhack = {
      nginx.enable = true;

      sharkey.settings = {
        id = "aidx";

        url = "https://${cfg.fqdn}/";
        port = 5312;

        db = {
          inherit (cfg.database) host port;
          db = cfg.database.name;
          user = cfg.database.name;
          pass = "sharkey-password";
        };
        redis = {
          path = config.services.redis.servers."sharkey".unixSocket;
        };
      };

      persist.directories = [
        {
          directory = "${config.services.redis.servers."sharkey".settings.dir}";
          user = "sharkey";
          group = "redis-sharey";
          mode = "0770";
        }
        {
          directory = "${cfg.dataDirectory}";
          user = "sharkey";
          group = "sharkey";
          mode = "0770";
        }
      ];
    };

    services = {
      nginx.virtualHosts."${cfg.fqdn}" = {
        locations."/" = {
          proxyPass = "http://127.0.0.1:${toString cfg.settings.port}";
          proxyWebsockets = true;
        };

        # proxy_set_header Host $host;
        # proxy_http_version 1.1;
        # proxy_redirect off;
        #
        # # If it's behind another reverse proxy or CDN, remove the following.
        # proxy_set_header X-Real-IP $remote_addr;
        # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # proxy_set_header X-Forwarded-Proto https;
        #
        # # For WebSocket
        # proxy_set_header Upgrade $http_upgrade;
        # proxy_set_header Connection $connection_upgrade;
        #
        # # Cache settings
        # proxy_cache cache1;
        # proxy_cache_lock on;
        # proxy_cache_use_stale updating;
        # proxy_force_ranges on;
        # add_header X-Cache $upstream_cache_status;

        enableACME = true;
        forceSSL = true;
      };

      postgresql = lib.mkIf createDB {
        enable = true;
        settings.port = cfg.database.port;
        ensureUsers = [
          {
            inherit (cfg.database) name;
            ensureDBOwnership = true;
          }
        ];
        ensureDatabases = [cfg.database.name];
      };

      redis = {
        servers."sharkey" = {
          enable = true;

          user = "sharkey";

          # Disable TCP listening. (We have a UNIX socket)
          port = 0;
          bind = null;

          settings = {
            protected-mode = true;
            enable-protected-configs = false;
            enable-debug-command = false;
            enable-module-command = false;

            supervised = "systemd";
            stop-writes-on-bgsave-error = true;
            sanitize-dump-payload = "clients";
          };
        };
      };
    };

    systemd.services.postgresql.postStart = ''
      $PSQL -tAc "ALTER ROLE ${cfg.database.name} WITH ENCRYPTED PASSWORD 'sharkey-password';"
    '';

    systemd.services.sharkey = {
      requires =
        [
          "redis-sharkey.service"
          "network-online.target"
        ]
        ++ lib.optionals createDB ["postgresql.service"];

      after =
        [
          "redis-sharkey.service"
          "network-online.target"
        ]
        ++ lib.optionals createDB ["postgresql.service"];

      wantedBy = ["multi-user.target"];

      environment = {
        MISSKEY_CONFIG_YML = "${configFile}";
        NODE_ENV = "production";
      };

      serviceConfig = {
        Type = "simple";

        StateDirectory = "sharkey";
        StateDirectoryMode = "0700";
        CacheDirectory = "sharkey";
        RuntimeDirectory = "sharkey";
        RuntimeDirectoryMode = "0700";
        ExecStart = "${lib.getExe cfg.package} migrateandstart";

        TimeoutSec = 60;
        Restart = "no";

        StandardOutput = "journal";
        StandardError = "journal";
        SyslogIdentifier = "sharkey";

        User = "sharkey";
        Group = "sharkey";

        # Bind standard privileged ports
        AmbientCapabilities = [];
        CapabilityBoundingSet = [];

        ReadWritePaths = [
          "${cfg.dataDirectory}"
        ];

        # Hardening
        DeviceAllow = [""];
        LockPersonality = true;
        # Probably needed for v8's JIT (crashes with it on).
        MemoryDenyWriteExecute = false;
        PrivateDevices = true;
        PrivateUsers = true;
        ProcSubset = "pid";
        PrivateTmp = true;
        ProtectClock = true;
        ProtectControlGroups = true;
        ProtectHome = true;
        ProtectHostname = true;
        ProtectKernelLogs = true;
        ProtectKernelModules = true;
        ProtectKernelTunables = true;
        ProtectProc = "invisible";
        ProtectSystem = "strict";
        RestrictAddressFamilies = [
          "AF_UNIX" # Local communication                        unix(7)
          "AF_INET" # IPv4 Internet protocols                    ip(7)
          "AF_INET6" # IPv6 Internet protocols                   ipv6(7)
          # Needed for nodes `os.networkInterfaces()` function.
          "AF_NETLINK" # Kernel user interface device            netlink(7)
        ];
        RestrictNamespaces = true;
        RestrictRealtime = true;
        RestrictSUIDSGID = true;
        SystemCallArchitectures = "native";
        SystemCallFilter = [
          "@system-service"
          "~@privileged"
          "~@mount"
        ];
        UMask = "0077";
      };
    };

    users = {
      groups.sharkey = {
        gid = config.vhack.constants.ids.gids.sharkey;
      };
      users.sharkey = {
        isSystemUser = true;
        group = "sharkey";
        uid = config.vhack.constants.ids.uids.sharkey;
        home = cfg.package;
        packages = [cfg.package];
      };

      groups.redis-sharkey = {
        gid = config.vhack.constants.ids.gids.redis-sharkey;
      };
      users.redis-sharkey = {
        group = "redis-sharkey";
        uid = config.vhack.constants.ids.uids.redis-sharkey;
      };
    };
  };
}