Skip to content

Commit

Permalink
simplify implementation + and actually make it work in this use case
Browse files Browse the repository at this point in the history
  • Loading branch information
TheXorog committed May 16, 2024
1 parent 6df1291 commit 7a308dc
Showing 1 changed file with 5 additions and 43 deletions.
48 changes: 5 additions & 43 deletions DisCatSharp/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,54 +97,16 @@ static Utilities()
/// </summary>
/// <param name="str">The string to remove the tokens from.</param>
/// <returns>A new string with the tokens replaced with <c>{KEY_TOKEN}</c></returns>
public static string StripTokens(string str)
public static string? StripTokens(string? str)
{
if (string.IsNullOrWhiteSpace(str))
return str;

var parts = str.Split('/');
str = Regex.Replace(str, @"([a-zA-Z0-9]{68})", "{WEBHOOK_TOKEN}");
str = Regex.Replace(str, @"^(.+):\d+?:[a-zA-Z0-9]{128}$", "{INTERACTION_TOKEN}");
str = Regex.Replace(str, @"(mfa\.[a-z0-9_-]{20,})|((?<botid>[a-z0-9_-]{23,28})\.(?<creation>[a-z0-9_-]{6,7})\.(?<enc>[a-z0-9_-]{27,}))", "{ACCOUNT_TOKEN}");

// calculate the base64 data size
var base64Size = parts.Max(x =>
{
var padding = x.EndsWith("==", StringComparison.Ordinal)
? 2
: x.EndsWith("=", StringComparison.Ordinal)
? 1
: 0;
return (Encoding.UTF8.GetByteCount(x) * (3 / 4)) - padding;
});

// allocate a buffer for any base64 decoding.
var dest = base64Size <= 1024 ? stackalloc byte[base64Size] : new byte[base64Size];

var isWebhook = parts.Contains("webhooks") || parts.Contains("webhook");

for (var i = 0; i < parts.Length; i++)
{
var part = parts[i];

if (isWebhook && Regex.IsMatch(part, @"([a-zA-Z0-9]{68})"))
{
parts[i] = "{WEBHOOK_TOKEN}";
continue;
}

if (!Convert.TryFromBase64String(part, dest, out var count))
continue;

var b64Content = Encoding.UTF8.GetString(dest[..count]);

var tokenInnersMatch = Regex.Match(b64Content, @"^(.+):\d+?:[a-zA-Z0-9]{128}$");

if (!tokenInnersMatch.Success)
continue;

// replaces the token with the {KEY}_TOKEN, ex 'interaction:USERID:TOKEN' is replaced as 'INTERACTION_TOKEN'
parts[i] = $"{{{tokenInnersMatch.Groups[1].Value.ToUpperInvariant()}_TOKEN}}";
}

return string.Join('/', parts);
return str;
}

/// <summary>
Expand Down

0 comments on commit 7a308dc

Please sign in to comment.