Files
nix-stuff/validate-matrix-user-id.nix
2025-04-29 00:57:01 -07:00

34 lines
1.3 KiB
Nix

{ lib }:
let
inherit (lib) length isString substring optional elemAt match;
in
userId:
assert isString userId;
let
splitOnColon = lib.splitString ":" userId;
# https://spec.matrix.org/v1.14/appendices/#user-identifiers
errors = []
# "The length of a user ID, including the @ sigil and the domain, MUST NOT exceed 255 bytes."
++ optional ((length userId) > 255) "must be 255 bytes or shorter"
++ optional ((substring 0 1 userId) != "@") "must start with an @ symbol"
++ optional ((length splitOnColon) < 2) "must have a : inbetween the username and the server"
++ optional ((length splitOnColon) > 3) "too many : symbols"
++ if (length splitOnColon) < 2 || (length splitOnColon) > 3 then [] else (
let
localpart_with_at = elemAt splitOnColon 0;
localpart = substring 1 -1 localpart_with_at;
domain = elemAt splitOnColon 1;
port = if (length splitOnColon) == 3 then elemAt splitOnColon 2 else null;
in
[]
++ optional ((length localpart) == 0) "username is missing"
++ optional ((match "[0-9a-z+/_=.-]+" localpart) == null) "username must only contain digits 0-9, lowercase letters a-z, and any of the symbols +/_=.-"
++ optional (
)
;
in
{
inherit errors;
valid = (length errors) == 0;
}