Skip to content

Commit b46e91e

Browse files
bkudiessCopilot
andauthored
Use gateway challenge time for node authentication (#1067)
Co-authored-by: Copilot App <[email protected]>
1 parent 4806eaa commit b46e91e

6 files changed

Lines changed: 653 additions & 58 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System.Text.Json;
2+
3+
namespace OpenClaw.Shared;
4+
5+
internal static class ConnectAuthTimestamp
6+
{
7+
public static long? ReadChallengeTimestamp(JsonElement payload)
8+
{
9+
if (!payload.TryGetProperty("ts", out var timestamp) ||
10+
timestamp.ValueKind != JsonValueKind.Number ||
11+
!timestamp.TryGetInt64(out var timestampMs) ||
12+
timestampMs <= 0)
13+
{
14+
return null;
15+
}
16+
17+
return timestampMs;
18+
}
19+
20+
public static long ResolveSignedAt(long? challengeTimestampMs, TimeProvider? timeProvider = null)
21+
{
22+
if (challengeTimestampMs is > 0)
23+
{
24+
return challengeTimestampMs.Value;
25+
}
26+
27+
return (timeProvider ?? TimeProvider.System).GetUtcNow().ToUnixTimeMilliseconds();
28+
}
29+
}

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 60 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1428,7 +1428,7 @@ private async Task SendConnectMessageAsync(string? nonce = null)
14281428
var role = GetConnectRole();
14291429
var requestedScopes = GetRequestedScopes(role);
14301430

1431-
var signedAt = _challengeTimestampMs ?? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
1431+
var signedAt = ConnectAuthTimestamp.ResolveSignedAt(_challengeTimestampMs);
14321432
var connectNonce = nonce ?? string.Empty;
14331433
var signatureToken = GetSignatureToken();
14341434
var authPayload = BuildAuthPayload();
@@ -2146,6 +2146,7 @@ JsonValueKind.Object when value.TryGetProperty("message", out var message) => Tr
21462146
private void HandleRequestError(string? method, JsonElement root)
21472147
{
21482148
var message = TryGetErrorMessage(root) ?? "request failed";
2149+
var detailCode = method == "connect" ? TryGetErrorDetailCode(root) : null;
21492150

21502151
if (string.IsNullOrEmpty(method))
21512152
{
@@ -2155,17 +2156,24 @@ private void HandleRequestError(string? method, JsonElement root)
21552156

21562157
if (method == "connect")
21572158
{
2158-
var detailCode = TryGetErrorDetailCode(root);
21592159
_logger.Warn($"[HANDSHAKE] Connect error from gateway: message=\"{message}\", detailCode={detailCode ?? "none"}");
21602160
// Log raw JSON for debugging (truncated)
21612161
var rawJson = root.ToString() ?? "";
21622162
if (rawJson.Length > 500) rawJson = rawJson[..500] + "...";
21632163
_logger.Info($"[HANDSHAKE] Raw error response: {rawJson}");
21642164
}
21652165

2166+
if (method == "connect" && detailCode == "DEVICE_AUTH_SIGNATURE_EXPIRED")
2167+
{
2168+
_authFailed = true;
2169+
RaiseAuthenticationFailed($"{detailCode}: {message}");
2170+
RaiseStatusChanged(ConnectionStatus.Error);
2171+
return;
2172+
}
2173+
21662174
if (method == "connect" &&
21672175
(message.Contains("device signature invalid", StringComparison.OrdinalIgnoreCase) ||
2168-
TryGetErrorDetailCode(root) == "DEVICE_AUTH_SIGNATURE_INVALID"))
2176+
detailCode == "DEVICE_AUTH_SIGNATURE_INVALID"))
21692177
{
21702178
if (!_useV2Signature)
21712179
{
@@ -2197,8 +2205,7 @@ private void HandleRequestError(string? method, JsonElement root)
21972205
}
21982206

21992207
// Permanent auth failures — stop retrying and notify the app
2200-
var detailCode2 = TryGetErrorDetailCode(root);
2201-
if (method == "connect" && (IsTerminalAuthError(message) || IsTerminalAuthDetailCode(detailCode2)))
2208+
if (method == "connect" && (IsTerminalAuthError(message) || IsTerminalAuthDetailCode(detailCode)))
22022209
{
22032210
_authFailed = true;
22042211
RaiseAuthenticationFailed(message);
@@ -2344,43 +2351,66 @@ private static string RedactAuthPayload(string authJson)
23442351
{
23452352
if (!root.TryGetProperty("error", out var error) || error.ValueKind != JsonValueKind.Object)
23462353
return null;
2347-
if (TryGetPairingDetailsElement(error, out var details) &&
2348-
details.ValueKind == JsonValueKind.Object &&
2349-
details.TryGetProperty("code", out var code) &&
2350-
code.ValueKind == JsonValueKind.String)
2351-
return code.GetString();
2352-
return null;
2354+
return TryGetErrorDetailString(error, "code");
23532355
}
23542356

23552357
private static PairingConnectErrorDetails TryGetPairingConnectErrorDetails(JsonElement root)
23562358
{
23572359
if (!root.TryGetProperty("error", out var error) || error.ValueKind != JsonValueKind.Object)
23582360
return default;
23592361

2360-
if (!TryGetPairingDetailsElement(error, out var details) || details.ValueKind != JsonValueKind.Object)
2361-
return default;
2362-
2363-
var isPairingRequired = details.TryGetProperty("code", out var code)
2364-
&& code.ValueKind == JsonValueKind.String
2365-
&& string.Equals(code.GetString(), "PAIRING_REQUIRED", StringComparison.Ordinal);
2366-
var requestId = GetSafeRequestId(details, "requestId");
2362+
var isPairingRequired = string.Equals(
2363+
TryGetErrorDetailString(error, "code"),
2364+
"PAIRING_REQUIRED",
2365+
StringComparison.Ordinal);
2366+
var requestId = TryGetSafeErrorDetailRequestId(error);
23672367
return new PairingConnectErrorDetails(isPairingRequired, requestId);
23682368
}
23692369

2370-
private static bool TryGetPairingDetailsElement(JsonElement error, out JsonElement details)
2370+
private static string? TryGetErrorDetailString(JsonElement error, string property)
23712371
{
2372-
if (error.TryGetProperty("details", out details))
2373-
return true;
2372+
if (error.TryGetProperty("details", out var details) &&
2373+
details.ValueKind == JsonValueKind.Object &&
2374+
details.TryGetProperty(property, out var value) &&
2375+
value.ValueKind == JsonValueKind.String &&
2376+
!string.IsNullOrWhiteSpace(value.GetString()))
2377+
{
2378+
return value.GetString();
2379+
}
23742380

23752381
if (error.TryGetProperty("data", out var data)
23762382
&& data.ValueKind == JsonValueKind.Object
2377-
&& data.TryGetProperty("details", out details))
2383+
&& data.TryGetProperty("details", out details)
2384+
&& details.ValueKind == JsonValueKind.Object
2385+
&& details.TryGetProperty(property, out value)
2386+
&& value.ValueKind == JsonValueKind.String
2387+
&& !string.IsNullOrWhiteSpace(value.GetString()))
23782388
{
2379-
return true;
2389+
return value.GetString();
23802390
}
23812391

2382-
details = default;
2383-
return false;
2392+
return null;
2393+
}
2394+
2395+
private static string? TryGetSafeErrorDetailRequestId(JsonElement error)
2396+
{
2397+
if (error.TryGetProperty("details", out var details) &&
2398+
details.ValueKind == JsonValueKind.Object)
2399+
{
2400+
var requestId = GetSafeRequestId(details, "requestId");
2401+
if (requestId is not null)
2402+
return requestId;
2403+
}
2404+
2405+
if (error.TryGetProperty("data", out var data) &&
2406+
data.ValueKind == JsonValueKind.Object &&
2407+
data.TryGetProperty("details", out details) &&
2408+
details.ValueKind == JsonValueKind.Object)
2409+
{
2410+
return GetSafeRequestId(details, "requestId");
2411+
}
2412+
2413+
return null;
23842414
}
23852415

23862416
private static string? GetSafeRequestId(JsonElement parent, string property)
@@ -2410,7 +2440,7 @@ private static bool IsTerminalAuthError(string errorMessage)
24102440
private static bool IsTerminalAuthDetailCode(string? code) => code is
24112441
"AUTH_TOKEN_MISMATCH" or "AUTH_BOOTSTRAP_TOKEN_INVALID" or
24122442
"AUTH_DEVICE_TOKEN_MISMATCH" or "AUTH_RATE_LIMITED" or
2413-
"AUTH_TOKEN_NOT_CONFIGURED";
2443+
"AUTH_TOKEN_NOT_CONFIGURED" or "DEVICE_AUTH_SIGNATURE_EXPIRED";
24142444

24152445
private static bool IsMissingScopeError(string errorMessage, string scope)
24162446
{
@@ -2954,15 +2984,13 @@ private void HandleConnectChallenge(JsonElement root)
29542984
{
29552985
string? nonce = null;
29562986
long? ts = null;
2957-
if (root.TryGetProperty("payload", out var payload) &&
2958-
payload.TryGetProperty("nonce", out var nonceProp))
2987+
if (root.TryGetProperty("payload", out var payload))
29592988
{
2960-
nonce = nonceProp.GetString();
2961-
2962-
if (payload.TryGetProperty("ts", out var tsProp) && tsProp.ValueKind == JsonValueKind.Number)
2989+
if (payload.TryGetProperty("nonce", out var nonceProp))
29632990
{
2964-
ts = tsProp.GetInt64();
2991+
nonce = nonceProp.GetString();
29652992
}
2993+
ts = ConnectAuthTimestamp.ReadChallengeTimestamp(payload);
29662994
}
29672995

29682996
_challengeTimestampMs = ts;

‎src/OpenClaw.Shared/WindowsNodeClient.cs‎

Lines changed: 68 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -601,29 +601,26 @@ private async Task SendNodeInvokeResultAsync(string requestId, bool success, obj
601601
private async Task HandleConnectChallengeAsync(JsonElement root)
602602
{
603603
string? nonce = null;
604-
long ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
604+
long? challengeTimestampMs = null;
605605

606606
if (root.TryGetProperty("payload", out var payload))
607607
{
608608
if (payload.TryGetProperty("nonce", out var nonceProp))
609609
{
610610
nonce = nonceProp.GetString();
611611
}
612-
if (payload.TryGetProperty("ts", out var tsProp))
613-
{
614-
ts = tsProp.GetInt64();
615-
}
612+
challengeTimestampMs = ConnectAuthTimestamp.ReadChallengeTimestamp(payload);
616613
}
617614

618-
_logger.Info($"[HANDSHAKE] Received connect.challenge: nonce={nonce}, ts={ts}");
615+
_logger.Info($"[HANDSHAKE] Received connect.challenge: nonce={nonce}, ts={challengeTimestampMs?.ToString() ?? "missing"}");
619616

620617
_pendingNonce = nonce;
621-
await SendNodeConnectAsync(nonce, ts);
618+
await SendNodeConnectAsync(nonce, challengeTimestampMs);
622619
}
623620

624621
private const string ClientId = "node-host"; // Must be "node-host" for nodes
625622

626-
private async Task SendNodeConnectAsync(string? nonce, long ts)
623+
private async Task SendNodeConnectAsync(string? nonce, long? challengeTimestampMs)
627624
{
628625
var isPaired = !string.IsNullOrEmpty(_deviceIdentity.NodeDeviceToken);
629626
var usingBootstrap = !isPaired && !string.IsNullOrEmpty(_bootstrapToken);
@@ -641,14 +638,14 @@ private async Task SendNodeConnectAsync(string? nonce, long ts)
641638
_logger.Info($"[HANDSHAKE] signature format={(_useV2Signature ? "v2" : "v3")}, platform={_registration.Platform}, family={_registration.DeviceFamily}");
642639
_logger.Info($"[HANDSHAKE] auth: {{{authType}}}");
643640

644-
await SendRawAsync(BuildNodeConnectMessage(nonce, ts));
641+
await SendRawAsync(BuildNodeConnectMessage(nonce, challengeTimestampMs));
645642
}
646643

647-
private string BuildNodeConnectMessage(string? nonce, long ts)
644+
private string BuildNodeConnectMessage(string? nonce, long? challengeTimestampMs)
648645
{
649646
// Sign the full payload with Ed25519 - this is how device pairing works
650647
string? signature = null;
651-
var signedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
648+
var signedAt = ConnectAuthTimestamp.ResolveSignedAt(challengeTimestampMs);
652649
var (auth, tokenForSignature) = BuildConnectAuth();
653650

654651
if (!string.IsNullOrEmpty(nonce))
@@ -861,10 +858,12 @@ private void HandleRequestError(JsonElement root)
861858
{
862859
var error = "Unknown error";
863860
var errorCode = "none";
861+
string? detailCode = null;
864862
string? pairingReason = null;
865863
string? pairingRequestId = null;
866864

867-
if (root.TryGetProperty("error", out var errorProp))
865+
if (root.TryGetProperty("error", out var errorProp) &&
866+
errorProp.ValueKind == JsonValueKind.Object)
868867
{
869868
if (errorProp.TryGetProperty("message", out var msgProp))
870869
{
@@ -874,17 +873,16 @@ private void HandleRequestError(JsonElement root)
874873
{
875874
errorCode = codeProp.ToString();
876875
}
877-
if (errorProp.TryGetProperty("details", out var detailsProp))
876+
detailCode = TryGetErrorDetailString(errorProp, "code", out var code) ? code : null;
877+
if (TryGetErrorDetailString(errorProp, "reason", out var reason))
878878
{
879-
if (TryGetString(detailsProp, "reason", out var reason))
880-
{
881-
pairingReason = reason;
882-
}
883-
pairingRequestId = TryGetSafePairingRequestId(detailsProp);
879+
pairingReason = reason;
884880
}
881+
pairingRequestId = TryGetSafeErrorDetailRequestId(errorProp);
885882
}
886883

887-
_logger.Info($"[HANDSHAKE] Connect error: message=\"{error}\", code={errorCode}");
884+
var effectiveErrorCode = detailCode ?? errorCode;
885+
_logger.Info($"[HANDSHAKE] Connect error: message=\"{error}\", code={errorCode}, detailCode={detailCode ?? "none"}");
888886

889887
if (string.Equals(errorCode, "NOT_PAIRED", StringComparison.OrdinalIgnoreCase))
890888
{
@@ -916,18 +914,19 @@ private void HandleRequestError(JsonElement root)
916914
if (error.Contains("too many failed", StringComparison.OrdinalIgnoreCase) ||
917915
error.Contains("rate limit", StringComparison.OrdinalIgnoreCase) ||
918916
error.Contains("origin not allowed", StringComparison.OrdinalIgnoreCase) ||
919-
error.Contains("token mismatch", StringComparison.OrdinalIgnoreCase))
917+
error.Contains("token mismatch", StringComparison.OrdinalIgnoreCase) ||
918+
string.Equals(effectiveErrorCode, "DEVICE_AUTH_SIGNATURE_EXPIRED", StringComparison.Ordinal))
920919
{
921920
_rateLimited = true;
922921
_logger.Warn($"[NODE] Terminal auth error; stopping reconnect. Error: {TokenSanitizer.Sanitize(error)}");
923-
ConnectionFailure?.Invoke(this, ClassifyConnectionFailure(error, errorCode));
922+
ConnectionFailure?.Invoke(this, ClassifyConnectionFailure(error, effectiveErrorCode));
924923
RaiseStatusChanged(ConnectionStatus.Error);
925924
return;
926925
}
927926

928927
// v3 signature rejected — fall back to v2 for this session
929928
if (error.Contains("device signature invalid", StringComparison.OrdinalIgnoreCase) ||
930-
errorCode == "DEVICE_AUTH_SIGNATURE_INVALID")
929+
effectiveErrorCode == "DEVICE_AUTH_SIGNATURE_INVALID")
931930
{
932931
if (!_useV2Signature)
933932
{
@@ -994,10 +993,56 @@ private bool PayloadTargetsCurrentDevice(JsonElement payload)
994993
return s_pairingRequestIdValidator.IsMatch(requestId) ? requestId : null;
995994
}
996995

996+
private static bool TryGetErrorDetailString(
997+
JsonElement error,
998+
string propertyName,
999+
out string? value)
1000+
{
1001+
if (error.TryGetProperty("details", out var details) &&
1002+
TryGetString(details, propertyName, out value))
1003+
{
1004+
return true;
1005+
}
1006+
1007+
if (error.TryGetProperty("data", out var data) &&
1008+
data.ValueKind == JsonValueKind.Object &&
1009+
data.TryGetProperty("details", out details) &&
1010+
TryGetString(details, propertyName, out value))
1011+
{
1012+
return true;
1013+
}
1014+
1015+
value = null;
1016+
return false;
1017+
}
1018+
1019+
private static string? TryGetSafeErrorDetailRequestId(JsonElement error)
1020+
{
1021+
if (error.TryGetProperty("details", out var details) &&
1022+
details.ValueKind == JsonValueKind.Object)
1023+
{
1024+
var requestId = TryGetSafePairingRequestId(details);
1025+
if (requestId is not null)
1026+
return requestId;
1027+
}
1028+
1029+
if (error.TryGetProperty("data", out var data) &&
1030+
data.ValueKind == JsonValueKind.Object &&
1031+
data.TryGetProperty("details", out details) &&
1032+
details.ValueKind == JsonValueKind.Object)
1033+
{
1034+
return TryGetSafePairingRequestId(details);
1035+
}
1036+
1037+
return null;
1038+
}
1039+
9971040
private static bool TryGetString(JsonElement element, string propertyName, out string? value)
9981041
{
9991042
value = null;
1000-
if (!element.TryGetProperty(propertyName, out var prop) || prop.ValueKind != JsonValueKind.String)
1043+
if (element.ValueKind != JsonValueKind.Object ||
1044+
!element.TryGetProperty(propertyName, out var prop) ||
1045+
prop.ValueKind != JsonValueKind.String)
10011046
{
10021047
return false;
10031048
}

0 commit comments

Comments
 (0)