about summary refs log tree commit diff
path: root/nixos/modules/services/hardware/kanata.nix
blob: 46af3e36b985951e8db4acc9f981368c837aad80 (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
{ config, lib, pkgs, utils, ... }:

with lib;

let
  cfg = config.services.kanata;

  upstreamDoc = "See [the upstream documentation](https://github.com/jtroo/kanata/blob/main/docs/config.adoc) and [example config files](https://github.com/jtroo/kanata/tree/main/cfg_samples) for more information.";

  keyboard = {
    options = {
      devices = mkOption {
        type = types.listOf types.str;
        default = [ ];
        example = [ "/dev/input/by-id/usb-0000_0000-event-kbd" ];
        description = ''
          Paths to keyboard devices.

          An empty list, the default value, lets kanata detect which
          input devices are keyboards and intercept them all.
        '';
      };
      config = mkOption {
        type = types.lines;
        example = ''
          (defsrc
            caps)

          (deflayermap (default-layer)
            ;; tap caps lock as caps lock, hold caps lock as left control
            caps (tap-hold 100 100 caps lctl))
        '';
        description = ''
          Configuration other than `defcfg`.

          ${upstreamDoc}
        '';
      };
      extraDefCfg = mkOption {
        type = types.lines;
        default = "";
        example = "danger-enable-cmd yes";
        description = ''
          Configuration of `defcfg` other than `linux-dev` (generated
          from the devices option) and
          `linux-continue-if-no-devs-found` (hardcoded to be yes).

          ${upstreamDoc}
        '';
      };
      extraArgs = mkOption {
        type = types.listOf types.str;
        default = [ ];
        description = "Extra command line arguments passed to kanata.";
      };
      port = mkOption {
        type = types.nullOr types.port;
        default = null;
        example = 6666;
        description = ''
          Port to run the TCP server on. `null` will not run the server.
        '';
      };
    };
  };

  mkName = name: "kanata-${name}";

  mkDevices = devices:
    let
      devicesString = pipe devices [
        (map (device: "\"" + device + "\""))
        (concatStringsSep " ")
      ];
    in
    optionalString ((length devices) > 0) "linux-dev (${devicesString})";

  mkConfig = name: keyboard: pkgs.writeTextFile {
    name = "${mkName name}-config.kdb";
    text = ''
      (defcfg
        ${keyboard.extraDefCfg}
        ${mkDevices keyboard.devices}
        linux-continue-if-no-devs-found yes)

      ${keyboard.config}
    '';
    checkPhase = ''
      ${getExe cfg.package} --cfg "$target" --check --debug
    '';
  };

  mkService = name: keyboard: nameValuePair (mkName name) {
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      Type = "notify";
      ExecStart = ''
        ${getExe cfg.package} \
          --cfg ${mkConfig name keyboard} \
          --symlink-path ''${RUNTIME_DIRECTORY}/${name} \
          ${optionalString (keyboard.port != null) "--port ${toString keyboard.port}"} \
          ${utils.escapeSystemdExecArgs keyboard.extraArgs}
      '';

      DynamicUser = true;
      RuntimeDirectory = mkName name;
      SupplementaryGroups = with config.users.groups; [
        input.name
        uinput.name
      ];

      # hardening
      DeviceAllow = [
        "/dev/uinput rw"
        "char-input r"
      ];
      CapabilityBoundingSet = [ "" ];
      DevicePolicy = "closed";
      IPAddressAllow = optional (keyboard.port != null) "localhost";
      IPAddressDeny = [ "any" ];
      LockPersonality = true;
      MemoryDenyWriteExecute = true;
      PrivateNetwork = keyboard.port == null;
      PrivateUsers = true;
      ProcSubset = "pid";
      ProtectClock = true;
      ProtectControlGroups = true;
      ProtectHome = true;
      ProtectHostname = true;
      ProtectKernelLogs = true;
      ProtectKernelModules = true;
      ProtectKernelTunables = true;
      ProtectProc = "invisible";
      RestrictAddressFamilies = [ "AF_UNIX" ] ++ optional (keyboard.port != null) "AF_INET";
      RestrictNamespaces = true;
      RestrictRealtime = true;
      SystemCallArchitectures = [ "native" ];
      SystemCallFilter = [
        "@system-service"
        "~@privileged"
        "~@resources"
      ];
      UMask = "0077";
    };
  };
in
{
  options.services.kanata = {
    enable = mkEnableOption "kanata, a tool to improve keyboard comfort and usability with advanced customization";
    package = mkPackageOption pkgs "kanata" {
      example = [ "kanata-with-cmd" ];
      extraDescription = ''
        ::: {.note}
        If {option}`danger-enable-cmd` is enabled in any of the keyboards, the
        `kanata-with-cmd` package should be used.
        :::
      '';
    };
    keyboards = mkOption {
      type = types.attrsOf (types.submodule keyboard);
      default = { };
      description = "Keyboard configurations.";
    };
  };

  config = mkIf cfg.enable {
    warnings =
      let
        keyboardsWithEmptyDevices = filterAttrs (name: keyboard: keyboard.devices == [ ]) cfg.keyboards;
        existEmptyDevices = length (attrNames keyboardsWithEmptyDevices) > 0;
        moreThanOneKeyboard = length (attrNames cfg.keyboards) > 1;
      in
      optional (existEmptyDevices && moreThanOneKeyboard) "One device can only be intercepted by one kanata instance.  Setting services.kanata.keyboards.${head (attrNames keyboardsWithEmptyDevices)}.devices = [ ] and using more than one services.kanata.keyboards may cause a race condition.";

    hardware.uinput.enable = true;

    systemd.services = mapAttrs' mkService cfg.keyboards;
  };

  meta.maintainers = with maintainers; [ linj ];
}