summary refs log tree commit diff
path: root/nixos/modules/services/web-apps/hedgedoc.nix
blob: bfa5fd5aff25f4f2be6f67bea31ee3a3fbb26e5c (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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
{ config, lib, pkgs, ... }:

let
  inherit (lib) literalExpression mdDoc mkEnableOption mkIf mkOption mkPackageOptionMD mkRenamedOptionModule types versionAtLeast;

  cfg = config.services.hedgedoc;

  # 21.03 will not be an official release - it was instead 21.05.  This
  # versionAtLeast statement remains set to 21.03 for backwards compatibility.
  # See https://github.com/NixOS/nixpkgs/pull/108899 and
  # https://github.com/NixOS/rfcs/blob/master/rfcs/0080-nixos-release-schedule.md.
  name = if versionAtLeast config.system.stateVersion "21.03"
    then "hedgedoc"
    else "codimd";

  settingsFormat = pkgs.formats.json {};

  prettyJSON = conf:
    pkgs.runCommandLocal "hedgedoc-config.json" {
      nativeBuildInputs = [ pkgs.jq ];
    } ''
      jq '{production:del(.[]|nulls)|del(.[][]?|nulls)}' \
        < ${settingsFormat.generate "hedgedoc-ugly.json" cfg.settings} \
        > $out
    '';
in
{
  imports = [
    (mkRenamedOptionModule [ "services" "codimd" ] [ "services" "hedgedoc" ])
    (mkRenamedOptionModule
      [ "services" "hedgedoc" "configuration" ] [ "services" "hedgedoc" "settings" ])
  ];

  options.services.hedgedoc = {
    package = mkPackageOptionMD pkgs "hedgedoc" { };
    enable = mkEnableOption (lib.mdDoc "the HedgeDoc Markdown Editor");

    groups = mkOption {
      type = types.listOf types.str;
      default = [];
      description = lib.mdDoc ''
        Groups to which the service user should be added.
      '';
    };

    workDir = mkOption {
      type = types.path;
      default = "/var/lib/${name}";
      description = lib.mdDoc ''
        Working directory for the HedgeDoc service.
      '';
    };

    settings = let options = {
      debug = mkEnableOption (lib.mdDoc "debug mode");
      domain = mkOption {
        type = types.nullOr types.str;
        default = null;
        example = "hedgedoc.org";
        description = lib.mdDoc ''
          Domain name for the HedgeDoc instance.
        '';
      };
      urlPath = mkOption {
        type = types.nullOr types.str;
        default = null;
        example = "/url/path/to/hedgedoc";
        description = lib.mdDoc ''
          Path under which HedgeDoc is accessible.
        '';
      };
      host = mkOption {
        type = types.str;
        default = "localhost";
        description = lib.mdDoc ''
          Address to listen on.
        '';
      };
      port = mkOption {
        type = types.port;
        default = 3000;
        example = 80;
        description = lib.mdDoc ''
          Port to listen on.
        '';
      };
      path = mkOption {
        type = types.nullOr types.str;
        default = null;
        example = "/run/hedgedoc.sock";
        description = lib.mdDoc ''
          Specify where a UNIX domain socket should be placed.
        '';
      };
      allowOrigin = mkOption {
        type = types.listOf types.str;
        default = [];
        example = [ "localhost" "hedgedoc.org" ];
        description = lib.mdDoc ''
          List of domains to whitelist.
        '';
      };
      useSSL = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Enable to use SSL server. This will also enable
          {option}`protocolUseSSL`.
        '';
      };
      enableStatsApi = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Enables or disables the /status and /metrics endpoint.
        '';
      };
      hsts = {
        enable = mkOption {
          type = types.bool;
          default = true;
          description = lib.mdDoc ''
            Whether to enable HSTS if HTTPS is also enabled.
          '';
        };
        maxAgeSeconds = mkOption {
          type = types.int;
          default = 31536000;
          description = lib.mdDoc ''
            Max duration for clients to keep the HSTS status.
          '';
        };
        includeSubdomains = mkOption {
          type = types.bool;
          default = true;
          description = lib.mdDoc ''
            Whether to include subdomains in HSTS.
          '';
        };
        preload = mkOption {
          type = types.bool;
          default = true;
          description = lib.mdDoc ''
            Whether to allow preloading of the site's HSTS status.
          '';
        };
      };
      csp = mkOption {
        type = types.nullOr types.attrs;
        default = null;
        example = literalExpression ''
          {
            enable = true;
            directives = {
              scriptSrc = "trustworthy.scripts.example.com";
            };
            upgradeInsecureRequest = "auto";
            addDefaults = true;
          }
        '';
        description = lib.mdDoc ''
          Specify the Content Security Policy which is passed to Helmet.
          For configuration details see <https://helmetjs.github.io/docs/csp/>.
        '';
      };
      protocolUseSSL = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Enable to use TLS for resource paths.
          This only applies when {option}`domain` is set.
        '';
      };
      urlAddPort = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Enable to add the port to callback URLs.
          This only applies when {option}`domain` is set
          and only for ports other than 80 and 443.
        '';
      };
      useCDN = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Whether to use CDN resources or not.
        '';
      };
      allowAnonymous = mkOption {
        type = types.bool;
        default = true;
        description = lib.mdDoc ''
          Whether to allow anonymous usage.
        '';
      };
      allowAnonymousEdits = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Whether to allow guests to edit existing notes with the `freely` permission,
          when {option}`allowAnonymous` is enabled.
        '';
      };
      allowFreeURL = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Whether to allow note creation by accessing a nonexistent note URL.
        '';
      };
      requireFreeURLAuthentication = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Whether to require authentication for FreeURL mode style note creation.
        '';
      };
      defaultPermission = mkOption {
        type = types.enum [ "freely" "editable" "limited" "locked" "private" ];
        default = "editable";
        description = lib.mdDoc ''
          Default permissions for notes.
          This only applies for signed-in users.
        '';
      };
      dbURL = mkOption {
        type = types.nullOr types.str;
        default = null;
        example = ''
          postgres://user:pass@host:5432/dbname
        '';
        description = lib.mdDoc ''
          Specify which database to use.
          HedgeDoc supports mysql, postgres, sqlite and mssql.
          See [
          https://sequelize.readthedocs.io/en/v3/](https://sequelize.readthedocs.io/en/v3/) for more information.
          Note: This option overrides {option}`db`.
        '';
      };
      db = mkOption {
        type = types.attrs;
        default = {};
        example = literalExpression ''
          {
            dialect = "sqlite";
            storage = "/var/lib/${name}/db.${name}.sqlite";
          }
        '';
        description = lib.mdDoc ''
          Specify the configuration for sequelize.
          HedgeDoc supports mysql, postgres, sqlite and mssql.
          See [
          https://sequelize.readthedocs.io/en/v3/](https://sequelize.readthedocs.io/en/v3/) for more information.
          Note: This option overrides {option}`db`.
        '';
      };
      sslKeyPath= mkOption {
        type = types.nullOr types.str;
        default = null;
        example = "/var/lib/hedgedoc/hedgedoc.key";
        description = lib.mdDoc ''
          Path to the SSL key. Needed when {option}`useSSL` is enabled.
        '';
      };
      sslCertPath = mkOption {
        type = types.nullOr types.str;
        default = null;
        example = "/var/lib/hedgedoc/hedgedoc.crt";
        description = lib.mdDoc ''
          Path to the SSL cert. Needed when {option}`useSSL` is enabled.
        '';
      };
      sslCAPath = mkOption {
        type = types.listOf types.str;
        default = [];
        example = [ "/var/lib/hedgedoc/ca.crt" ];
        description = lib.mdDoc ''
          SSL ca chain. Needed when {option}`useSSL` is enabled.
        '';
      };
      dhParamPath = mkOption {
        type = types.nullOr types.str;
        default = null;
        example = "/var/lib/hedgedoc/dhparam.pem";
        description = lib.mdDoc ''
          Path to the SSL dh params. Needed when {option}`useSSL` is enabled.
        '';
      };
      tmpPath = mkOption {
        type = types.str;
        default = "/tmp";
        description = lib.mdDoc ''
          Path to the temp directory HedgeDoc should use.
          Note that {option}`serviceConfig.PrivateTmp` is enabled for
          the HedgeDoc systemd service by default.
          (Non-canonical paths are relative to HedgeDoc's base directory)
        '';
      };
      defaultNotePath = mkOption {
        type = types.nullOr types.str;
        default = "${cfg.package}/public/default.md";
        defaultText = literalExpression "\"\${cfg.package}/public/default.md\"";
        description = lib.mdDoc ''
          Path to the default Note file.
          (Non-canonical paths are relative to HedgeDoc's base directory)
        '';
      };
      docsPath = mkOption {
        type = types.nullOr types.str;
        default = "${cfg.package}/public/docs";
        defaultText = literalExpression "\"\${cfg.package}/public/docs\"";
        description = lib.mdDoc ''
          Path to the docs directory.
          (Non-canonical paths are relative to HedgeDoc's base directory)
        '';
      };
      indexPath = mkOption {
        type = types.nullOr types.str;
        default = "${cfg.package}/public/views/index.ejs";
        defaultText = literalExpression "\"\${cfg.package}/public/views/index.ejs\"";
        description = lib.mdDoc ''
          Path to the index template file.
          (Non-canonical paths are relative to HedgeDoc's base directory)
        '';
      };
      hackmdPath = mkOption {
        type = types.nullOr types.str;
        default = "${cfg.package}/public/views/hackmd.ejs";
        defaultText = literalExpression "\"\${cfg.package}/public/views/hackmd.ejs\"";
        description = lib.mdDoc ''
          Path to the hackmd template file.
          (Non-canonical paths are relative to HedgeDoc's base directory)
        '';
      };
      errorPath = mkOption {
        type = types.nullOr types.str;
        default = "${cfg.package}/public/views/error.ejs";
        defaultText = literalExpression "\"\${cfg.package}/public/views/error.ejs\"";
        description = lib.mdDoc ''
          Path to the error template file.
          (Non-canonical paths are relative to HedgeDoc's base directory)
        '';
      };
      prettyPath = mkOption {
        type = types.nullOr types.str;
        default = "${cfg.package}/public/views/pretty.ejs";
        defaultText = literalExpression "\"\${cfg.package}/public/views/pretty.ejs\"";
        description = lib.mdDoc ''
          Path to the pretty template file.
          (Non-canonical paths are relative to HedgeDoc's base directory)
        '';
      };
      slidePath = mkOption {
        type = types.nullOr types.str;
        default = "${cfg.package}/public/views/slide.hbs";
        defaultText = literalExpression "\"\${cfg.package}/public/views/slide.hbs\"";
        description = lib.mdDoc ''
          Path to the slide template file.
          (Non-canonical paths are relative to HedgeDoc's base directory)
        '';
      };
      uploadsPath = mkOption {
        type = types.str;
        default = "${cfg.workDir}/uploads";
        defaultText = literalExpression "\"\${cfg.workDir}/uploads\"";
        description = lib.mdDoc ''
          Path under which uploaded files are saved.
        '';
      };
      sessionName = mkOption {
        type = types.str;
        default = "connect.sid";
        description = lib.mdDoc ''
          Specify the name of the session cookie.
        '';
      };
      sessionSecret = mkOption {
        type = types.nullOr types.str;
        default = null;
        description = lib.mdDoc ''
          Specify the secret used to sign the session cookie.
          If unset, one will be generated on startup.
        '';
      };
      sessionLife = mkOption {
        type = types.int;
        default = 1209600000;
        description = lib.mdDoc ''
          Session life time in milliseconds.
        '';
      };
      heartbeatInterval = mkOption {
        type = types.int;
        default = 5000;
        description = lib.mdDoc ''
          Specify the socket.io heartbeat interval.
        '';
      };
      heartbeatTimeout = mkOption {
        type = types.int;
        default = 10000;
        description = lib.mdDoc ''
          Specify the socket.io heartbeat timeout.
        '';
      };
      documentMaxLength = mkOption {
        type = types.int;
        default = 100000;
        description = lib.mdDoc ''
          Specify the maximum document length.
        '';
      };
      email = mkOption {
        type = types.bool;
        default = true;
        description = lib.mdDoc ''
          Whether to enable email sign-in.
        '';
      };
      allowEmailRegister = mkOption {
        type = types.bool;
        default = true;
        description = lib.mdDoc ''
          Whether to enable email registration.
        '';
      };
      allowGravatar = mkOption {
        type = types.bool;
        default = true;
        description = lib.mdDoc ''
          Whether to use gravatar as profile picture source.
        '';
      };
      imageUploadType = mkOption {
        type = types.enum [ "imgur" "s3" "minio" "filesystem" ];
        default = "filesystem";
        description = lib.mdDoc ''
          Specify where to upload images.
        '';
      };
      minio = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            accessKey = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Minio access key.
              '';
            };
            secretKey = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Minio secret key.
              '';
            };
            endPoint = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Minio endpoint.
              '';
            };
            port = mkOption {
              type = types.port;
              default = 9000;
              description = lib.mdDoc ''
                Minio listen port.
              '';
            };
            secure = mkOption {
              type = types.bool;
              default = true;
              description = lib.mdDoc ''
                Whether to use HTTPS for Minio.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the minio third-party integration.";
      };
      s3 = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            accessKeyId = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                AWS access key id.
              '';
            };
            secretAccessKey = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                AWS access key.
              '';
            };
            region = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                AWS S3 region.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the s3 third-party integration.";
      };
      s3bucket = mkOption {
        type = types.nullOr types.str;
        default = null;
        description = lib.mdDoc ''
          Specify the bucket name for upload types `s3` and `minio`.
        '';
      };
      allowPDFExport = mkOption {
        type = types.bool;
        default = true;
        description = lib.mdDoc ''
          Whether to enable PDF exports.
        '';
      };
      imgur.clientId = mkOption {
        type = types.nullOr types.str;
        default = null;
        description = lib.mdDoc ''
          Imgur API client ID.
        '';
      };
      azure = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            connectionString = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Azure Blob Storage connection string.
              '';
            };
            container = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Azure Blob Storage container name.
                It will be created if non-existent.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the azure third-party integration.";
      };
      oauth2 = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            authorizationURL = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Specify the OAuth authorization URL.
              '';
            };
            tokenURL = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Specify the OAuth token URL.
              '';
            };
            baseURL = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the OAuth base URL.
              '';
            };
            userProfileURL = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the OAuth userprofile URL.
              '';
            };
            userProfileUsernameAttr = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the name of the attribute for the username from the claim.
              '';
            };
            userProfileDisplayNameAttr = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the name of the attribute for the display name from the claim.
              '';
            };
            userProfileEmailAttr = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the name of the attribute for the email from the claim.
              '';
            };
            scope = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the OAuth scope.
              '';
            };
            providerName = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the name to be displayed for this strategy.
              '';
            };
            rolesClaim = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the role claim name.
              '';
            };
            accessRole = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify role which should be included in the ID token roles claim to grant access
              '';
            };
            clientID = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Specify the OAuth client ID.
              '';
            };
            clientSecret = mkOption {
              type = with types; nullOr str;
              default = null;
              description = lib.mdDoc ''
                Specify the OAuth client secret.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the OAuth integration.";
      };
      facebook = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            clientID = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Facebook API client ID.
              '';
            };
            clientSecret = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Facebook API client secret.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the facebook third-party integration";
      };
      twitter = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            consumerKey = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Twitter API consumer key.
              '';
            };
            consumerSecret = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Twitter API consumer secret.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the Twitter third-party integration.";
      };
      github = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            clientID = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                GitHub API client ID.
              '';
            };
            clientSecret = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Github API client secret.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the GitHub third-party integration.";
      };
      gitlab = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            baseURL = mkOption {
              type = types.str;
              default = "";
              description = lib.mdDoc ''
                GitLab API authentication endpoint.
                Only needed for other endpoints than gitlab.com.
              '';
            };
            clientID = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                GitLab API client ID.
              '';
            };
            clientSecret = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                GitLab API client secret.
              '';
            };
            scope = mkOption {
              type = types.enum [ "api" "read_user" ];
              default = "api";
              description = lib.mdDoc ''
                GitLab API requested scope.
                GitLab snippet import/export requires api scope.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the GitLab third-party integration.";
      };
      mattermost = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            baseURL = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Mattermost authentication endpoint.
              '';
            };
            clientID = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Mattermost API client ID.
              '';
            };
            clientSecret = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Mattermost API client secret.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the Mattermost third-party integration.";
      };
      dropbox = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            clientID = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Dropbox API client ID.
              '';
            };
            clientSecret = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Dropbox API client secret.
              '';
            };
            appKey = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Dropbox app key.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the Dropbox third-party integration.";
      };
      google = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            clientID = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Google API client ID.
              '';
            };
            clientSecret = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Google API client secret.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the Google third-party integration.";
      };
      ldap = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            providerName = mkOption {
              type = types.str;
              default = "";
              description = lib.mdDoc ''
                Optional name to be displayed at login form, indicating the LDAP provider.
              '';
            };
            url = mkOption {
              type = types.str;
              example = "ldap://localhost";
              description = lib.mdDoc ''
                URL of LDAP server.
              '';
            };
            bindDn = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Bind DN for LDAP access.
              '';
            };
            bindCredentials = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Bind credentials for LDAP access.
              '';
            };
            searchBase = mkOption {
              type = types.str;
              example = "o=users,dc=example,dc=com";
              description = lib.mdDoc ''
                LDAP directory to begin search from.
              '';
            };
            searchFilter = mkOption {
              type = types.str;
              example = "(uid={{username}})";
              description = lib.mdDoc ''
                LDAP filter to search with.
              '';
            };
            searchAttributes = mkOption {
              type = types.nullOr (types.listOf types.str);
              default = null;
              example = [ "displayName" "mail" ];
              description = lib.mdDoc ''
                LDAP attributes to search with.
              '';
            };
            userNameField = mkOption {
              type = types.str;
              default = "";
              description = lib.mdDoc ''
                LDAP field which is used as the username on HedgeDoc.
                By default {option}`useridField` is used.
              '';
            };
            useridField = mkOption {
              type = types.str;
              example = "uid";
              description = lib.mdDoc ''
                LDAP field which is a unique identifier for users on HedgeDoc.
              '';
            };
            tlsca = mkOption {
              type = types.str;
              default = "/etc/ssl/certs/ca-certificates.crt";
              example = "server-cert.pem,root.pem";
              description = lib.mdDoc ''
                Root CA for LDAP TLS in PEM format.
              '';
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the LDAP integration.";
      };
      saml = mkOption {
        type = types.nullOr (types.submodule {
          options = {
            idpSsoUrl = mkOption {
              type = types.str;
              example = "https://idp.example.com/sso";
              description = lib.mdDoc ''
                IdP authentication endpoint.
              '';
            };
            idpCert = mkOption {
              type = types.path;
              example = "/path/to/cert.pem";
              description = lib.mdDoc ''
                Path to IdP certificate file in PEM format.
              '';
            };
            issuer = mkOption {
              type = types.str;
              default = "";
              description = lib.mdDoc ''
                Optional identity of the service provider.
                This defaults to the server URL.
              '';
            };
            identifierFormat = mkOption {
              type = types.str;
              default = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
              description = lib.mdDoc ''
                Optional name identifier format.
              '';
            };
            groupAttribute = mkOption {
              type = types.str;
              default = "";
              example = "memberOf";
              description = lib.mdDoc ''
                Optional attribute name for group list.
              '';
            };
            externalGroups = mkOption {
              type = types.listOf types.str;
              default = [];
              example = [ "Temporary-staff" "External-users" ];
              description = lib.mdDoc ''
                Excluded group names.
              '';
            };
            requiredGroups = mkOption {
              type = types.listOf types.str;
              default = [];
              example = [ "Hedgedoc-Users" ];
              description = lib.mdDoc ''
                Required group names.
              '';
            };
            providerName = mkOption {
              type = types.str;
              default = "";
              example = "My institution";
              description = lib.mdDoc ''
                Optional name to be displayed at login form indicating the SAML provider.
              '';
            };
            attribute = {
              id = mkOption {
                type = types.str;
                default = "";
                description = lib.mdDoc ''
                  Attribute map for `id`.
                  Defaults to `NameID` of SAML response.
                '';
              };
              username = mkOption {
                type = types.str;
                default = "";
                description = lib.mdDoc ''
                  Attribute map for `username`.
                  Defaults to `NameID` of SAML response.
                '';
              };
              email = mkOption {
                type = types.str;
                default = "";
                description = lib.mdDoc ''
                  Attribute map for `email`.
                  Defaults to `NameID` of SAML response if
                  {option}`identifierFormat` has
                  the default value.
                '';
              };
            };
          };
        });
        default = null;
        description = lib.mdDoc "Configure the SAML integration.";
      };
    }; in lib.mkOption {
      type = lib.types.submodule {
        freeformType = settingsFormat.type;
        inherit options;
      };
      description = lib.mdDoc ''
        HedgeDoc configuration, see
        <https://docs.hedgedoc.org/configuration/>
        for documentation.
      '';
    };

    environmentFile = mkOption {
      type = with types; nullOr path;
      default = null;
      example = "/var/lib/hedgedoc/hedgedoc.env";
      description = lib.mdDoc ''
        Environment file as defined in {manpage}`systemd.exec(5)`.

        Secrets may be passed to the service without adding them to the world-readable
        Nix store, by specifying placeholder variables as the option value in Nix and
        setting these variables accordingly in the environment file.

        ```
          # snippet of HedgeDoc-related config
          services.hedgedoc.settings.dbURL = "postgres://hedgedoc:\''${DB_PASSWORD}@db-host:5432/hedgedocdb";
          services.hedgedoc.settings.minio.secretKey = "$MINIO_SECRET_KEY";
        ```

        ```
          # content of the environment file
          DB_PASSWORD=verysecretdbpassword
          MINIO_SECRET_KEY=verysecretminiokey
        ```

        Note that this file needs to be available on the host on which
        `HedgeDoc` is running.
      '';
    };
  };

  config = mkIf cfg.enable {
    assertions = [
      { assertion = cfg.settings.db == {} -> (
          cfg.settings.dbURL != "" && cfg.settings.dbURL != null
        );
        message = "Database configuration for HedgeDoc missing."; }
    ];
    users.groups.${name} = {};
    users.users.${name} = {
      description = "HedgeDoc service user";
      group = name;
      extraGroups = cfg.groups;
      home = cfg.workDir;
      createHome = true;
      isSystemUser = true;
    };

    systemd.services.hedgedoc = {
      description = "HedgeDoc Service";
      wantedBy = [ "multi-user.target" ];
      after = [ "networking.target" ];
      preStart = ''
        ${pkgs.envsubst}/bin/envsubst \
          -o ${cfg.workDir}/config.json \
          -i ${prettyJSON cfg.settings}
        mkdir -p ${cfg.settings.uploadsPath}
      '';
      serviceConfig = {
        WorkingDirectory = cfg.workDir;
        StateDirectory = [ cfg.workDir cfg.settings.uploadsPath ];
        ExecStart = "${lib.getExe cfg.package}";
        EnvironmentFile = mkIf (cfg.environmentFile != null) [ cfg.environmentFile ];
        Environment = [
          "CMD_CONFIG_FILE=${cfg.workDir}/config.json"
          "NODE_ENV=production"
        ];
        Restart = "always";
        User = name;
        PrivateTmp = true;
      };
    };
  };
}