Authenticate CultMesh authority routes and replay operations

This commit is contained in:
Meta Vens 2026-08-18 19:02:46 +02:00
commit f622ee1b24
30 changed files with 1432 additions and 142 deletions

View file

@ -0,0 +1,349 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using GameCult.Networking;
namespace GameCult.Mesh
{
public enum CultMeshAuthorityTrustMode
{
AuthenticatedRemote,
LocalDevelopment
}
public sealed class CultMeshEcdsaP256PublicKey
{
public CultMeshEcdsaP256PublicKey(string keyId, string x, string y)
{
KeyId = Require(keyId, nameof(keyId));
X = RequireCoordinate(x, nameof(x));
Y = RequireCoordinate(y, nameof(y));
}
public string KeyId { get; }
public string X { get; }
public string Y { get; }
internal ECDsa CreateVerifier()
{
var verifier = ECDsa.Create();
verifier.ImportParameters(new ECParameters
{
Curve = ECCurve.NamedCurves.nistP256,
Q = new ECPoint { X = Convert.FromBase64String(X), Y = Convert.FromBase64String(Y) }
});
return verifier;
}
public static CultMeshEcdsaP256PublicKey From(string keyId, ECDsa key)
{
if (key == null) throw new ArgumentNullException(nameof(key));
var parameters = key.ExportParameters(false);
return new CultMeshEcdsaP256PublicKey(
keyId,
Convert.ToBase64String(parameters.Q.X ?? throw new InvalidOperationException("P-256 key has no X coordinate.")),
Convert.ToBase64String(parameters.Q.Y ?? throw new InvalidOperationException("P-256 key has no Y coordinate.")));
}
private static string RequireCoordinate(string value, string name)
{
var required = Require(value, name);
byte[] bytes;
try { bytes = Convert.FromBase64String(required); }
catch (FormatException error) { throw new ArgumentException("P-256 coordinates must be base64.", name, error); }
if (bytes.Length != 32) throw new ArgumentException("P-256 coordinates must contain 32 bytes.", name);
return required;
}
private static string Require(string value, string name) =>
string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value must be non-empty.", name) : value.Trim();
}
public sealed class CultMeshRouteCertificate
{
public CultMeshRouteCertificate(
CultMeshEcdsaP256PublicKey providerKey,
string odinKeyId,
long issuedAtUnixMilliseconds,
long expiresAtUnixMilliseconds,
string signature)
{
ProviderKey = providerKey ?? throw new ArgumentNullException(nameof(providerKey));
OdinKeyId = string.IsNullOrWhiteSpace(odinKeyId)
? throw new ArgumentException("Odin key identity is required.", nameof(odinKeyId))
: odinKeyId.Trim();
if (issuedAtUnixMilliseconds < 0) throw new ArgumentOutOfRangeException(nameof(issuedAtUnixMilliseconds));
if (expiresAtUnixMilliseconds <= issuedAtUnixMilliseconds) throw new ArgumentOutOfRangeException(nameof(expiresAtUnixMilliseconds));
IssuedAtUnixMilliseconds = issuedAtUnixMilliseconds;
ExpiresAtUnixMilliseconds = expiresAtUnixMilliseconds;
Signature = signature?.Trim() ?? string.Empty;
}
public CultMeshEcdsaP256PublicKey ProviderKey { get; }
public string OdinKeyId { get; }
public long IssuedAtUnixMilliseconds { get; }
public long ExpiresAtUnixMilliseconds { get; }
public string Signature { get; }
}
public sealed class CultMeshAuthorityTrustPolicy
{
private readonly Dictionary<string, CultMeshEcdsaP256PublicKey> _odinRoots;
public CultMeshAuthorityTrustPolicy(
CultMeshAuthorityTrustMode mode,
IEnumerable<CultMeshEcdsaP256PublicKey>? odinRoots = null)
{
Mode = mode;
_odinRoots = (odinRoots ?? Array.Empty<CultMeshEcdsaP256PublicKey>())
.ToDictionary(key => key.KeyId, StringComparer.Ordinal);
}
public CultMeshAuthorityTrustMode Mode { get; }
public IReadOnlyCollection<CultMeshEcdsaP256PublicKey> OdinRoots => _odinRoots.Values;
/// <summary>Fails closed unless the route is valid under this consumer-owned policy.</summary>
public void Validate(string verseId, CultMeshAuthorityRoute route, DateTimeOffset now) =>
Verify(verseId, route, now);
internal CultMeshVerifiedAuthorityRoute Verify(
string verseId,
CultMeshAuthorityRoute route,
DateTimeOffset now)
{
if (route == null) throw new ArgumentNullException(nameof(route));
var certificate = route.Certificate;
if (certificate == null || string.IsNullOrWhiteSpace(certificate.Signature))
{
if (Mode == CultMeshAuthorityTrustMode.LocalDevelopment && IsLoopback(route.Endpoint))
return CultMeshVerifiedAuthorityRoute.Local(route);
throw Failure(route, "Remote CultMesh routes require an Odin-signed authority certificate.");
}
if (!IsProtected(route.Endpoint) &&
!(Mode == CultMeshAuthorityTrustMode.LocalDevelopment && IsLoopback(route.Endpoint)))
throw Failure(route, "Authenticated remote CultMesh routes require TLS or QUIC channel protection.");
if (!_odinRoots.TryGetValue(certificate.OdinKeyId, out var root))
throw Failure(route, $"Odin key '{certificate.OdinKeyId}' is not trusted by this consumer.");
var nowMs = now.ToUnixTimeMilliseconds();
if (nowMs < certificate.IssuedAtUnixMilliseconds || nowMs >= certificate.ExpiresAtUnixMilliseconds)
throw Failure(route, "The Odin route certificate is not currently valid.");
byte[] signature;
try { signature = Convert.FromBase64String(certificate.Signature); }
catch (FormatException error) { throw Failure(route, "The Odin route signature is not base64.", error); }
if (signature.Length != 64) throw Failure(route, "The Odin route signature is not IEEE P1363 P-256.");
using var verifier = root.CreateVerifier();
if (!verifier.VerifyData(
CultMeshAuthorityProof.CanonicalRoute(verseId, route),
signature,
HashAlgorithmName.SHA256))
throw Failure(route, "The Odin route certificate signature is invalid.");
return CultMeshVerifiedAuthorityRoute.Authenticated(route, certificate.ProviderKey);
}
private static bool IsLoopback(string endpoint)
{
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri)) return false;
return uri.IsLoopback ||
string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase) ||
string.Equals(uri.Host, "127.0.0.1", StringComparison.Ordinal) ||
string.Equals(uri.Host, "::1", StringComparison.Ordinal);
}
private static bool IsProtected(string endpoint)
{
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri)) return false;
return string.Equals(uri.Scheme, "wss", StringComparison.OrdinalIgnoreCase) ||
string.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase) ||
uri.Scheme.IndexOf("quic", StringComparison.OrdinalIgnoreCase) >= 0;
}
private static CultMeshSessionException Failure(CultMeshAuthorityRoute route, string message, Exception? inner = null) =>
new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authentication,
message,
route.Endpoint), inner);
}
internal sealed class CultMeshVerifiedAuthorityRoute
{
private CultMeshVerifiedAuthorityRoute(
CultMeshAuthorityRoute route,
CultMeshEcdsaP256PublicKey? providerKey,
bool localDevelopment)
{
Route = route;
ProviderKey = providerKey;
IsLocalDevelopment = localDevelopment;
}
public CultMeshAuthorityRoute Route { get; }
public CultMeshEcdsaP256PublicKey? ProviderKey { get; }
public bool IsLocalDevelopment { get; }
public static CultMeshVerifiedAuthorityRoute Authenticated(CultMeshAuthorityRoute route, CultMeshEcdsaP256PublicKey key) => new(route, key, false);
public static CultMeshVerifiedAuthorityRoute Local(CultMeshAuthorityRoute route) => new(route, null, true);
}
public sealed class CultMeshSessionProofSigner
{
private readonly ECDsa _key;
public CultMeshSessionProofSigner(CultMeshAuthorityRoute route, ECDsa providerPrivateKey)
{
Route = route ?? throw new ArgumentNullException(nameof(route));
_key = providerPrivateKey ?? throw new ArgumentNullException(nameof(providerPrivateKey));
var certificate = route.Certificate ?? throw new ArgumentException("A session proof signer requires a certified route.", nameof(route));
ProviderKeyId = certificate.ProviderKey.KeyId;
var exported = CultMeshEcdsaP256PublicKey.From(ProviderKeyId, _key);
if (!string.Equals(exported.X, certificate.ProviderKey.X, StringComparison.Ordinal) ||
!string.Equals(exported.Y, certificate.ProviderKey.Y, StringComparison.Ordinal))
throw new ArgumentException("Provider private key does not match the certified route key.", nameof(providerPrivateKey));
}
public CultMeshAuthorityRoute Route { get; }
public string ProviderKeyId { get; }
public string Sign(CultMeshSessionOpenMessage request)
{
var bytes = CultMeshAuthorityProof.CanonicalSession(request, Route.Endpoint);
return Convert.ToBase64String(CultMeshAuthorityProof.SignP256(_key, bytes));
}
}
public static class CultMeshAuthorityProof
{
private const string RouteDomain = "gamecult.cultmesh.route-certificate.v1";
private const string SessionDomain = "gamecult.cultmesh.session-proof.v1";
public static CultMeshAuthorityRoute CreateSignedRoute(
string verseId,
string authorityRuntimeId,
string endpoint,
IEnumerable<string> protocolIds,
int priority,
string generation,
CultMeshEcdsaP256PublicKey providerKey,
string odinKeyId,
DateTimeOffset issuedAt,
DateTimeOffset expiresAt,
ECDsa odinPrivateKey)
{
if (odinPrivateKey == null) throw new ArgumentNullException(nameof(odinPrivateKey));
var unsignedCertificate = new CultMeshRouteCertificate(
providerKey,
odinKeyId,
issuedAt.ToUnixTimeMilliseconds(),
expiresAt.ToUnixTimeMilliseconds(),
string.Empty);
var unsignedRoute = new CultMeshAuthorityRoute(
authorityRuntimeId, endpoint, protocolIds, priority, generation, unsignedCertificate);
var signature = Convert.ToBase64String(SignP256(
odinPrivateKey,
CanonicalRoute(verseId, unsignedRoute)));
return new CultMeshAuthorityRoute(
authorityRuntimeId,
endpoint,
protocolIds,
priority,
generation,
new CultMeshRouteCertificate(
providerKey,
odinKeyId,
issuedAt.ToUnixTimeMilliseconds(),
expiresAt.ToUnixTimeMilliseconds(),
signature));
}
/// <summary>Verifies both the Odin route certificate and provider nonce proof.</summary>
public static bool VerifySessionProof(
CultMeshSessionOpenMessage request,
CultMeshSessionAcceptedMessage response,
string verseId,
CultMeshAuthorityRoute route,
CultMeshAuthorityTrustPolicy trust,
DateTimeOffset now)
{
if (request == null) throw new ArgumentNullException(nameof(request));
if (response == null) throw new ArgumentNullException(nameof(response));
if (trust == null) throw new ArgumentNullException(nameof(trust));
return VerifySession(request, response, trust.Verify(verseId, route, now));
}
internal static byte[] CanonicalRoute(string verseId, CultMeshAuthorityRoute route)
{
var certificate = route.Certificate ?? throw new InvalidOperationException("Route certificate is required.");
return Canonical(
RouteDomain,
verseId,
route.AuthorityRuntimeId,
route.Endpoint,
string.Join("\u001f", route.ProtocolIds.OrderBy(value => value, StringComparer.Ordinal)),
route.Priority.ToString(System.Globalization.CultureInfo.InvariantCulture),
route.Generation,
certificate.ProviderKey.KeyId,
certificate.ProviderKey.X,
certificate.ProviderKey.Y,
certificate.OdinKeyId,
certificate.IssuedAtUnixMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture),
certificate.ExpiresAtUnixMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
internal static byte[] CanonicalSession(CultMeshSessionOpenMessage request, string endpoint) => Canonical(
SessionDomain,
request.ClientNonce ?? string.Empty,
request.MessageId ?? string.Empty,
request.SourceRuntimeId ?? string.Empty,
request.VerseId ?? string.Empty,
request.AuthorityRuntimeId ?? string.Empty,
request.ProtocolId ?? string.Empty,
endpoint ?? string.Empty,
request.RouteGeneration ?? string.Empty);
internal static bool VerifySession(
CultMeshSessionOpenMessage request,
CultMeshSessionAcceptedMessage response,
CultMeshVerifiedAuthorityRoute route)
{
if (route.IsLocalDevelopment) return true;
if (route.ProviderKey == null ||
!string.Equals(response.ProviderKeyId, route.ProviderKey.KeyId, StringComparison.Ordinal) ||
!string.Equals(response.ClientNonce, request.ClientNonce, StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(response.ProviderSignature))
return false;
byte[] signature;
try { signature = Convert.FromBase64String(response.ProviderSignature); }
catch (FormatException) { return false; }
if (signature.Length != 64) return false;
using var verifier = route.ProviderKey.CreateVerifier();
return verifier.VerifyData(
CanonicalSession(request, route.Route.Endpoint),
signature,
HashAlgorithmName.SHA256);
}
internal static byte[] SignP256(ECDsa key, byte[] payload)
{
var signature = key.SignData(payload, HashAlgorithmName.SHA256);
if (signature.Length != 64)
throw new CryptographicException("ECDSA provider did not emit IEEE P1363 P-256 signature bytes.");
return signature;
}
private static byte[] Canonical(params string[] values)
{
using var stream = new MemoryStream();
var length = new byte[4];
foreach (var value in values)
{
var bytes = Encoding.UTF8.GetBytes(value ?? string.Empty);
BinaryPrimitives.WriteInt32BigEndian(length, bytes.Length);
stream.Write(length, 0, length.Length);
stream.Write(bytes, 0, bytes.Length);
}
return stream.ToArray();
}
}
}

View file

@ -136,7 +136,9 @@ namespace GameCult.Mesh
"cultmesh-content-client",
target,
CultMeshProtocols.Content,
candidate.Generation,
candidate,
null,
_options.Clock.UtcNow,
_options.ResponseTimeout,
cancellationToken).ConfigureAwait(false);
return new LegacyRudpContentTransport(

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Networking;
@ -68,6 +69,7 @@ namespace GameCult.Mesh
private readonly HashSet<string> _verseIds;
private readonly HashSet<string> _protocolIds;
private readonly HashSet<string> _routeGenerations;
private readonly Dictionary<string, CultMeshSessionProofSigner> _proofSigners;
private readonly Func<CultMeshSessionOpenMessage, ICultNetSchemaServerPeer, Task> _handler;
private bool _disposed;
@ -76,13 +78,16 @@ namespace GameCult.Mesh
string authorityRuntimeId,
IEnumerable<string> verseIds,
IEnumerable<string> protocolIds,
IEnumerable<string> routeGenerations)
IEnumerable<string> routeGenerations,
IEnumerable<CultMeshSessionProofSigner>? proofSigners = null)
{
_server = server ?? throw new ArgumentNullException(nameof(server));
_authorityRuntimeId = Require(authorityRuntimeId, nameof(authorityRuntimeId));
_verseIds = Clean(verseIds, nameof(verseIds));
_protocolIds = Clean(protocolIds, nameof(protocolIds));
_routeGenerations = Clean(routeGenerations, nameof(routeGenerations));
_proofSigners = (proofSigners ?? Array.Empty<CultMeshSessionProofSigner>())
.ToDictionary(signer => signer.Route.Generation, StringComparer.Ordinal);
_handler = HandleAsync;
_server.OnCultNet(_handler);
}
@ -97,6 +102,7 @@ namespace GameCult.Mesh
private Task HandleAsync(CultMeshSessionOpenMessage request, ICultNetSchemaServerPeer peer)
{
var error = Validate(request);
_proofSigners.TryGetValue(request.RouteGeneration ?? string.Empty, out var signer);
peer.SendCultNet(new CultMeshSessionAcceptedMessage
{
MessageId = request.MessageId ?? string.Empty,
@ -105,6 +111,9 @@ namespace GameCult.Mesh
AuthorityRuntimeId = _authorityRuntimeId,
ProtocolId = request.ProtocolId ?? string.Empty,
RouteGeneration = request.RouteGeneration ?? string.Empty,
ClientNonce = request.ClientNonce ?? string.Empty,
ProviderKeyId = error == null ? signer?.ProviderKeyId ?? string.Empty : string.Empty,
ProviderSignature = error == null && signer != null ? signer.Sign(request) : string.Empty,
Error = error
});
return Task.CompletedTask;
@ -114,6 +123,7 @@ namespace GameCult.Mesh
{
if (string.IsNullOrWhiteSpace(request.MessageId)) return "session-message-id-required";
if (string.IsNullOrWhiteSpace(request.SourceRuntimeId)) return "source-runtime-id-required";
if (!TryNonce(request.ClientNonce)) return "client-nonce-invalid";
if (!string.Equals(request.AuthorityRuntimeId, _authorityRuntimeId, StringComparison.Ordinal))
return "target-runtime-mismatch";
if (!_verseIds.Contains(request.VerseId ?? string.Empty)) return "verse-not-served";
@ -122,6 +132,13 @@ namespace GameCult.Mesh
return null;
}
private static bool TryNonce(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return false;
try { return Convert.FromBase64String(value).Length == 32; }
catch (FormatException) { return false; }
}
private static HashSet<string> Clean(IEnumerable<string> values, string name)
{
if (values == null) throw new ArgumentNullException(name);
@ -145,26 +162,45 @@ namespace GameCult.Mesh
string sourceRuntimeId,
CultMeshSessionTarget target,
CultMeshProtocolId protocol,
string routeGeneration,
CultMeshTransportCandidate candidate,
CultMeshAuthorityTrustPolicy? trust,
DateTimeOffset now,
TimeSpan timeout,
CancellationToken cancellationToken = default)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
var route = candidate.AuthorityRoute ?? new CultMeshAuthorityRoute(
target.AuthorityRuntimeId,
candidate.Endpoint,
new[] { protocol.Value },
candidate.Priority,
candidate.Generation);
var verifiedRoute = candidate.VerifiedAuthority ??
(trust ?? throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authentication,
"No consumer trust policy verified this CultMesh route.",
candidate.Endpoint))).Verify(target.VerseId, route, now);
if (client is ICultMeshVerifiedSchemaClient verified)
{
if (!verified.IsVerifiedFor(
target.VerseId,
target.AuthorityRuntimeId,
protocol.Value,
routeGeneration ?? string.Empty))
candidate.Generation))
{
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"Native transport identity did not match CultMesh target '{target}' for '{protocol}'."));
}
return;
// Native identity is sufficient only for an explicitly selected
// loopback development route. Remote schema sessions still prove
// possession of the provider key certified by Odin.
if (verifiedRoute.IsLocalDevelopment) return;
}
var messageId = Guid.NewGuid().ToString("N");
var nonce = new byte[32];
using (var random = RandomNumberGenerator.Create()) random.GetBytes(nonce);
var completion = new TaskCompletionSource<CultMeshSessionAcceptedMessage>(
TaskCreationOptions.RunContinuationsAsynchronously);
client.OnCultNet<CultMeshSessionAcceptedMessage>(response =>
@ -172,15 +208,17 @@ namespace GameCult.Mesh
if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal))
completion.TrySetResult(response);
});
client.SendCultNet(new CultMeshSessionOpenMessage
var request = new CultMeshSessionOpenMessage
{
MessageId = messageId,
SourceRuntimeId = sourceRuntimeId,
VerseId = target.VerseId,
AuthorityRuntimeId = target.AuthorityRuntimeId,
ProtocolId = protocol.Value,
RouteGeneration = routeGeneration ?? string.Empty
});
RouteGeneration = candidate.Generation,
ClientNonce = Convert.ToBase64String(nonce)
};
client.SendCultNet(request);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(timeout);
@ -201,7 +239,8 @@ namespace GameCult.Mesh
!string.Equals(accepted.VerseId, target.VerseId, StringComparison.Ordinal) ||
!string.Equals(accepted.AuthorityRuntimeId, target.AuthorityRuntimeId, StringComparison.Ordinal) ||
!string.Equals(accepted.ProtocolId, protocol.Value, StringComparison.Ordinal) ||
!string.Equals(accepted.RouteGeneration, routeGeneration ?? string.Empty, StringComparison.Ordinal))
!string.Equals(accepted.RouteGeneration, candidate.Generation, StringComparison.Ordinal) ||
!CultMeshAuthorityProof.VerifySession(request, accepted, verifiedRoute))
{
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,

View file

@ -86,19 +86,28 @@ namespace GameCult.Mesh
CultMeshTransportPathKind pathKind = CultMeshTransportPathKind.Direct,
int priority = 0,
string authorityRuntimeId = "",
string generation = "")
string generation = "",
CultMeshAuthorityRoute? authorityRoute = null)
{
Endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Physical endpoint is required.", nameof(endpoint)) : endpoint;
PathKind = pathKind;
Priority = priority;
AuthorityRuntimeId = authorityRuntimeId?.Trim() ?? string.Empty;
Generation = generation?.Trim() ?? string.Empty;
AuthorityRoute = authorityRoute;
}
public string Endpoint { get; }
public CultMeshTransportPathKind PathKind { get; }
public int Priority { get; }
public string AuthorityRuntimeId { get; }
public string Generation { get; }
public CultMeshAuthorityRoute? AuthorityRoute { get; }
internal CultMeshVerifiedAuthorityRoute? VerifiedAuthority { get; private set; }
internal CultMeshTransportCandidate WithVerifiedAuthority(CultMeshVerifiedAuthorityRoute verified)
{
VerifiedAuthority = verified ?? throw new ArgumentNullException(nameof(verified));
return this;
}
}
public enum CultMeshSessionStatus { Connecting, Online, Degraded, Reconnecting, Offline }
@ -534,6 +543,9 @@ namespace GameCult.Mesh
public int MaxRacedCandidates { get; set; } = 2;
public string RuntimeId { get; set; } = "cultmesh-client";
public TimeSpan IdentityHandshakeTimeout { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>Gets or sets the consumer-owned trust roots and explicit local-development policy.</summary>
public CultMeshAuthorityTrustPolicy Trust { get; set; } = new(
CultMeshAuthorityTrustMode.AuthenticatedRemote);
}
public sealed class CultMeshSessionManager : IDisposable
@ -1039,7 +1051,9 @@ namespace GameCult.Mesh
_options.RuntimeId,
target,
protocol,
route.Candidate.Generation,
route.Candidate,
_options.Trust,
_options.Clock.UtcNow,
_options.IdentityHandshakeTimeout).ConfigureAwait(false);
return new ConnectedPath(route.Candidate, client);
}
@ -1065,7 +1079,7 @@ namespace GameCult.Mesh
private CultMeshSessionException Failure(CultMeshSessionFailureReason reason, string message, Exception? inner = null) =>
new CultMeshSessionException(new CultMeshSessionFailure(reason, message), inner);
private static CultMeshTransportCandidate[] BoundCandidates(
private CultMeshTransportCandidate[] BoundCandidates(
CultMeshDiscoveryState discovery,
CultMeshSessionTarget target,
CultMeshProtocolId protocol)
@ -1080,10 +1094,15 @@ namespace GameCult.Mesh
.GroupBy(route => route.Endpoint, StringComparer.Ordinal)
.Select(group => group.OrderBy(route => route.Priority).First())
.Select(route => new CultMeshTransportCandidate(
route.Endpoint,
priority: route.Priority,
authorityRuntimeId: route.AuthorityRuntimeId,
generation: route.Generation))
route.Endpoint,
priority: route.Priority,
authorityRuntimeId: route.AuthorityRuntimeId,
generation: route.Generation,
authorityRoute: route)
.WithVerifiedAuthority(_options.Trust.Verify(
target.VerseId,
route,
_options.Clock.UtcNow)))
.OrderBy(candidate => candidate.Priority)
.ThenBy(candidate => candidate.Endpoint, StringComparer.Ordinal)
.ToArray();

