Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/apps/api/Accounts/AccountNamePolicy.cs
blob: fd969845716a35f844b91c5ef8772fcb8d8c4aa3 (plain)
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
// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.0

using System.Collections.Frozen;
using System.Text.RegularExpressions;

namespace Progmasoft.Progmaweb.Api.Accounts;

internal static partial class AccountNamePolicy
{
    public const int MinimumLength = 8;
    public const int MaximumLength = 128;

    // These names identify Progmasoft itself and the initial administrative identity. They are provisioned only by
    // trusted operations tooling, never by the public registration endpoint.
    private static readonly FrozenSet<string> ReservedNames =
        new[] { "LEITWOLF", "PROGMASOFT" }.ToFrozenSet(StringComparer.Ordinal);

    [GeneratedRegex("^[A-Z][A-Za-z0-9]{7,127}$", RegexOptions.CultureInvariant)]
    private static partial Regex CanonicalPattern();

    public static bool TryNormalize(string? value, out string canonical, out string error)
    {
        canonical = value?.Trim() ?? string.Empty;

        if (canonical.Length is < MinimumLength or > MaximumLength)
        {
            error = $"Account names must contain {MinimumLength}–{MaximumLength} characters.";
            return false;
        }

        if (!CanonicalPattern().IsMatch(canonical))
        {
            error = "Account names must begin with an uppercase ASCII letter and contain only ASCII letters or digits.";
            return false;
        }

        if (ReservedNames.Contains(NormalizeForLookup(canonical)))
        {
            error = "That account name is reserved.";
            return false;
        }

        error = string.Empty;
        return true;
    }

    public static string NormalizeForLookup(string canonical) => canonical.ToUpperInvariant();
}