Compare commits
12 Commits
feature/pl
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec4359ec1c | ||
|
|
62d160a29b | ||
|
|
2119281141 | ||
|
|
cac72c5682 | ||
|
|
034b272882 | ||
|
|
90bd954a47 | ||
|
|
373c1cbd6a | ||
|
|
edd7e8d2ed | ||
|
|
5faf9ce9c0 | ||
|
|
717f55d2a6 | ||
|
|
3836fe6b38 | ||
|
|
d34405970b |
@ -175,6 +175,161 @@ public class BtcMapsServiceTests
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.OnionUrl));
|
||||
}
|
||||
|
||||
// BTC Map import-RPC fields are mandatory only when SubmitToBtcMap=true. The
|
||||
// default-false path preserves the directory-only callers untouched.
|
||||
|
||||
private static BtcMapsSubmitRequest MakeValidBtcMap()
|
||||
{
|
||||
var req = MakeValid();
|
||||
req.SubmitToBtcMap = true;
|
||||
req.Lat = 51.5074;
|
||||
req.Lon = -0.1278;
|
||||
req.Category = "cafe";
|
||||
req.ExternalId = "store.example.com:abc123";
|
||||
return req;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_AcceptsValidBtcMapSubmission()
|
||||
{
|
||||
Assert.Empty(MakeService().Validate(MakeValidBtcMap()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_DoesNotRequireBtcMapFieldsByDefault()
|
||||
{
|
||||
// Directory-only callers (the pre-existing shape) must not break: a
|
||||
// request with SubmitToBtcMap unset (default false) and no Lat / Lon /
|
||||
// Category / ExternalId is still valid.
|
||||
Assert.Empty(MakeService().Validate(MakeValid()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsMissingLatWhenSubmitToBtcMap()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.Lat = null;
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.Lat));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsOutOfRangeLat()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.Lat = 91.0;
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.Lat));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsNaNLat()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.Lat = double.NaN;
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.Lat));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsMissingLonWhenSubmitToBtcMap()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.Lon = null;
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.Lon));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsOutOfRangeLon()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.Lon = -180.5;
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.Lon));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsMissingCategoryWhenSubmitToBtcMap()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.Category = null;
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.Category));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsUppercaseCategoryWhenSubmitToBtcMap()
|
||||
{
|
||||
// BTC Map docs: "Use a short, single-word (if possible), lowercase identifier."
|
||||
var req = MakeValidBtcMap();
|
||||
req.Category = "Cafe";
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.Category));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsCategoryWithInvalidCharacters()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.Category = "cafe!";
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.Category));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsMissingExternalIdWhenSubmitToBtcMap()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.ExternalId = null;
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.ExternalId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsOverlongExternalId()
|
||||
{
|
||||
var req = MakeValidBtcMap();
|
||||
req.ExternalId = new string('x', 201);
|
||||
Assert.Contains(MakeService().Validate(req), e => e.Path == nameof(BtcMapsSubmitRequest.ExternalId));
|
||||
}
|
||||
|
||||
private static BtcMapsService MakeServiceWithConfig(IDictionary<string, string?> config) =>
|
||||
new BtcMapsService(
|
||||
configuration: new ConfigurationBuilder().AddInMemoryCollection(config).Build(),
|
||||
httpClientFactory: new StubHttpClientFactory(),
|
||||
logger: NullLogger<BtcMapsService>.Instance);
|
||||
|
||||
[Fact]
|
||||
public async System.Threading.Tasks.Task SubmitToBtcMapAsync_RejectsHttpEndpoint()
|
||||
{
|
||||
// Bearer token must never cross the wire over plaintext http://. Misconfigured
|
||||
// endpoint surfaces as InvalidOperationException before HttpClient.SendAsync,
|
||||
// so the token is never built into a request header.
|
||||
var service = MakeServiceWithConfig(new Dictionary<string, string?>
|
||||
{
|
||||
["BTCMAPS:BtcMapImportToken"] = "test-token",
|
||||
["BTCMAPS:BtcMapImportEndpoint"] = "http://api.btcmap.org/rpc"
|
||||
});
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => service.SubmitToBtcMapAsync(MakeValidBtcMap()));
|
||||
Assert.Contains("https", ex.Message, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async System.Threading.Tasks.Task SubmitToBtcMapAsync_RejectsNonAbsoluteEndpoint()
|
||||
{
|
||||
var service = MakeServiceWithConfig(new Dictionary<string, string?>
|
||||
{
|
||||
["BTCMAPS:BtcMapImportToken"] = "test-token",
|
||||
["BTCMAPS:BtcMapImportEndpoint"] = "/rpc"
|
||||
});
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => service.SubmitToBtcMapAsync(MakeValidBtcMap()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async System.Threading.Tasks.Task SubmitToBtcMapAsync_ThrowsTokenMissingWhenUnset()
|
||||
{
|
||||
// Token unset is the ops-deployment-pending shape; controller maps this to
|
||||
// 503 btcmap-not-configured. Test the underlying exception type so the
|
||||
// controller exception ladder stays wired.
|
||||
var service = MakeServiceWithConfig(new Dictionary<string, string?>());
|
||||
await Assert.ThrowsAsync<BtcMapsService.BtcMapTokenMissingException>(
|
||||
() => service.SubmitToBtcMapAsync(MakeValidBtcMap()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormalizeUrl_LowercasesSchemeAndHostOnly()
|
||||
{
|
||||
|
||||
@ -12,4 +12,35 @@ public sealed class BtcMapsSubmitRequest
|
||||
public string? Twitter { get; set; }
|
||||
public string? Github { get; set; }
|
||||
public string? OnionUrl { get; set; }
|
||||
public string? Phone { get; set; }
|
||||
|
||||
// BTC Map import RPC fields. Required iff SubmitToBtcMap=true.
|
||||
// Plugin captures lat/lon and composes external_id as hostname:storeId
|
||||
// so this endpoint just passes through to the btcmap submit_place RPC.
|
||||
public double? Lat { get; set; }
|
||||
public double? Lon { get; set; }
|
||||
public string? Category { get; set; }
|
||||
public string? ExternalId { get; set; }
|
||||
|
||||
// Address fields. Optional; forwarded to btcmap as osm:addr:* tags per the
|
||||
// BTC Map import-RPC doc's osm:<tag_name> custom-field convention.
|
||||
public string? HouseNumber { get; set; }
|
||||
public string? Street { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? Postcode { get; set; }
|
||||
|
||||
// Email - first-class field on btcmap rest/v4/places.md. Plain key, no prefix.
|
||||
public string? Email { get; set; }
|
||||
|
||||
// Payment-rail flags. Plugin sets these per the store's enabled rails;
|
||||
// each true value emits the corresponding `payment:onchain=yes` /
|
||||
// `payment:lightning=yes` marker in extra_fields. Null / false = omitted.
|
||||
public bool? AcceptsOnchain { get; set; }
|
||||
public bool? AcceptsLightning { get; set; }
|
||||
|
||||
// Routing flags. Default-true preserves the existing call-site semantics
|
||||
// for SubmitToDirectory; SubmitToBtcMap defaults false so callers must
|
||||
// opt in to the new path.
|
||||
public bool SubmitToDirectory { get; set; } = true;
|
||||
public bool SubmitToBtcMap { get; set; }
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@ namespace PluginBuilder.APIModels;
|
||||
public sealed class BtcMapsSubmitResponse
|
||||
{
|
||||
public BtcMapsDirectoryResult? Directory { get; set; }
|
||||
public BtcMapsBtcMapResult? BtcMap { get; set; }
|
||||
}
|
||||
|
||||
public sealed class BtcMapsDirectoryResult
|
||||
@ -12,3 +13,10 @@ public sealed class BtcMapsDirectoryResult
|
||||
public string? Branch { get; set; }
|
||||
public string? Skipped { get; set; }
|
||||
}
|
||||
|
||||
public sealed class BtcMapsBtcMapResult
|
||||
{
|
||||
public long? Id { get; set; }
|
||||
public string? Origin { get; set; }
|
||||
public string? ExternalId { get; set; }
|
||||
}
|
||||
|
||||
@ -30,57 +30,80 @@ public sealed class BtcMapsController(
|
||||
if (errors.Count > 0)
|
||||
return BadRequest(new { errors });
|
||||
|
||||
// At least one downstream lane must run; "submit nothing" is almost
|
||||
// certainly a caller bug (forgot to set the flag) rather than a legit
|
||||
// intent, and silently 200-ing an empty response would hide it.
|
||||
if (!request.SubmitToDirectory && !request.SubmitToBtcMap)
|
||||
{
|
||||
return BadRequest(new { errors = new[] {
|
||||
new ValidationError("body", "At least one of SubmitToDirectory or SubmitToBtcMap must be true.")
|
||||
}});
|
||||
}
|
||||
|
||||
var correlationId = Guid.NewGuid().ToString("N");
|
||||
BtcMapsDirectoryResult directory;
|
||||
BtcMapsDirectoryResult? directory = null;
|
||||
BtcMapsBtcMapResult? btcMap = null;
|
||||
|
||||
try
|
||||
if (request.SubmitToDirectory)
|
||||
{
|
||||
directory = await btcMapsService.SubmitToDirectoryAsync(request, cancellationToken);
|
||||
}
|
||||
catch (BtcMapsService.DirectoryTokenMissingException ex)
|
||||
{
|
||||
// Missing token is a server-side deployment / configuration outage,
|
||||
// not a normal "skipped" outcome. Surface 503 so clients (and ops)
|
||||
// can distinguish it from an accepted submission.
|
||||
logger.LogError(ex, "BTCMaps directory submission rejected: token not configured (correlationId={CorrelationId})", correlationId);
|
||||
return StatusCode(StatusCodes.Status503ServiceUnavailable, new
|
||||
try
|
||||
{
|
||||
error = "directory-not-configured",
|
||||
correlationId
|
||||
});
|
||||
}
|
||||
catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Caller cancelled (client disconnect, request abort). Rethrow so
|
||||
// the pipeline drops the connection without producing a response
|
||||
// body the client will never read.
|
||||
logger.LogInformation(ex, "BTCMaps directory submission cancelled by caller (correlationId={CorrelationId})", correlationId);
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
// OCE without caller cancellation = HttpClient.Timeout surfacing as
|
||||
// TaskCanceledException. Treat as an upstream timeout, distinct
|
||||
// from a generic 502 so ops + the plugin client can tell them apart.
|
||||
logger.LogError(ex, "BTCMaps directory submission timed out upstream (correlationId={CorrelationId}) for {Name} ({Url})",
|
||||
correlationId, request.Name, request.Url);
|
||||
return StatusCode(StatusCodes.Status504GatewayTimeout, new
|
||||
directory = await btcMapsService.SubmitToDirectoryAsync(request, cancellationToken);
|
||||
}
|
||||
catch (BtcMapsService.DirectoryTokenMissingException ex)
|
||||
{
|
||||
error = "directory-upstream-timeout",
|
||||
correlationId
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "BTCMaps directory submission failed (correlationId={CorrelationId}) for {Name} ({Url})",
|
||||
correlationId, request.Name, request.Url);
|
||||
return StatusCode(StatusCodes.Status502BadGateway, new
|
||||
logger.LogError(ex, "BTCMaps directory submission rejected: token not configured (correlationId={CorrelationId})", correlationId);
|
||||
return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "directory-not-configured", correlationId });
|
||||
}
|
||||
catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
error = "directory-upstream-failed",
|
||||
correlationId
|
||||
});
|
||||
logger.LogInformation(ex, "BTCMaps directory submission cancelled by caller (correlationId={CorrelationId})", correlationId);
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
logger.LogError(ex, "BTCMaps directory submission timed out upstream (correlationId={CorrelationId}) for {Name} ({Url})",
|
||||
correlationId, request.Name, request.Url);
|
||||
return StatusCode(StatusCodes.Status504GatewayTimeout, new { error = "directory-upstream-timeout", correlationId });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "BTCMaps directory submission failed (correlationId={CorrelationId}) for {Name} ({Url})",
|
||||
correlationId, request.Name, request.Url);
|
||||
return StatusCode(StatusCodes.Status502BadGateway, new { error = "directory-upstream-failed", correlationId });
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(new BtcMapsSubmitResponse { Directory = directory });
|
||||
if (request.SubmitToBtcMap)
|
||||
{
|
||||
try
|
||||
{
|
||||
btcMap = await btcMapsService.SubmitToBtcMapAsync(request, cancellationToken);
|
||||
}
|
||||
catch (BtcMapsService.BtcMapTokenMissingException ex)
|
||||
{
|
||||
logger.LogError(ex, "BTCMaps import submission rejected: token not configured (correlationId={CorrelationId})", correlationId);
|
||||
return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "btcmap-not-configured", correlationId });
|
||||
}
|
||||
catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
logger.LogInformation(ex, "BTCMaps import submission cancelled by caller (correlationId={CorrelationId})", correlationId);
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
logger.LogError(ex, "BTCMaps import submission timed out upstream (correlationId={CorrelationId}) for {Name} ({Url})",
|
||||
correlationId, request.Name, request.Url);
|
||||
return StatusCode(StatusCodes.Status504GatewayTimeout, new { error = "btcmap-upstream-timeout", correlationId });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "BTCMaps import submission failed (correlationId={CorrelationId}) for {Name} ({Url})",
|
||||
correlationId, request.Name, request.Url);
|
||||
return StatusCode(StatusCodes.Status502BadGateway, new { error = "btcmap-upstream-failed", correlationId });
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(new BtcMapsSubmitResponse { Directory = directory, BtcMap = btcMap });
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,4 +5,5 @@ public static class HttpClientNames
|
||||
public const string GitHub = nameof(GitHub);
|
||||
public const string GitLab = nameof(GitLab);
|
||||
public const string BtcMapsDirectory = nameof(BtcMapsDirectory);
|
||||
public const string BtcMap = nameof(BtcMap);
|
||||
}
|
||||
|
||||
@ -223,6 +223,16 @@ public class Program
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
||||
client.Timeout = TimeSpan.FromSeconds(15);
|
||||
});
|
||||
services.AddHttpClient(HttpClientNames.BtcMap, client =>
|
||||
{
|
||||
// BTC Map import RPC is a single JSON-RPC 2.0 dispatch endpoint.
|
||||
// Per-call timeout caps a single round-trip at 15s, matching the
|
||||
// BtcMapsDirectory budget so a hung remote can't pin the request
|
||||
// longer than the per-IP rate-limit window.
|
||||
client.DefaultRequestHeaders.Add("User-Agent", "PluginBuilder-BtcMap/1.0");
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
client.Timeout = TimeSpan.FromSeconds(15);
|
||||
});
|
||||
services.AddHttpClient(HttpClientNames.GitLab, client =>
|
||||
{
|
||||
client.BaseAddress = new Uri("https://gitlab.com/api/v4/");
|
||||
@ -281,13 +291,16 @@ public class Program
|
||||
});
|
||||
options.AddPolicy(Policies.BtcMapsSubmitRateLimit, httpContext =>
|
||||
{
|
||||
// Per-source-IP fixed window: 5 submissions per 24h. Caps automation
|
||||
// Per-source-IP fixed window: 3 submissions per 24h. Caps automation
|
||||
// abuse of /apis/btcmaps/v1/submit without throttling honest single
|
||||
// submissions from a merchant.
|
||||
// submissions from a merchant. Tightened from 5/24h with the
|
||||
// multi-vendor BTC Map import-RPC lane (PR #226) since that path
|
||||
// forwards into a moderator review queue and rate-limit is the
|
||||
// primary spam control on the public endpoint.
|
||||
var clientIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
return RateLimitPartition.GetFixedWindowLimiter(clientIp, _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = 5,
|
||||
PermitLimit = 3,
|
||||
Window = TimeSpan.FromHours(24),
|
||||
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
|
||||
QueueLimit = 0
|
||||
|
||||
@ -75,48 +75,79 @@ public sealed class BtcMapsService
|
||||
public DirectoryTokenMissingException() : base("BTCMAPS:DirectoryGithubToken is not configured.") { }
|
||||
}
|
||||
|
||||
public sealed class BtcMapTokenMissingException : Exception
|
||||
{
|
||||
public BtcMapTokenMissingException() : base("BTCMAPS:BtcMapImportToken is not configured.") { }
|
||||
}
|
||||
|
||||
private const string DefaultBtcMapImportEndpoint = "https://api.btcmap.org/rpc";
|
||||
private const string BtcMapImportOrigin = "btcpayserver";
|
||||
private const string BtcMapImportMethod = "submit_place";
|
||||
|
||||
public IReadOnlyList<ValidationError> Validate(BtcMapsSubmitRequest request)
|
||||
{
|
||||
var errors = new List<ValidationError>();
|
||||
|
||||
// Name is the only field both lanes need - btcmap submit_place requires it
|
||||
// as part of the params payload, and the directory merchants.json keys
|
||||
// entries by name.
|
||||
var name = (request.Name ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(name) || name.Length > 200)
|
||||
errors.Add(new ValidationError(nameof(request.Name), "Required, 1-200 characters."));
|
||||
|
||||
var url = (request.Url ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(url))
|
||||
errors.Add(new ValidationError(nameof(request.Url), "Required."));
|
||||
else if (!Uri.TryCreate(url, UriKind.Absolute, out var parsed) || parsed.Scheme != Uri.UriSchemeHttps)
|
||||
errors.Add(new ValidationError(nameof(request.Url), "Must be a valid https:// URL."));
|
||||
|
||||
var description = (request.Description ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(description) || description.Length > 1000)
|
||||
errors.Add(new ValidationError(nameof(request.Description), "Required, 1-1000 characters."));
|
||||
|
||||
var type = (request.Type ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(type) || !ValidTypes.Contains(type))
|
||||
errors.Add(new ValidationError(nameof(request.Type),
|
||||
$"Required. One of: {string.Join(", ", ValidTypes)}."));
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.SubType))
|
||||
// Directory-lane required fields. Skip when the caller opted out of the
|
||||
// directory submission so a btcmap-only call doesn't need to fill in
|
||||
// unrelated directory metadata.
|
||||
if (request.SubmitToDirectory)
|
||||
{
|
||||
var subType = request.SubType.Trim();
|
||||
if (string.Equals(type, "merchants", StringComparison.OrdinalIgnoreCase) &&
|
||||
!ValidMerchantSubTypes.Contains(subType))
|
||||
var url = (request.Url ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(url))
|
||||
errors.Add(new ValidationError(nameof(request.Url), "Required when SubmitToDirectory=true."));
|
||||
else if (!Uri.TryCreate(url, UriKind.Absolute, out var parsed) || parsed.Scheme != Uri.UriSchemeHttps)
|
||||
errors.Add(new ValidationError(nameof(request.Url), "Must be a valid https:// URL."));
|
||||
|
||||
var description = (request.Description ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(description) || description.Length > 1000)
|
||||
errors.Add(new ValidationError(nameof(request.Description), "Required when SubmitToDirectory=true. 1-1000 characters."));
|
||||
|
||||
var type = (request.Type ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(type) || !ValidTypes.Contains(type))
|
||||
errors.Add(new ValidationError(nameof(request.Type),
|
||||
$"Required when SubmitToDirectory=true. One of: {string.Join(", ", ValidTypes)}."));
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.SubType))
|
||||
{
|
||||
errors.Add(new ValidationError(nameof(request.SubType),
|
||||
"Invalid merchant subtype."));
|
||||
var subType = request.SubType.Trim();
|
||||
if (string.Equals(type, "merchants", StringComparison.OrdinalIgnoreCase) &&
|
||||
!ValidMerchantSubTypes.Contains(subType))
|
||||
{
|
||||
errors.Add(new ValidationError(nameof(request.SubType),
|
||||
"Invalid merchant subtype."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Country format check applies to either lane. GLOBAL is the directory's
|
||||
// pseudonym for online-only / multi-region merchants but it is NOT a valid
|
||||
// physical-place country code for the btcmap directory map (every place
|
||||
// there is geocoded). Reject GLOBAL when the btcmap lane is on; allow it
|
||||
// when only the directory lane is in play.
|
||||
if (!string.IsNullOrWhiteSpace(request.Country))
|
||||
{
|
||||
var country = request.Country.Trim();
|
||||
// GLOBAL is the directory's pseudonym for online-only / multi-region merchants.
|
||||
// Everything else must be an actual ISO 3166-1 alpha-2 code.
|
||||
if (country != "GLOBAL" && !Iso3166Alpha2.Contains(country))
|
||||
if (country == "GLOBAL")
|
||||
{
|
||||
if (request.SubmitToBtcMap)
|
||||
{
|
||||
errors.Add(new ValidationError(nameof(request.Country),
|
||||
"Country=GLOBAL is incompatible with SubmitToBtcMap=true (btcmap places are physical locations). Use an ISO 3166-1 alpha-2 code or omit Country."));
|
||||
}
|
||||
}
|
||||
else if (!Iso3166Alpha2.Contains(country))
|
||||
{
|
||||
errors.Add(new ValidationError(nameof(request.Country),
|
||||
"Must be ISO 3166-1 alpha-2 or GLOBAL."));
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.OnionUrl))
|
||||
@ -130,9 +161,144 @@ public sealed class BtcMapsService
|
||||
}
|
||||
}
|
||||
|
||||
// BTC Map import RPC fields become mandatory only when the caller
|
||||
// opts into that lane via SubmitToBtcMap=true. Directory-only callers
|
||||
// (the existing PR #224 shape) are unaffected.
|
||||
if (request.SubmitToBtcMap)
|
||||
{
|
||||
if (!request.Lat.HasValue || request.Lat.Value is < -90 or > 90 || double.IsNaN(request.Lat.Value))
|
||||
errors.Add(new ValidationError(nameof(request.Lat),
|
||||
"Required when SubmitToBtcMap=true. Must be in [-90, 90]."));
|
||||
|
||||
if (!request.Lon.HasValue || request.Lon.Value is < -180 or > 180 || double.IsNaN(request.Lon.Value))
|
||||
errors.Add(new ValidationError(nameof(request.Lon),
|
||||
"Required when SubmitToBtcMap=true. Must be in [-180, 180]."));
|
||||
|
||||
var category = (request.Category ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(category) || category.Length > 50 ||
|
||||
!category.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '-' or '_'))
|
||||
{
|
||||
errors.Add(new ValidationError(nameof(request.Category),
|
||||
"Required when SubmitToBtcMap=true. Short lowercase identifier (a-z, 0-9, -, _; max 50 chars)."));
|
||||
}
|
||||
|
||||
var externalId = (request.ExternalId ?? string.Empty).Trim();
|
||||
if (string.IsNullOrEmpty(externalId) || externalId.Length > 200)
|
||||
errors.Add(new ValidationError(nameof(request.ExternalId),
|
||||
"Required when SubmitToBtcMap=true. 1-200 characters."));
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
public async Task<BtcMapsBtcMapResult> SubmitToBtcMapAsync(
|
||||
BtcMapsSubmitRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var token = _configuration["BTCMAPS:BtcMapImportToken"];
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
throw new BtcMapTokenMissingException();
|
||||
|
||||
// Bearer tokens MUST NOT cross the wire over http://; an operator-
|
||||
// misconfigured endpoint would silently leak the scoped token to
|
||||
// anyone on the network path. Parse the configured value into an
|
||||
// absolute https URI before we even create the request, so a bad
|
||||
// BTCMAPS:BtcMapImportEndpoint fails loudly with the offending
|
||||
// value in the message instead of producing a quiet credential leak.
|
||||
var endpoint = (_configuration["BTCMAPS:BtcMapImportEndpoint"] ?? DefaultBtcMapImportEndpoint).Trim();
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var endpointUri) ||
|
||||
endpointUri.Scheme != Uri.UriSchemeHttps)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"BTCMAPS:BtcMapImportEndpoint must be an absolute https:// URL (got '{endpoint}').");
|
||||
}
|
||||
|
||||
var client = _httpClientFactory.CreateClient(HttpClientNames.BtcMap);
|
||||
|
||||
// BTC Map import-RPC takes a JSON-RPC 2.0 envelope at /rpc with method=submit_place.
|
||||
// Required params: origin, external_id, lat, lon, category, name. extra_fields uses
|
||||
// the documented first-class keys (phone, website, description) and the osm:<tag_name>
|
||||
// convention for granular OSM tags (osm:addr:*).
|
||||
var extraFields = new Dictionary<string, object?>();
|
||||
// First-class btcmap fields (plain keys per rest/v4/places.md).
|
||||
if (!string.IsNullOrWhiteSpace(request.Url)) extraFields["website"] = request.Url.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.Description)) extraFields["description"] = request.Description.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.Phone)) extraFields["phone"] = request.Phone.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.Email)) extraFields["email"] = request.Email.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.Twitter))
|
||||
{
|
||||
// btcmap's `twitter` field is documented as a URL. Normalize the @handle
|
||||
// shape the rest of the API accepts (with or without leading @) into
|
||||
// the URL form the directory map expects.
|
||||
var t = request.Twitter.Trim();
|
||||
var handle = t.StartsWith("@") ? t[1..] : t;
|
||||
extraFields["twitter"] = handle.StartsWith("http", StringComparison.OrdinalIgnoreCase)
|
||||
? handle
|
||||
: $"https://x.com/{handle}";
|
||||
}
|
||||
// OSM custom tags use osm:<tag_name> per the same doc.
|
||||
if (!string.IsNullOrWhiteSpace(request.HouseNumber)) extraFields["osm:addr:housenumber"] = request.HouseNumber.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.Street)) extraFields["osm:addr:street"] = request.Street.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.City)) extraFields["osm:addr:city"] = request.City.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.Postcode)) extraFields["osm:addr:postcode"] = request.Postcode.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(request.Country)) extraFields["osm:addr:country"] = request.Country.Trim();
|
||||
// Payment-rail flags. Plugin sets per the store's enabled rails - omit
|
||||
// when null or false so a Lightning-only store doesn't claim on-chain
|
||||
// support (or vice versa).
|
||||
if (request.AcceptsOnchain == true) extraFields["osm:payment:onchain"] = "yes";
|
||||
if (request.AcceptsLightning == true) extraFields["osm:payment:lightning"] = "yes";
|
||||
|
||||
var rpcParams = new Dictionary<string, object?>
|
||||
{
|
||||
["origin"] = BtcMapImportOrigin,
|
||||
["external_id"] = request.ExternalId!.Trim(),
|
||||
["lat"] = request.Lat!.Value,
|
||||
["lon"] = request.Lon!.Value,
|
||||
["category"] = request.Category!.Trim().ToLowerInvariant(),
|
||||
["name"] = request.Name!.Trim(),
|
||||
["extra_fields"] = extraFields
|
||||
};
|
||||
|
||||
var envelope = new Dictionary<string, object?>
|
||||
{
|
||||
["jsonrpc"] = "2.0",
|
||||
["method"] = BtcMapImportMethod,
|
||||
["params"] = rpcParams,
|
||||
["id"] = 1
|
||||
};
|
||||
|
||||
using var req = new HttpRequestMessage(HttpMethod.Post, endpointUri);
|
||||
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
req.Content = new StringContent(JsonSerializer.Serialize(envelope), Encoding.UTF8, "application/json");
|
||||
|
||||
using var response = await client.SendAsync(req, cancellationToken);
|
||||
var body = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new HttpRequestException($"BtcMap RPC {(int)response.StatusCode} {endpointUri}: {body}");
|
||||
|
||||
using var doc = JsonDocument.Parse(body);
|
||||
var root = doc.RootElement;
|
||||
|
||||
// JSON-RPC 2.0 response shape: either {result: {...}} on success or {error: {...}}.
|
||||
// 2xx status with an error body is a legal JSON-RPC outcome we must surface.
|
||||
if (root.TryGetProperty("error", out var errorElement))
|
||||
{
|
||||
var errorJson = errorElement.GetRawText();
|
||||
throw new HttpRequestException($"BtcMap RPC error response: {errorJson}");
|
||||
}
|
||||
|
||||
if (!root.TryGetProperty("result", out var result))
|
||||
throw new HttpRequestException($"BtcMap RPC missing result: {body}");
|
||||
|
||||
return new BtcMapsBtcMapResult
|
||||
{
|
||||
Id = result.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.Number ? id.GetInt64() : null,
|
||||
Origin = result.TryGetProperty("origin", out var origin) ? origin.GetString() : null,
|
||||
ExternalId = result.TryGetProperty("external_id", out var ext) ? ext.GetString() : null
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<BtcMapsDirectoryResult> SubmitToDirectoryAsync(
|
||||
BtcMapsSubmitRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user