From 5828af9fc19e18dc85e49fcc1a251a7eb25d909c Mon Sep 17 00:00:00 2001 From: Max Audron Date: Fri, 11 Aug 2023 16:51:35 +0200 Subject: init --- modules/matrix/conduit.nix | 142 + modules/matrix/default.nix | 73 + modules/matrix/mautrix-slack.nix | 194 + modules/matrix/mx-puppet-slack.nix | 132 + modules/matrix/options.nix | 38 + .../matrix/patches/heisenbridge_channel_name.patch | 13 + .../matrix/patches/heisenbridge_private_name.patch | 13 + .../patches/heisenbridge_user_presence.patch | 103 + modules/matrix/pkgs/generate.sh | 20 + modules/matrix/pkgs/mautrix-slack.nix | 26 + modules/matrix/pkgs/mx-puppet-slack.nix | 49 + modules/matrix/pkgs/node-composition.nix | 17 + modules/matrix/pkgs/node-env.nix | 689 ++++ modules/matrix/pkgs/node-packages.nix | 4275 ++++++++++++++++++++ modules/matrix/pkgs/slack_presence.patch | 21 + 15 files changed, 5805 insertions(+) create mode 100644 modules/matrix/conduit.nix create mode 100644 modules/matrix/default.nix create mode 100644 modules/matrix/mautrix-slack.nix create mode 100644 modules/matrix/mx-puppet-slack.nix create mode 100644 modules/matrix/options.nix create mode 100644 modules/matrix/patches/heisenbridge_channel_name.patch create mode 100644 modules/matrix/patches/heisenbridge_private_name.patch create mode 100644 modules/matrix/patches/heisenbridge_user_presence.patch create mode 100755 modules/matrix/pkgs/generate.sh create mode 100644 modules/matrix/pkgs/mautrix-slack.nix create mode 100644 modules/matrix/pkgs/mx-puppet-slack.nix create mode 100644 modules/matrix/pkgs/node-composition.nix create mode 100644 modules/matrix/pkgs/node-env.nix create mode 100644 modules/matrix/pkgs/node-packages.nix create mode 100644 modules/matrix/pkgs/slack_presence.patch (limited to 'modules/matrix') diff --git a/modules/matrix/conduit.nix b/modules/matrix/conduit.nix new file mode 100644 index 0000000..10612b9 --- /dev/null +++ b/modules/matrix/conduit.nix @@ -0,0 +1,142 @@ +{ config, lib, pkgs, ... }: + + +let + cfg = config.services.matrix; + + # Build a dervation that stores the content of `${server_name}/.well-known/matrix/server` + well_known_server = pkgs.writeText "well-known-matrix-server" '' + { + "m.server": "${cfg.matrix_hostname}" + } + ''; + + # Build a dervation that stores the content of `${server_name}/.well-known/matrix/client` + well_known_client = pkgs.writeText "well-known-matrix-client" '' + { + "m.homeserver": { + "base_url": "https://${cfg.matrix_hostname}" + } + } + ''; +in +{ + # Configure Conduit itself + services.matrix-conduit = { + enable = true; + + # This causes NixOS to use the flake defined in this repository instead of + # the build of Conduit built into nixpkgs. + package = pkgs.unstable.matrix-conduit; + + settings.global = { + inherit (cfg) server_name; + + allow_registration = true; + allow_federation = true; + trusted_servers = [ "matrix.org" ]; + enable_lightning_bolt = false; + }; + }; + + security.acme = { + acceptTerms = true; + defaults = { + email = cfg.admin_email; + }; + }; + + # ACME data must be readable by the NGINX user + users.users.nginx.extraGroups = [ + "acme" + ]; + + # Configure NGINX as a reverse proxy + services.nginx = { + enable = true; + recommendedProxySettings = true; + + virtualHosts = { + "${cfg.matrix_hostname}" = { + forceSSL = true; + enableACME = true; + + listen = [ + { + addr = "0.0.0.0"; + port = 443; + ssl = true; + } + { + addr = "0.0.0.0"; + port = 8448; + ssl = true; + } + { + addr = "[::0]"; + port = 443; + ssl = true; + } + { + addr = "[::0]"; + port = 8448; + ssl = true; + } + ]; + + locations."/_matrix/" = { + proxyPass = "http://backend_conduit$request_uri"; + proxyWebsockets = true; + extraConfig = '' + proxy_set_header Host $host; + proxy_buffering off; + ''; + }; + + extraConfig = '' + merge_slashes off; + ''; + }; + + "${cfg.server_name}" = { + forceSSL = true; + enableACME = true; + + locations."=/.well-known/matrix/server" = { + # Use the contents of the derivation built previously + alias = "${well_known_server}"; + + extraConfig = '' + # Set the header since by default NGINX thinks it's just bytes + default_type application/json; + ''; + }; + + locations."=/.well-known/matrix/client" = { + # Use the contents of the derivation built previously + alias = "${well_known_client}"; + + extraConfig = '' + # Set the header since by default NGINX thinks it's just bytes + default_type application/json; + + # https://matrix.org/docs/spec/client_server/r0.4.0#web-browser-clients + add_header Access-Control-Allow-Origin "*"; + ''; + }; + }; + }; + + upstreams = { + "backend_conduit" = { + servers = { + "localhost:${toString config.services.matrix-conduit.settings.global.port}" = { }; + }; + }; + }; + }; + + # Open firewall ports for HTTP, HTTPS, and Matrix federation + networking.firewall.allowedTCPPorts = [ 80 443 8448 ]; + networking.firewall.allowedUDPPorts = [ 80 443 8448 ]; +} diff --git a/modules/matrix/default.nix b/modules/matrix/default.nix new file mode 100644 index 0000000..7964f9b --- /dev/null +++ b/modules/matrix/default.nix @@ -0,0 +1,73 @@ +{ config, lib, pkgs, secrets, ... }: + + +let cfg = config.services.matrix; +in +{ + imports = [ + ./options.nix + ./conduit.nix + ./mautrix-slack.nix + ]; + + services.matrix = { + server_name = "vapor.systems"; + admin_email = "info@cocaine.farm"; + }; + + services.heisenbridge = { + enable = true; + owner = "@audron:vapor.systems"; + homeserver = "https://${cfg.matrix_hostname}"; + # extraArgs = [ "--generate-compat" ]; + # + package = pkgs.heisenbridge.overrideAttrs (prev: rec { + version = "1.14.2"; + + src = pkgs.fetchFromGitHub { + owner = "hifi"; + repo = prev.pname; + rev = "refs/tags/v${version}"; + sha256 = "sha256-qp0LVcmWf5lZ52h0V58S6FoIM8RLOd6Y3FRb85j7KRg="; + }; + + patches = [ + ./patches/heisenbridge_channel_name.patch + ./patches/heisenbridge_private_name.patch + ./patches/heisenbridge_user_presence.patch + ]; + }); + + identd.enable = true; + }; + + + services.mautrix-slack = { + enable = true; + environmentFile = "/var/lib/mautrix-slack/secrets.env"; + settings = { + homeserver = { + address = "https://${cfg.matrix_hostname}"; + domain = cfg.server_name; + }; + + appservice = + let s = builtins.fromJSON (builtins.readFile "${secrets}/matrix/mautrix-slack.json"); + in + { + as_token = s.as_token; + hs_token = s.hs_token; + }; + + bridge = { + permissions = { + "*" = "relay"; + "vapor.systems" = "user"; + "@audron:vapor.systems" = "admin"; + }; + }; + }; + + configurePostgresql = true; + }; +} diff --git a/modules/matrix/mautrix-slack.nix b/modules/matrix/mautrix-slack.nix new file mode 100644 index 0000000..d0324a1 --- /dev/null +++ b/modules/matrix/mautrix-slack.nix @@ -0,0 +1,194 @@ +{ config, pkgs, lib, ... }: + +with lib; + +let + cfg = config.services.mautrix-slack; + dataDir = "/var/lib/mautrix-slack"; + registrationFile = "${dataDir}/slack-registration.yaml"; + settingsFormat = pkgs.formats.json { }; + settingsFile = settingsFormat.generate "mautrix-slack-config.json" cfg.settings; +in +{ + options = { + services.mautrix-slack = { + enable = mkEnableOption (lib.mdDoc "Mautrix-Slack, a Matrix-Slack hybrid puppeting/relaybot bridge"); + + package = mkOption { + type = types.package; + default = pkgs.callPackage ./pkgs/mautrix-slack.nix { }; + defaultText = "pkgs.mautrix-slack"; + example = "pkgs.mautrix-slack.override { … = …; }"; + description = lib.mdDoc '' + Package of the application to run, exposed for overriding purposes. + ''; + }; + + settings = mkOption rec { + apply = recursiveUpdate default; + type = settingsFormat.type; + default = { + homeserver = { + software = "standard"; + }; + + appservice = rec { + address = "http://${hostname}:${toString port}"; + hostname = "localhost"; + port = 29319; + + database = { + type = "postgres"; + uri = "postgres:///mautrix-slack?host=/run/postgresql&sslmode=disable"; + }; + + id = "slack"; + bot = { + username = "slackbot"; + }; + + # backfill = { + # enable = false; + # conversations_count = 200; + # unread_hours_threshold = 720; + # immediate_messages = 10; + # incremental = { + # messages_per_batch = 100; + # post_batch_delay = 20; + # max_messages = { + # channel = -1; + # group_dm = -1; + # dm = -1; + # }; + # }; + # }; + + # encryption = { + # allow = false; + # default = false; + # appservice = false; + # require = false; + # allow_key_sharing = false; + # verification_levels = { + # receive = "unverified"; + # send = "unverified"; + # share = "cross-signed-tofu"; + # }; + # rotation = { + # enable_custom = false; + # milliseconds = 604800000; + # messages = 100; + # }; + # }; + + # provisioning = { + # prefix = "/_matrix/provision"; + # shared_secret = "generate"; + # }; + }; + + logging = { + directory = "/var/log/mautrix"; + file_name_format = "slack-{{.Date}}-{{.Index}}.log"; + file_date_format = "2006-01-02"; + file_mode = 384; + timestamp_format = "Jan _2, 2006 15:04:05"; + print_level = "debug"; + print_json = false; + file_json = false; + }; + }; + }; + + environmentFile = mkOption { + type = types.nullOr types.path; + default = null; + description = lib.mdDoc '' + File containing environment variables to be passed to the mautrix-slack service. + Any config variable can be overridden by setting `MAUTRIX_SLACK_SOME_KEY` to override the `some.key` variable. + ''; + }; + + configurePostgresql = mkOption { + type = types.bool; + default = true; + description = lib.mdDoc '' + Enable PostgreSQL and create a user and database for mautrix-slack. The default `settings` reference this database, if you disable this option you must provide a database URL. + ''; + }; + }; + }; + + config = mkIf cfg.enable { + users.groups.mautrix-slack = { }; + + users.users.mautrix-slack = { + group = "mautrix-slack"; + isSystemUser = true; + }; + + services.postgresql = mkIf cfg.configurePostgresql { + enable = true; + ensureDatabases = [ "mautrix-slack" ]; + ensureUsers = [{ + name = "mautrix-slack"; + ensurePermissions = { + "DATABASE \"mautrix-slack\"" = "ALL PRIVILEGES"; + }; + }]; + }; + + systemd.services.mautrix-slack = rec { + wantedBy = [ "multi-user.target" ]; + wants = [ + "network-online.target" + ] ++ optional config.services.matrix-synapse.enable "matrix-synapse.service" + ++ optional cfg.configurePostgresql "postgresql.service"; + after = wants; + + preStart = '' + # generate the appservice's registration file if absent + if [ ! -f '${registrationFile}' ]; then + ${cfg.package}/bin/mautrix-slack -g -c ${settingsFile} \ + -r ${registrationFile} + fi + ''; + + serviceConfig = { + Type = "simple"; + Restart = "always"; + + User = "mautrix-slack"; + + NoNewPrivileges = true; + MemoryDenyWriteExecute = true; + PrivateDevices = true; + PrivateTmp = true; + ProtectHome = true; + ProtectSystem = "strict"; + ProtectControlGroups = true; + RestrictSUIDSGID = true; + RestrictRealtime = true; + LockPersonality = true; + ProtectKernelLogs = true; + ProtectKernelTunables = true; + ProtectHostname = true; + ProtectKernelModules = true; + PrivateUsers = true; + ProtectClock = true; + SystemCallArchitectures = "native"; + SystemCallErrorNumber = "EPERM"; + SystemCallFilter = "@system-service"; + + StateDirectory = baseNameOf dataDir; + LogsDirectory = "mautrix"; + LogsDirectoryMode = "0750"; + EnvironmentFile = cfg.environmentFile; + + ExecStart = '' + ${cfg.package}/bin/mautrix-slack --no-update --config=${settingsFile} --registration=${registrationFile} + ''; + }; + }; + }; +} diff --git a/modules/matrix/mx-puppet-slack.nix b/modules/matrix/mx-puppet-slack.nix new file mode 100644 index 0000000..5737319 --- /dev/null +++ b/modules/matrix/mx-puppet-slack.nix @@ -0,0 +1,132 @@ +{ config, pkgs, lib, ... }: + +with lib; + +let + dataDir = "/var/lib/mx-puppet-slack"; + registrationFile = "${dataDir}/slack-registration.yaml"; + cfg = config.services.mx-puppet-slack; + settingsFormat = pkgs.formats.json {}; + settingsFile = settingsFormat.generate "mx-puppet-slack-config.json" cfg.settings; + +in { + options = { + services.mx-puppet-slack = { + enable = mkEnableOption (lib.mdDoc '' + mx-puppet-slack is a slack puppeting bridge for matrix. + It handles bridging private and group DMs + ''); + + package = mkOption { + type = types.package; + default = pkgs.callPackage ./pkgs/mx-puppet-slack.nix {}; + defaultText = "pkgs.mx-puppet-slack"; + example = "pkgs.mx-puppet-slack.override { … = …; }"; + description = lib.mdDoc '' + Package of the application to run, exposed for overriding purposes. + ''; + }; + + settings = mkOption rec { + apply = recursiveUpdate default; + inherit (settingsFormat) type; + default = { + bridge = { + port = 8432; + }; + presence = { + enabled = true; + interval = 500; + }; + provisioning.whitelist = [ ]; + + # variables are preceded by a colon. + namePatterns = { + user = ":name"; + room = ":name[:team? - :team,]"; + group = ":name"; + }; + + #defaults to sqlite but can be configured to use postgresql with + #connstring + database.filename = "${dataDir}/database.db"; + logging = { + console = "info"; + lineDateFormat = "MMM-D HH:mm:ss.SSS"; + }; + }; + example = literalExpression '' + { + bridge = { + bindAddress = "localhost"; + domain = "example.com"; + homeserverUrl = "https://example.com"; + }; + provisioning.whitelist = [ "@admin:example.com" ]; + relay.whitelist = [ "@.*:example.com" ]; + } + ''; + description = lib.mdDoc '' + {file}`config.yaml` configuration as a Nix attribute set. + Configuration options should match those described in + [ + sample.config.yaml](https://github.com/matrix-slack/mx-puppet-slack/blob/master/sample.config.yaml). + ''; + }; + serviceDependencies = mkOption { + type = with types; listOf str; + default = optional config.services.matrix-synapse.enable "matrix-synapse.service"; + defaultText = literalExpression '' + optional config.services.matrix-synapse.enable "matrix-synapse.service" + ''; + description = lib.mdDoc '' + List of Systemd services to require and wait for when starting the application service. + ''; + }; + }; + }; + + config = mkIf cfg.enable { + systemd.services.mx-puppet-slack = { + description = "Matrix to Slack puppeting bridge"; + + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ] ++ cfg.serviceDependencies; + after = [ "network-online.target" ] ++ cfg.serviceDependencies; + + preStart = '' + # generate the appservice's registration file if absent + if [ ! -f '${registrationFile}' ]; then + ${cfg.package}/bin/mx-puppet-slack -r -c ${settingsFile} \ + -f ${registrationFile} + fi + ''; + + serviceConfig = { + Type = "simple"; + Restart = "always"; + + ProtectSystem = "strict"; + ProtectHome = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + + DynamicUser = true; + PrivateTmp = true; + WorkingDirectory = cfg.package; + StateDirectory = baseNameOf dataDir; + + UMask = "0027"; + + ExecStart = '' + ${cfg.package}/bin/mx-puppet-slack \ + -c ${settingsFile} \ + -f ${registrationFile} + ''; + }; + }; + }; + + meta.maintainers = with maintainers; [ govanify ]; +} diff --git a/modules/matrix/options.nix b/modules/matrix/options.nix new file mode 100644 index 0000000..61a9201 --- /dev/null +++ b/modules/matrix/options.nix @@ -0,0 +1,38 @@ +{ config, lib, pkgs, ... }: + +with lib; +{ + options = { + services.matrix = { + server_name = mkOption { + type = types.str; + example = "example.com"; + description = lib.mdDoc '' + The hostname that will appear in your user and room IDs + ''; + }; + + matrix_hostname = mkOption { + type = types.str; + default = "matrix.${config.services.matrix.server_name}"; + example = "matrix.example.com"; + description = lib.mdDoc '' + The hostname that Conduit actually runs on + + This can be the same as `server_name` if you want. This is only necessary + when Conduit is running on a different machine than the one hosting your + root domain. This configuration also assumes this is all running on a single + machine, some tweaks will need to be made if this is not the case. + ''; + }; + + admin_email = mkOption { + type = types.str; + example = "admin@example.com"; + description = lib.mdDoc '' + An admin email for TLS certificate notifications + ''; + }; + }; + }; +} diff --git a/modules/matrix/patches/heisenbridge_channel_name.patch b/modules/matrix/patches/heisenbridge_channel_name.patch new file mode 100644 index 0000000..130f96b --- /dev/null +++ b/modules/matrix/patches/heisenbridge_channel_name.patch @@ -0,0 +1,13 @@ +diff --git i/heisenbridge/channel_room.py w/heisenbridge/channel_room.py +index 119dad0..f1a17f6 100644 +--- i/heisenbridge/channel_room.py ++++ w/heisenbridge/channel_room.py +@@ -207,7 +207,7 @@ class ChannelRoom(PrivateRoom): + self.hidden_room_id = self.serv.hidden_room.id + + self.id = await self.network.serv.create_room( +- f"{visible_name} ({self.network.name})", ++ f"{visible_name}", + "", + [self.network.user_id], + self.hidden_room_id, diff --git a/modules/matrix/patches/heisenbridge_private_name.patch b/modules/matrix/patches/heisenbridge_private_name.patch new file mode 100644 index 0000000..6cff153 --- /dev/null +++ b/modules/matrix/patches/heisenbridge_private_name.patch @@ -0,0 +1,13 @@ +diff --git i/heisenbridge/private_room.py w/heisenbridge/private_room.py +index d8118e8..6d33a3e 100644 +--- i/heisenbridge/private_room.py ++++ w/heisenbridge/private_room.py +@@ -466,7 +466,7 @@ class PrivateRoom(Room): + if self.id is None: + irc_user_id = await self.network.serv.ensure_irc_user_id(self.network.name, displayname, update_cache=False) + self.id = await self.network.serv.create_room( +- "{} ({})".format(displayname, self.network.name), ++ "{}".format(displayname), + "Private chat with {} on {}".format(displayname, self.network.name), + [self.network.user_id, irc_user_id], + ) diff --git a/modules/matrix/patches/heisenbridge_user_presence.patch b/modules/matrix/patches/heisenbridge_user_presence.patch new file mode 100644 index 0000000..a5fc96d --- /dev/null +++ b/modules/matrix/patches/heisenbridge_user_presence.patch @@ -0,0 +1,103 @@ +diff --git i/heisenbridge/__main__.py w/heisenbridge/__main__.py +index d59febd..4898955 100644 +--- i/heisenbridge/__main__.py ++++ w/heisenbridge/__main__.py +@@ -28,6 +28,7 @@ from mautrix.errors import MUserInUse + from mautrix.types import EventType + from mautrix.types import JoinRule + from mautrix.types import Membership ++from mautrix.types import PresenceState + from mautrix.util.bridge_state import BridgeState + from mautrix.util.bridge_state import BridgeStateEvent + from mautrix.util.config import yaml +@@ -192,6 +193,19 @@ class BridgeAppService(AppService): + + return ret + ++ def set_user_state(self, user_id, away, status=None): ++ if user_id not in self._users: ++ return ++ ++ presence = PresenceState.ONLINE ++ if away: ++ presence = PresenceState.UNAVAILABLE ++ ++ async def later(): ++ await self.az.intent.user(user_id).set_presence(presence=presence, status=status) ++ ++ asyncio.ensure_future(later()) ++ + async def cache_user(self, user_id, displayname): + # start by caching that the user_id exists without a displayname + if user_id not in self._users: +diff --git i/heisenbridge/channel_room.py w/heisenbridge/channel_room.py +index 119dad0..3e0651d 100644 +--- i/heisenbridge/channel_room.py ++++ w/heisenbridge/channel_room.py +@@ -478,6 +478,9 @@ class ChannelRoom(PrivateRoom): + + asyncio.ensure_future(autocmd(self)) + ++ # Run a WHO on the channel to get initial away status ++ self.network.conn.who(target=event.target) ++ + return + + # ensure, append, invite and join +diff --git i/heisenbridge/network_room.py w/heisenbridge/network_room.py +index 3c20654..2758462 100644 +--- i/heisenbridge/network_room.py ++++ w/heisenbridge/network_room.py +@@ -139,7 +139,7 @@ class NetworkRoom(Room): + self.tls_cert = None + self.rejoin_invite = True + self.rejoin_kick = False +- self.caps = ["message-tags", "chghost", "znc.in/self-message"] ++ self.caps = ["message-tags", "chghost", "znc.in/self-message", "away-notify"] + self.forward = False + self.backoff = 0 + self.backoff_task = None +@@ -1378,6 +1378,7 @@ class NetworkRoom(Room): + self.conn.add_global_handler("338", self.on_whoisrealhost) # is actually using host + self.conn.add_global_handler("away", self.on_away) + self.conn.add_global_handler("endofwhois", self.on_endofwhois) ++ self.conn.add_global_handler("whoreply", self.on_whoreply) + + # tags + self.conn.add_global_handler("tagmsg", self.on_pass_or_ignore) +@@ -1936,9 +1937,34 @@ class NetworkRoom(Room): + data = self.whois_data[event.arguments[0].lower()] + data["realhost"] = event.arguments[1] + ++ def on_whoreply(self, conn, event) -> None: ++ data = self.whois_data[event.arguments[4].lower()] ++ data["nick"] = event.arguments[4] ++ data["user"] = event.arguments[1] ++ data["host"] = event.arguments[2] ++ if "G" in event.arguments[5]: ++ data["away"] = True ++ elif "H" in event.arguments[5]: ++ data["away"] = False ++ # data["realname"] = event.arguments[4] ++ ++ nick, mode = self.serv.strip_nick(data["nick"]) ++ irc_user_id = self.serv.irc_user_id(self.name, data["nick"]) ++ self.serv.set_user_state(irc_user_id, data["away"]) ++ + def on_away(self, conn, event) -> None: ++ nick, mode = self.serv.strip_nick(event.arguments[0]) ++ irc_user_id = self.serv.irc_user_id(self.name, event.arguments[0]) ++ + if event.arguments[0].lower() in self.whois_data: +- self.whois_data[event.arguments[0].lower()]["away"] = event.arguments[1] ++ if len(event.arguments) > 1: ++ self.whois_data[event.arguments[0].lower()]["away"] = True ++ self.whois_data[event.arguments[0].lower()]["awaymsg"] = event.arguments[1] ++ self.serv.set_user_state(irc_user_id, True, event.arguments[1]) ++ else: ++ self.whois_data[event.arguments[0].lower()]["away"] = False ++ self.whois_data[event.arguments[0].lower()]["awaymsg"] = "" ++ self.serv.set_user_state(irc_user_id, False) + else: + self.send_notice(f"{event.arguments[0]} is away: {event.arguments[1]}") + diff --git a/modules/matrix/pkgs/generate.sh b/modules/matrix/pkgs/generate.sh new file mode 100755 index 0000000..1192e12 --- /dev/null +++ b/modules/matrix/pkgs/generate.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env nix-shell +#! nix-shell -i bash -p nodePackages.node2nix + +tag="v0.1.2" +u="https://gitlab.com/mx-puppet/slack/mx-puppet-slack/-/raw/$tag" +# Download package.json and patch in @slackjs/opus optional dependency +curl $u/package.json | + sed 's|"typescript":.*|"typescript": "^4.8.3",|' >package.json + +node2nix \ + --nodejs-14 \ + --input package.json \ + --strip-optional-dependencies \ + --output node-packages.nix \ + --composition node-composition.nix \ + --registry https://registry.npmjs.org \ + --registry https://gitlab.com/api/v4/packages/npm \ + --registry-scope '@mx-puppet' + +rm -f package.json diff --git a/modules/matrix/pkgs/mautrix-slack.nix b/modules/matrix/pkgs/mautrix-slack.nix new file mode 100644 index 0000000..4310e7b --- /dev/null +++ b/modules/matrix/pkgs/mautrix-slack.nix @@ -0,0 +1,26 @@ +{ lib, buildGoModule, fetchFromGitHub, olm }: + +buildGoModule rec { + pname = "mautrix-slack"; + version = "20230316"; + + src = fetchFromGitHub { + owner = "mautrix"; + repo = "slack"; + rev = "main"; + sha256 = "sha256-kA2IzYkvWoh/LxykuSzOLif76ZDbj7hKRjdIGDHY1W0="; + }; + + buildInputs = [ olm ]; + + vendorSha256 = "sha256-kYaeVXxrfA8WuL10+2DC6c2cYJ2li4/3ulKxcy/KviQ="; + + doCheck = false; + + meta = with lib; { + homepage = "https://github.com/mautrix/slack"; + description = "Matrix <-> Slack hybrid puppeting/relaybot bridge"; + license = licenses.agpl3Plus; + maintainers = with maintainers; [ ]; + }; +} diff --git a/modules/matrix/pkgs/mx-puppet-slack.nix b/modules/matrix/pkgs/mx-puppet-slack.nix new file mode 100644 index 0000000..110cdca --- /dev/null +++ b/modules/matrix/pkgs/mx-puppet-slack.nix @@ -0,0 +1,49 @@ +{ stdenv, fetchFromGitLab, pkgs, lib, nodejs-14_x, pkg-config +, libjpeg, pixman, cairo, pango, which, postgresql }: + +let + nodejs = nodejs-14_x; + + version = "0.1.2"; + + src = fetchFromGitLab { + owner = "cocainefarm"; + repo = "mx-puppet-slack"; + rev = "e4b51ed"; + hash = "sha256-y2q3m5E6FuYSwn691SfFlwoFqkVolXl4esgiuVYHNOA="; + }; + + myNodePackages = import ./node-composition.nix { + inherit pkgs nodejs; + inherit (stdenv.hostPlatform) system; + }; + +in myNodePackages.package.override { + inherit version src; + + nativeBuildInputs = [ nodejs.pkgs.node-pre-gyp nodejs.pkgs.node-gyp-build pkg-config which ]; + buildInputs = [ libjpeg pixman cairo pango postgresql ]; + + postRebuild = '' + # Build typescript stuff + npm run build + ''; + + postInstall = '' + # Make an executable to run the server + mkdir -p $out/bin + cat < $out/bin/mx-puppet-slack + #!/bin/sh + exec ${nodejs}/bin/node $out/lib/node_modules/@mx-puppet/mx-puppet-slack/build/index.js "\$@" + EOF + chmod +x $out/bin/mx-puppet-slack + ''; + + meta = with lib; { + description = "A slack puppeting bridge for matrix"; + license = licenses.asl20; + homepage = "https://gitlab.com/mx-puppet/slack/mx-puppet-slack"; + maintainers = with maintainers; [ ]; + platforms = platforms.unix; + }; +} diff --git a/modules/matrix/pkgs/node-composition.nix b/modules/matrix/pkgs/node-composition.nix new file mode 100644 index 0000000..08f947e --- /dev/null +++ b/modules/matrix/pkgs/node-composition.nix @@ -0,0 +1,17 @@ +# This file has been generated by node2nix 1.11.1. Do not edit! + +{pkgs ? import { + inherit system; + }, system ? builtins.currentSystem, nodejs ? pkgs."nodejs-14_x"}: + +let + nodeEnv = import ./node-env.nix { + inherit (pkgs) stdenv lib python2 runCommand writeTextFile writeShellScript; + inherit pkgs nodejs; + libtool = if pkgs.stdenv.isDarwin then pkgs.darwin.cctools else null; + }; +in +import ./node-packages.nix { + inherit (pkgs) fetchurl nix-gitignore stdenv lib fetchgit; + inherit nodeEnv; +} diff --git a/modules/matrix/pkgs/node-env.nix b/modules/matrix/pkgs/node-env.nix new file mode 100644 index 0000000..bc1e366 --- /dev/null +++ b/modules/matrix/pkgs/node-env.nix @@ -0,0 +1,689 @@ +# This file originates from node2nix + +{lib, stdenv, nodejs, python2, pkgs, libtool, runCommand, writeTextFile, writeShellScript}: + +let + # Workaround to cope with utillinux in Nixpkgs 20.09 and util-linux in Nixpkgs master + utillinux = if pkgs ? utillinux then pkgs.utillinux else pkgs.util-linux; + + python = if nodejs ? python then nodejs.python else python2; + + # Create a tar wrapper that filters all the 'Ignoring unknown extended header keyword' noise + tarWrapper = runCommand "tarWrapper" {} '' + mkdir -p $out/bin + + cat > $out/bin/tar <> $out/nix-support/hydra-build-products + ''; + }; + + # Common shell logic + installPackage = writeShellScript "install-package" '' + installPackage() { + local packageName=$1 src=$2 + + local strippedName + + local DIR=$PWD + cd $TMPDIR + + unpackFile $src + + # Make the base dir in which the target dependency resides first + mkdir -p "$(dirname "$DIR/$packageName")" + + if [ -f "$src" ] + then + # Figure out what directory has been unpacked + packageDir="$(find . -maxdepth 1 -type d | tail -1)" + + # Restore write permissions to make building work + find "$packageDir" -type d -exec chmod u+x {} \; + chmod -R u+w "$packageDir" + + # Move the extracted tarball into the output folder + mv "$packageDir" "$DIR/$packageName" + elif [ -d "$src" ] + then + # Get a stripped name (without hash) of the source directory. + # On old nixpkgs it's already set internally. + if [ -z "$strippedName" ] + then + strippedName="$(stripHash $src)" + fi + + # Restore write permissions to make building work + chmod -R u+w "$strippedName" + + # Move the extracted directory into the output folder + mv "$strippedName" "$DIR/$packageName" + fi + + # Change to the package directory to install dependencies + cd "$DIR/$packageName" + } + ''; + + # Bundle the dependencies of the package + # + # Only include dependencies if they don't exist. They may also be bundled in the package. + includeDependencies = {dependencies}: + lib.optionalString (dependencies != []) ( + '' + mkdir -p node_modules + cd node_modules + '' + + (lib.concatMapStrings (dependency: + '' + if [ ! -e "${dependency.packageName}" ]; then + ${composePackage dependency} + fi + '' + ) dependencies) + + '' + cd .. + '' + ); + + # Recursively composes the dependencies of a package + composePackage = { name, packageName, src, dependencies ? [], ... }@args: + builtins.addErrorContext "while evaluating node package '${packageName}'" '' + installPackage "${packageName}" "${src}" + ${includeDependencies { inherit dependencies; }} + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + ''; + + pinpointDependencies = {dependencies, production}: + let + pinpointDependenciesFromPackageJSON = writeTextFile { + name = "pinpointDependencies.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + function resolveDependencyVersion(location, name) { + if(location == process.env['NIX_STORE']) { + return null; + } else { + var dependencyPackageJSON = path.join(location, "node_modules", name, "package.json"); + + if(fs.existsSync(dependencyPackageJSON)) { + var dependencyPackageObj = JSON.parse(fs.readFileSync(dependencyPackageJSON)); + + if(dependencyPackageObj.name == name) { + return dependencyPackageObj.version; + } + } else { + return resolveDependencyVersion(path.resolve(location, ".."), name); + } + } + } + + function replaceDependencies(dependencies) { + if(typeof dependencies == "object" && dependencies !== null) { + for(var dependency in dependencies) { + var resolvedVersion = resolveDependencyVersion(process.cwd(), dependency); + + if(resolvedVersion === null) { + process.stderr.write("WARNING: cannot pinpoint dependency: "+dependency+", context: "+process.cwd()+"\n"); + } else { + dependencies[dependency] = resolvedVersion; + } + } + } + } + + /* Read the package.json configuration */ + var packageObj = JSON.parse(fs.readFileSync('./package.json')); + + /* Pinpoint all dependencies */ + replaceDependencies(packageObj.dependencies); + if(process.argv[2] == "development") { + replaceDependencies(packageObj.devDependencies); + } + else { + packageObj.devDependencies = {}; + } + replaceDependencies(packageObj.optionalDependencies); + replaceDependencies(packageObj.peerDependencies); + + /* Write the fixed package.json file */ + fs.writeFileSync("package.json", JSON.stringify(packageObj, null, 2)); + ''; + }; + in + '' + node ${pinpointDependenciesFromPackageJSON} ${if production then "production" else "development"} + + ${lib.optionalString (dependencies != []) + '' + if [ -d node_modules ] + then + cd node_modules + ${lib.concatMapStrings (dependency: pinpointDependenciesOfPackage dependency) dependencies} + cd .. + fi + ''} + ''; + + # Recursively traverses all dependencies of a package and pinpoints all + # dependencies in the package.json file to the versions that are actually + # being used. + + pinpointDependenciesOfPackage = { packageName, dependencies ? [], production ? true, ... }@args: + '' + if [ -d "${packageName}" ] + then + cd "${packageName}" + ${pinpointDependencies { inherit dependencies production; }} + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + fi + ''; + + # Extract the Node.js source code which is used to compile packages with + # native bindings + nodeSources = runCommand "node-sources" {} '' + tar --no-same-owner --no-same-permissions -xf ${nodejs.src} + mv node-* $out + ''; + + # Script that adds _integrity fields to all package.json files to prevent NPM from consulting the cache (that is empty) + addIntegrityFieldsScript = writeTextFile { + name = "addintegrityfields.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + function augmentDependencies(baseDir, dependencies) { + for(var dependencyName in dependencies) { + var dependency = dependencies[dependencyName]; + + // Open package.json and augment metadata fields + var packageJSONDir = path.join(baseDir, "node_modules", dependencyName); + var packageJSONPath = path.join(packageJSONDir, "package.json"); + + if(fs.existsSync(packageJSONPath)) { // Only augment packages that exist. Sometimes we may have production installs in which development dependencies can be ignored + console.log("Adding metadata fields to: "+packageJSONPath); + var packageObj = JSON.parse(fs.readFileSync(packageJSONPath)); + + if(dependency.integrity) { + packageObj["_integrity"] = dependency.integrity; + } else { + packageObj["_integrity"] = "sha1-000000000000000000000000000="; // When no _integrity string has been provided (e.g. by Git dependencies), add a dummy one. It does not seem to harm and it bypasses downloads. + } + + if(dependency.resolved) { + packageObj["_resolved"] = dependency.resolved; // Adopt the resolved property if one has been provided + } else { + packageObj["_resolved"] = dependency.version; // Set the resolved version to the version identifier. This prevents NPM from cloning Git repositories. + } + + if(dependency.from !== undefined) { // Adopt from property if one has been provided + packageObj["_from"] = dependency.from; + } + + fs.writeFileSync(packageJSONPath, JSON.stringify(packageObj, null, 2)); + } + + // Augment transitive dependencies + if(dependency.dependencies !== undefined) { + augmentDependencies(packageJSONDir, dependency.dependencies); + } + } + } + + if(fs.existsSync("./package-lock.json")) { + var packageLock = JSON.parse(fs.readFileSync("./package-lock.json")); + + if(![1, 2].includes(packageLock.lockfileVersion)) { + process.stderr.write("Sorry, I only understand lock file versions 1 and 2!\n"); + process.exit(1); + } + + if(packageLock.dependencies !== undefined) { + augmentDependencies(".", packageLock.dependencies); + } + } + ''; + }; + + # Reconstructs a package-lock file from the node_modules/ folder structure and package.json files with dummy sha1 hashes + reconstructPackageLock = writeTextFile { + name = "reconstructpackagelock.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + var packageObj = JSON.parse(fs.readFileSync("package.json")); + + var lockObj = { + name: packageObj.name, + version: packageObj.version, + lockfileVersion: 2, + requires: true, + packages: { + "": { + name: packageObj.name, + version: packageObj.version, + license: packageObj.license, + bin: packageObj.bin, + dependencies: packageObj.dependencies, + engines: packageObj.engines, + optionalDependencies: packageObj.optionalDependencies + } + }, + dependencies: {} + }; + + function augmentPackageJSON(filePath, packages, dependencies) { + var packageJSON = path.join(filePath, "package.json"); + if(fs.existsSync(packageJSON)) { + var packageObj = JSON.parse(fs.readFileSync(packageJSON)); + packages[filePath] = { + version: packageObj.version, + integrity: "sha1-000000000000000000000000000=", + dependencies: packageObj.dependencies, + engines: packageObj.engines, + optionalDependencies: packageObj.optionalDependencies + }; + dependencies[packageObj.name] = { + version: packageObj.version, + integrity: "sha1-000000000000000000000000000=", + dependencies: {} + }; + processDependencies(path.join(filePath, "node_modules"), packages, dependencies[packageObj.name].dependencies); + } + } + + function processDependencies(dir, packages, dependencies) { + if(fs.existsSync(dir)) { + var files = fs.readdirSync(dir); + + files.forEach(function(entry) { + var filePath = path.join(dir, entry); + var stats = fs.statSync(filePath); + + if(stats.isDirectory()) { + if(entry.substr(0, 1) == "@") { + // When we encounter a namespace folder, augment all packages belonging to the scope + var pkgFiles = fs.readdirSync(filePath); + + pkgFiles.forEach(function(entry) { + if(stats.isDirectory()) { + var pkgFilePath = path.join(filePath, entry); + augmentPackageJSON(pkgFilePath, packages, dependencies); + } + }); + } else { + augmentPackageJSON(filePath, packages, dependencies); + } + } + }); + } + } + + processDependencies("node_modules", lockObj.packages, lockObj.dependencies); + + fs.writeFileSync("package-lock.json", JSON.stringify(lockObj, null, 2)); + ''; + }; + + # Script that links bins defined in package.json to the node_modules bin directory + # NPM does not do this for top-level packages itself anymore as of v7 + linkBinsScript = writeTextFile { + name = "linkbins.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + var packageObj = JSON.parse(fs.readFileSync("package.json")); + + var nodeModules = Array(packageObj.name.split("/").length).fill("..").join(path.sep); + + if(packageObj.bin !== undefined) { + fs.mkdirSync(path.join(nodeModules, ".bin")) + + if(typeof packageObj.bin == "object") { + Object.keys(packageObj.bin).forEach(function(exe) { + if(fs.existsSync(packageObj.bin[exe])) { + console.log("linking bin '" + exe + "'"); + fs.symlinkSync( + path.join("..", packageObj.name, packageObj.bin[exe]), + path.join(nodeModules, ".bin", exe) + ); + } + else { + console.log("skipping non-existent bin '" + exe + "'"); + } + }) + } + else { + if(fs.existsSync(packageObj.bin)) { + console.log("linking bin '" + packageObj.bin + "'"); + fs.symlinkSync( + path.join("..", packageObj.name, packageObj.bin), + path.join(nodeModules, ".bin", packageObj.name.split("/").pop()) + ); + } + else { + console.log("skipping non-existent bin '" + packageObj.bin + "'"); + } + } + } + else if(packageObj.directories !== undefined && packageObj.directories.bin !== undefined) { + fs.mkdirSync(path.join(nodeModules, ".bin")) + + fs.readdirSync(packageObj.directories.bin).forEach(function(exe) { + if(fs.existsSync(path.join(packageObj.directories.bin, exe))) { + console.log("linking bin '" + exe + "'"); + fs.symlinkSync( + path.join("..", packageObj.name, packageObj.directories.bin, exe), + path.join(nodeModules, ".bin", exe) + ); + } + else { + console.log("skipping non-existent bin '" + exe + "'"); + } + }) + } + ''; + }; + + prepareAndInvokeNPM = {packageName, bypassCache, reconstructLock, npmFlags, production}: + let + forceOfflineFlag = if bypassCache then "--offline" else "--registry http://www.example.com"; + in + '' + # Pinpoint the versions of all dependencies to the ones that are actually being used + echo "pinpointing versions of dependencies..." + source $pinpointDependenciesScriptPath + + # Patch the shebangs of the bundled modules to prevent them from + # calling executables outside the Nix store as much as possible + patchShebangs . + + # Deploy the Node.js package by running npm install. Since the + # dependencies have been provided already by ourselves, it should not + # attempt to install them again, which is good, because we want to make + # it Nix's responsibility. If it needs to install any dependencies + # anyway (e.g. because the dependency parameters are + # incomplete/incorrect), it fails. + # + # The other responsibilities of NPM are kept -- version checks, build + # steps, postprocessing etc. + + export HOME=$TMPDIR + cd "${packageName}" + runHook preRebuild + + ${lib.optionalString bypassCache '' + ${lib.optionalString reconstructLock '' + if [ -f package-lock.json ] + then + echo "WARNING: Reconstruct lock option enabled, but a lock file already exists!" + echo "This will most likely result in version mismatches! We will remove the lock file and regenerate it!" + rm package-lock.json + else + echo "No package-lock.json file found, reconstructing..." + fi + + node ${reconstructPackageLock} + ''} + + node ${addIntegrityFieldsScript} + ''} + + npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${lib.optionalString production "--production"} rebuild + + runHook postRebuild + + if [ "''${dontNpmInstall-}" != "1" ] + then + # NPM tries to download packages even when they already exist if npm-shrinkwrap is used. + rm -f npm-shrinkwrap.json + + npm ${forceOfflineFlag} --nodedir=${nodeSources} --no-bin-links --ignore-scripts ${npmFlags} ${lib.optionalString production "--production"} install + fi + + # Link executables defined in package.json + node ${linkBinsScript} + ''; + + # Builds and composes an NPM package including all its dependencies + buildNodePackage = + { name + , packageName + , version ? null + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , preRebuild ? "" + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , meta ? {} + , ... }@args: + + let + extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "preRebuild" "unpackPhase" "buildPhase" "meta" ]; + in + stdenv.mkDerivation ({ + name = "${name}${if version == null then "" else "-${version}"}"; + buildInputs = [ tarWrapper python nodejs ] + ++ lib.optional (stdenv.isLinux) utillinux + ++ lib.optional (stdenv.isDarwin) libtool + ++ buildInputs; + + inherit nodejs; + + inherit dontStrip; # Stripping may fail a build for some package deployments + inherit dontNpmInstall preRebuild unpackPhase buildPhase; + + compositionScript = composePackage args; + pinpointDependenciesScript = pinpointDependenciesOfPackage args; + + passAsFile = [ "compositionScript" "pinpointDependenciesScript" ]; + + installPhase = '' + source ${installPackage} + + # Create and enter a root node_modules/ folder + mkdir -p $out/lib/node_modules + cd $out/lib/node_modules + + # Compose the package and all its dependencies + source $compositionScriptPath + + ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }} + + # Create symlink to the deployed executable folder, if applicable + if [ -d "$out/lib/node_modules/.bin" ] + then + ln -s $out/lib/node_modules/.bin $out/bin + + # Fixup all executables + ls $out/bin/* | while read i + do + file="$(readlink -f "$i")" + chmod u+rwx "$file" + if isScript "$file" + then + sed -i 's/\r$//' "$file" # convert crlf to lf + fi + done + fi + + # Create symlinks to the deployed manual page folders, if applicable + if [ -d "$out/lib/node_modules/${packageName}/man" ] + then + mkdir -p $out/share + for dir in "$out/lib/node_modules/${packageName}/man/"* + do + mkdir -p $out/share/man/$(basename "$dir") + for page in "$dir"/* + do + ln -s $page $out/share/man/$(basename "$dir") + done + done + fi + + # Run post install hook, if provided + runHook postInstall + ''; + + meta = { + # default to Node.js' platforms + platforms = nodejs.meta.platforms; + } // meta; + } // extraArgs); + + # Builds a node environment (a node_modules folder and a set of binaries) + buildNodeDependencies = + { name + , packageName + , version ? null + , src + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , ... }@args: + + let + extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" ]; + in + stdenv.mkDerivation ({ + name = "node-dependencies-${name}${if version == null then "" else "-${version}"}"; + + buildInputs = [ tarWrapper python nodejs ] + ++ lib.optional (stdenv.isLinux) utillinux + ++ lib.optional (stdenv.isDarwin) libtool + ++ buildInputs; + + inherit dontStrip; # Stripping may fail a build for some package deployments + inherit dontNpmInstall unpackPhase buildPhase; + + includeScript = includeDependencies { inherit dependencies; }; + pinpointDependenciesScript = pinpointDependenciesOfPackage args; + + passAsFile = [ "includeScript" "pinpointDependenciesScript" ]; + + installPhase = '' + source ${installPackage} + + mkdir -p $out/${packageName} + cd $out/${packageName} + + source $includeScriptPath + + # Create fake package.json to make the npm commands work properly + cp ${src}/package.json . + chmod 644 package.json + ${lib.optionalString bypassCache '' + if [ -f ${src}/package-lock.json ] + then + cp ${src}/package-lock.json . + chmod 644 package-lock.json + fi + ''} + + # Go to the parent folder to make sure that all packages are pinpointed + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + + ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }} + + # Expose the executables that were installed + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + + mv ${packageName} lib + ln -s $out/lib/node_modules/.bin $out/bin + ''; + } // extraArgs); + + # Builds a development shell + buildNodeShell = + { name + , packageName + , version ? null + , src + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , ... }@args: + + let + nodeDependencies = buildNodeDependencies args; + extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "unpackPhase" "buildPhase" ]; + in + stdenv.mkDerivation ({ + name = "node-shell-${name}${if version == null then "" else "-${version}"}"; + + buildInputs = [ python nodejs ] ++ lib.optional (stdenv.isLinux) utillinux ++ buildInputs; + buildCommand = '' + mkdir -p $out/bin + cat > $out/bin/shell < { + log.verbose("Received new reaction"); -- cgit v1.2.3