Merge pull request #7743 from NicolasDorier/harden-json-parsing
What changed, and why it matters
This commit replaces many direct JSON parsing calls across BTCPay Server with a new, stricter helper called JsonParser. The helper prevents two specific problems: it no longer turns strings that look like dates into real date values automatically, and it limits how deeply nested JSON structures can be. These changes reduce the risk that an attacker could craft unusual JSON data that causes the server to misinterpret values or crash during processing. The commit also adds a test showing that deeply nested and date-like strings are handled safely.
Treat this as a worthwhile hardening patch. Review whether any callers still bypass JsonParser, and confirm that the default MaxDepth of 64 is sufficient for all production data shapes. Consider backporting to supported release branches because it changes parsing semantics for stored blobs and external JSON inputs.
Security signals we found
Replaces permissive Newtonsoft.Json parsing with a hardened wrapper
Disables automatic date string coercion (DateParseHandling.None)
Enforces explicit maximum JSON nesting depth (default 64)
Adds round-trip safety test for date-like strings and deep nesting
Updates coding conventions to mandate JsonParser usage
Touches blob serialization/deserialization paths for invoices, payments, payouts, and store configs
Evidence from the diff
The change introduces BTCPayServer.Abstractions/JsonParser.cs, a wrapper around Newtonsoft.Json’s JsonTextReader configured with DateParseHandling.None and MaxDepth=64 (default). It exposes ParseObject, ParseArray, and ParseToken. The commit then mechanically replaces JObject.Parse, JToken.Parse, and JArray.Parse with the corresponding JsonParser methods in 48 files covering invoice/payment/payout blobs, store configs, plugin manifests, webhooks, migrations, wallet data, and UI controllers. SetBlob helpers now re-parse serialized JSON through JsonParser before storage. A FastTests test verifies round-trip safety for a date-like order ID string and a 62-level nested PosData object, and confirms that 63 levels throw. The patch is broad but defensive; it does not by itself fix a known exploitable vulnerability, but hardens parsing behavior that has historically been a source of subtle bugs in Newtonsoft.Json-based code.
Changed components
BTCPayServer.Abstractions.JsonParser (new)Invoice/payment/payout blob serialization and migrationsStore configuration and derivation strategy parsingPlugin manifest loadingWebhook delivery pruningWallet object and transaction label parsingUI invoice/LNURL/PointOfSale/Crowdfund controllersTranslation and language servicesSwagger providerVault client response parsingInspect captured patch +179 / −90
### BTCPayServer.Abstractions/Extensions/ITempDataDictionaryExtensions.cs
@@ -43,7 +43,7 @@ public static StatusMessageModel GetStatusMessageModel(this ITempDataDictionary
}
if (model is string str)
{
- return JObject.Parse(str).ToObject<StatusMessageModel>();
+ return JsonParser.ParseObject(str).ToObject<StatusMessageModel>();
}
return null;
}
### BTCPayServer.Abstractions/Form/Form.cs
@@ -12,7 +12,7 @@ public class Form
public static Form Parse(string str)
{
ArgumentNullException.ThrowIfNull(str);
- return JObject.Parse(str).ToObject<Form>(CamelCaseSerializerSettings.Serializer) ?? throw new InvalidOperationException("Impossible to deserialize Form");
+ return JsonParser.ParseObject(str).ToObject<Form>(CamelCaseSerializerSettings.Serializer) ?? throw new InvalidOperationException("Impossible to deserialize Form");
}
public override string ToString()
{
### BTCPayServer.Abstractions/JsonParser.cs
@@ -0,0 +1,45 @@
+#nullable enable
+
+using System;
+using System.IO;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+
+namespace BTCPayServer;
+
+/// <summary>
+/// Parses arbitrary JSON without converting date-like strings into date tokens.
+/// </summary>
+public static class JsonParser
+{
+ public const int DefaultMaxDepth = 64;
+
+ public static JObject ParseObject(string json, int maxDepth = DefaultMaxDepth)
+ => Load(json, maxDepth, JObject.Load);
+
+ public static JArray ParseArray(string json, int maxDepth = DefaultMaxDepth)
+ => Load(json, maxDepth, JArray.Load);
+
+ public static JToken ParseToken(string json, int maxDepth = DefaultMaxDepth)
+ => Load(json, maxDepth, JToken.Load);
+
+ private static T Load<T>(string json, int maxDepth, Func<JsonReader, T> load)
+ {
+ ArgumentNullException.ThrowIfNull(json);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxDepth);
+
+ using var stringReader = new StringReader(json);
+ using var jsonReader = new JsonTextReader(stringReader)
+ {
+ DateParseHandling = DateParseHandling.None,
+ MaxDepth = maxDepth
+ };
+ var result = load(jsonReader);
+ while (jsonReader.Read())
+ {
+ if (jsonReader.TokenType is not JsonToken.Comment)
+ throw new JsonReaderException("Additional text encountered after finished reading JSON content.");
+ }
+ return result;
+ }
+}
### BTCPayServer.Data/Data/BaseEntityData.cs
@@ -43,7 +43,7 @@ static BaseEntityData()
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
public T? GetAdditionalData<T>(string key) where T: class
- => JObject.Parse(AdditionalData)[key]?.ToObject<T>(Serializer);
+ => JsonParser.ParseObject(AdditionalData)[key]?.ToObject<T>(Serializer);
[Obsolete("Avoid using this method, if another plugin is modifying additional data at the same time, it would overwrite the changes. Only use if you can ensure that no other plugin is modifying the data at the same time.")]
public void SetAdditionalData<T>(string key, T? obj)
@@ -57,14 +57,14 @@ public void SetAdditionalData<T>(string key, T? obj)
var w = new StringWriter();
Serializer.Serialize(w, obj);
w.Flush();
- var jobj = JObject.Parse(AdditionalData);
- jobj[key] = JToken.Parse(w.ToString());
+ var jobj = JsonParser.ParseObject(AdditionalData);
+ jobj[key] = JsonParser.ParseToken(w.ToString());
AdditionalData = jobj.ToString();
}
}
public void RemoveAdditionalData(string key)
{
- var jobj = JObject.Parse(AdditionalData);
+ var jobj = JsonParser.ParseObject(AdditionalData);
jobj.Remove(key);
AdditionalData = jobj.ToString();
}
### BTCPayServer.Data/Data/InvoiceData.Migration.cs
@@ -54,7 +54,7 @@ public bool TryMigrate()
Blob2 = MigrationExtensions.SanitizeJSON(Blob2);
Blob = null;
}
- var blob = JObject.Parse(Blob2);
+ var blob = JsonParser.ParseObject(Blob2);
if (blob["cryptoData"]?["BTC"] is not (null or { Type: JTokenType.Null }))
{
blob.Move(["rate"], ["cryptoData", "BTC", "rate"]);
@@ -135,7 +135,7 @@ public bool TryMigrate()
{
try
{
- posData.Value = JObject.Parse(posData.Value<string>());
+ posData.Value = JsonParser.ParseObject(posData.Value<string>());
}
catch
{
@@ -146,7 +146,7 @@ public bool TryMigrate()
posData.Remove();
if (blob["derivationStrategies"] is JValue { Type: JTokenType.String } v)
- blob["derivationStrategies"] = JObject.Parse(v.Value<string>());
+ blob["derivationStrategies"] = JsonParser.ParseObject(v.Value<string>());
if (blob["derivationStrategies"] is JObject derivations)
{
foreach (var prop in derivations.Properties().ToList())
@@ -161,7 +161,7 @@ public bool TryMigrate()
})
{
if (val[0] == '{')
- derivations[prop.Name] = JObject.Parse(val);
+ derivations[prop.Name] = JsonParser.ParseObject(val);
else
{
if (val.Contains('-', StringComparison.OrdinalIgnoreCase))
### BTCPayServer.Data/Data/PaymentData.Migration.cs
@@ -23,7 +23,7 @@ public bool TryMigrate()
Blob2 = MigrationExtensions.SanitizeJSON(Blob2);
Blob = null;
}
- var blob = JObject.Parse(Blob2);
+ var blob = JsonParser.ParseObject(Blob2);
if (blob["cryptoPaymentDataType"] is null)
blob["cryptoPaymentDataType"] = "BTCLike";
if (blob["cryptoCode"] is null)
@@ -58,7 +58,7 @@ public bool TryMigrate()
}
else
{
- cryptoData = JObject.Parse(blob["cryptoPaymentData"].Value<string>());
+ cryptoData = JsonParser.ParseObject(blob["cryptoPaymentData"].Value<string>());
foreach (var prop in cryptoData.Properties().ToList())
{
if (prop.Name is "rbf")
### BTCPayServer.Data/Data/PaymentRequestData.Migration.cs
@@ -22,7 +22,7 @@ public bool TryMigrate()
}
Blob = null;
#pragma warning restore CS0618 // Type or member is obsolete
- var jobj = JObject.Parse(Blob2);
+ var jobj = JsonParser.ParseObject(Blob2);
// Fixup some legacy payment requests
if (jobj["expiryDate"]?.Type == JTokenType.Date)
{
### BTCPayServer.Data/Data/WalletObjectData.cs
@@ -38,7 +38,7 @@ static Types()
public string Id { get; set; }
public string Data { get; set; }
#nullable enable
- public JObject? GetData() => Data is null ? null : JObject.Parse(Data);
+ public JObject? GetData() => Data is null ? null : JsonParser.ParseObject(Data);
#nullable restore
public List<WalletObjectLinkData> Bs { get; set; }
public List<WalletObjectLinkData> As { get; set; }
@@ -49,7 +49,7 @@ static Types()
public IEnumerable<(string type, string id, JObject? linkdata, JObject? objectdata)> GetLinks()
{
- static JObject? AsJObj(string? data) => data is null ? null : JObject.Parse(data);
+ static JObject? AsJObj(string? data) => data is null ? null : JsonParser.ParseObject(data);
if (Bs is not null)
foreach (var c in Bs)
{
### BTCPayServer.Tests/FastTests.cs
@@ -2803,6 +2803,40 @@ private static JObject SortPropertiesAlphabetically(JObject original)
return result;
}
+ [Fact]
+ public void CanSafelyRoundTripJsonBlobs()
+ {
+ JObject Nested(int levels) => levels == 1 ? new JObject() : new JObject { ["a"] = Nested(levels - 1) };
+
+ const string date = "/Date(99999999999999999)/";
+ var entity = new InvoiceEntity
+ {
+ Currency = "USD",
+ Metadata = new InvoiceMetadata { OrderId = date, PosData = Nested(62) }
+ };
+ var data = new Data.InvoiceData { Status = "New" };
+
+ data.SetBlob(entity);
+
+ Assert.Equal(date, data.GetBlob().Metadata.OrderId);
+ var row = JsonParser.ParseObject($"{{\"Id\":\"a\",\"Blob2\":{data.Blob2}}}", 128);
+ Assert.Equal(data.Blob2, row["Blob2"]!.ToString(Formatting.None));
+
+ entity.Metadata.PosData = Nested(63);
+ Assert.Throws<JsonReaderException>(() => data.SetBlob(entity));
+
+ var payment = new Data.PaymentData
+ {
+ Id = "a",
+ Status = PaymentStatus.Settled,
+ Currency = "BTC",
+ Amount = 1.0m,
+ Created = DateTimeOffset.UtcNow
+ };
+ payment.SetBlob(PaymentMethodId.Parse("BTC-LN"), new PaymentBlob { Destination = date });
+ Assert.Equal(date, payment.GetBlob().Destination);
+ }
+
[Fact]
public void CanParseInvoiceEntityDerivationStrategies()
{
### BTCPayServer/Controllers/UIInvoiceController.UI.cs
@@ -181,7 +181,7 @@ public async Task<IActionResult> Invoice(string invoiceId)
// overwrite with parsed JSON if possible
try
{
- additionalData["posData"] = PosDataParser.ParsePosData(JObject.Parse(posData));
+ additionalData["posData"] = PosDataParser.ParsePosData(JsonParser.ParseObject(posData));
}
catch (Exception)
{
@@ -1219,7 +1219,7 @@ public async Task<IActionResult> CreateInvoice(CreateInvoiceModel model, Cancell
{
try
{
- metadataObj = JObject.Parse(model.Metadata);
+ metadataObj = JsonParser.ParseObject(model.Metadata);
}
catch (Exception)
{
### BTCPayServer/Controllers/UILNURLController.cs
@@ -974,7 +974,7 @@ public async Task<IActionResult> EditLightningAddress(string storeId, [FromForm]
{
try
{
- metadata = JObject.Parse(vm.Add.InvoiceMetadata);
+ metadata = JsonParser.ParseObject(vm.Add.InvoiceMetadata);
}
catch (Exception)
{
### BTCPayServer/Data/IHasBlobExtensions.cs
@@ -58,7 +58,7 @@ public static IHasBlob HasTypedBlob(this IHasBlobUntyped data, Type blobType)
public static B? GetBlob<B>(this IHasBlob<B> data, JsonSerializerSettings? settings = null)
{
if (data.Blob2 is not null)
- return JObject.Parse(data.Blob2).ToObject<B>(JsonSerializer.CreateDefault(settings ?? DefaultSerializerSettings));
+ return JsonParser.ParseObject(data.Blob2).ToObject<B>(JsonSerializer.CreateDefault(settings ?? DefaultSerializerSettings));
#pragma warning disable CS0618 // Type or member is obsolete
if (data.Blob is not null && data.Blob.Length != 0)
{
@@ -67,7 +67,7 @@ public static IHasBlob HasTypedBlob(this IHasBlobUntyped data, Type blobType)
str = Encoding.UTF8.GetString(data.Blob);
else
str = ZipUtils.Unzip(data.Blob);
- return JObject.Parse(str).ToObject<B>(JsonSerializer.CreateDefault(settings ?? DefaultSerializerSettings));
+ return JsonParser.ParseObject(str).ToObject<B>(JsonSerializer.CreateDefault(settings ?? DefaultSerializerSettings));
}
#pragma warning restore CS0618 // Type or member is obsolete
return default;
@@ -76,10 +76,10 @@ public static IHasBlob HasTypedBlob(this IHasBlobUntyped data, Type blobType)
public static object? GetBlob(this IHasBlob data, JsonSerializerSettings? settings = null)
{
if (data.Blob2 is not null)
- return JObject.Parse(data.Blob2).ToObject(data.Type, JsonSerializer.CreateDefault(settings ?? DefaultSerializerSettings));
+ return JsonParser.ParseObject(data.Blob2).ToObject(data.Type, JsonSerializer.CreateDefault(settings ?? DefaultSerializerSettings));
#pragma warning disable CS0618 // Type or member is obsolete
if (data.Blob is not null && data.Blob.Length != 0)
- return JObject.Parse(ZipUtils.Unzip(data.Blob)).ToObject(data.Type, JsonSerializer.CreateDefault(settings ?? DefaultSerializerSettings));
+ return JsonParser.ParseObject(ZipUtils.Unzip(data.Blob)).ToObject(data.Type, JsonSerializer.CreateDefault(settings ?? DefaultSerializerSettings));
#pragma warning restore CS0618 // Type or member is obsolete
return default;
}
@@ -97,7 +97,11 @@ public static T SetBlob<T, B>(this T data, B blob, JsonSerializer? settings) whe
if (blob is null)
data.Blob2 = null;
else
- data.Blob2 = JObject.FromObject(blob, settings ?? DefaultSerializer).ToString(Formatting.None);
+ {
+ var json = JObject.FromObject(blob, settings ?? DefaultSerializer).ToString(Formatting.None);
+ JsonParser.ParseObject(json);
+ data.Blob2 = json;
+ }
#pragma warning disable CS0618 // Type or member is obsolete
data.Blob = new byte[0];
#pragma warning restore CS0618 // Type or member is obsolete
### BTCPayServer/Data/PaymentDataExtensions.cs
@@ -32,12 +32,14 @@ public static PaymentEntity SetBlob(this PaymentData paymentData, PaymentEntity
public static PaymentData SetBlob(this PaymentData paymentData, PaymentMethodId paymentMethodId, PaymentBlob blob)
{
paymentData.PaymentMethodId = paymentMethodId.ToString();
- paymentData.Blob2 = JToken.FromObject(blob, InvoiceDataExtensions.DefaultSerializer).ToString(Newtonsoft.Json.Formatting.None);
+ var json = JToken.FromObject(blob, InvoiceDataExtensions.DefaultSerializer).ToString(Newtonsoft.Json.Formatting.None);
+ JsonParser.ParseToken(json);
+ paymentData.Blob2 = json;
return paymentData;
}
public static PaymentEntity GetBlob(this PaymentData paymentData)
{
- var entity = JToken.Parse(paymentData.Blob2).ToObject<PaymentEntity>(InvoiceDataExtensions.DefaultSerializer) ?? throw new FormatException($"Invalid {nameof(PaymentEntity)}");
+ var entity = JsonParser.ParseToken(paymentData.Blob2).ToObject<PaymentEntity>(InvoiceDataExtensions.DefaultSerializer) ?? throw new FormatException($"Invalid {nameof(PaymentEntity)}");
entity.Status = paymentData.Status!.Value;
entity.Currency = paymentData.Currency;
entity.PaymentMethodId = PaymentMethodId.Parse(paymentData.PaymentMethodId);
### BTCPayServer/Data/Payouts/BitcoinLike/BitcoinLikePayoutHandler.cs
@@ -146,7 +146,7 @@ public static void ParseProofType(string proof, out JObject obj, out string type
return;
}
- obj = JObject.Parse(proof);
+ obj = JsonParser.ParseObject(proof);
TryParseProofType(obj, out type);
}
### BTCPayServer/Data/Payouts/PayoutExtensions.cs
@@ -53,7 +53,7 @@ public static void SetBlob(this PayoutData data, PayoutBlob blob, BTCPayNetworkJ
public static JObject GetProofBlobJson(this PayoutData data)
{
- return data?.Proof is null ? null : JObject.Parse(data.Proof);
+ return data?.Proof is null ? null : JsonParser.ParseObject(data.Proof);
}
public static void SetProofBlob(this PayoutData data, IPayoutProof blob, JsonSerializerSettings settings)
{
@@ -75,7 +75,7 @@ public static void SetProofBlob(this PayoutData data, JObject blob)
return;
}
// We only update the property if the bytes actually changed, this prevent from hammering the DB too much
- if (!JToken.DeepEquals(blob, data.Proof is null ? null : JObject.Parse(data.Proof)))
+ if (!JToken.DeepEquals(blob, data.Proof is null ? null : JsonParser.ParseObject(data.Proof)))
{
data.Proof = blob.ToString(Formatting.None);
}
### BTCPayServer/Data/StoreDataExtensions.cs
@@ -78,13 +78,13 @@ public static bool SetStoreBlob(this StoreData storeData, StoreBlob storeBlob)
return null;
if (!onlyEnabled)
{
- JObject strategies = JObject.Parse(storeData.DerivationStrategies);
+ JObject strategies = JsonParser.ParseObject(storeData.DerivationStrategies);
return strategies[paymentMethodId.ToString()];
}
else
{
var excludeFilter = storeData.GetStoreBlob().GetExcludedPaymentMethods();
- JObject strategies = JObject.Parse(storeData.DerivationStrategies);
+ JObject strategies = JsonParser.ParseObject(storeData.DerivationStrategies);
return excludeFilter.Match(paymentMethodId) ? null : strategies[paymentMethodId.ToString()];
}
}
@@ -102,7 +102,7 @@ public static void SetPaymentMethodConfig(this StoreData storeData, IPaymentMeth
}
public static void SetPaymentMethodConfig(this StoreData storeData, PaymentMethodId paymentMethodId, JToken? config)
{
- JObject strategies = string.IsNullOrEmpty(storeData.DerivationStrategies) ? new JObject() : JObject.Parse(storeData.DerivationStrategies);
+ JObject strategies = string.IsNullOrEmpty(storeData.DerivationStrategies) ? new JObject() : JsonParser.ParseObject(storeData.DerivationStrategies);
if (config is null)
strategies.Remove(paymentMethodId.ToString());
else
@@ -128,7 +128,7 @@ public static Dictionary<PaymentMethodId, JToken> GetPaymentMethodConfigs(this S
return new Dictionary<PaymentMethodId, JToken>();
var excludeFilter = onlyEnabled ? storeData.GetStoreBlob().GetExcludedPaymentMethods() : null;
var paymentMethodConfigurations = new Dictionary<PaymentMethodId, JToken>();
- JObject strategies = JObject.Parse(storeData.DerivationStrategies);
+ JObject strategies = JsonParser.ParseObject(storeData.DerivationStrategies);
foreach (var strat in strategies.Properties())
{
if (!PaymentMethodId.TryParse(strat.Name, out var paymentMethodId))
### BTCPayServer/HostedServices/DbMigrationsHostedService.cs
@@ -76,7 +76,7 @@ static LegacyWalletTransactionInfo GetBlobInfo(WalletTransactionData walletTrans
{
if (walletTransactionData.Labels.StartsWith('['))
{
- foreach (var jtoken in JArray.Parse(walletTransactionData.Labels))
+ foreach (var jtoken in JsonParser.ParseArray(walletTransactionData.Labels))
{
var l = jtoken.Type == JTokenType.String ? Label.Parse(jtoken.Value<string>())
: Label.Parse(jtoken.ToString());
@@ -150,7 +150,7 @@ internal async Task MigratedTransactionLabels(int startFromOffset)
{
try
{
- labelId = JObject.Parse(label.Key)["value"].Value<string>();
+ labelId = JsonParser.ParseObject(label.Key)["value"].Value<string>();
}
catch
{
### BTCPayServer/HostedServices/GithubVersionFetcher.cs
@@ -57,7 +57,7 @@ public virtual async Task<string> Fetch(CancellationToken cancellation)
var strResp = await resp.Content.ReadAsStringAsync(cancellation);
if (resp.IsSuccessStatusCode)
{
- var jobj = JObject.Parse(strResp);
+ var jobj = JsonParser.ParseObject(strResp);
var tag = jobj["tag_name"].ToString();
var isReleaseVersionTag = _releaseVersionTag.IsMatch(tag);
### BTCPayServer/Hosting/MigrationStartupTask.cs
@@ -254,7 +254,7 @@ private async Task MigrateOldDerivationSchemes()
{
if (string.IsNullOrEmpty(store.DerivationStrategies))
continue;
- JObject strategies = JObject.Parse(store.DerivationStrategies);
+ JObject strategies = JsonParser.ParseObject(store.DerivationStrategies);
if (strategies is null)
continue;
foreach (var prop in strategies.Properties())
@@ -279,7 +279,7 @@ private async Task MigrateStoreExcludedPaymentMethods()
{
if (store.StoreBlob is null)
continue;
- var blob = JObject.Parse(store.StoreBlob);
+ var blob = JsonParser.ParseObject(store.StoreBlob);
var array = blob["excludedPaymentMethods"] as JArray;
if (array is null || array.Count == 0)
continue;
@@ -298,7 +298,7 @@ private async Task MigrateBlockExplorerLinks()
var settings = await ctx.Settings.Where(s => s.Id == "BTCPayServer.Services.PoliciesSettings").FirstOrDefaultAsync();
if (settings is null)
return;
- var obj = JObject.Parse(settings.Value);
+ var obj = JsonParser.ParseObject(settings.Value);
var arr = obj["BlockExplorerLinks"] as JArray;
if (arr is null or { Count: 0 })
return;
@@ -322,7 +322,7 @@ private async Task MigrateToStoreConfig()
{
if (string.IsNullOrEmpty(store.DerivationStrategies))
continue;
- var strategies = JObject.Parse(store.DerivationStrategies);
+ var strategies = JsonParser.ParseObject(store.DerivationStrategies);
foreach (var s in strategies.Properties().ToList())
{
var ls = s;
@@ -375,7 +375,7 @@ string MapToString(int v)
_ => throw new NotSupportedException()
};
}
- var data = JObject.Parse(setting.Value);
+ var data = JsonParser.ParseObject(setting.Value);
if (data["RootAppType"]?.Type is JTokenType.Integer)
{
var v = data["RootAppType"].Value<int>();
@@ -401,7 +401,7 @@ static async Task<string> GetMigrationState(ApplicationDbContext postgresContext
var o = (await postgresContext.Settings.FromSqlRaw("SELECT \"Id\", \"Value\" FROM \"Settings\" WHERE \"Id\"='MigrationData'").AsNoTracking().FirstOrDefaultAsync())?.Value;
if (o is null)
return null;
- return JObject.Parse(o)["state"]?.Value<string>();
+ return JsonParser.ParseObject(o)["state"]?.Value<string>();
}
static async Task UpdateSequenceInvoiceSearch(ApplicationDbContext postgresContext)
{
@@ -564,7 +564,7 @@ private async Task MigrateMigrateLabels()
{
try
{
- labelId = JObject.Parse(label.Key)["value"].Value<string>();
+ labelId = JsonParser.ParseObject(label.Key)["value"].Value<string>();
}
catch
{
@@ -848,7 +848,7 @@ private async Task TransitionInternalNodeConnectionString()
if (string.IsNullOrEmpty(store.DerivationStrategies))
continue;
- var strats = JObject.Parse(store.DerivationStrategies);
+ var strats = JsonParser.ParseObject(store.DerivationStrategies);
bool updated = false;
foreach (var prop in strats.Properties().Where(p => IsLN(PaymentMethodId.Parse(p.Name))))
{
### BTCPayServer/IHasAdditionalData.cs
@@ -47,7 +47,7 @@ public static void SetAdditionalData<T>(this IHasAdditionalData o, string propNa
{
if (value is string s)
{
- data = JToken.Parse(s);
+ data = JsonParser.ParseToken(s);
}
else
{
### BTCPayServer/Payments/Lightning/LightningPendingPayoutListener.cs
@@ -142,7 +142,7 @@ await _pullPaymentHostedService.MarkPaid(new HostedServices.MarkPayoutRequest()
{
PayoutId = payoutData.Id,
State = payoutData.State,
- Proof = payoutData.State is PayoutState.Completed ? JObject.Parse(payoutData.Proof) : null
+ Proof = payoutData.State is PayoutState.Completed ? JsonParser.ParseObject(payoutData.Proof) : null
});
}
}
### BTCPayServer/Plugins/Bitpay/BitpayIPNSender.cs
@@ -197,7 +197,7 @@ private async Task<HttpResponseMessage> SendNotification(InvoicePaymentNotificat
request.Method = HttpMethod.Post;
var notificationString = NBitcoin.JsonConverters.Serializer.ToString(notification);
- var jobj = JObject.Parse(notificationString);
+ var jobj = JsonParser.ParseObject(notificationString);
if (notification.ExtendedNotification)
{
### BTCPayServer/Plugins/Crowdfund/Controllers/UICrowdfundController.cs
@@ -256,7 +256,7 @@ private JObject TryParseJObject(string posData)
{
try
{
- return JObject.Parse(posData);
+ return JsonParser.ParseObject(posData);
}
catch
{
### BTCPayServer/Plugins/PluginManager.cs
@@ -502,7 +502,7 @@ private static bool ExecuteCommands(string pluginsFolder)
var manifestFileName = Path.Join(dirName, plugin + ".json");
if (File.Exists(manifestFileName))
{
- var pluginManifest = JObject.Parse(File.ReadAllText(manifestFileName)).ToObject<PluginService.AvailablePlugin>();
+ var pluginManifest = JsonParser.ParseObject(File.ReadAllText(manifestFileName)).ToObject<PluginService.AvailablePlugin>();
if (pluginManifest is not null)
installed.TryAdd(pluginManifest.Identifier, (pluginManifest.Version, pluginManifest.Dependencies, isDisabled));
}
@@ -521,7 +521,7 @@ private static bool DependenciesMet(string pluginsFolder, string plugin, Diction
var dirName = Path.Join(pluginsFolder, plugin);
var manifestFileName = dirName + ".json";
if (!File.Exists(manifestFileName)) return true;
- var pluginManifest = JObject.Parse(File.ReadAllText(manifestFileName)).ToObject<PluginService.AvailablePlugin>();
+ var pluginManifest = JsonParser.ParseObject(File.ReadAllText(manifestFileName)).ToObject<PluginService.AvailablePlugin>();
if (pluginManifest is not null)
return DependenciesMet(pluginManifest.Dependencies, installed);
return true;
@@ -831,7 +831,7 @@ private static void WritePluginFailures(string pluginDir,
return null;
try
{
- return JObject.Parse(File.ReadAllText(manifestFileName))
+ return JsonParser.ParseObject(File.ReadAllText(manifestFileName))
.ToObject<PluginService.AvailablePlugin>();
}
catch
### BTCPayServer/Plugins/PluginManager/PluginService.cs
@@ -55,7 +55,7 @@ internal AvailablePlugin GetPendingPluginManifest(string command, string plugin)
_ => null
};
if (manifestFileName is null || !File.Exists(manifestFileName)) return null;
- return JObject.Parse(File.ReadAllText(manifestFileName)).ToObject<AvailablePlugin>();
+ return JsonParser.ParseObject(File.ReadAllText(manifestFileName)).ToObject<AvailablePlugin>();
}
internal string GetShortBtcpayVersion() => Env.Version.TrimStart('v').Split('+')[0];
### BTCPayServer/Plugins/PointOfSale/Controllers/UIPointOfSaleController.cs
@@ -468,7 +468,7 @@ private JObject TryParseJObject(string posData)
{
try
{
- return JObject.Parse(posData);
+ return JsonParser.ParseObject(posData);
}
catch
{
### BTCPayServer/Plugins/Subscriptions/Mapper.cs
@@ -60,7 +60,7 @@ public static SubscriberModel MapToSubscriberModel(SubscriberData sub)
Id = sub.CustomerId,
ExternalId = customer.ExternalRef,
Identities = customer.CustomerIdentities is {} v ? new JObject(v.Select(i => new JProperty(i.Type, i.Value))) : null,
- Metadata = JObject.Parse(customer.Metadata)
+ Metadata = JsonParser.ParseObject(customer.Metadata)
},
Created = sub.CreatedAt,
Offering = MapOffering(offering),
@@ -73,7 +73,7 @@ public static SubscriberModel MapToSubscriberModel(SubscriberData sub)
Phase = Map(sub.Phase),
SuspensionReason = sub.SuspensionReason,
AutoRenew = sub.AutoRenew,
- Metadata = JObject.Parse(sub.Metadata),
+ Metadata = JsonParser.ParseObject(sub.Metadata),
ProcessingInvoiceId = sub.ProcessingInvoiceId,
NextPlan = MapPlan(sub.NextPlan),
ScheduledPlan = sub.NewPlanId is not null ? MapPlan(sub.NewPlan!) : null,
@@ -103,7 +103,7 @@ public static OfferingPlanModel MapPlan(PlanData plan)
OptimisticActivation = plan.OptimisticActivation,
Renewable = plan.Renewable,
Features = plan.GetFeatureIds(),
- Metadata = JObject.Parse(plan.Metadata),
+ Metadata = JsonParser.ParseObject(plan.Metadata),
};
}
@@ -117,7 +117,7 @@ public static OfferingModel MapOffering(OfferingData offering)
SuccessRedirectUrl = offering.SuccessRedirectUrl,
Plans = offering?.Plans is {} plans ? plans.Select(MapPlan).ToList() : null,
Features = offering?.Features is {} features ? features.Select(MapFeature).ToList() : null,
- Metadata = JObject.Parse(offering.Metadata)
+ Metadata = JsonParser.ParseObject(offering.Metadata)
};
private static FeatureModel MapFeature(FeatureData arg)
@@ -138,13 +138,13 @@ public static PlanCheckoutModel MapPlanCheckout(PlanCheckoutData checkout)
Expiration = checkout.Expiration,
RedirectUrl = checkout.GetRedirectUrl(),
BaseUrl = checkout.BaseUrl.ToString(),
- InvoiceMetadata = JObject.Parse(checkout.InvoiceMetadata),
- Metadata = JObject.Parse(checkout.Metadata),
+ InvoiceMetadata = JsonParser.ParseObject(checkout.InvoiceMetadata),
+ Metadata = JsonParser.ParseObject(checkout.Metadata),
NewSubscriber = checkout.NewSubscriber,
IsTrial = checkout.IsTrial,
Created = checkout.CreatedAt,
PlanStarted = checkout.PlanStarted,
- NewSubscriberMetadata = JObject.Parse(checkout.NewSubscriberMetadata),
+ NewSubscriberMetadata = JsonParser.ParseObject(checkout.NewSubscriberMetadata),
RefundAmount = checkout.RefundAmount,
CreditedByInvoice = checkout.CreditedByInvoice,
OnPayBehavior = MapOnPay(checkout.OnPay),
### BTCPayServer/Plugins/Subscriptions/SubscriberWebhookProvider.cs
@@ -28,20 +28,20 @@ protected override async Task<JObject> GetEmailModel(WebhookTriggerContext<Subsc
["Name"] = evt.Subscriber.Offering.App.Name,
["Id"] = evt.Subscriber.Offering.Id,
["AppId"] = evt.Subscriber.Offering.AppId,
- ["Metadata"] = JObject.Parse(evt.Subscriber.Offering.Metadata),
+ ["Metadata"] = JsonParser.ParseObject(evt.Subscriber.Offering.Metadata),
};
model["Subscriber"] = new JObject()
{
["Phase"] = evt.Subscriber.Phase.ToString(),
// TODO: When the subscriber can customize the email, also check it!
["Email"] = evt.Subscriber.Customer.NotificationEmail.Get() ?? evt.Subscriber.Customer.Email.Get(),
- ["Metadata"] = JObject.Parse(evt.Subscriber.Metadata)
+ ["Metadata"] = JsonParser.ParseObject(evt.Subscriber.Metadata)
};
model["Customer"] = new JObject()
{
["ExternalRef"] = evt.Subscriber.Customer.ExternalRef ?? "",
["Name"] = evt.Subscriber.Customer.Name,
- ["Metadata"] = JObject.Parse(evt.Subscriber.Customer.Metadata)
+ ["Metadata"] = JsonParser.ParseObject(evt.Subscriber.Customer.Metadata)
};
if (evt is SubscriptionEvent.CreditRefunded refunded)
{
### BTCPayServer/Plugins/Subscriptions/SubscriptionHostedService.cs
@@ -181,7 +181,7 @@ SubscriptionContext CreateContext(CancellationToken cancellationToken) =>
private async Task CreateInvoiceForCheckout(SubscriptionContext subCtx, PlanCheckoutData checkout)
{
- var invoiceMetadata = JObject.Parse(checkout.InvoiceMetadata);
+ var invoiceMetadata = JsonParser.ParseObject(checkout.InvoiceMetadata);
if (checkout.NewSubscriber)
{
invoiceMetadata["planId"] = checkout.PlanId;
@@ -615,7 +615,7 @@ public async Task MoveTime(long subscriberId, PhaseTypes phase)
var cust = await ctx.Customers.GetOrUpdate(checkout.Plan.Offering.App.StoreDataId, CustomerSelector.ByEmail(email));
var (sub, created) =
await ctx.Subscribers.GetOrCreateByCustomerId(cust.Id, plan.OfferingId, plan.Id, optimisticActivation, checkout.TestAccount,
- JObject.Parse(checkout.NewSubscriberMetadata));
+ JsonParser.ParseObject(checkout.NewSubscriberMetadata));
if (!created || sub is null)
return null;
checkout.Subscriber = sub;
### BTCPayServer/Plugins/Translations/Controllers/UITranslationController.cs
@@ -152,7 +152,7 @@ public async Task<IActionResult> EditTranslation(string translation, EditTransla
if (environment.CheatMode && viewModel.Command == "Fake")
{
var t = await localizer.GetTranslations(translation);
- var jobj = JObject.Parse(t.Translations.ToJsonFormat());
+ var jobj = JsonParser.ParseObject(t.Translations.ToJsonFormat());
foreach (var prop in jobj.Properties())
{
prop.Value = "OK";
### BTCPayServer/Plugins/Translations/LocalizerService.cs
@@ -63,7 +63,7 @@ public async Task<LoadedTranslations> GetTranslations(string translationName)
dict_id = translationName,
});
var metadata = await conn.QueryFirstOrDefaultAsync<string?>("SELECT metadata FROM lang_dictionaries WHERE dict_id=@dict_id", new { dict_id = translationName });
- var rtl = metadata is not null && JObject.Parse(metadata)["rtl"]?.Value<bool>() == true;
+ var rtl = metadata is not null && JsonParser.ParseObject(metadata)["rtl"]?.Value<bool>() == true;
var defaultDict = Translations.Default;
var loading = defaultTranslationProviders.Select(d => d.GetDefaultTranslations()).ToArray();
Dictionary<string, string?> additionalDefault = new();
@@ -160,7 +160,7 @@ public async Task<Translation[]> GetTranslations()
await using var ctx = contextFactory.CreateContext();
var db = ctx.Database.GetDbConnection();
var rows = await db.QueryAsync<(string dict_id, string? fallback, string? source, string? metadata)>("SELECT * FROM lang_dictionaries");
- return rows.Select(r => new Translation(r.dict_id, r.fallback, r.source ?? "", JObject.Parse(r.metadata ?? "{}"))).ToArray();
+ return rows.Select(r => new Translation(r.dict_id, r.fallback, r.source ?? "", JsonParser.ParseObject(r.metadata ?? "{}"))).ToArray();
}
public async Task<Translation?> GetTranslation(string name)
{
@@ -169,7 +169,7 @@ public async Task<Translation[]> GetTranslations()
var r = await db.QueryFirstOrDefaultAsync("SELECT * FROM lang_dictionaries WHERE dict_id=@dict_id", new { dict_id = name });
if (r is null)
return null;
- return new Translation(r.dict_id, r.fallback, r.source ?? "", JObject.Parse(r.metadata ?? "{}"));
+ return new Translation(r.dict_id, r.fallback, r.source ?? "", JsonParser.ParseObject(r.metadata ?? "{}"));
}
public async Task<Translation> CreateTranslation(string langName, string? fallback, string source)
### BTCPayServer/Plugins/Translations/Translations.cs
@@ -34,7 +34,7 @@ public static Translations CreateFromJson(string text)
{
text = (text ?? "{}");
var translations = new List<(string key, string? value)>();
- foreach (var prop in JObject.Parse(text).Properties())
+ foreach (var prop in JsonParser.ParseObject(text).Properties())
{
var v = prop.Value.Value<string>();
if (string.IsNullOrEmpty(v))
### BTCPayServer/Plugins/Wallets/Controllers/GreenfieldStoreOnChainWalletsController.cs
@@ -859,7 +859,7 @@ private OnChainWalletObjectData ToModel(WalletObjectData data)
{
return new OnChainWalletObjectData()
{
- Data = string.IsNullOrEmpty(data.Data) ? null : JObject.Parse(data.Data),
+ Data = string.IsNullOrEmpty(data.Data) ? null : JsonParser.ParseObject(data.Data),
Type = data.Type,
Id = data.Id,
Links = data.GetLinks().Select(linkData => ToModel(linkData)).ToArray()
### BTCPayServer/Plugins/Wallets/Controllers/UIStoreOnChainWalletsController.cs
@@ -210,7 +210,7 @@ private async Task<IActionResult> UpdateWalletCore(WalletSetupViewModel vm)
{
try
{
- strategy = handler.ParsePaymentMethodConfig(JToken.Parse(_dataProtector.UnprotectString(vm.Config)));
+ strategy = handler.ParsePaymentMethodConfig(JsonParser.ParseToken(_dataProtector.UnprotectString(vm.Config)));
}
catch
{
### BTCPayServer/Plugins/Webhooks/WebhookDataExtensions.cs
@@ -31,7 +31,7 @@ public class WebhookDeliveryBlob
public byte[] Request { get; set; }
public void Prune()
{
- var request = JObject.Parse(UTF8Encoding.UTF8.GetString(Request));
+ var request = JsonParser.ParseObject(UTF8Encoding.UTF8.GetString(Request));
foreach (var prop in request.Properties().ToList())
{
if (prop.Name == "type")
### BTCPayServer/Services/Apps/AppService.cs
@@ -417,13 +417,13 @@ public async Task UpdateInventory(string appId, InventoryChange[] changes)
CrowdfundAppType.AppType => "PerksTemplate",
_ => "Template"
};
- var settings = JObject.Parse(row.settings);
+ var settings = JsonParser.ParseObject(row.settings);
if (!settings.TryGetValue(templatePath, out var template))
return;
var items = template.Type switch
{
- JTokenType.String => JArray.Parse(template.Value<string>()!),
+ JTokenType.String => JsonParser.ParseArray(template.Value<string>()!),
JTokenType.Array => (JArray)template,
_ => null
};
@@ -482,7 +482,7 @@ private static bool TryParseJson(string json, [MaybeNullWhen(false)] out JObject
result = null;
try
{
- result = JObject.Parse(json);
+ result = JsonParser.ParseObject(json);
return true;
}
catch
### BTCPayServer/Services/DefaultSwaggerProvider.cs
@@ -31,7 +31,7 @@ public async Task<JObject> Fetch()
{
await using var stream = fi.CreateReadStream();
using var reader = new StreamReader(fi.CreateReadStream());
- var jObject = JObject.Parse(await reader.ReadToEndAsync());
+ var jObject = JsonParser.ParseObject(await reader.ReadToEndAsync());
if (jObject.Remove("x_experimental") && !Policies.Settings.Experimental)
continue;
json.Merge(jObject);
### BTCPayServer/Services/Invoices/InvoiceEntity.cs
@@ -173,7 +173,7 @@ public JObject PosData
if (jt.Type == JTokenType.String)
try
{
- return JObject.Parse(jt.Value<string>());
+ return JsonParser.ParseObject(jt.Value<string>());
}
catch
{
@@ -207,7 +207,7 @@ public string PosDataLegacy
{
try
{
- PosData = JObject.Parse(value);
+ PosData = JsonParser.ParseObject(value);
return;
}
catch
### BTCPayServer/Services/Invoices/InvoiceRepository.cs
@@ -147,7 +147,7 @@ FROM invoices_payments ip
List<InvoiceEntity> invoices = new List<InvoiceEntity>();
foreach (var row in rows)
{
- var jobj = JObject.Parse(row.invoice);
+ var jobj = JsonParser.ParseObject(row.invoice, 128);
jobj.Remove("Blob");
jobj["Blob2"] = jobj["Blob2"].ToString(Formatting.None);
var invoiceData = jobj.ToObject<InvoiceData>();
@@ -156,7 +156,7 @@ FROM invoices_payments ip
invoiceData.Payments = new List<PaymentData>();
foreach (var payment in row.payments)
{
- jobj = JObject.Parse(payment);
+ jobj = JsonParser.ParseObject(payment, 128);
jobj.Remove("Blob");
jobj["Blob2"] = jobj["Blob2"].ToString(Formatting.None);
var paymentData = jobj.ToObject<PaymentData>();
### BTCPayServer/Services/Invoices/PosAppData.cs
@@ -12,7 +12,7 @@ public static PosAppData TryParse(string posData)
{
try
{
- return JObject.Parse(posData).ToObject<PosAppData>();
+ return JsonParser.ParseObject(posData).ToObject<PosAppData>();
}
catch
{
### BTCPayServer/Services/Invoices/RateBook.cs
@@ -18,7 +18,7 @@ public static RateBook Parse(string rates, string defaultCurrency)
ArgumentNullException.ThrowIfNull(defaultCurrency);
if (rates == "")
return new(defaultCurrency, new());
- var o = JObject.Parse(rates);
+ var o = JsonParser.ParseObject(rates);
var ratesDict = new Dictionary<string, decimal>();
foreach (var property in o.Properties())
{
### BTCPayServer/Services/Labels/Label.cs
@@ -60,7 +60,7 @@ public static Label Parse(string str)
ArgumentNullException.ThrowIfNull(str);
if (str.StartsWith("{", StringComparison.InvariantCultureIgnoreCase))
{
- var jObj = JObject.Parse(str);
+ var jObj = JsonParser.ParseObject(str);
string type = null;
// Legacy label
if (!jObj.ContainsKey("type"))
### BTCPayServer/Services/LanguageService.cs
@@ -44,7 +44,7 @@ public LanguageService(IWebHostEnvironment environment, ILogger<LanguageService>
using var stream = new StreamReader(file);
var json = stream.ReadToEnd();
- result.Add(JObject.Parse(json).ToObject<Language>()!);
+ result.Add(JsonParser.ParseObject(json).ToObject<Language>()!);
}
catch (Exception e)
{
### BTCPayServer/Services/Stores/StoreRepository.cs
@@ -880,7 +880,7 @@ public async Task SetDefaultStoreTemplate(StoreData? store)
DefaultPaymentMethodId = store.GetDefaultPaymentId()?.ToString(),
Blob = store.GetStoreBlob()
};
- policies.DefaultStoreTemplate = JObject.Parse(serializer.ToString(r));
+ policies.DefaultStoreTemplate = JsonParser.ParseObject(serializer.ToString(r));
await _settingsRepository.UpdateSetting(policies);
}
### BTCPayServer/Services/WalletRepository.cs
@@ -258,7 +258,7 @@ private Dictionary<string, WalletTransactionInfo> GetWalletTransactionsInfoCore(
var result = new Dictionary<string, WalletTransactionInfo>(wos.Count);
foreach (var obj in wos.Values)
{
- var data = obj.Data is null ? null : JObject.Parse(obj.Data);
+ var data = obj.Data is null ? null : JsonParser.ParseObject(obj.Data);
var info = new WalletTransactionInfo(walletId)
{
Comment = data?["comment"]?.Value<string>(),
@@ -484,7 +484,7 @@ LEFT JOIN "WalletObjects" l
return o.Data is null
? (o.Id, ColorPalette.Default.DeterministicColor(o.Id))
: (o.Id,
- JObject.Parse(o.Data)["color"]?.Value<string>() ?? ColorPalette.Default.DeterministicColor(o.Id));
+ JsonParser.ParseObject(o.Data)["color"]?.Value<string>() ?? ColorPalette.Default.DeterministicColor(o.Id));
}
public async Task<bool> RemoveWalletObjects(WalletObjectId walletObjectId)
@@ -632,7 +632,7 @@ public async Task ModifyWalletObjectData(WalletObjectId id, Action<JObject> modi
ctx.WalletObjects.Add(obj);
}
- var currentData = obj.Data is null ? new JObject() : JObject.Parse(obj.Data);
+ var currentData = obj.Data is null ? new JObject() : JsonParser.ParseObject(obj.Data);
modify(currentData);
obj.Data = currentData.ToString();
if (obj.Data == "{}")
### BTCPayServer/Services/Wallets/Import/Bip329Import.cs
@@ -40,7 +40,7 @@ public static async Task<Result> Parse(TextReader reader, Network network)
JObject obj;
try
{
- obj = JObject.Parse(line);
+ obj = JsonParser.ParseObject(line);
}
catch (JsonException)
{
### BTCPayServer/VaultClient.cs
@@ -32,7 +32,7 @@ public async Task<VaultPermissionResult> AskPermission(CancellationToken cancell
throw new VaultNotConnectedException();
if (p != 200)
throw new VaultException($"Unexpected response code from vault {p}");
- return (resp.Body)?.ToJsonString() is { } str ? JToken.Parse(str) : null;
+ return (resp.Body)?.ToJsonString() is { } str ? JsonParser.ParseToken(str) : null;
}
public class SendRequestResponse
### docs/maintainers/coding-conventions.md
@@ -7,6 +7,10 @@
- Prefer expression-bodied methods when the implementation fits on one line.
- Prefer `Newtonsoft.Json` over `System.Text.Json` when adding or changing JSON
serialization.
+- Use `JsonParser` instead of `JObject.Parse`, `JToken.Parse`, or `JArray.Parse`.
+ It preserves date-like strings and enforces an explicit maximum depth. Pass a
+ different depth only when the JSON envelope is intentionally deeper than the
+ default limit.
- Do not use `ConfigureAwait(false)`; BTCPay Server does not rely on a
synchronization context.
Why this scored 63/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.