about summary refs log tree commit diff
path: root/nixpkgs/nixos/modules/services/web-apps/writefreely.nix
blob: 2e9a34897909217647e2855150a57569227d976b (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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
{ config, lib, pkgs, ... }:

let
  inherit (builtins) toString;
  inherit (lib) types mkIf mkOption mkDefault;
  inherit (lib) optional optionals optionalAttrs optionalString;

  inherit (pkgs) sqlite;

  format = pkgs.formats.ini {
    mkKeyValue = key: value:
      let
        value' = lib.optionalString (value != null)
          (if builtins.isBool value then
            if value == true then "true" else "false"
          else
            toString value);
      in "${key} = ${value'}";
  };

  cfg = config.services.writefreely;

  isSqlite = cfg.database.type == "sqlite3";
  isMysql = cfg.database.type == "mysql";
  isMysqlLocal = isMysql && cfg.database.createLocally == true;

  hostProtocol = if cfg.acme.enable then "https" else "http";

  settings = cfg.settings // {
    app = cfg.settings.app or { } // {
      host = cfg.settings.app.host or "${hostProtocol}://${cfg.host}";
    };

    database = if cfg.database.type == "sqlite3" then {
      type = "sqlite3";
      filename = cfg.settings.database.filename or "writefreely.db";
      database = cfg.database.name;
    } else {
      type = "mysql";
      username = cfg.database.user;
      password = "#dbpass#";
      database = cfg.database.name;
      host = cfg.database.host;
      port = cfg.database.port;
      tls = cfg.database.tls;
    };

    server = cfg.settings.server or { } // {
      bind = cfg.settings.server.bind or "localhost";
      gopher_port = cfg.settings.server.gopher_port or 0;
      autocert = !cfg.nginx.enable && cfg.acme.enable;
      templates_parent_dir =
        cfg.settings.server.templates_parent_dir or cfg.package.src;
      static_parent_dir = cfg.settings.server.static_parent_dir or assets;
      pages_parent_dir =
        cfg.settings.server.pages_parent_dir or cfg.package.src;
      keys_parent_dir = cfg.settings.server.keys_parent_dir or cfg.stateDir;
    };
  };

  configFile = format.generate "config.ini" settings;

  assets = pkgs.stdenvNoCC.mkDerivation {
    pname = "writefreely-assets";

    inherit (cfg.package) version src;

    nativeBuildInputs = with pkgs.nodePackages; [ less ];

    buildPhase = ''
      mkdir -p $out

      cp -r static $out/
    '';

    installPhase = ''
      less_dir=$src/less
      css_dir=$out/static/css

      lessc $less_dir/app.less $css_dir/write.css
      lessc $less_dir/fonts.less $css_dir/fonts.css
      lessc $less_dir/icons.less $css_dir/icons.css
      lessc $less_dir/prose.less $css_dir/prose.css
    '';
  };

  withConfigFile = text: ''
    db_pass=${
      optionalString (cfg.database.passwordFile != null)
      "$(head -n1 ${cfg.database.passwordFile})"
    }

    cp -f ${configFile} '${cfg.stateDir}/config.ini'
    sed -e "s,#dbpass#,$db_pass,g" -i '${cfg.stateDir}/config.ini'
    chmod 440 '${cfg.stateDir}/config.ini'

    ${text}
  '';

  withMysql = text:
    withConfigFile ''
      query () {
        local result=$(${config.services.mysql.package}/bin/mysql \
          --user=${cfg.database.user} \
          --password=$db_pass \
          --database=${cfg.database.name} \
          --silent \
          --raw \
          --skip-column-names \
          --execute "$1" \
        )

        echo $result
      }

      ${text}
    '';

  withSqlite = text:
    withConfigFile ''
      query () {
        local result=$(${sqlite}/bin/sqlite3 \
          '${cfg.stateDir}/${settings.database.filename}' \
          "$1" \
        )

        echo $result
      }

      ${text}
    '';
