feat(S1): add webhook Ed25519 verification, WS-only config and health endpoint
This commit is contained in:
@@ -18,3 +18,10 @@ appsettings.*.local.json
|
|||||||
|
|
||||||
# WorkBuddy 会话数据
|
# WorkBuddy 会话数据
|
||||||
.workbuddy/
|
.workbuddy/
|
||||||
|
|
||||||
|
# 本地 EF CLI 工具、SQLite 数据库与测试结果
|
||||||
|
.tools/
|
||||||
|
*.db
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
TestResults/
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<IsTestProject>true</IsTestProject>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.3" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\OshimaBot\OshimaBot.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using OshimaBot.Models;
|
||||||
|
using OshimaBot.Security;
|
||||||
|
using Rebex.Security.Cryptography;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace OshimaBot.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 测试数据取自 QQ 机器人官方文档:
|
||||||
|
/// 安全和授权 https://bot.qq.com/wiki/develop/api-v2/dev-prepare/interface-framework/sign.html
|
||||||
|
/// Webhook 方式 https://bot.qq.com/wiki/develop/api-v2/dev-prepare/event-emit/webhook.html
|
||||||
|
///
|
||||||
|
/// 注意:sign.html DEMO 中的 sig(865ad13a…)与其展示的 secret/body 并不自洽,
|
||||||
|
/// 用同一 secret 对 "timestamp + body" 实签得到的是 2eb9983e…。
|
||||||
|
/// 因此验签正例改用「自签往返」,另有 DocumentedDemoSignature_IsNotReproducible 记录该差异。
|
||||||
|
/// 密钥派生、op=13 验证签名仍以官方 DEMO 为准(均可精确复现)。
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WebhookSignatureVerifierTests
|
||||||
|
{
|
||||||
|
private const string Secret = "naOC0ocQE3shWLAfffVLB1rhYPG7";
|
||||||
|
private const string OfficialSeed = "naOC0ocQE3shWLAfffVLB1rhYPG7naOC";
|
||||||
|
private const string Body = "{ \"op\": 0,\"d\": {}, \"t\": \"GATEWAY_EVENT_NAME\"}";
|
||||||
|
private const string Timestamp = "1725442341";
|
||||||
|
private const string DocumentedDemoSignature =
|
||||||
|
"865ad13a61752ca65e26bde6676459cd36cf1be609375b37bd62af366e1dc25a8dc789ba7f14e017ada3d554c671a911bfdf075ba54835b23391d509579ed002";
|
||||||
|
private const string AppId = "11111111";
|
||||||
|
|
||||||
|
private static readonly byte[] OfficialPublicKey =
|
||||||
|
[
|
||||||
|
215, 195, 98, 254, 120, 174, 248, 31, 242, 50, 135, 180, 147, 98,
|
||||||
|
139, 93, 176, 42, 60, 79, 227, 11, 33, 94, 77, 25, 96, 155, 93,
|
||||||
|
118, 103, 58
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly DateTimeOffset EventTime = DateTimeOffset.FromUnixTimeSeconds(1725442341);
|
||||||
|
|
||||||
|
private static WebhookSignatureVerifier Create(string secret = Secret, string appId = AppId, int maxAge = 300)
|
||||||
|
=> new(Options.Create(new QQBotOptions
|
||||||
|
{
|
||||||
|
Secret = secret,
|
||||||
|
AppId = appId,
|
||||||
|
SignatureMaxAgeSeconds = maxAge
|
||||||
|
}));
|
||||||
|
|
||||||
|
/// <summary>用官方 DEMO 的 secret 对 "timestamp + body" 生成合法签名,供往返测试使用。</summary>
|
||||||
|
private static string SignBody(string body = Body)
|
||||||
|
{
|
||||||
|
Ed25519 ed25519 = new();
|
||||||
|
ed25519.FromSeed(WebhookSignatureVerifier.DeriveSeed(Secret));
|
||||||
|
byte[] signature = ed25519.SignMessage(Encoding.UTF8.GetBytes(Timestamp + body));
|
||||||
|
return Convert.ToHexString(signature).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DeriveSeed_MatchesOfficialDemo()
|
||||||
|
{
|
||||||
|
byte[] seed = WebhookSignatureVerifier.DeriveSeed(Secret);
|
||||||
|
Assert.Equal(32, seed.Length);
|
||||||
|
Assert.Equal(OfficialSeed, Encoding.UTF8.GetString(seed));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DerivePublicKey_MatchesOfficialDemo()
|
||||||
|
=> Assert.Equal(OfficialPublicKey, WebhookSignatureVerifier.DerivePublicKey(Secret));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DocumentedDemoSignature_IsNotReproducible()
|
||||||
|
=> Assert.NotEqual(DocumentedDemoSignature, SignBody());
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RoundTrip_SignatureIsAccepted()
|
||||||
|
{
|
||||||
|
WebhookVerificationResult result = Create().Verify(
|
||||||
|
SignBody(), Timestamp, AppId, Encoding.UTF8.GetBytes(Body), EventTime);
|
||||||
|
Assert.True(result.IsValid, $"{result.Failure}: {result.Reason}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TamperedBody_IsRejected()
|
||||||
|
{
|
||||||
|
byte[] body = Encoding.UTF8.GetBytes(Body.Replace("GATEWAY_EVENT_NAME", "GATEWAY_EVENT_OTHER"));
|
||||||
|
WebhookVerificationResult result = Create().Verify(SignBody(), Timestamp, AppId, body, EventTime);
|
||||||
|
Assert.False(result.IsValid);
|
||||||
|
Assert.Equal(WebhookVerificationFailure.InvalidSignature, result.Failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TamperedSignature_IsRejected()
|
||||||
|
{
|
||||||
|
string signature = SignBody();
|
||||||
|
string tampered = (signature[0] == '8' ? "7" : "8") + signature[1..];
|
||||||
|
WebhookVerificationResult result = Create().Verify(
|
||||||
|
tampered, Timestamp, AppId, Encoding.UTF8.GetBytes(Body), EventTime);
|
||||||
|
Assert.False(result.IsValid);
|
||||||
|
Assert.Equal(WebhookVerificationFailure.InvalidSignature, result.Failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingHeaders_AreRejected()
|
||||||
|
{
|
||||||
|
WebhookVerificationResult result = Create().Verify(
|
||||||
|
null, null, AppId, Encoding.UTF8.GetBytes(Body), EventTime);
|
||||||
|
Assert.Equal(WebhookVerificationFailure.MissingHeaders, result.Failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MalformedSignature_IsRejected()
|
||||||
|
{
|
||||||
|
WebhookVerificationResult result = Create().Verify(
|
||||||
|
"not-hex", Timestamp, AppId, Encoding.UTF8.GetBytes(Body), EventTime);
|
||||||
|
Assert.Equal(WebhookVerificationFailure.MalformedSignature, result.Failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ExpiredTimestamp_IsRejected()
|
||||||
|
{
|
||||||
|
WebhookVerificationResult result = Create().Verify(
|
||||||
|
SignBody(), Timestamp, AppId, Encoding.UTF8.GetBytes(Body), EventTime.AddMinutes(30));
|
||||||
|
Assert.Equal(WebhookVerificationFailure.TimestampExpired, result.Failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AppIdMismatch_IsRejected()
|
||||||
|
{
|
||||||
|
WebhookVerificationResult result = Create().Verify(
|
||||||
|
SignBody(), Timestamp, "99999999", Encoding.UTF8.GetBytes(Body), EventTime);
|
||||||
|
Assert.Equal(WebhookVerificationFailure.AppIdMismatch, result.Failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingSecret_IsRejected()
|
||||||
|
{
|
||||||
|
WebhookVerificationResult result = Create(secret: "").Verify(
|
||||||
|
SignBody(), Timestamp, AppId, Encoding.UTF8.GetBytes(Body), EventTime);
|
||||||
|
Assert.Equal(WebhookVerificationFailure.MissingSecret, result.Failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ValidationSignature_MatchesOfficialWebhookDemo()
|
||||||
|
{
|
||||||
|
// 官方 webhook.html:appid 11111111 / secret DG5g3B4j9X2KOErG
|
||||||
|
const string secret = "DG5g3B4j9X2KOErG";
|
||||||
|
const string plainToken = "Arq0D5A61EgUu4OxUvOp";
|
||||||
|
const string eventTs = "1725442341";
|
||||||
|
const string expected =
|
||||||
|
"87befc99c42c651b3aac0278e71ada338433ae26fcb24307bdc5ad38c1adc2d01bcfcadc0842edac85e85205028a1132afe09280305f13aa6909ffc2d652c706";
|
||||||
|
|
||||||
|
byte[] signature = WebhookSignatureVerifier.SignValidation(secret, eventTs, plainToken);
|
||||||
|
Assert.Equal(expected, Convert.ToHexString(signature).ToLowerInvariant());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class QQBotOptionsTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Defaults_UseWebSocketSingleMode()
|
||||||
|
{
|
||||||
|
QQBotOptions options = new();
|
||||||
|
Assert.Equal(QQBotMode.WebSocket, options.Mode);
|
||||||
|
Assert.False(options.EnableWebhook);
|
||||||
|
Assert.Equal(100663296, options.Intents);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ApiBaseAddress_ResolvesByEnvironment()
|
||||||
|
{
|
||||||
|
Assert.Equal("https://sandbox.api.sgroup.qq.com", new QQBotOptions().ResolvedApiBaseAddress);
|
||||||
|
Assert.Equal("https://api.sgroup.qq.com", new QQBotOptions
|
||||||
|
{
|
||||||
|
Environment = QQBotEnvironment.Production
|
||||||
|
}.ResolvedApiBaseAddress);
|
||||||
|
Assert.Equal("https://example.test", new QQBotOptions
|
||||||
|
{
|
||||||
|
ApiBaseAddress = "https://example.test/"
|
||||||
|
}.ResolvedApiBaseAddress);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,4 +3,5 @@
|
|||||||
<Project Path="OshimaBot.Content/OshimaBot.Content.csproj" />
|
<Project Path="OshimaBot.Content/OshimaBot.Content.csproj" />
|
||||||
<Project Path="OshimaBot.Game/OshimaBot.Game.csproj" />
|
<Project Path="OshimaBot.Game/OshimaBot.Game.csproj" />
|
||||||
<Project Path="OshimaBot/OshimaBot.csproj" />
|
<Project Path="OshimaBot/OshimaBot.csproj" />
|
||||||
|
<Project Path="OshimaBot.Tests/OshimaBot.Tests.csproj" />
|
||||||
</Solution>
|
</Solution>
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
using System.Text;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using OshimaBot.Models;
|
|
||||||
using OshimaBot.Security;
|
|
||||||
using OshimaBot.Services;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Caching.Memory;
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Rebex.Security.Cryptography;
|
using OshimaBot.Models;
|
||||||
|
using OshimaBot.Security;
|
||||||
|
using OshimaBot.Services;
|
||||||
|
|
||||||
namespace OshimaBot.Controllers
|
namespace OshimaBot.Controllers
|
||||||
{
|
{
|
||||||
@@ -23,6 +21,8 @@ namespace OshimaBot.Controllers
|
|||||||
[HttpPost]
|
[HttpPost]
|
||||||
public async Task<IActionResult> Post([FromBody] Payload? payload, CancellationToken cancellationToken)
|
public async Task<IActionResult> Post([FromBody] Payload? payload, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
// WebSocket 为唯一运行模式;webhook 仅在 QQBot:EnableWebhook=true 时接受平台回调。
|
||||||
|
if (!_options.EnableWebhook) return NotFound();
|
||||||
if (payload is null) return BadRequest("Payload 格式无效。");
|
if (payload is null) return BadRequest("Payload 格式无效。");
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -30,6 +30,8 @@ namespace OshimaBot.Controllers
|
|||||||
return payload.Op switch
|
return payload.Op switch
|
||||||
{
|
{
|
||||||
13 => HandleValidation(payload),
|
13 => HandleValidation(payload),
|
||||||
|
// op=12 是 HTTP 回调模式的 ACK 回包;平台不会主动推送,HTTP 200 即视为确认。
|
||||||
|
12 => Ok(),
|
||||||
0 => await HandleEventAsync(payload, cancellationToken),
|
0 => await HandleEventAsync(payload, cancellationToken),
|
||||||
_ => Ok()
|
_ => Ok()
|
||||||
};
|
};
|
||||||
@@ -54,13 +56,8 @@ namespace OshimaBot.Controllers
|
|||||||
return BadRequest("无效的验证 Payload 格式。");
|
return BadRequest("无效的验证 Payload 格式。");
|
||||||
}
|
}
|
||||||
|
|
||||||
string seed = _options.Secret;
|
byte[] signature = WebhookSignatureVerifier.SignValidation(
|
||||||
while (seed.Length < 32) seed += seed;
|
_options.Secret, validation.EventTs, validation.PlainToken);
|
||||||
seed = seed[..32];
|
|
||||||
|
|
||||||
Ed25519 ed25519 = new();
|
|
||||||
ed25519.FromSeed(Encoding.UTF8.GetBytes(seed));
|
|
||||||
byte[] signature = ed25519.SignMessage(Encoding.UTF8.GetBytes(validation.EventTs + validation.PlainToken));
|
|
||||||
|
|
||||||
return Ok(new ValidationResponse
|
return Ok(new ValidationResponse
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,21 +1,74 @@
|
|||||||
namespace OshimaBot.Models
|
namespace OshimaBot.Models
|
||||||
{
|
{
|
||||||
|
/// <summary>QQ 官方事件接入方式。</summary>
|
||||||
|
public enum QQBotMode
|
||||||
|
{
|
||||||
|
WebSocket,
|
||||||
|
Webhook
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>QQ 开放平台运行环境(决定 API 域名)。</summary>
|
||||||
|
public enum QQBotEnvironment
|
||||||
|
{
|
||||||
|
Sandbox,
|
||||||
|
Production
|
||||||
|
}
|
||||||
|
|
||||||
public sealed class QQBotOptions
|
public sealed class QQBotOptions
|
||||||
{
|
{
|
||||||
public const string SectionName = "QQBot";
|
public const string SectionName = "QQBot";
|
||||||
|
|
||||||
|
/// <summary>GROUP_AND_C2C_EVENT (1<<25) | INTERACTION (1<<26)。官方示例的 513 属于频道事件,不适用于本项目。</summary>
|
||||||
|
public const int DefaultIntents = (1 << 25) | (1 << 26);
|
||||||
|
|
||||||
public bool Enabled { get; set; }
|
public bool Enabled { get; set; }
|
||||||
|
|
||||||
|
/// <summary>开发与部署均使用 WebSocket;Webhook 仅作可选兜底。</summary>
|
||||||
|
public QQBotMode Mode { get; set; } = QQBotMode.WebSocket;
|
||||||
|
|
||||||
|
public QQBotEnvironment Environment { get; set; } = QQBotEnvironment.Sandbox;
|
||||||
|
|
||||||
|
/// <summary>默认关闭。开启后 POST /QQBot 才接受平台回调,并执行入站验签。</summary>
|
||||||
|
public bool EnableWebhook { get; set; }
|
||||||
|
|
||||||
public string AppId { get; set; } = "";
|
public string AppId { get; set; } = "";
|
||||||
public string Secret { get; set; } = "";
|
public string Secret { get; set; } = "";
|
||||||
public string ApiBaseAddress { get; set; } = "https://api.sgroup.qq.com";
|
|
||||||
|
/// <summary>留空时按 Environment 自动选择正式/沙箱域名。</summary>
|
||||||
|
public string ApiBaseAddress { get; set; } = "";
|
||||||
|
|
||||||
public string TokenAddress { get; set; } = "https://bots.qq.com/app/getAppAccessToken";
|
public string TokenAddress { get; set; } = "https://bots.qq.com/app/getAppAccessToken";
|
||||||
public int RequestTimeoutSeconds { get; set; } = 30;
|
public int RequestTimeoutSeconds { get; set; } = 30;
|
||||||
|
public int Intents { get; set; } = DefaultIntents;
|
||||||
|
|
||||||
|
/// <summary>回调时间戳允许的最大偏移(秒),用于防重放。</summary>
|
||||||
|
public int SignatureMaxAgeSeconds { get; set; } = 300;
|
||||||
|
|
||||||
|
/// <summary>心跳周期由 op 10 Hello 下发,此处仅作为网关请求超时兜底。</summary>
|
||||||
|
public int GatewayRequestTimeoutSeconds { get; set; } = 15;
|
||||||
|
|
||||||
|
public string ResolvedApiBaseAddress => string.IsNullOrWhiteSpace(ApiBaseAddress)
|
||||||
|
? Environment == QQBotEnvironment.Sandbox
|
||||||
|
? "https://sandbox.api.sgroup.qq.com"
|
||||||
|
: "https://api.sgroup.qq.com"
|
||||||
|
: ApiBaseAddress.TrimEnd('/');
|
||||||
|
|
||||||
public bool IsConfigured => Enabled
|
public bool IsConfigured => Enabled
|
||||||
&& !string.IsNullOrWhiteSpace(AppId)
|
&& !string.IsNullOrWhiteSpace(AppId)
|
||||||
&& !string.IsNullOrWhiteSpace(Secret);
|
&& !string.IsNullOrWhiteSpace(Secret);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public sealed class DatabaseOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "Database";
|
||||||
|
|
||||||
|
/// <summary>SQLite 数据库文件不纳入版本控制。</summary>
|
||||||
|
public string ConnectionString { get; set; } = "Data Source=oshimobot.db";
|
||||||
|
|
||||||
|
/// <summary>启动时自动应用 EF Core Migration。</summary>
|
||||||
|
public bool ApplyMigrationsOnStartup { get; set; } = true;
|
||||||
|
}
|
||||||
|
|
||||||
public sealed class ServerOptions
|
public sealed class ServerOptions
|
||||||
{
|
{
|
||||||
public const string SectionName = "Server";
|
public const string SectionName = "Server";
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
|
using Microsoft.Extensions.Options;
|
||||||
using OshimaBot.Game.Services;
|
using OshimaBot.Game.Services;
|
||||||
using OshimaBot.Models;
|
using OshimaBot.Models;
|
||||||
|
using OshimaBot.Security;
|
||||||
using OshimaBot.Services;
|
using OshimaBot.Services;
|
||||||
|
|
||||||
FunGameRuntime.EnsureInitialized();
|
FunGameRuntime.EnsureInitialized();
|
||||||
@@ -15,11 +17,20 @@ builder.Services.AddOptions<QQBotOptions>()
|
|||||||
.Bind(builder.Configuration.GetSection(QQBotOptions.SectionName))
|
.Bind(builder.Configuration.GetSection(QQBotOptions.SectionName))
|
||||||
.Validate(options => !options.Enabled || options.IsConfigured, "启用 QQBot 时必须配置 AppId 和 Secret。")
|
.Validate(options => !options.Enabled || options.IsConfigured, "启用 QQBot 时必须配置 AppId 和 Secret。")
|
||||||
.Validate(options => options.RequestTimeoutSeconds is > 0 and <= 300, "QQBot 请求超时必须在 1 到 300 秒之间。")
|
.Validate(options => options.RequestTimeoutSeconds is > 0 and <= 300, "QQBot 请求超时必须在 1 到 300 秒之间。")
|
||||||
|
.Validate(options => options.Intents > 0, "QQBot Intents 必须大于 0。")
|
||||||
|
.Validate(options => options.SignatureMaxAgeSeconds is > 0 and <= 3600, "回调签名时间戳窗口必须在 1 到 3600 秒之间。")
|
||||||
|
.Validate(options => !options.EnableWebhook || !string.IsNullOrWhiteSpace(options.Secret), "启用 Webhook 回调时必须配置 Secret 用于验签。")
|
||||||
.ValidateOnStart();
|
.ValidateOnStart();
|
||||||
builder.Services.AddOptions<ServerOptions>()
|
builder.Services.AddOptions<ServerOptions>()
|
||||||
.Bind(builder.Configuration.GetSection(ServerOptions.SectionName))
|
.Bind(builder.Configuration.GetSection(ServerOptions.SectionName))
|
||||||
.Validate(options => options.MaximumRespawnTimes is >= 0 and <= 100, "最大复活次数必须在 0 到 100 之间。")
|
.Validate(options => options.MaximumRespawnTimes is >= 0 and <= 100, "最大复活次数必须在 0 到 100 之间。")
|
||||||
.ValidateOnStart();
|
.ValidateOnStart();
|
||||||
|
builder.Services.AddOptions<DatabaseOptions>()
|
||||||
|
.Bind(builder.Configuration.GetSection(DatabaseOptions.SectionName))
|
||||||
|
.Validate(options => !string.IsNullOrWhiteSpace(options.ConnectionString), "Database:ConnectionString 不能为空。")
|
||||||
|
.ValidateOnStart();
|
||||||
|
|
||||||
|
builder.Services.AddSingleton<WebhookSignatureVerifier>();
|
||||||
|
|
||||||
builder.Services.AddHttpClient(QQBotService.HttpClientName, client =>
|
builder.Services.AddHttpClient(QQBotService.HttpClientName, client =>
|
||||||
{
|
{
|
||||||
@@ -36,11 +47,19 @@ WebApplication app = builder.Build();
|
|||||||
|
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
|
|
||||||
|
// 仅当 QQBot:EnableWebhook=true 时对 POST /QQBot 校验 Ed25519 签名。
|
||||||
|
app.UseMiddleware<WebhookSignatureMiddleware>();
|
||||||
|
|
||||||
if (app.Environment.IsDevelopment())
|
if (app.Environment.IsDevelopment())
|
||||||
{
|
{
|
||||||
app.MapOpenApi();
|
app.MapOpenApi();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
QQBotOptions botOptions = app.Services.GetRequiredService<IOptions<QQBotOptions>>().Value;
|
||||||
|
app.Logger.LogInformation(
|
||||||
|
"OshimaBot 启动:Mode={Mode}, Environment={Environment}, Webhook={WebhookEnabled}, Intents={Intents}",
|
||||||
|
botOptions.Mode, botOptions.Environment, botOptions.EnableWebhook, botOptions.Intents);
|
||||||
|
|
||||||
app.MapGet("/", () => Results.Ok(new
|
app.MapGet("/", () => Results.Ok(new
|
||||||
{
|
{
|
||||||
name = "OshimaBot",
|
name = "OshimaBot",
|
||||||
@@ -51,6 +70,16 @@ app.MapGet("/", () => Results.Ok(new
|
|||||||
skills = FunGameService.AllSkills.Count,
|
skills = FunGameService.AllSkills.Count,
|
||||||
items = FunGameService.AllItems.Count
|
items = FunGameService.AllItems.Count
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
app.MapGet("/health", () => Results.Ok(new
|
||||||
|
{
|
||||||
|
status = "ok",
|
||||||
|
mode = botOptions.Mode.ToString(),
|
||||||
|
environment = botOptions.Environment.ToString(),
|
||||||
|
webhookEnabled = botOptions.EnableWebhook,
|
||||||
|
startedAt = FunGameRuntime.StartedAt
|
||||||
|
}));
|
||||||
|
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using OshimaBot.Models;
|
||||||
|
|
||||||
|
namespace OshimaBot.Security
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 仅在 QQBot:EnableWebhook=true 时对 POST /QQBot 做入站验签。
|
||||||
|
/// op=13 回调地址验证请求按官方示例不携带签名头,仅校验 X-Bot-Appid。
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WebhookSignatureMiddleware(
|
||||||
|
RequestDelegate next,
|
||||||
|
IOptions<QQBotOptions> options,
|
||||||
|
ILogger<WebhookSignatureMiddleware> logger)
|
||||||
|
{
|
||||||
|
private readonly QQBotOptions _options = options.Value;
|
||||||
|
|
||||||
|
public async Task InvokeAsync(HttpContext context, WebhookSignatureVerifier verifier)
|
||||||
|
{
|
||||||
|
if (!_options.EnableWebhook || !IsPlatformCallback(context.Request))
|
||||||
|
{
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Request.EnableBuffering();
|
||||||
|
using MemoryStream buffer = new();
|
||||||
|
await context.Request.Body.CopyToAsync(buffer, context.RequestAborted);
|
||||||
|
byte[] body = buffer.ToArray();
|
||||||
|
context.Request.Body.Position = 0;
|
||||||
|
|
||||||
|
string appId = context.Request.Headers[WebhookSignatureVerifier.AppIdHeader].ToString();
|
||||||
|
if (!string.IsNullOrWhiteSpace(_options.AppId) && !string.Equals(appId, _options.AppId, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
await RejectAsync(context, "X-Bot-Appid 与配置不匹配。");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 官方 webhook.html 的 op=13 示例 headers 只有 User-Agent / X-Bot-Appid,
|
||||||
|
// 验证请求由 plain_token + signature 机制自身完成,不做入站签名校验。
|
||||||
|
if (TryGetOpCode(body, out int op) && op == 13)
|
||||||
|
{
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
WebhookVerificationResult result = verifier.Verify(
|
||||||
|
context.Request.Headers[WebhookSignatureVerifier.SignatureHeader].ToString(),
|
||||||
|
context.Request.Headers[WebhookSignatureVerifier.TimestampHeader].ToString(),
|
||||||
|
appId,
|
||||||
|
body,
|
||||||
|
DateTimeOffset.UtcNow);
|
||||||
|
|
||||||
|
if (!result.IsValid)
|
||||||
|
{
|
||||||
|
logger.LogWarning("拒绝 QQ Webhook 回调:{Failure}({Reason})", result.Failure, result.Reason);
|
||||||
|
await RejectAsync(context, result.Reason);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await next(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsPlatformCallback(HttpRequest request)
|
||||||
|
=> HttpMethods.IsPost(request.Method)
|
||||||
|
&& string.Equals(request.Path.Value?.TrimEnd('/'), "/QQBot", StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
private static bool TryGetOpCode(byte[] body, out int op)
|
||||||
|
{
|
||||||
|
op = 0;
|
||||||
|
if (body.Length == 0) return false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using JsonDocument document = JsonDocument.Parse(body);
|
||||||
|
return document.RootElement.TryGetProperty("op", out JsonElement element) && element.TryGetInt32(out op);
|
||||||
|
}
|
||||||
|
catch (JsonException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task RejectAsync(HttpContext context, string reason)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||||
|
return context.Response.WriteAsJsonAsync(new { error = reason }, context.RequestAborted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using OshimaBot.Models;
|
||||||
|
using Rebex.Security.Cryptography;
|
||||||
|
|
||||||
|
namespace OshimaBot.Security
|
||||||
|
{
|
||||||
|
public enum WebhookVerificationFailure
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
MissingSecret,
|
||||||
|
MissingHeaders,
|
||||||
|
AppIdMismatch,
|
||||||
|
MalformedSignature,
|
||||||
|
InvalidTimestamp,
|
||||||
|
TimestampExpired,
|
||||||
|
InvalidSignature
|
||||||
|
}
|
||||||
|
|
||||||
|
public readonly record struct WebhookVerificationResult(bool IsValid, WebhookVerificationFailure Failure, string Reason)
|
||||||
|
{
|
||||||
|
public static WebhookVerificationResult Success() => new(true, WebhookVerificationFailure.None, "");
|
||||||
|
public static WebhookVerificationResult Fail(WebhookVerificationFailure failure, string reason) => new(false, failure, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// QQ 官方 Webhook 入站验签:Bot Secret repeat 补齐 32 字节作为 Ed25519 seed,
|
||||||
|
/// 由 seed 派生公钥,校验 X-Signature-Ed25519 对 "timestamp + 原始 body" 的签名。
|
||||||
|
/// 参考 https://bot.qq.com/wiki/develop/api-v2/dev-prepare/interface-framework/sign.html
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WebhookSignatureVerifier
|
||||||
|
{
|
||||||
|
public const string SignatureHeader = "X-Signature-Ed25519";
|
||||||
|
public const string TimestampHeader = "X-Signature-Timestamp";
|
||||||
|
public const string AppIdHeader = "X-Bot-Appid";
|
||||||
|
|
||||||
|
private readonly byte[]? _publicKey;
|
||||||
|
private readonly string _appId;
|
||||||
|
private readonly int _maxAgeSeconds;
|
||||||
|
|
||||||
|
public WebhookSignatureVerifier(IOptions<QQBotOptions> options)
|
||||||
|
{
|
||||||
|
QQBotOptions value = options.Value;
|
||||||
|
_publicKey = string.IsNullOrEmpty(value.Secret) ? null : DerivePublicKey(value.Secret);
|
||||||
|
_appId = value.AppId;
|
||||||
|
_maxAgeSeconds = Math.Max(1, value.SignatureMaxAgeSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] DeriveSeed(string secret)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(secret))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Bot Secret 不能为空。", nameof(secret));
|
||||||
|
}
|
||||||
|
|
||||||
|
string seed = secret;
|
||||||
|
while (seed.Length < 32) seed += seed;
|
||||||
|
return Encoding.UTF8.GetBytes(seed[..32]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] DerivePublicKey(string secret)
|
||||||
|
{
|
||||||
|
Ed25519 ed25519 = new();
|
||||||
|
ed25519.FromSeed(DeriveSeed(secret));
|
||||||
|
return ed25519.GetPublicKey();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>op=13 回调地址验证:对 "event_ts + plain_token" 签名。</summary>
|
||||||
|
public static byte[] SignValidation(string secret, string eventTs, string plainToken)
|
||||||
|
{
|
||||||
|
Ed25519 ed25519 = new();
|
||||||
|
ed25519.FromSeed(DeriveSeed(secret));
|
||||||
|
return ed25519.SignMessage(Encoding.UTF8.GetBytes(eventTs + plainToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
public WebhookVerificationResult Verify(
|
||||||
|
string? signatureHex,
|
||||||
|
string? timestamp,
|
||||||
|
string? appId,
|
||||||
|
ReadOnlySpan<byte> body,
|
||||||
|
DateTimeOffset now)
|
||||||
|
{
|
||||||
|
if (_publicKey is null)
|
||||||
|
{
|
||||||
|
return WebhookVerificationResult.Fail(WebhookVerificationFailure.MissingSecret, "QQBot Secret 尚未配置。");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(signatureHex) || string.IsNullOrWhiteSpace(timestamp))
|
||||||
|
{
|
||||||
|
return WebhookVerificationResult.Fail(WebhookVerificationFailure.MissingHeaders, "缺少签名或时间戳请求头。");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(_appId) && !string.Equals(appId, _appId, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return WebhookVerificationResult.Fail(WebhookVerificationFailure.AppIdMismatch, "X-Bot-Appid 与配置不匹配。");
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] signature;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
signature = Convert.FromHexString(signatureHex);
|
||||||
|
}
|
||||||
|
catch (FormatException)
|
||||||
|
{
|
||||||
|
return WebhookVerificationResult.Fail(WebhookVerificationFailure.MalformedSignature, "签名不是合法的十六进制字符串。");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (signature.Length != 64)
|
||||||
|
{
|
||||||
|
return WebhookVerificationResult.Fail(WebhookVerificationFailure.MalformedSignature, "Ed25519 签名长度必须为 64 字节。");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture, out long seconds))
|
||||||
|
{
|
||||||
|
return WebhookVerificationResult.Fail(WebhookVerificationFailure.InvalidTimestamp, "时间戳格式无效。");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Math.Abs(now.ToUnixTimeSeconds() - seconds) > _maxAgeSeconds)
|
||||||
|
{
|
||||||
|
return WebhookVerificationResult.Fail(WebhookVerificationFailure.TimestampExpired, "回调时间戳超出允许范围。");
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] timestampBytes = Encoding.UTF8.GetBytes(timestamp);
|
||||||
|
byte[] signed = new byte[timestampBytes.Length + body.Length];
|
||||||
|
Buffer.BlockCopy(timestampBytes, 0, signed, 0, timestampBytes.Length);
|
||||||
|
body.CopyTo(signed.AsSpan(timestampBytes.Length));
|
||||||
|
|
||||||
|
Ed25519 ed25519 = new();
|
||||||
|
ed25519.FromPublicKey(_publicKey);
|
||||||
|
// Rebex 的 VerifyMessage 参数顺序是 (message, signature)。
|
||||||
|
return ed25519.VerifyMessage(signed, signature)
|
||||||
|
? WebhookVerificationResult.Success()
|
||||||
|
: WebhookVerificationResult.Fail(WebhookVerificationFailure.InvalidSignature, "Ed25519 签名校验失败。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -116,7 +116,7 @@ namespace OshimaBot.Services
|
|||||||
{
|
{
|
||||||
EnsureConfigured();
|
EnsureConfigured();
|
||||||
string accessToken = await GetAccessTokenAsync(cancellationToken);
|
string accessToken = await GetAccessTokenAsync(cancellationToken);
|
||||||
using HttpRequestMessage request = new(HttpMethod.Post, $"{_options.ApiBaseAddress.TrimEnd('/')}{path}");
|
using HttpRequestMessage request = new(HttpMethod.Post, $"{_options.ResolvedApiBaseAddress}{path}");
|
||||||
request.Headers.Authorization = new AuthenticationHeaderValue("QQBot", accessToken);
|
request.Headers.Authorization = new AuthenticationHeaderValue("QQBot", accessToken);
|
||||||
request.Content = new StringContent(JsonSerializer.Serialize(body, JsonOptions), Encoding.UTF8, "application/json");
|
request.Content = new StringContent(JsonSerializer.Serialize(body, JsonOptions), Encoding.UTF8, "application/json");
|
||||||
|
|
||||||
|
|||||||
@@ -8,11 +8,21 @@
|
|||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"QQBot": {
|
"QQBot": {
|
||||||
"Enabled": false,
|
"Enabled": false,
|
||||||
|
"Mode": "WebSocket",
|
||||||
|
"Environment": "Sandbox",
|
||||||
|
"EnableWebhook": false,
|
||||||
"AppId": "",
|
"AppId": "",
|
||||||
"Secret": "",
|
"Secret": "",
|
||||||
"ApiBaseAddress": "https://api.sgroup.qq.com",
|
"ApiBaseAddress": "",
|
||||||
"TokenAddress": "https://bots.qq.com/app/getAppAccessToken",
|
"TokenAddress": "https://bots.qq.com/app/getAppAccessToken",
|
||||||
"RequestTimeoutSeconds": 30
|
"RequestTimeoutSeconds": 30,
|
||||||
|
"Intents": 100663296,
|
||||||
|
"SignatureMaxAgeSeconds": 300,
|
||||||
|
"GatewayRequestTimeoutSeconds": 15
|
||||||
|
},
|
||||||
|
"Database": {
|
||||||
|
"ConnectionString": "Data Source=oshimobot.db",
|
||||||
|
"ApplyMigrationsOnStartup": true
|
||||||
},
|
},
|
||||||
"Server": {
|
"Server": {
|
||||||
"ApiKey": "",
|
"ApiKey": "",
|
||||||
|
|||||||
Reference in New Issue
Block a user