View file

@ -17,6 +17,7 @@ namespace GameCult.Mesh
public string VerseId { get; set; } = string.Empty;
public string AuthorityRuntimeId { get; set; } = string.Empty;
public string RouteGeneration { get; set; } = string.Empty;
public CultMeshSessionProofSigner? ProofSigner { get; set; }
internal void Validate()
{
@ -344,7 +345,10 @@ namespace GameCult.Mesh
var requestBytes = await CultMeshTcpContentWire.ReadFrameAsync(stream, cancellationToken).ConfigureAwait(false);
var request = CultNetSchemaMessageSerialization.Deserialize(requestBytes) as CultMeshSessionOpenMessage
?? throw new InvalidDataException("TCP content session did not begin with an authority handshake.");
var accepted = string.Equals(request.VerseId, _options.VerseId, StringComparison.Ordinal) &&
var accepted = !string.IsNullOrWhiteSpace(request.MessageId) &&
!string.IsNullOrWhiteSpace(request.SourceRuntimeId) &&
IsNonce(request.ClientNonce) &&
string.Equals(request.VerseId, _options.VerseId, StringComparison.Ordinal) &&
string.Equals(request.AuthorityRuntimeId, _options.AuthorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(request.ProtocolId, CultMeshProtocols.Content.Value, StringComparison.Ordinal) &&
string.Equals(request.RouteGeneration, _options.RouteGeneration, StringComparison.Ordinal);
@ -356,6 +360,11 @@ namespace GameCult.Mesh
AuthorityRuntimeId = _options.AuthorityRuntimeId,
ProtocolId = CultMeshProtocols.Content.Value,
RouteGeneration = _options.RouteGeneration,
ClientNonce = request.ClientNonce ?? string.Empty,
ProviderKeyId = accepted ? _options.ProofSigner?.ProviderKeyId ?? string.Empty : string.Empty,
ProviderSignature = accepted && _options.ProofSigner != null
? _options.ProofSigner.Sign(request)
: string.Empty,
Error = accepted ? null : "Content session target does not match this authority route."
};
await CultMeshTcpContentWire.WriteFrameAsync(
@ -365,6 +374,13 @@ namespace GameCult.Mesh
return accepted;
}
private static bool IsNonce(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return false;
try { return Convert.FromBase64String(value).Length == 32; }
catch (FormatException) { return false; }
}
private async Task SendChunkAsync(
Stream stream,
CultMeshContentChunkRequestMessage request,
@ -473,7 +489,8 @@ namespace GameCult.Mesh
VerseId = target.VerseId,
AuthorityRuntimeId = target.AuthorityRuntimeId,
ProtocolId = CultMeshProtocols.Content.Value,
RouteGeneration = candidate.Generation
RouteGeneration = candidate.Generation,
ClientNonce = CreateNonce()
};
await WriteFrameAsync(stream, CultNetSchemaMessageSerialization.Serialize(request), cancellationToken)
.ConfigureAwait(false);
@ -485,13 +502,22 @@ namespace GameCult.Mesh
!string.Equals(response.VerseId, target.VerseId, StringComparison.Ordinal) ||
!string.Equals(response.AuthorityRuntimeId, target.AuthorityRuntimeId, StringComparison.Ordinal) ||
!string.Equals(response.ProtocolId, CultMeshProtocols.Content.Value, StringComparison.Ordinal) ||
!string.Equals(response.RouteGeneration, candidate.Generation, StringComparison.Ordinal))
!string.Equals(response.RouteGeneration, candidate.Generation, StringComparison.Ordinal) ||
candidate.VerifiedAuthority == null ||
!CultMeshAuthorityProof.VerifySession(request, response, candidate.VerifiedAuthority))
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
response.Error ?? "TCP content endpoint did not prove the selected authority route.",
candidate.Endpoint));
}
private static string CreateNonce()
{
var nonce = new byte[32];
using (var random = System.Security.Cryptography.RandomNumberGenerator.Create()) random.GetBytes(nonce);
return Convert.ToBase64String(nonce);
}
public static async Task<byte[]> ReadFrameAsync(Stream stream, CancellationToken cancellationToken)
{
var header = new byte[HeaderBytes];

View file

@ -102,7 +102,8 @@ namespace GameCult.Mesh
string endpoint,
IEnumerable<string>? protocolIds = null,
int priority = 0,
string? generation = null)
string? generation = null,
CultMeshRouteCertificate? certificate = null)
{
AuthorityRuntimeId = RequireNonEmpty(authorityRuntimeId, nameof(authorityRuntimeId));
Endpoint = RequireNonEmpty(endpoint, nameof(endpoint));
@ -112,6 +113,7 @@ namespace GameCult.Mesh
Generation = string.IsNullOrWhiteSpace(generation)
? AuthorityRuntimeId + "@" + Endpoint
: generation!.Trim();
Certificate = certificate;
}
public string AuthorityRuntimeId { get; }
@ -119,6 +121,8 @@ namespace GameCult.Mesh
public IReadOnlyList<string> ProtocolIds { get; }
public int Priority { get; }
public string Generation { get; }
/// <summary>Gets the optional Odin-signed binding from this route to its provider key.</summary>
public CultMeshRouteCertificate? Certificate { get; }
public bool Supports(CultMeshProtocolId protocol) =>
protocol != null &&