in {
  options.services.writefreely = {
    enable =
      lib.mkEnableOption (lib.mdDoc "Writefreely, build a digital writing community");

    package = lib.mkOption {
      type = lib.types.package;
      default = pkgs.writefreely;
      defaultText = lib.literalExpression "pkgs.writefreely";
      description = lib.mdDoc "Writefreely package to use.";
    };

    stateDir = mkOption {
      type = types.path;
      default = "/var/lib/writefreely";
      description = lib.mdDoc "The state directory where keys and data are stored.";
    };

    user = mkOption {
      type = types.str;
      default = "writefreely";
      description = lib.mdDoc "User under which Writefreely is ran.";
    };

    group = mkOption {
      type = types.str;
      default = "writefreely";
      description = lib.mdDoc "Group under which Writefreely is ran.";
    };

    host = mkOption {
      type = types.str;
      default = "";
      description = lib.mdDoc "The public host name to serve.";
      example = "example.com";
    };

    settings = mkOption {
      default = { };
      description = lib.mdDoc ''
        Writefreely configuration ({file}`config.ini`). Refer to
        <https://writefreely.org/docs/latest/admin/config>
        for details.
      '';

      type = types.submodule {
        freeformType = format.type;

        options = {
          app = {
            theme = mkOption {
              type = types.str;
              default = "write";
              description = lib.mdDoc "The theme to apply.";
            };
          };

          server = {
            port = mkOption {
              type = types.port;
              default = if cfg.nginx.enable then 18080 else 80;
              defaultText = "80";
              description = lib.mdDoc "The port WriteFreely should listen on.";
            };
          };
        };
      };
    };

    database = {
      type = mkOption {
        type = types.enum [ "sqlite3" "mysql" ];
        default = "sqlite3";
        description = lib.mdDoc "The database provider to use.";
      };

      name = mkOption {
        type = types.str;
        default = "writefreely";
        description = lib.mdDoc "The name of the database to store data in.";
      };

      user = mkOption {
        type = types.nullOr types.str;
        default = if cfg.database.type == "mysql" then "writefreely" else null;
        defaultText = "writefreely";
        description = lib.mdDoc "The database user to connect as.";
      };

      passwordFile = mkOption {
        type = types.nullOr types.path;
        default = null;
        description = lib.mdDoc "The file to load the database password from.";
      };

      host = mkOption {
        type = types.str;
        default = "localhost";
        description = lib.mdDoc "The database host to connect to.";
      };

      port = mkOption {
        type = types.port;
        default = 3306;
        description = lib.mdDoc "The port used when connecting to the database host.";
      };

      tls = mkOption {
        type = types.bool;
        default = false;
        description =
          lib.mdDoc "Whether or not TLS should be used for the database connection.";
      };

      migrate = mkOption {
        type = types.bool;
        default = true;
        description =
          lib.mdDoc "Whether or not to automatically run migrations on startup.";
      };

      createLocally = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          When {option}`services.writefreely.database.type` is set to
          `"mysql"`, this option will enable the MySQL service locally.
        '';
      };
    };

    admin = {
      name = mkOption {
        type = types.nullOr types.str;
        description = lib.mdDoc "The name of the first admin user.";
        default = null;
      };

      initialPasswordFile = mkOption {
        type = types.path;
        description = lib.mdDoc ''
          Path to a file containing the initial password for the admin user.
          If not provided, the default password will be set to `nixos`.
        '';
        default = pkgs.writeText "default-admin-pass" "nixos";
        defaultText = "/nix/store/xxx-default-admin-pass";
      };
    };

    nginx = {
      enable = mkOption {
        type = types.bool;
        default = false;
        description =
          lib.mdDoc "Whether or not to enable and configure nginx as a proxy for WriteFreely.";
      };

      forceSSL = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc "Whether or not to force the use of SSL.";
      };
    };

    acme = {
      enable = mkOption {
        type = types.bool;
        default = false;
        description =
          lib.mdDoc "Whether or not to automatically fetch and configure SSL certs.";
      };
    };
  };

  config = mkIf cfg.enable {
    assertions = [
      {
        assertion = cfg.host != "";
        message = "services.writefreely.host must be set";
      }
      {
        assertion = isMysqlLocal -> cfg.database.passwordFile != null;
        message =
          "services.writefreely.database.passwordFile must be set if services.writefreely.database.createLocally is set to true";
      }
      {
        assertion = isSqlite -> !cfg.database.createLocally;
        message =
          "services.writefreely.database.createLocally has no use when services.writefreely.database.type is set to sqlite3";
      }
    ];

    users = {
      users = optionalAttrs (cfg.user == "writefreely") {
        writefreely = {
          group = cfg.group;
          home = cfg.stateDir;
          isSystemUser = true;
        };
      };

      groups =
        optionalAttrs (cfg.group == "writefreely") { writefreely = { }; };
    };

    systemd.tmpfiles.settings."10-writefreely".${cfg.stateDir}.d = {
      inherit (cfg) user group;
      mode = "0750";
    };

    systemd.services.writefreely = {
      after = [ "network.target" ]
        ++ optional isSqlite "writefreely-sqlite-init.service"
        ++ optional isMysql "writefreely-mysql-init.service"
        ++ optional isMysqlLocal "mysql.service";
      wantedBy = [ "multi-user.target" ];

      serviceConfig = {
        Type = "simple";
        User = cfg.user;
        Group = cfg.group;
        WorkingDirectory = cfg.stateDir;
        Restart = "always";
        RestartSec = 20;
        ExecStart =
          "${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' serve";
        AmbientCapabilities =
          optionalString (settings.server.port < 1024) "cap_net_bind_service";
      };

      preStart = ''
        if ! test -d "${cfg.stateDir}/keys"; then
          mkdir -p ${cfg.stateDir}/keys

          # Key files end up with the wrong permissions by default.
          # We need to correct them so that Writefreely can read them.
          chmod -R 750 "${cfg.stateDir}/keys"

          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' keys generate
        fi
      '';
    };

    systemd.services.writefreely-sqlite-init = mkIf isSqlite {
      wantedBy = [ "multi-user.target" ];

      serviceConfig = {
        Type = "oneshot";
        User = cfg.user;
        Group = cfg.group;
        WorkingDirectory = cfg.stateDir;
        ReadOnlyPaths = optional (cfg.admin.initialPasswordFile != null)
          cfg.admin.initialPasswordFile;
      };

      script = let
        migrateDatabase = optionalString cfg.database.migrate ''
          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' db migrate
        '';

        createAdmin = optionalString (cfg.admin.name != null) ''
          if [[ $(query "SELECT COUNT(*) FROM users") == 0 ]]; then
            admin_pass=$(head -n1 ${cfg.admin.initialPasswordFile})

            ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' --create-admin ${cfg.admin.name}:$admin_pass
          fi
        '';
      in withSqlite ''
        if ! test -f '${settings.database.filename}'; then
          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' db init
        fi

        ${migrateDatabase}

        ${createAdmin}
      '';
    };

    systemd.services.writefreely-mysql-init = mkIf isMysql {
      wantedBy = [ "multi-user.target" ];
      after = optional isMysqlLocal "mysql.service";

      serviceConfig = {
        Type = "oneshot";
        User = cfg.user;
        Group = cfg.group;
        WorkingDirectory = cfg.stateDir;
        ReadOnlyPaths = optional isMysqlLocal cfg.database.passwordFile
          ++ optional (cfg.admin.initialPasswordFile != null)
          cfg.admin.initialPasswordFile;
      };

      script = let
        updateUser = optionalString isMysqlLocal ''
          # WriteFreely currently *requires* a password for authentication, so we
          # need to update the user in MySQL accordingly. By default MySQL users
          # authenticate with auth_socket or unix_socket.
          # See: https://github.com/writefreely/writefreely/issues/568
          ${config.services.mysql.package}/bin/mysql --skip-column-names --execute "ALTER USER '${cfg.database.user}'@'localhost' IDENTIFIED VIA unix_socket OR mysql_native_password USING PASSWORD('$db_pass'); FLUSH PRIVILEGES;"
        '';

        migrateDatabase = optionalString cfg.database.migrate ''
          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' db migrate
        '';

        createAdmin = optionalString (cfg.admin.name != null) ''
          if [[ $(query 'SELECT COUNT(*) FROM users') == 0 ]]; then
            admin_pass=$(head -n1 ${cfg.admin.initialPasswordFile})
            ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' --create-admin ${cfg.admin.name}:$admin_pass
          fi
        '';
      in withMysql ''
        ${updateUser}

        if [[ $(query "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '${cfg.database.name}'") == 0 ]]; then
          ${cfg.package}/bin/writefreely -c '${cfg.stateDir}/config.ini' db init
        fi

        ${migrateDatabase}

        ${createAdmin}
      '';
    };

    services.mysql = mkIf isMysqlLocal {
      enable = true;
      package = mkDefault pkgs.mariadb;
      ensureDatabases = [ cfg.database.name ];
      ensureUsers = [{
        name = cfg.database.user;
        ensurePermissions = {
          "${cfg.database.name}.*" = "ALL PRIVILEGES";
          # WriteFreely requires the use of passwords, so we need permissions
          # to `ALTER` the user to add password support and also to reload
          # permissions so they can be used.
          "*.*" = "CREATE USER, RELOAD";
        };
      }];
    };

    services.nginx = lib.mkIf cfg.nginx.enable {
      enable = true;
      recommendedProxySettings = true;

      virtualHosts."${cfg.host}" = {
        enableACME = cfg.acme.enable;
        forceSSL = cfg.nginx.forceSSL;

        locations."/" = {
          proxyPass = "http://127.0.0.1:${toString settings.server.port}";
        };
      };
    };
  };
}