mirror of
https://github.com/DorkSquadRR/DorkNet.git
synced 2026-10-26 07:28:45 -07:00
327dcb789c
Audits every route the March-2023 client can call against what this server
actually serves, and fixes the defects that were breaking gameplay. Adds
docs/recroom-2023-client-api-complete.md as the reference: ~500 route
literals across 13 subsystems, with verb, request/response shape, and a
per-subsystem diff. 315 defects catalogued; the ones fixed here are listed
in its "Already fixed" table.
Path coverage was never the problem — 465 of 506 routes already had
handlers. The failures were in shape, and they cluster into four causes:
- Wrong verb. The verb is a BestHTTP.HTTPMethods ordinal (GET=0 .. PATCH=5),
confirmed from that enum's static constructor. Routes registered POST-only
while the client PUTs returned 405, which made room consumables neither
buyable nor consumable and blocked every room-key edit.
- Bare scalar wrapped in an object. The client reads `1000`, not
`{"Limit":1000}`; the issuing method signature says which. Wrapping makes
the deserializer throw and the feature dies silently.
- [FromBody] vs form-urlencoded. The client sends nearly every write as form
data, which an [ApiController] action bound [FromBody] rejects with 415
before the handler runs. This alone broke all 13 club member-management
endpoints. Adds Binding/FormOrJsonModelBinder so this is fixed once.
- Notify dispatch keys. Both enum overloads of the client's RegisterHandler
lower the id via Int32.ToString() and register only that numeric key, and
lookup is a case-sensitive TryGetValue that returns silently on a miss. We
were sending the enum NAME for most ids, so friend-request updates, forced
logout, maintenance broadcasts, live balance and consumable updates, and
invention moderation pushes all evaporated with no error anywhere.
Notable behavioural bugs fixed:
- Editing a club announcement deleted it: PUT was a third binding on the
delete handler. Split apart, and the missing create route added.
- leaderboard/CheckAndSetStat did not exist. The 2023 client has no SetStat
literal at all, so every leaderboard score it wrote was discarded.
- Setting a club clubhouse cleared it: the handler read roomId from the query
while the client sends it in the body, then wrote the resulting null.
- Club join requests were inverted (the enum is Open=0, InviteOnly=1,
AskToJoin=2), so ask-to-join clubs rejected everyone and invite-only clubs
quietly admitted them.
- Room bans were pushed as id 24, for which the client registers no handler;
they now go out as ModerationKick with IsBan, so the ban takes effect
immediately instead of at next login.
- Room-key ownership queries answered for the wrong player, and "has anyone
bought this key" asked "did I buy it" — always false for the creator.
Also persists settings that were previously acknowledged and dropped
(playlist accessibility/restrictions/level-voting/warning, per-player status
visibility, VR movement mode and avoid-juniors, custom room codes), which is
what the new columns in the migration are for.
One test asserted the old nested PriceAndCurrency response shape; the
client's consumable formatter has no such key and reads Price and
PurchaseCurrencyId flat, so the test was corrected alongside the handler.
143 lines
5.9 KiB
C#
143 lines
5.9 KiB
C#
using System.Reflection;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
|
|
|
namespace DorkNet.Server.Binding;
|
|
|
|
/// <summary>
|
|
/// Binds an action's request DTO from either a form-urlencoded body or a JSON
|
|
/// body, whichever the caller actually sent.
|
|
///
|
|
/// The Rec Room client's HTTP layer (<c>BNDIAONDFFF</c> in RecNet.Runtime)
|
|
/// sends nearly every write as <c>application/x-www-form-urlencoded</c>, adding
|
|
/// fields one at a time. Handlers written against <c>[FromBody]</c> only accept
|
|
/// JSON, so with <c>[ApiController]</c> those requests were rejected with 415
|
|
/// Unsupported Media Type before the action body ever ran — this is why every
|
|
/// club member-management action (invite, ban, kick, promote, approve, modify)
|
|
/// failed on the 2023 client.
|
|
///
|
|
/// Rather than hand-rolling a form reader per handler, apply this binder to the
|
|
/// DTO parameter:
|
|
///
|
|
/// <code>
|
|
/// public Task<IActionResult> MemberBan(
|
|
/// long clubId,
|
|
/// [ModelBinder(typeof(FormOrJsonModelBinder))] MemberTargetRequest req)
|
|
/// </code>
|
|
///
|
|
/// The explicit <c>[ModelBinder]</c> is required: without it <c>[ApiController]</c>
|
|
/// infers <c>[FromBody]</c> for complex types and this binder never runs.
|
|
///
|
|
/// Matching is case-insensitive on both paths, and a scalar property also
|
|
/// accepts the singular/plural spellings the client uses interchangeably. A
|
|
/// missing or unparseable body yields a default-constructed DTO rather than a
|
|
/// 400, matching how the client treats these calls as fire-and-forget.
|
|
/// </summary>
|
|
public sealed class FormOrJsonModelBinder : IModelBinder
|
|
{
|
|
public async Task BindModelAsync(ModelBindingContext bindingContext)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(bindingContext);
|
|
|
|
var type = bindingContext.ModelType;
|
|
var request = bindingContext.HttpContext.Request;
|
|
var model = Activator.CreateInstance(type)!;
|
|
|
|
if (request.HasFormContentType)
|
|
{
|
|
var form = await request.ReadFormAsync(bindingContext.HttpContext.RequestAborted);
|
|
foreach (var prop in Writable(type))
|
|
{
|
|
var values = Lookup(form, prop.Name);
|
|
if (values.Count == 0) continue;
|
|
var converted = Convert(values, prop.PropertyType);
|
|
if (converted is not null) prop.SetValue(model, converted);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{
|
|
request.EnableBuffering();
|
|
request.Body.Position = 0;
|
|
var parsed = await JsonSerializer.DeserializeAsync(
|
|
request.Body, type,
|
|
new JsonSerializerOptions { PropertyNameCaseInsensitive = true },
|
|
bindingContext.HttpContext.RequestAborted);
|
|
request.Body.Position = 0;
|
|
if (parsed is not null) model = parsed;
|
|
}
|
|
catch (JsonException) { /* empty or non-JSON body → defaults */ }
|
|
catch (NotSupportedException) { /* unreadable body → defaults */ }
|
|
}
|
|
|
|
bindingContext.Result = ModelBindingResult.Success(model);
|
|
}
|
|
|
|
private static IEnumerable<PropertyInfo> Writable(Type type) =>
|
|
type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
|
.Where(p => p.CanWrite);
|
|
|
|
/// <summary>Form keys, case-insensitively, also accepting the other
|
|
/// number of the name — the client says <c>accountId</c> where the DTO says
|
|
/// <c>AccountIds</c> and vice versa depending on the endpoint.</summary>
|
|
private static List<string> Lookup(IFormCollection form, string propertyName)
|
|
{
|
|
var candidates = new List<string> { propertyName };
|
|
if (propertyName.EndsWith('s')) candidates.Add(propertyName[..^1]);
|
|
else candidates.Add(propertyName + "s");
|
|
|
|
foreach (var candidate in candidates)
|
|
{
|
|
foreach (var key in form.Keys)
|
|
{
|
|
if (!string.Equals(key, candidate, StringComparison.OrdinalIgnoreCase)) continue;
|
|
var values = form[key]
|
|
.Where(v => !string.IsNullOrWhiteSpace(v))
|
|
.Select(v => v!)
|
|
.ToList();
|
|
if (values.Count > 0) return values;
|
|
}
|
|
}
|
|
return [];
|
|
}
|
|
|
|
private static object? Convert(List<string> values, Type target)
|
|
{
|
|
var underlying = Nullable.GetUnderlyingType(target) ?? target;
|
|
|
|
if (underlying.IsGenericType && underlying.GetGenericTypeDefinition() == typeof(List<>))
|
|
{
|
|
var element = underlying.GetGenericArguments()[0];
|
|
var list = (System.Collections.IList)Activator.CreateInstance(underlying)!;
|
|
// A repeated field arrives as multiple values; a single field may
|
|
// still carry a comma-separated list.
|
|
foreach (var raw in values.SelectMany(v => v.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)))
|
|
{
|
|
var item = ConvertScalar(raw, element);
|
|
if (item is not null) list.Add(item);
|
|
}
|
|
return list.Count > 0 ? list : null;
|
|
}
|
|
|
|
return ConvertScalar(values[0], underlying);
|
|
}
|
|
|
|
private static object? ConvertScalar(string raw, Type target)
|
|
{
|
|
try
|
|
{
|
|
if (target == typeof(string)) return raw;
|
|
if (target == typeof(bool)) return bool.TryParse(raw, out var b) ? b : raw == "1";
|
|
if (target.IsEnum) return Enum.TryParse(target, raw, ignoreCase: true, out var e) ? e : null;
|
|
if (target == typeof(Guid)) return Guid.TryParse(raw, out var g) ? g : null;
|
|
if (target == typeof(DateTime)) return DateTime.TryParse(raw, out var d) ? d : null;
|
|
return System.Convert.ChangeType(raw, target, System.Globalization.CultureInfo.InvariantCulture);
|
|
}
|
|
catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
}
|