View file

@ -39,7 +39,17 @@ namespace GameCult.Mesh
Endpoint = route.Endpoint,
ProtocolIds = route.ProtocolIds.ToArray(),
Priority = route.Priority,
Generation = route.Generation
Generation = route.Generation,
Certificate = route.Certificate == null ? null : new CultMeshRouteCertificateMessage
{
ProviderKeyId = route.Certificate.ProviderKey.KeyId,
ProviderPublicKeyX = route.Certificate.ProviderKey.X,
ProviderPublicKeyY = route.Certificate.ProviderKey.Y,
OdinKeyId = route.Certificate.OdinKeyId,
IssuedAtUnixMilliseconds = route.Certificate.IssuedAtUnixMilliseconds,
ExpiresAtUnixMilliseconds = route.Certificate.ExpiresAtUnixMilliseconds,
Signature = route.Certificate.Signature
}
}).ToArray(),
ParentVerseId = verse.ParentVerseId,
Description = verse.Description
@ -63,7 +73,16 @@ namespace GameCult.Mesh
route.Endpoint,
route.ProtocolIds,
route.Priority,
route.Generation)).ToArray();
route.Generation,
route.Certificate == null ? null : new CultMeshRouteCertificate(
new CultMeshEcdsaP256PublicKey(
route.Certificate.ProviderKeyId,
route.Certificate.ProviderPublicKeyX,
route.Certificate.ProviderPublicKeyY),
route.Certificate.OdinKeyId,
route.Certificate.IssuedAtUnixMilliseconds,
route.Certificate.ExpiresAtUnixMilliseconds,
route.Certificate.Signature))).ToArray();
return new CultMeshVerseDescriptor(
message.VerseId,
message.DisplayName,

View file

@ -8,7 +8,8 @@ This is the implementation map for the browser Verse boundary.
`samples/eve-two-runtime` remains the clean package-consumer/jsdom checkpoint.
`samples/eve-browser-network` runs a durable C# provider, a real Chromium Eve
lowerer, an independent C# headless observer, and a separate local Odin fixture
over authenticated binary CultNet WebSocket routes. It proves one canonical
over binary loopback CultNet WebSocket routes under an explicit
`local-development` trust policy. It proves one canonical
command effect, idempotent retry, shared observation, provider restart on a new
physical route, browser rediscovery, retained lease resubscription, and a second
canonical command after reconnection.
@ -29,6 +30,10 @@ not a complete public Verse proof:
`cultmesh.verse_catalog_request.v0` and
`cultmesh.verse_catalog_response.v0`; application callbacks no longer need to
smuggle provider URLs into the browser client;
- `CultMeshBrowserClient` owns the final authority gate: remote use requires a
consumer-pinned Odin P-256 root, an Odin-signed route certificate, `wss://`,
and provider possession proof over a fresh nonce. A catalog source cannot
bypass that gate by returning a route-shaped object;
- Kotlin has a channel-aware WebSocket transport adapter, TypeScript has the
browser client, and `GameCult.Networking.WebSockets` provides the bounded C#
schema server host adapter;
@ -58,9 +63,9 @@ Owner:
Inputs:
- an Odin-discovered WebSocket transport candidate;
- an Odin-discovered route certificate and consumer-configured Odin root;
- stable Verse and provider identities;
- authenticated session evidence;
- provider key possession over a fresh client nonce;
- requested schema ids and record keys;
- typed operation invocations and idempotency keys;
- canonical CultNet schema-v0 MessagePack messages.

View file

@ -9,9 +9,10 @@ selection owner then resolves the provider runtime from Odin's descriptor before
opening the session. Discovery owns the current physical routes, and the session
manager owns connection reuse, path rotation, and transport failure state.
Each Odin route binds that authority runtime to one endpoint, protocol set, and
generation. The client verifies the same tuple with the connected peer before
the session becomes online; runtime membership and endpoint reachability are
not independent routing evidence.
generation. For a remote Verse, Odin signs that exact tuple and the provider's
P-256 public key. The client pins an Odin root from its own configuration, then
requires the connected provider to sign a fresh client nonce. A route cannot
become usable by merely repeating the expected Verse and runtime strings.
```csharp
using GameCult.Mesh;
@ -22,9 +23,22 @@ const string verseId = "sample.counter";
var target = new CultMeshSessionTarget(verseId, "sample.counter-daemon");
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var cancellationToken = timeout.Token;
var odinRoot = new CultMeshEcdsaP256PublicKey(
Environment.GetEnvironmentVariable("ODIN_ROOT_KEY_ID")
?? throw new InvalidOperationException("Set ODIN_ROOT_KEY_ID."),
Environment.GetEnvironmentVariable("ODIN_ROOT_P256_X")
?? throw new InvalidOperationException("Set ODIN_ROOT_P256_X."),
Environment.GetEnvironmentVariable("ODIN_ROOT_P256_Y")
?? throw new InvalidOperationException("Set ODIN_ROOT_P256_Y."));
using var mesh = new CultMeshClient(new CultMeshClientOptions
{
RendezvousEndpoints = new[] { odinEndpoint }
RendezvousEndpoints = new[] { odinEndpoint },
Sessions = new CultMeshSessionManagerOptions
{
Trust = new CultMeshAuthorityTrustPolicy(
CultMeshAuthorityTrustMode.AuthenticatedRemote,
new[] { odinRoot })
}
});
using var counterLease = await mesh.LeaseDocumentAsync<CounterState>(
@ -64,6 +78,21 @@ using var stateWatch = session.WatchState().Subscribe(state =>
Application code does not reconnect, sleep, rank endpoints, or replace the
session. Those decisions belong to CultMesh.
For a deliberately local, moddable Verse, select the exception explicitly and
use only in-process or loopback routes:
```csharp
Sessions = new CultMeshSessionManagerOptions
{
Trust = new CultMeshAuthorityTrustPolicy(CultMeshAuthorityTrustMode.LocalDevelopment)
}
```
`LocalDevelopment` never accepts an unsigned non-loopback route. Verse names,
provider names, and Odin wire fields cannot turn this exception on. Remote
routes require a trusted Odin signature, provider nonce proof, certificate
validity, and a protected channel.
Fast session-management check (this uses controlled transports; it is not the
network proof):
@ -71,7 +100,7 @@ network proof):
dotnet test tests/GameCult.Mesh.Tests/GameCult.Mesh.Tests.csproj --filter FullyQualifiedName~CultMeshSessionManagerTests
```
The real checkpoint in chapter 4 additionally advertises a better-priority
The local checkpoint in chapter 4 additionally advertises a better-priority
endpoint for the wrong authority runtime. Both the C# and browser clients must
ignore it, verify the intended peer, survive route replacement, and reject
wrong-source operation responses.

View file

@ -64,13 +64,20 @@ operation.
transport diagnostics. None of these grant provider authority or become content
identity.
Before a schema, content, or realtime session becomes online, the transport
must prove that the connected peer matches the selected Verse, authority
runtime, protocol, and route generation. TCP schema and content lanes use the
portable CultNet session-open handshake. QUIC uses the exact Odin-bound route
plus its TLS endpoint/certificate proof. A connector that returns bytes without
authority proof is rejected; racing every endpoint in a Verse descriptor is
not route selection.
Before a schema, content, or realtime session becomes online, consumer-owned
trust verifies an Odin-signed route certificate binding Verse, authority
runtime, protocol set, endpoint, generation, validity interval, and provider
P-256 key. Schema and content lanes then require a fresh client nonce signed by
that provider key. QUIC uses the signed endpoint plus its TLS
endpoint/certificate proof. A connector that returns bytes without this chain
is rejected; racing every endpoint in a Verse descriptor is not route
selection. Unsigned traffic exists only under an explicitly selected
`LocalDevelopment` policy and only for in-process or loopback routes.
Route and session signatures use ECDSA P-256 with SHA-256 and fixed-width IEEE
P1363 `r || s` encoding, matching browser WebCrypto. Their canonical
transcripts are ordered UTF-8 fields prefixed by four-byte big-endian lengths;
serializer bytes are never signature authority.
**Forbidden writers:** applications and renderers do not choose unadvertised
endpoints, implement reconnect loops, or bypass verification. Schema messages
@ -94,7 +101,8 @@ new seam does not pretend that migration has already occurred.
## Security and release gate
The current TCP control and content connectors are plaintext and therefore
restricted to local or otherwise trusted deployment. Adding TLS must not move
restricted to explicit loopback development. They cannot carry an authenticated
remote session. Adding TLS must not move
discovery, authorization, content verification, or application semantics into
the TCP adapter.

View file

@ -136,9 +136,9 @@ namespace GameCult.Networking
/// </summary>
public const string VerseCatalogResponse = "cultmesh.verse_catalog_response.v0";
/// <summary>CultMesh session identity request contract identifier.</summary>
public const string SessionOpen = "cultmesh.session_open.v1";
public const string SessionOpen = "cultmesh.session_open.v2";
/// <summary>CultMesh verified session identity response contract identifier.</summary>
public const string SessionAccepted = "cultmesh.session_accepted.v1";
public const string SessionAccepted = "cultmesh.session_accepted.v2";
/// <summary>
/// CultMesh peer exchange request contract identifier.
/// </summary>
@ -1194,6 +1194,7 @@ namespace GameCult.Networking
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
[Key("protocolId")] public string ProtocolId { get; set; } = string.Empty;
[Key("routeGeneration")] public string RouteGeneration { get; set; } = string.Empty;
[Key("clientNonce")] public string ClientNonce { get; set; } = string.Empty;
}
/// <summary>Accepts or rejects a CultMesh session with the server's actual identity.</summary>
@ -1207,6 +1208,9 @@ namespace GameCult.Networking
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
[Key("protocolId")] public string ProtocolId { get; set; } = string.Empty;
[Key("routeGeneration")] public string RouteGeneration { get; set; } = string.Empty;
[Key("clientNonce")] public string ClientNonce { get; set; } = string.Empty;
[Key("providerKeyId")] public string ProviderKeyId { get; set; } = string.Empty;
[Key("providerSignature")] public string ProviderSignature { get; set; } = string.Empty;
[Key("error")] public string? Error { get; set; }
}
@ -1308,6 +1312,19 @@ namespace GameCult.Networking
[Key("protocolIds")] public string[] ProtocolIds { get; set; } = Array.Empty<string>();
[Key("priority")] public int Priority { get; set; }
[Key("generation")] public string Generation { get; set; } = string.Empty;
[Key("certificate")] public CultMeshRouteCertificateMessage? Certificate { get; set; }
}
[MessagePackObject]
public class CultMeshRouteCertificateMessage
{
[Key("providerKeyId")] public string ProviderKeyId { get; set; } = string.Empty;
[Key("providerPublicKeyX")] public string ProviderPublicKeyX { get; set; } = string.Empty;
[Key("providerPublicKeyY")] public string ProviderPublicKeyY { get; set; } = string.Empty;
[Key("odinKeyId")] public string OdinKeyId { get; set; } = string.Empty;
[Key("issuedAtUnixMilliseconds")] public long IssuedAtUnixMilliseconds { get; set; }
[Key("expiresAtUnixMilliseconds")] public long ExpiresAtUnixMilliseconds { get; set; }
[Key("signature")] public string Signature { get; set; } = string.Empty;
}
/// <summary>