diff --git a/.gitignore b/.gitignore
index a4f9a9f..c84e117 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,3 +18,10 @@ appsettings.*.local.json
# WorkBuddy 会话数据
.workbuddy/
+
+# 本地 EF CLI 工具、SQLite 数据库与测试结果
+.tools/
+*.db
+*.db-wal
+*.db-shm
+TestResults/
diff --git a/OshimaBot.Tests/OshimaBot.Tests.csproj b/OshimaBot.Tests/OshimaBot.Tests.csproj
new file mode 100644
index 0000000..556fbb8
--- /dev/null
+++ b/OshimaBot.Tests/OshimaBot.Tests.csproj
@@ -0,0 +1,24 @@
+
+
+
+ net10.0
+ enable
+ enable
+ false
+ true
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
+
diff --git a/OshimaBot.Tests/WebhookSignatureVerifierTests.cs b/OshimaBot.Tests/WebhookSignatureVerifierTests.cs
new file mode 100644
index 0000000..f355369
--- /dev/null
+++ b/OshimaBot.Tests/WebhookSignatureVerifierTests.cs
@@ -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;
+
+///
+/// 测试数据取自 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 为准(均可精确复现)。
+///
+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
+ }));
+
+ /// 用官方 DEMO 的 secret 对 "timestamp + body" 生成合法签名,供往返测试使用。
+ 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);
+ }
+}
diff --git a/OshimaBot.slnx b/OshimaBot.slnx
index 2b8f05c..e0db6c4 100644
--- a/OshimaBot.slnx
+++ b/OshimaBot.slnx
@@ -3,4 +3,5 @@
+
diff --git a/OshimaBot/Controllers/QQBotController.cs b/OshimaBot/Controllers/QQBotController.cs
index 8edbb82..bff989d 100644
--- a/OshimaBot/Controllers/QQBotController.cs
+++ b/OshimaBot/Controllers/QQBotController.cs
@@ -1,12 +1,10 @@
-using System.Text;
using System.Text.Json;
-using OshimaBot.Models;
-using OshimaBot.Security;
-using OshimaBot.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
-using Rebex.Security.Cryptography;
+using OshimaBot.Models;
+using OshimaBot.Security;
+using OshimaBot.Services;
namespace OshimaBot.Controllers
{
@@ -23,6 +21,8 @@ namespace OshimaBot.Controllers
[HttpPost]
public async Task Post([FromBody] Payload? payload, CancellationToken cancellationToken)
{
+ // WebSocket 为唯一运行模式;webhook 仅在 QQBot:EnableWebhook=true 时接受平台回调。
+ if (!_options.EnableWebhook) return NotFound();
if (payload is null) return BadRequest("Payload 格式无效。");
try
@@ -30,6 +30,8 @@ namespace OshimaBot.Controllers
return payload.Op switch
{
13 => HandleValidation(payload),
+ // op=12 是 HTTP 回调模式的 ACK 回包;平台不会主动推送,HTTP 200 即视为确认。
+ 12 => Ok(),
0 => await HandleEventAsync(payload, cancellationToken),
_ => Ok()
};
@@ -54,13 +56,8 @@ namespace OshimaBot.Controllers
return BadRequest("无效的验证 Payload 格式。");
}
- string seed = _options.Secret;
- while (seed.Length < 32) seed += seed;
- seed = seed[..32];
-
- Ed25519 ed25519 = new();
- ed25519.FromSeed(Encoding.UTF8.GetBytes(seed));
- byte[] signature = ed25519.SignMessage(Encoding.UTF8.GetBytes(validation.EventTs + validation.PlainToken));
+ byte[] signature = WebhookSignatureVerifier.SignValidation(
+ _options.Secret, validation.EventTs, validation.PlainToken);
return Ok(new ValidationResponse
{
diff --git a/OshimaBot/Models/BotOptions.cs b/OshimaBot/Models/BotOptions.cs
index 576f92c..04c4b24 100644
--- a/OshimaBot/Models/BotOptions.cs
+++ b/OshimaBot/Models/BotOptions.cs
@@ -1,21 +1,74 @@
namespace OshimaBot.Models
{
+ /// QQ 官方事件接入方式。
+ public enum QQBotMode
+ {
+ WebSocket,
+ Webhook
+ }
+
+ /// QQ 开放平台运行环境(决定 API 域名)。
+ public enum QQBotEnvironment
+ {
+ Sandbox,
+ Production
+ }
+
public sealed class QQBotOptions
{
public const string SectionName = "QQBot";
+ /// GROUP_AND_C2C_EVENT (1<<25) | INTERACTION (1<<26)。官方示例的 513 属于频道事件,不适用于本项目。
+ public const int DefaultIntents = (1 << 25) | (1 << 26);
+
public bool Enabled { get; set; }
+
+ /// 开发与部署均使用 WebSocket;Webhook 仅作可选兜底。
+ public QQBotMode Mode { get; set; } = QQBotMode.WebSocket;
+
+ public QQBotEnvironment Environment { get; set; } = QQBotEnvironment.Sandbox;
+
+ /// 默认关闭。开启后 POST /QQBot 才接受平台回调,并执行入站验签。
+ public bool EnableWebhook { get; set; }
+
public string AppId { get; set; } = "";
public string Secret { get; set; } = "";
- public string ApiBaseAddress { get; set; } = "https://api.sgroup.qq.com";
+
+ /// 留空时按 Environment 自动选择正式/沙箱域名。
+ public string ApiBaseAddress { get; set; } = "";
+
public string TokenAddress { get; set; } = "https://bots.qq.com/app/getAppAccessToken";
public int RequestTimeoutSeconds { get; set; } = 30;
+ public int Intents { get; set; } = DefaultIntents;
+
+ /// 回调时间戳允许的最大偏移(秒),用于防重放。
+ public int SignatureMaxAgeSeconds { get; set; } = 300;
+
+ /// 心跳周期由 op 10 Hello 下发,此处仅作为网关请求超时兜底。
+ 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
&& !string.IsNullOrWhiteSpace(AppId)
&& !string.IsNullOrWhiteSpace(Secret);
}
+ public sealed class DatabaseOptions
+ {
+ public const string SectionName = "Database";
+
+ /// SQLite 数据库文件不纳入版本控制。
+ public string ConnectionString { get; set; } = "Data Source=oshimobot.db";
+
+ /// 启动时自动应用 EF Core Migration。
+ public bool ApplyMigrationsOnStartup { get; set; } = true;
+ }
+
public sealed class ServerOptions
{
public const string SectionName = "Server";
diff --git a/OshimaBot/Program.cs b/OshimaBot/Program.cs
index a9d4a68..1bcb9c8 100644
--- a/OshimaBot/Program.cs
+++ b/OshimaBot/Program.cs
@@ -1,5 +1,7 @@
+using Microsoft.Extensions.Options;
using OshimaBot.Game.Services;
using OshimaBot.Models;
+using OshimaBot.Security;
using OshimaBot.Services;
FunGameRuntime.EnsureInitialized();
@@ -15,11 +17,20 @@ builder.Services.AddOptions()
.Bind(builder.Configuration.GetSection(QQBotOptions.SectionName))
.Validate(options => !options.Enabled || options.IsConfigured, "启用 QQBot 时必须配置 AppId 和 Secret。")
.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();
builder.Services.AddOptions()
.Bind(builder.Configuration.GetSection(ServerOptions.SectionName))
.Validate(options => options.MaximumRespawnTimes is >= 0 and <= 100, "最大复活次数必须在 0 到 100 之间。")
.ValidateOnStart();
+builder.Services.AddOptions()
+ .Bind(builder.Configuration.GetSection(DatabaseOptions.SectionName))
+ .Validate(options => !string.IsNullOrWhiteSpace(options.ConnectionString), "Database:ConnectionString 不能为空。")
+ .ValidateOnStart();
+
+builder.Services.AddSingleton();
builder.Services.AddHttpClient(QQBotService.HttpClientName, client =>
{
@@ -36,11 +47,19 @@ WebApplication app = builder.Build();
app.UseExceptionHandler();
+// 仅当 QQBot:EnableWebhook=true 时对 POST /QQBot 校验 Ed25519 签名。
+app.UseMiddleware();
+
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
+QQBotOptions botOptions = app.Services.GetRequiredService>().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
{
name = "OshimaBot",
@@ -51,6 +70,16 @@ app.MapGet("/", () => Results.Ok(new
skills = FunGameService.AllSkills.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.Run();
diff --git a/OshimaBot/Security/WebhookSignatureMiddleware.cs b/OshimaBot/Security/WebhookSignatureMiddleware.cs
new file mode 100644
index 0000000..563ba6f
--- /dev/null
+++ b/OshimaBot/Security/WebhookSignatureMiddleware.cs
@@ -0,0 +1,89 @@
+using System.Text.Json;
+using Microsoft.Extensions.Options;
+using OshimaBot.Models;
+
+namespace OshimaBot.Security
+{
+ ///
+ /// 仅在 QQBot:EnableWebhook=true 时对 POST /QQBot 做入站验签。
+ /// op=13 回调地址验证请求按官方示例不携带签名头,仅校验 X-Bot-Appid。
+ ///
+ public sealed class WebhookSignatureMiddleware(
+ RequestDelegate next,
+ IOptions options,
+ ILogger 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);
+ }
+ }
+}
diff --git a/OshimaBot/Security/WebhookSignatureVerifier.cs b/OshimaBot/Security/WebhookSignatureVerifier.cs
new file mode 100644
index 0000000..d29e624
--- /dev/null
+++ b/OshimaBot/Security/WebhookSignatureVerifier.cs
@@ -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);
+ }
+
+ ///
+ /// 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
+ ///
+ 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 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();
+ }
+
+ /// op=13 回调地址验证:对 "event_ts + plain_token" 签名。
+ 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 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 签名校验失败。");
+ }
+ }
+}
diff --git a/OshimaBot/Services/QQBotService.cs b/OshimaBot/Services/QQBotService.cs
index 045aad1..a1cdddb 100644
--- a/OshimaBot/Services/QQBotService.cs
+++ b/OshimaBot/Services/QQBotService.cs
@@ -116,7 +116,7 @@ namespace OshimaBot.Services
{
EnsureConfigured();
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.Content = new StringContent(JsonSerializer.Serialize(body, JsonOptions), Encoding.UTF8, "application/json");
diff --git a/OshimaBot/appsettings.json b/OshimaBot/appsettings.json
index 48685e7..f47523c 100644
--- a/OshimaBot/appsettings.json
+++ b/OshimaBot/appsettings.json
@@ -8,11 +8,21 @@
"AllowedHosts": "*",
"QQBot": {
"Enabled": false,
+ "Mode": "WebSocket",
+ "Environment": "Sandbox",
+ "EnableWebhook": false,
"AppId": "",
"Secret": "",
- "ApiBaseAddress": "https://api.sgroup.qq.com",
+ "ApiBaseAddress": "",
"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": {
"ApiKey": "",