From 052fe47db743a44459c728ce5e7522fd9a268566 Mon Sep 17 00:00:00 2001 From: milimoe Date: Mon, 9 Nov 2026 22:47:20 +0800 Subject: [PATCH] feat(S6): add QQ identity resolution, DB-backed API keys and one-time bind codes --- OshimaBot.Tests/EventPipelineTests.cs | 36 ++- OshimaBot.Tests/IdentityTests.cs | 229 +++++++++++++++++++ OshimaBot/Controllers/QQBotController.cs | 40 +++- OshimaBot/Data/DatabaseInitializer.cs | 54 ++++- OshimaBot/Models/AuthRequests.cs | 12 + OshimaBot/Models/BotMessages.cs | 8 + OshimaBot/Models/BotOptions.cs | 7 + OshimaBot/Program.cs | 13 ++ OshimaBot/Security/ApiKeyAuthenticator.cs | 66 ++++++ OshimaBot/Security/BindCodeService.cs | 103 +++++++++ OshimaBot/Security/IdentityModels.cs | 85 +++++++ OshimaBot/Security/RequireApiKeyAttribute.cs | 51 +---- OshimaBot/Security/UserDirectory.cs | 190 +++++++++++++++ OshimaBot/Services/QQEventDispatcher.cs | 22 ++ OshimaBot/Services/RainBotService.cs | 13 +- OshimaBot/appsettings.json | 4 +- 16 files changed, 875 insertions(+), 58 deletions(-) create mode 100644 OshimaBot.Tests/IdentityTests.cs create mode 100644 OshimaBot/Models/AuthRequests.cs create mode 100644 OshimaBot/Security/ApiKeyAuthenticator.cs create mode 100644 OshimaBot/Security/BindCodeService.cs create mode 100644 OshimaBot/Security/IdentityModels.cs create mode 100644 OshimaBot/Security/UserDirectory.cs diff --git a/OshimaBot.Tests/EventPipelineTests.cs b/OshimaBot.Tests/EventPipelineTests.cs index 4981653..714a471 100644 --- a/OshimaBot.Tests/EventPipelineTests.cs +++ b/OshimaBot.Tests/EventPipelineTests.cs @@ -1,3 +1,4 @@ +using System.Security.Claims; using System.Text.Json; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; @@ -7,6 +8,7 @@ using Microsoft.Extensions.Logging.Abstractions; using OshimaBot.Data; using OshimaBot.Messaging; using OshimaBot.Models; +using OshimaBot.Security; using OshimaBot.Services; using Xunit; @@ -30,7 +32,7 @@ public sealed class EventPipelineTests private static QQEventDispatcher CreateDispatcher( FakeDedup dedup, FakeAck ack, FakeSink sink) => new( - dedup, ack, sink, NullLogger.Instance); + dedup, ack, sink, new FakeUserDirectory(), NullLogger.Instance); [Fact] public async Task DedupStore_SecondMarkIsRejected() @@ -77,6 +79,24 @@ public sealed class EventPipelineTests Assert.Equal(1, dedup.MarkedCount); } + [Fact] + public async Task Dispatcher_AttachesResolvedIdentityBeforeQueue() + { + FakeDedup dedup = new(); + FakeSink sink = new(); + FakeUserDirectory users = new(); + QQEventDispatcher dispatcher = new(dedup, new FakeAck(), sink, users, NullLogger.Instance); + + EventDispatchResult result = await dispatcher.DispatchAsync(Parse(C2CJson), QQEventSource.WebSocket); + + Assert.Equal(EventDispatchStatus.Accepted, result.Status); + IBotMessage message = Assert.Single(sink.Messages); + Assert.Equal(42, message.FunGameUID); + Assert.NotNull(message.Principal); + Assert.Equal("42", message.Principal!.FindFirst(ClaimTypes.NameIdentifier)!.Value); + Assert.Equal(1, users.Calls); + } + [Fact] public async Task Dispatcher_RejectsDuplicateAcrossBothSources() { @@ -264,6 +284,20 @@ public sealed class EventPipelineTests } } + private sealed class FakeUserDirectory : IUserDirectory + { + public int Calls { get; private set; } + + public Task ResolveAsync(ExternalIdentity identity, CancellationToken cancellationToken = default) + { + Calls++; + return Task.FromResult(new BotUserPrincipal(42, "U000042", "", [BotRole.Player], false)); + } + + public Task LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default) + => Task.FromResult(IdentityLinkStatus.Linked); + } + private sealed class FakeSink : IBotMessageSink { public List Messages { get; } = []; diff --git a/OshimaBot.Tests/IdentityTests.cs b/OshimaBot.Tests/IdentityTests.cs new file mode 100644 index 0000000..55817ac --- /dev/null +++ b/OshimaBot.Tests/IdentityTests.cs @@ -0,0 +1,229 @@ +using System.Security.Claims; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using OshimaBot.Data; +using OshimaBot.Data.Entities; +using OshimaBot.Models; +using OshimaBot.Security; +using Xunit; + +namespace OshimaBot.Tests; + +public sealed class IdentityTests +{ + [Fact] + public async Task UserDirectory_RegistersLazilyOnlyOnce() + { + using TestDatabase db = new(); + IUserDirectory directory = db.Get(); + + BotUserPrincipal first = await directory.ResolveAsync(ExternalIdentity.Qq("OPENID1")); + BotUserPrincipal second = await directory.ResolveAsync(ExternalIdentity.Qq("OPENID1")); + + Assert.True(first.IsNew); + Assert.False(second.IsNew); + Assert.Equal(first.UserId, second.UserId); + Assert.Equal(BotRole.Player, Assert.Single(first.Roles)); + Assert.StartsWith("U", first.Handle); + + using IServiceScope scope = db.Provider.CreateScope(); + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await context.Users.CountAsync()); + Assert.Equal(1, await context.UserIdentities.CountAsync()); + Assert.Equal(1, await context.AuditLogs.CountAsync()); + Assert.Equal("user.register", (await context.AuditLogs.FirstAsync()).Action); + } + + [Fact] + public async Task UserDirectory_UnionSubjectReusesExistingAccount() + { + using TestDatabase db = new(); + IUserDirectory directory = db.Get(); + + BotUserPrincipal c2c = await directory.ResolveAsync(ExternalIdentity.Qq("C2C-1", "c2c", "UNION-1")); + BotUserPrincipal group = await directory.ResolveAsync(ExternalIdentity.Qq("GROUP-1", "group", "UNION-1")); + + Assert.Equal(c2c.UserId, group.UserId); + Assert.False(group.IsNew); + using IServiceScope scope = db.Provider.CreateScope(); + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await context.Users.CountAsync()); + Assert.Equal(2, await context.UserIdentities.CountAsync()); + Assert.Equal(2, await context.AuditLogs.CountAsync()); // register + union_link + } + + [Fact] + public async Task UserDirectory_SuperAdminWhitelistGrantsOwner() + { + using TestDatabase db = new(new ServerOptions { SuperAdminOpenIds = ["BOSS-OPENID"] }); + BotUserPrincipal principal = await db.Get().ResolveAsync(ExternalIdentity.Qq("BOSS-OPENID")); + + Assert.Contains(BotRole.Owner, principal.Roles); + Assert.True(principal.HasRole(BotRole.Admin)); + Assert.True(principal.ToClaimsPrincipal().IsInRole("Owner")); + } + + [Fact] + public async Task BindCodeService_IsSixDigitsOneTimeAndLinksIdentity() + { + using TestDatabase db = new(); + BotUserPrincipal host = await db.Get().ResolveAsync(ExternalIdentity.Qq("HOST")); + IBindCodeService codes = db.Get(); + + string code = await codes.IssueAsync(host.UserId); + Assert.Matches(@"^\d{6}$", code); + Assert.Equal(300, codes.TtlSeconds); + + BindRedeemResult redeemed = await codes.RedeemAsync(code, ExternalIdentity.Qq("NEW-OPENID")); + Assert.Equal(BindRedeemStatus.Success, redeemed.Status); + Assert.Equal(host.UserId, redeemed.UserId); + Assert.Equal(BindRedeemStatus.Used, (await codes.RedeemAsync(code, ExternalIdentity.Qq("ANOTHER"))).Status); + + using IServiceScope scope = db.Provider.CreateScope(); + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await context.UserIdentities.FirstOrDefaultAsync(x => x.Subject == "NEW-OPENID")); + Assert.Null(await context.UserIdentities.FirstOrDefaultAsync(x => x.Subject == "ANOTHER")); + Assert.NotNull((await context.BindCodes.FirstAsync()).UsedAtUtc); + } + + [Fact] + public async Task BindCodeService_RejectsExpiredConflictAndMissingUser() + { + using TestDatabase db = new(); + IUserDirectory directory = db.Get(); + BotUserPrincipal host = await directory.ResolveAsync(ExternalIdentity.Qq("HOST")); + BotUserPrincipal other = await directory.ResolveAsync(ExternalIdentity.Qq("TAKEN")); + IBindCodeService codes = db.Get(); + + Assert.Equal(BindRedeemStatus.NotFound, (await codes.RedeemAsync("000000", ExternalIdentity.Qq("X"))).Status); + Assert.Equal(BindRedeemStatus.Conflict, + (await codes.RedeemAsync(await codes.IssueAsync(host.UserId), ExternalIdentity.Qq("TAKEN"))).Status); + Assert.Equal(BindRedeemStatus.InvalidUser, + (await codes.RedeemAsync(await codes.IssueAsync(9999), ExternalIdentity.Qq("X"))).Status); + Assert.NotEqual(host.UserId, other.UserId); + + using IServiceScope scope = db.Provider.CreateScope(); + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + context.BindCodes.Add(new BindCode + { + Code = "123456", UserId = host.UserId, Purpose = "test", + ExpiresAtUtc = DateTime.UtcNow.AddMinutes(-1), CreatedAtUtc = DateTime.UtcNow.AddMinutes(-2) + }); + await context.SaveChangesAsync(); + Assert.Equal(BindRedeemStatus.Expired, (await codes.RedeemAsync("123456", ExternalIdentity.Qq("X"))).Status); + } + + [Fact] + public async Task ApiKeyAuthenticator_ValidatesHashRevocationAndExpiry() + { + using TestDatabase db = new(); + const string secret = "a-high-entropy-random-key-0123456789"; + ApiKeyAuthenticator authenticator = db.Get(); + using (IServiceScope scope = db.Provider.CreateScope()) + { + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + context.ApiKeys.Add(new ApiKey + { + Name = "test", KeyHash = ApiKeyDefaults.Hash(secret), ScopesJson = "[\"thirdparty\",\"bind\"]", + CreatedAtUtc = DateTime.UtcNow + }); + await context.SaveChangesAsync(); + } + + ApiKeyIdentity? valid = await authenticator.AuthenticateAsync(secret); + Assert.NotNull(valid); + Assert.Contains("thirdparty", valid!.Scopes); + Assert.Null(await authenticator.AuthenticateAsync("wrong-key")); + + using (IServiceScope scope = db.Provider.CreateScope()) + { + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + ApiKey row = await context.ApiKeys.FirstAsync(); + row.RevokedAtUtc = DateTime.UtcNow; + await context.SaveChangesAsync(); + } + Assert.Null(await authenticator.AuthenticateAsync(secret)); + + using (IServiceScope scope = db.Provider.CreateScope()) + { + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + ApiKey row = await context.ApiKeys.FirstAsync(); + row.RevokedAtUtc = null; + row.ExpiresAtUtc = DateTime.UtcNow.AddMinutes(-1); + await context.SaveChangesAsync(); + } + Assert.Null(await authenticator.AuthenticateAsync(secret)); + } + + [Fact] + public async Task DatabaseInitializer_BootstrapsApiKeyHashOnly() + { + using TestDatabase db = new(); + DatabaseInitializer initializer = new( + db.Provider.GetRequiredService(), + Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }), + Options.Create(new ServerOptions { ApiKey = "bootstrap-secret" }), + NullLogger.Instance); + + await initializer.InitializeAsync(CancellationToken.None); + + ApiKeyAuthenticator authenticator = db.Get(); + Assert.NotNull(await authenticator.AuthenticateAsync("bootstrap-secret")); + using IServiceScope scope = db.Provider.CreateScope(); + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + ApiKey row = await context.ApiKeys.FirstAsync(); + Assert.NotEqual("bootstrap-secret", row.KeyHash); + Assert.Equal(64, row.KeyHash.Length); + } + + [Fact] + public void Principals_CarryRolesAndScopes() + { + ApiKeyIdentity key = new(7, 42, "svc", ["thirdparty", "bind"], [BotRole.Admin]); + ClaimsPrincipal principal = key.ToClaimsPrincipal(ApiKeyDefaults.Scheme); + Assert.Equal("42", principal.FindFirst(ClaimTypes.NameIdentifier)!.Value); + Assert.True(principal.IsInRole("Admin")); + Assert.Contains(principal.FindAll("scope"), claim => claim.Value == "bind"); + + BotUserPrincipal user = new(1, "U000001", "", [BotRole.Owner], false); + Assert.True(user.HasRole(BotRole.Admin)); + Assert.False(new BotUserPrincipal(2, "U2", "", [BotRole.Player], false).HasRole(BotRole.Admin)); + Assert.Equal(ApiKeyDefaults.Hash("abc"), ApiKeyDefaults.Hash("abc")); + Assert.Equal(new[] { BotRole.Player }, ApiKeyDefaults.ParseRoles([0, 99, 0])); + } + + /// 共享的 SQLite 内存库 + 真实 DI 容器,保证测的是真实 EF Core 行为。 + private sealed class TestDatabase : IDisposable + { + public SqliteConnection Connection { get; } + public ServiceProvider Provider { get; } + + public TestDatabase(ServerOptions? serverOptions = null) + { + Connection = new SqliteConnection("Data Source=:memory:"); + Connection.Open(); + ServiceCollection services = new(); + services.AddLogging(); + services.AddDbContext(options => options.UseSqlite(Connection)); + services.AddSingleton(Options.Create(serverOptions ?? new ServerOptions())); + services.AddSingleton(Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false })); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + Provider = services.BuildServiceProvider(); + using IServiceScope scope = Provider.CreateScope(); + scope.ServiceProvider.GetRequiredService().Database.EnsureCreated(); + } + + public T Get() where T : notnull => Provider.GetRequiredService(); + + public void Dispose() + { + Provider.Dispose(); + Connection.Dispose(); + } + } +} diff --git a/OshimaBot/Controllers/QQBotController.cs b/OshimaBot/Controllers/QQBotController.cs index 2282b3f..5399855 100644 --- a/OshimaBot/Controllers/QQBotController.cs +++ b/OshimaBot/Controllers/QQBotController.cs @@ -1,3 +1,4 @@ +using System.Security.Claims; using System.Text.Json; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; @@ -12,7 +13,8 @@ namespace OshimaBot.Controllers public sealed class QQBotController( IOptions options, ILogger logger, - IQQEventDispatcher dispatcher) : ControllerBase + IQQEventDispatcher dispatcher, + IBindCodeService bindCodes) : ControllerBase { private readonly QQBotOptions _options = options.Value; @@ -85,11 +87,43 @@ namespace OshimaBot.Controllers { if (message is null) return Ok(""); + // 第三方消息自报的 openid 只用于回显,身份一律以 ApiKey 关联的 ClaimsPrincipal 为准。 + message.FunGameUID = CurrentUserId(); + message.Principal = HttpContext.User; OtherData data = new() { RequestUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}" }; bool handled = await rainBot.Handler(message, data, cancellationToken); return Ok(!handled || message.IsCompleted ? message.Result : ""); } + private long CurrentUserId() + => long.TryParse(HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier), out long userId) ? userId : 0; + + [RequireApiKey] + [HttpPost("bind")] + public async Task Bind([FromBody] BindRequest? request, CancellationToken cancellationToken) + { + if (request is null || string.IsNullOrWhiteSpace(request.Code) || string.IsNullOrWhiteSpace(request.OpenId)) + { + return BadRequest(new { error = "需要 code 与 openId。" }); + } + + ExternalIdentity identity = new( + string.IsNullOrWhiteSpace(request.Provider) ? "qq" : request.Provider.Trim(), + request.OpenId.Trim(), + string.IsNullOrWhiteSpace(request.Scene) ? "c2c" : request.Scene.Trim()); + BindRedeemResult result = await bindCodes.RedeemAsync(request.Code.Trim(), identity, cancellationToken); + logger.LogInformation("绑定码兑换:Status={Status}, UserId={UserId}, Provider={Provider}", + result.Status, result.UserId, identity.Provider); + + return result.Status switch + { + BindRedeemStatus.Success => Ok(new { bound = true, userId = result.UserId }), + BindRedeemStatus.Conflict => Conflict(new { error = result.Reason }), + BindRedeemStatus.InvalidUser => StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = result.Reason }), + _ => BadRequest(new { error = result.Reason }) + }; + } + [RequireApiKey] [HttpPost("thirdpartytest")] public async Task ThirdPartyTest( @@ -107,7 +141,9 @@ namespace OshimaBot.Controllers OpenId = openID, Detail = msg, Id = openID, - Timestamp = DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss") + Timestamp = DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss"), + FunGameUID = CurrentUserId(), + Principal = HttpContext.User }; OtherData data = new() { RequestUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}" }; bool handled = await rainBot.Handler(message, data, cancellationToken); diff --git a/OshimaBot/Data/DatabaseInitializer.cs b/OshimaBot/Data/DatabaseInitializer.cs index dde2da5..a23c9cd 100644 --- a/OshimaBot/Data/DatabaseInitializer.cs +++ b/OshimaBot/Data/DatabaseInitializer.cs @@ -1,6 +1,8 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; +using OshimaBot.Data.Entities; using OshimaBot.Models; +using OshimaBot.Security; namespace OshimaBot.Data; @@ -11,21 +13,51 @@ namespace OshimaBot.Data; public sealed class DatabaseInitializer( IServiceScopeFactory scopeFactory, IOptions options, + IOptions serverOptions, ILogger logger) : BackgroundService { - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - if (!options.Value.ApplyMigrationsOnStartup) - { - logger.LogInformation("已跳过数据库自动迁移(Database:ApplyMigrationsOnStartup=false)。"); - return; - } + protected override Task ExecuteAsync(CancellationToken stoppingToken) => InitializeAsync(stoppingToken); + /// 公开以便集成测试直接等待完成(BackgroundService.StartAsync 不会等待 ExecuteAsync)。 + public async Task InitializeAsync(CancellationToken cancellationToken) + { using IServiceScope scope = scopeFactory.CreateScope(); BotDbContext db = scope.ServiceProvider.GetRequiredService(); - await db.Database.MigrateAsync(stoppingToken); - await db.Database.ExecuteSqlRawAsync("PRAGMA journal_mode=WAL;", stoppingToken); - await db.Database.ExecuteSqlRawAsync("PRAGMA foreign_keys=ON;", stoppingToken); - logger.LogInformation("数据库迁移完成,已启用 WAL 与外键约束。"); + if (options.Value.ApplyMigrationsOnStartup) + { + await db.Database.MigrateAsync(cancellationToken); + await db.Database.ExecuteSqlRawAsync("PRAGMA journal_mode=WAL;", cancellationToken); + await db.Database.ExecuteSqlRawAsync("PRAGMA foreign_keys=ON;", cancellationToken); + logger.LogInformation("数据库迁移完成,已启用 WAL 与外键约束。"); + } + else + { + logger.LogInformation("已跳过数据库自动迁移(Database:ApplyMigrationsOnStartup=false)。"); + } + + await SeedBootstrapApiKeyAsync(db, cancellationToken); + } + + /// + /// 兼容旧配置的过渡:若 Server:ApiKey 非空,首次启动时把 SHA-256 摘要写入 api_keys。 + /// 认证只查库;写入后应从配置移除明文,后续密钥直接由数据库管理(可吊销/过期/分权)。 + /// + private async Task SeedBootstrapApiKeyAsync(BotDbContext db, CancellationToken cancellationToken) + { + string plain = serverOptions.Value.ApiKey; + if (string.IsNullOrWhiteSpace(plain)) return; + + string hash = ApiKeyDefaults.Hash(plain); + if (await db.ApiKeys.AnyAsync(x => x.KeyHash == hash, cancellationToken)) return; + + db.ApiKeys.Add(new ApiKey + { + Name = "bootstrap", + KeyHash = hash, + ScopesJson = "[\"thirdparty\",\"bind\"]", + CreatedAtUtc = DateTime.UtcNow + }); + await db.SaveChangesAsync(cancellationToken); + logger.LogWarning("已从 Server:ApiKey 引导写入 API Key 摘要;请从配置中移除明文,改用 api_keys 表管理密钥。"); } } diff --git a/OshimaBot/Models/AuthRequests.cs b/OshimaBot/Models/AuthRequests.cs new file mode 100644 index 0000000..6bfa22e --- /dev/null +++ b/OshimaBot/Models/AuthRequests.cs @@ -0,0 +1,12 @@ +using System.Text.Json.Serialization; + +namespace OshimaBot.Models; + +/// 第三方/管理端凭一次性绑定码把 QQ OpenID 绑到内部用户。 +public sealed class BindRequest +{ + [JsonPropertyName("code")] public string Code { get; set; } = ""; + [JsonPropertyName("openId")] public string OpenId { get; set; } = ""; + [JsonPropertyName("provider")] public string Provider { get; set; } = "qq"; + [JsonPropertyName("scene")] public string Scene { get; set; } = "c2c"; +} diff --git a/OshimaBot/Models/BotMessages.cs b/OshimaBot/Models/BotMessages.cs index 28f8c87..a110a78 100644 --- a/OshimaBot/Models/BotMessages.cs +++ b/OshimaBot/Models/BotMessages.cs @@ -1,3 +1,4 @@ +using System.Security.Claims; using System.Text.Json; using System.Text.Json.Serialization; using OshimaBot.Messaging; @@ -44,6 +45,9 @@ namespace OshimaBot.Models /// 互动事件的被动回复使用 event_id(与 msg_id 互斥);消息事件为 null。 string? EventId { get; set; } + + /// S6 起由事件管线注入;第三方接口则由 ApiKey ClaimsPrincipal 注入。 + ClaimsPrincipal? Principal { get; set; } } public sealed class ThirdPartyMessage : IBotMessage @@ -58,6 +62,7 @@ namespace OshimaBot.Models [JsonIgnore] public long FunGameUID { get; set; } [JsonIgnore] public bool SendProactive { get; set; } [JsonIgnore] public string? EventId { get; set; } + [JsonIgnore] public ClaimsPrincipal? Principal { get; set; } [JsonIgnore] public bool IsCompleted { get; set; } [JsonIgnore] public string Result { get; set; } = ""; } @@ -71,6 +76,7 @@ namespace OshimaBot.Models [JsonIgnore] public long FunGameUID { get; set; } [JsonIgnore] public bool SendProactive { get; set; } [JsonIgnore] public string? EventId { get; set; } + [JsonIgnore] public ClaimsPrincipal? Principal { get; set; } public string Detail { get => Content; set => Content = value; } public string OpenId => Author.UserOpenId; public string AuthorOpenId => Author.UserOpenId; @@ -87,6 +93,7 @@ namespace OshimaBot.Models [JsonIgnore] public long FunGameUID { get; set; } [JsonIgnore] public bool SendProactive { get; set; } [JsonIgnore] public string? EventId { get; set; } + [JsonIgnore] public ClaimsPrincipal? Principal { get; set; } public string Detail { get => Content; set => Content = value; } public string OpenId => GroupOpenId; public string AuthorOpenId => Author.MemberOpenId; @@ -104,6 +111,7 @@ namespace OshimaBot.Models [JsonIgnore] public long FunGameUID { get; set; } [JsonIgnore] public bool SendProactive { get; set; } [JsonIgnore] public string? EventId { get; set; } + [JsonIgnore] public ClaimsPrincipal? Principal { get; set; } public string Detail { get => Data.Resolved?.ButtonData ?? ""; set { } } public string OpenId => IsGroup ? GroupOpenId : UserOpenId; public string AuthorOpenId => UserOpenId; diff --git a/OshimaBot/Models/BotOptions.cs b/OshimaBot/Models/BotOptions.cs index 9931b28..93aa229 100644 --- a/OshimaBot/Models/BotOptions.cs +++ b/OshimaBot/Models/BotOptions.cs @@ -85,7 +85,14 @@ namespace OshimaBot.Models { public const string SectionName = "Server"; + /// 仅作首次启动引导密钥:启动时把其 SHA-256 写入 api_keys,认证阶段不再读取明文。 public string ApiKey { get; set; } = ""; public int MaximumRespawnTimes { get; set; } = 10; + + /// 超管白名单 QQ OpenID,与 user_roles 双轨;数据库清空后仍可恢复管理权限。 + public List SuperAdminOpenIds { get; set; } = []; + + /// 一次性绑定码有效期(秒)。 + public int BindCodeTtlSeconds { get; set; } = 300; } } diff --git a/OshimaBot/Program.cs b/OshimaBot/Program.cs index 9197385..c48cbec 100644 --- a/OshimaBot/Program.cs +++ b/OshimaBot/Program.cs @@ -1,3 +1,4 @@ +using Microsoft.AspNetCore.Authentication; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -31,6 +32,7 @@ builder.Services.AddOptions() builder.Services.AddOptions() .Bind(builder.Configuration.GetSection(ServerOptions.SectionName)) .Validate(options => options.MaximumRespawnTimes is >= 0 and <= 100, "最大复活次数必须在 0 到 100 之间。") + .Validate(options => options.BindCodeTtlSeconds is >= 30 and <= 3600, "绑定码有效期必须在 30 到 3600 秒之间。") .ValidateOnStart(); builder.Services.AddOptions() .Bind(builder.Configuration.GetSection(DatabaseOptions.SectionName)) @@ -38,6 +40,11 @@ builder.Services.AddOptions() .ValidateOnStart(); builder.Services.AddSingleton(); +builder.Services.AddAuthentication(ApiKeyDefaults.Scheme) + .AddScheme(ApiKeyDefaults.Scheme, null); +builder.Services.AddAuthorization(options => options.AddPolicy(ApiKeyDefaults.Policy, policy => policy + .AddAuthenticationSchemes(ApiKeyDefaults.Scheme) + .RequireAuthenticatedUser())); builder.Services.AddDbContext(options => { @@ -67,6 +74,9 @@ builder.Services.AddSingleton(sp => sp.GetRequiredService(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -81,6 +91,9 @@ app.UseExceptionHandler(); // 仅当 QQBot:EnableWebhook=true 时对 POST /QQBot 校验 Ed25519 签名。 app.UseMiddleware(); +app.UseAuthentication(); +app.UseAuthorization(); + if (app.Environment.IsDevelopment()) { app.MapOpenApi(); diff --git a/OshimaBot/Security/ApiKeyAuthenticator.cs b/OshimaBot/Security/ApiKeyAuthenticator.cs new file mode 100644 index 0000000..94a5f6a --- /dev/null +++ b/OshimaBot/Security/ApiKeyAuthenticator.cs @@ -0,0 +1,66 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using OshimaBot.Data; +using OshimaBot.Data.Entities; +using System.Text.Encodings.Web; + +namespace OshimaBot.Security; + +/// 数据库侧 API Key 校验:只认 api_keys 表中的 SHA-256 摘要,支持吊销/过期/按 key 分权。 +public sealed class ApiKeyAuthenticator(IServiceScopeFactory scopeFactory) +{ + public async Task AuthenticateAsync(string key, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(key)) return null; + string hash = ApiKeyDefaults.Hash(key); + + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + ApiKey? row = await db.ApiKeys.AsNoTracking() + .FirstOrDefaultAsync(x => x.KeyHash == hash, cancellationToken); + if (row is null || row.RevokedAtUtc is not null) return null; + if (row.ExpiresAtUtc is not null && row.ExpiresAtUtc <= DateTime.UtcNow) return null; + + List roleValues = row.UserId is null + ? [] + : await db.UserRoles.AsNoTracking() + .Where(x => x.UserId == row.UserId.Value).Select(x => x.Role).ToListAsync(cancellationToken); + return new ApiKeyIdentity(row.Id, row.UserId, row.Name, + ApiKeyDefaults.ParseScopes(row.ScopesJson), ApiKeyDefaults.ParseRoles(roleValues)); + } +} + +/// 把 X-API-Key / Bearer 换成标准 ClaimsPrincipal,供 Policy 与 S7 指令权限使用。 +public sealed class ApiKeyAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder) : AuthenticationHandler(options, logger, encoder) +{ + protected override async Task HandleAuthenticateAsync() + { + string key = Request.Headers[ApiKeyDefaults.HeaderName].ToString(); + if (string.IsNullOrWhiteSpace(key)) + { + string authorization = Request.Headers.Authorization.ToString(); + if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + key = authorization[7..].Trim(); + } + } + if (string.IsNullOrWhiteSpace(key)) return AuthenticateResult.NoResult(); + + ApiKeyAuthenticator authenticator = Context.RequestServices.GetRequiredService(); + ApiKeyIdentity? identity = await authenticator.AuthenticateAsync(key, Context.RequestAborted); + if (identity is null) return AuthenticateResult.Fail("API Key 无效、已吊销或已过期。"); + + AuthenticationTicket ticket = new(identity.ToClaimsPrincipal(ApiKeyDefaults.Scheme), Scheme.Name); + return AuthenticateResult.Success(ticket); + } + + protected override Task HandleChallengeAsync(AuthenticationProperties properties) + { + Response.Headers.WWWAuthenticate = "Bearer"; + return base.HandleChallengeAsync(properties); + } +} diff --git a/OshimaBot/Security/BindCodeService.cs b/OshimaBot/Security/BindCodeService.cs new file mode 100644 index 0000000..ca00aa7 --- /dev/null +++ b/OshimaBot/Security/BindCodeService.cs @@ -0,0 +1,103 @@ +using System.Security.Cryptography; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using OshimaBot.Data; +using OshimaBot.Data.Entities; +using OshimaBot.Models; + +namespace OshimaBot.Security; + +public enum BindRedeemStatus +{ + Success, + NotFound, + Expired, + Used, + Conflict, + InvalidUser +} + +public readonly record struct BindRedeemResult(BindRedeemStatus Status, long UserId = 0, string Reason = "") +{ + public static BindRedeemResult Ok(long userId) => new(BindRedeemStatus.Success, userId); + public static BindRedeemResult Fail(BindRedeemStatus status, string reason) => new(status, 0, reason); +} + +public interface IBindCodeService +{ + int TtlSeconds { get; } + Task IssueAsync(long userId, string purpose = "qq_bind", CancellationToken cancellationToken = default); + Task RedeemAsync(string code, ExternalIdentity identity, CancellationToken cancellationToken = default); +} + +/// 6 位一次性绑定码,替代旧版「获取接入码」直接回显 OpenID。 +public sealed class BindCodeService( + IServiceScopeFactory scopeFactory, + IUserDirectory userDirectory, + IOptions options, + ILogger logger) : IBindCodeService +{ + private readonly int _ttlSeconds = Math.Max(30, options.Value.BindCodeTtlSeconds); + + public int TtlSeconds => _ttlSeconds; + + public async Task IssueAsync(long userId, string purpose = "qq_bind", CancellationToken cancellationToken = default) + { + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + for (int attempt = 0; attempt < 12; attempt++) + { + string code = RandomNumberGenerator.GetInt32(100_000, 1_000_000).ToString(System.Globalization.CultureInfo.InvariantCulture); + if (await db.BindCodes.AnyAsync(x => x.Code == code, cancellationToken)) continue; + + BindCode entity = new() + { + Code = code, + UserId = userId, + Purpose = purpose, + ExpiresAtUtc = DateTime.UtcNow.AddSeconds(_ttlSeconds), + CreatedAtUtc = DateTime.UtcNow + }; + db.BindCodes.Add(entity); + try + { + await db.SaveChangesAsync(cancellationToken); + logger.LogInformation("已签发绑定码:UserId={UserId}, Purpose={Purpose}, TTL={Ttl}s", userId, purpose, _ttlSeconds); + return code; + } + catch (DbUpdateException) + { + // 6 位码碰撞:把失败的实体从跟踪器里摘掉,再换一个重试。 + db.Entry(entity).State = EntityState.Detached; + } + } + throw new InvalidOperationException("绑定码生成失败:连续碰撞,请稍后重试。"); + } + + public async Task RedeemAsync(string code, ExternalIdentity identity, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(code)) return BindRedeemResult.Fail(BindRedeemStatus.NotFound, "绑定码不能为空。"); + + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + BindCode? bind = await db.BindCodes.FirstOrDefaultAsync(x => x.Code == code, cancellationToken); + if (bind is null) return BindRedeemResult.Fail(BindRedeemStatus.NotFound, "绑定码不存在。"); + if (bind.UsedAtUtc is not null) return BindRedeemResult.Fail(BindRedeemStatus.Used, "绑定码已被使用。"); + if (bind.ExpiresAtUtc <= DateTime.UtcNow) return BindRedeemResult.Fail(BindRedeemStatus.Expired, "绑定码已过期。"); + + IdentityLinkStatus link = await userDirectory.LinkAsync(bind.UserId, identity, cancellationToken); + switch (link) + { + case IdentityLinkStatus.UserNotFound: + return BindRedeemResult.Fail(BindRedeemStatus.InvalidUser, "绑定码关联的用户不存在。"); + case IdentityLinkStatus.Conflict: + return BindRedeemResult.Fail(BindRedeemStatus.Conflict, "该 QQ 身份已绑定其它账号。"); + } + + bind.UsedAtUtc = DateTime.UtcNow; + await db.SaveChangesAsync(cancellationToken); + logger.LogInformation("绑定码已兑换:UserId={UserId}, Provider={Provider}, Subject={Subject}", + bind.UserId, identity.Provider, identity.Subject); + return BindRedeemResult.Ok(bind.UserId); + } +} diff --git a/OshimaBot/Security/IdentityModels.cs b/OshimaBot/Security/IdentityModels.cs new file mode 100644 index 0000000..bb9ae19 --- /dev/null +++ b/OshimaBot/Security/IdentityModels.cs @@ -0,0 +1,85 @@ +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +namespace OshimaBot.Security; + +/// 角色层级:数值越大权限越高,HasRole 按层级比较。 +public enum BotRole +{ + Player = 0, + Operator = 1, + Admin = 2, + Owner = 3 +} + +/// 外部身份坐标:业务代码永远不直接拿 OpenID 当用户主键。 +public sealed record ExternalIdentity(string Provider, string Subject, string Scene, string? UnionSubject = null) +{ + public static ExternalIdentity Qq(string openId, string scene = "c2c", string? unionOpenId = null) + => new("qq", openId, scene, unionOpenId); +} + +public sealed record BotUserPrincipal( + long UserId, string Handle, string Nickname, IReadOnlyList Roles, bool IsNew) +{ + public const string Scheme = "QQBotEvent"; + + public bool HasRole(BotRole required) => Roles.Any(role => role >= required); + + public ClaimsPrincipal ToClaimsPrincipal() + { + List claims = + [ + new(ClaimTypes.NameIdentifier, UserId.ToString(System.Globalization.CultureInfo.InvariantCulture)), + new(ClaimTypes.Name, string.IsNullOrWhiteSpace(Nickname) ? Handle : Nickname), + new("handle", Handle) + ]; + claims.AddRange(Roles.Select(role => new Claim(ClaimTypes.Role, role.ToString()))); + return new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme)); + } +} + +public sealed record ApiKeyIdentity( + long KeyId, long? UserId, string Name, IReadOnlyList Scopes, IReadOnlyList Roles) +{ + public ClaimsPrincipal ToClaimsPrincipal(string scheme) + { + List claims = + [ + new("api_key_id", KeyId.ToString(System.Globalization.CultureInfo.InvariantCulture)), + new(ClaimTypes.Name, Name) + ]; + if (UserId is not null) + { + claims.Add(new Claim(ClaimTypes.NameIdentifier, UserId.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + claims.AddRange(Scopes.Select(scope => new Claim("scope", scope))); + claims.AddRange(Roles.Select(role => new Claim(ClaimTypes.Role, role.ToString()))); + return new ClaimsPrincipal(new ClaimsIdentity(claims, scheme)); + } +} + +public static class ApiKeyDefaults +{ + public const string Scheme = "ApiKey"; + public const string Policy = "ApiKey"; + public const string HeaderName = "X-API-Key"; + + /// API Key 为高熵随机串,数据库只存 SHA-256 十六进制摘要,不存明文。 + public static string Hash(string key) + => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))).ToLowerInvariant(); + + public static IReadOnlyList ParseScopes(string json) + { + try { return JsonSerializer.Deserialize>(json) ?? []; } + catch (JsonException) { return []; } + } + + public static IReadOnlyList ParseRoles(IEnumerable values) + => values.Select(value => (BotRole)value) + .Where(Enum.IsDefined) + .Distinct() + .ToArray(); +} diff --git a/OshimaBot/Security/RequireApiKeyAttribute.cs b/OshimaBot/Security/RequireApiKeyAttribute.cs index 4b922e2..fa2aa82 100644 --- a/OshimaBot/Security/RequireApiKeyAttribute.cs +++ b/OshimaBot/Security/RequireApiKeyAttribute.cs @@ -1,51 +1,18 @@ -using System.Security.Cryptography; -using System.Text; -using OshimaBot.Models; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Options; +using Microsoft.AspNetCore.Authorization; namespace OshimaBot.Security { + /// + /// 旧版直接比对全局明文 Server:ApiKey;S6 起改为标准 AuthenticationScheme + Policy, + /// 由 ApiKeyAuthenticationHandler 查库校验哈希,支持吊销、过期与分权。 + /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] - public sealed class RequireApiKeyAttribute : Attribute, IAuthorizationFilter + public sealed class RequireApiKeyAttribute : AuthorizeAttribute { - public void OnAuthorization(AuthorizationFilterContext context) + public RequireApiKeyAttribute() { - ServerOptions options = context.HttpContext.RequestServices - .GetRequiredService>().Value; - if (string.IsNullOrWhiteSpace(options.ApiKey)) - { - context.Result = new ObjectResult(new ProblemDetails - { - Title = "第三方接口尚未配置 API Key。", - Status = StatusCodes.Status503ServiceUnavailable - }) - { - StatusCode = StatusCodes.Status503ServiceUnavailable - }; - return; - } - - string provided = context.HttpContext.Request.Headers["X-API-Key"].ToString(); - if (string.IsNullOrWhiteSpace(provided)) - { - string authorization = context.HttpContext.Request.Headers.Authorization.ToString(); - if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) - { - provided = authorization[7..].Trim(); - } - } - - byte[] expectedBytes = Encoding.UTF8.GetBytes(options.ApiKey); - byte[] providedBytes = Encoding.UTF8.GetBytes(provided); - if (providedBytes.Length == 0 - || providedBytes.Length != expectedBytes.Length - || !CryptographicOperations.FixedTimeEquals(providedBytes, expectedBytes)) - { - context.HttpContext.Response.Headers.WWWAuthenticate = "Bearer"; - context.Result = new UnauthorizedResult(); - } + AuthenticationSchemes = ApiKeyDefaults.Scheme; + Policy = ApiKeyDefaults.Policy; } } } diff --git a/OshimaBot/Security/UserDirectory.cs b/OshimaBot/Security/UserDirectory.cs new file mode 100644 index 0000000..b00814e --- /dev/null +++ b/OshimaBot/Security/UserDirectory.cs @@ -0,0 +1,190 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using OshimaBot.Data; +using OshimaBot.Data.Entities; +using OshimaBot.Models; + +namespace OshimaBot.Security; + +public enum IdentityLinkStatus +{ + Linked, + AlreadyLinked, + Conflict, + UserNotFound +} + +public interface IUserDirectory +{ + /// 按 (provider, subject) 解析内部 users.id;首次出现懒注册建档。 + Task ResolveAsync(ExternalIdentity identity, CancellationToken cancellationToken = default); + + /// 把外部身份绑定到指定内部用户(绑定码兑换时调用)。 + Task LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default); +} + +public sealed class UserDirectory( + IServiceScopeFactory scopeFactory, + IOptions options, + ILogger logger) : IUserDirectory +{ + private readonly ServerOptions _options = options.Value; + + public async Task ResolveAsync(ExternalIdentity identity, CancellationToken cancellationToken = default) + { + try + { + return await ResolveCoreAsync(identity, cancellationToken); + } + catch (DbUpdateException) + { + // 并发懒注册撞上 UNIQUE(provider, subject):回滚后按已有身份重查。 + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + UserIdentity? existing = await db.UserIdentities.AsNoTracking() + .FirstOrDefaultAsync(x => x.Provider == identity.Provider && x.Subject == identity.Subject, cancellationToken); + if (existing is null) throw; + return await BuildPrincipalAsync(db, existing.UserId, false, cancellationToken); + } + } + + private async Task ResolveCoreAsync(ExternalIdentity identity, CancellationToken cancellationToken) + { + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + + UserIdentity? existing = await db.UserIdentities.AsNoTracking() + .FirstOrDefaultAsync(x => x.Provider == identity.Provider && x.Subject == identity.Subject, cancellationToken); + if (existing is not null) + { + DateTime now = DateTime.UtcNow; + await db.Users.Where(x => x.Id == existing.UserId) + .ExecuteUpdateAsync(setters => setters.SetProperty(x => x.LastSeenAtUtc, now), cancellationToken); + return await BuildPrincipalAsync(db, existing.UserId, false, cancellationToken); + } + + await using Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction transaction = + await db.Database.BeginTransactionAsync(cancellationToken); + + long userId = 0; + bool created = false; + if (!string.IsNullOrWhiteSpace(identity.UnionSubject)) + { + UserIdentity? union = await db.UserIdentities.AsNoTracking() + .FirstOrDefaultAsync(x => x.UnionSubject == identity.UnionSubject, cancellationToken); + if (union is not null) userId = union.UserId; + } + + if (userId == 0) + { + User user = new() + { + Handle = "U" + Guid.NewGuid().ToString("N")[..8].ToUpperInvariant(), + Nickname = "", + Status = 0, + CreatedAtUtc = DateTime.UtcNow, + LastSeenAtUtc = DateTime.UtcNow + }; + db.Users.Add(user); + await db.SaveChangesAsync(cancellationToken); + userId = user.Id; + created = true; + } + + db.UserIdentities.Add(new UserIdentity + { + UserId = userId, + Provider = identity.Provider, + Subject = identity.Subject, + UnionSubject = identity.UnionSubject, + Scene = identity.Scene, + CreatedAtUtc = DateTime.UtcNow + }); + await EnsureRolesAsync(db, userId, identity, cancellationToken); + db.AuditLogs.Add(new AuditLog + { + ActorUserId = userId, + Action = created ? "user.register" : "identity.union_link", + Target = $"{identity.Provider}:{identity.Subject}", + PayloadJson = $"{{\"scene\":\"{identity.Scene}\"}}", + CreatedAtUtc = DateTime.UtcNow + }); + await db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + + BotUserPrincipal principal = await BuildPrincipalAsync(db, userId, created, cancellationToken); + logger.LogInformation("QQ 用户懒注册:UserId={UserId}, Handle={Handle}, Created={Created}", + userId, principal.Handle, created); + return principal; + } + + public async Task LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default) + { + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + if (!await db.Users.AnyAsync(x => x.Id == userId, cancellationToken)) return IdentityLinkStatus.UserNotFound; + + UserIdentity? existing = await db.UserIdentities.AsNoTracking() + .FirstOrDefaultAsync(x => x.Provider == identity.Provider && x.Subject == identity.Subject, cancellationToken); + if (existing is not null) + { + return existing.UserId == userId ? IdentityLinkStatus.AlreadyLinked : IdentityLinkStatus.Conflict; + } + + db.UserIdentities.Add(new UserIdentity + { + UserId = userId, + Provider = identity.Provider, + Subject = identity.Subject, + UnionSubject = identity.UnionSubject, + Scene = identity.Scene, + CreatedAtUtc = DateTime.UtcNow + }); + db.AuditLogs.Add(new AuditLog + { + ActorUserId = userId, + Action = "identity.bind_code_redeem", + Target = $"{identity.Provider}:{identity.Subject}", + PayloadJson = "{}", + CreatedAtUtc = DateTime.UtcNow + }); + try + { + await db.SaveChangesAsync(cancellationToken); + return IdentityLinkStatus.Linked; + } + catch (DbUpdateException) + { + return IdentityLinkStatus.Conflict; + } + } + + private async Task EnsureRolesAsync(BotDbContext db, long userId, ExternalIdentity identity, CancellationToken cancellationToken) + { + HashSet current = (await db.UserRoles.AsNoTracking() + .Where(x => x.UserId == userId).Select(x => x.Role).ToListAsync(cancellationToken)).ToHashSet(); + + if (current.Add((int)BotRole.Player)) + { + db.UserRoles.Add(new UserRole { UserId = userId, Role = (int)BotRole.Player }); + } + // 超管双轨:配置白名单 OpenID + user_roles,避免数据库被清空后彻底失去管理能力。 + if (string.Equals(identity.Provider, "qq", StringComparison.Ordinal) + && _options.SuperAdminOpenIds.Contains(identity.Subject, StringComparer.Ordinal) + && current.Add((int)BotRole.Owner)) + { + db.UserRoles.Add(new UserRole { UserId = userId, Role = (int)BotRole.Owner }); + logger.LogInformation("按白名单授予 Owner:UserId={UserId}", userId); + } + await db.SaveChangesAsync(cancellationToken); + } + + private static async Task BuildPrincipalAsync( + BotDbContext db, long userId, bool isNew, CancellationToken cancellationToken) + { + User user = await db.Users.AsNoTracking().FirstAsync(x => x.Id == userId, cancellationToken); + List roles = await db.UserRoles.AsNoTracking() + .Where(x => x.UserId == userId).Select(x => x.Role).ToListAsync(cancellationToken); + return new BotUserPrincipal(user.Id, user.Handle, user.Nickname, ApiKeyDefaults.ParseRoles(roles), isNew); + } +} diff --git a/OshimaBot/Services/QQEventDispatcher.cs b/OshimaBot/Services/QQEventDispatcher.cs index c46d78f..cdcacc3 100644 --- a/OshimaBot/Services/QQEventDispatcher.cs +++ b/OshimaBot/Services/QQEventDispatcher.cs @@ -1,6 +1,7 @@ using System.Text.Json; using OshimaBot.Messaging; using OshimaBot.Models; +using OshimaBot.Security; namespace OshimaBot.Services; @@ -47,6 +48,7 @@ public sealed class QQEventDispatcher( IEventDeduplicationStore deduplication, IInteractionAckService interactionAck, IBotMessageSink sink, + IUserDirectory userDirectory, ILogger logger) : IQQEventDispatcher { private const string InteractionPrefix = "INTERACTION_CREATE:"; @@ -98,6 +100,7 @@ public sealed class QQEventDispatcher( ? payload.Id : null; + await AttachIdentityAsync(message, eventKey, cancellationToken); await sink.QueueAsync(message, cancellationToken); await deduplication.MarkProcessedAsync(eventKey, 0, cancellationToken); logger.LogInformation("已接收 QQ {EventType} 事件:Source={Source}, EventId={EventId}, MessageId={MessageId}", @@ -117,6 +120,25 @@ public sealed class QQEventDispatcher( } } + private async Task AttachIdentityAsync(IBotMessage message, string eventKey, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(message.AuthorOpenId)) return; + ExternalIdentity identity = ExternalIdentity.Qq(message.AuthorOpenId, message.IsGroup ? "group" : "c2c"); + try + { + BotUserPrincipal principal = await userDirectory.ResolveAsync(identity, cancellationToken); + message.FunGameUID = principal.UserId; + message.Principal = principal.ToClaimsPrincipal(); + logger.LogDebug("QQ 身份解析完成:EventId={EventId}, UserId={UserId}, IsNew={IsNew}", + eventKey, principal.UserId, principal.IsNew); + } + catch (Exception exception) + { + // 用户库暂不可用时仍允许查询类指令工作;S7 起需要身份的指令再单独拦截。 + logger.LogWarning(exception, "QQ 用户身份解析失败:EventId={EventId},按未认证消息继续投递。", eventKey); + } + } + private static string ResolveEventKey(Payload payload, QQEventSource source) { if (!string.IsNullOrWhiteSpace(payload.Id)) return payload.Id; diff --git a/OshimaBot/Services/RainBotService.cs b/OshimaBot/Services/RainBotService.cs index bcc171e..295b9f2 100644 --- a/OshimaBot/Services/RainBotService.cs +++ b/OshimaBot/Services/RainBotService.cs @@ -2,6 +2,7 @@ using System.Text; using OshimaBot.Game.Services; using OshimaBot.Messaging; using OshimaBot.Models; +using OshimaBot.Security; using FunGame.Core.Library.Constant; namespace OshimaBot.Services @@ -10,6 +11,7 @@ namespace OshimaBot.Services FunGameQueryService queries, FunGameSimulationService simulations, MessageSender messageSender, + IBindCodeService bindCodes, ILogger logger) { public async Task Handler(IBotMessage message, OtherData data, CancellationToken cancellationToken = default) @@ -35,7 +37,16 @@ namespace OshimaBot.Services if (command == "帮助") return BotReply.FromMarkdown(CreateHelp()); if (command is "战斗帮助" or "角色帮助" or "物品帮助") return BotReply.FromMarkdown(CreateBattleHelp()); if (command == "重置状态") return "当前版本采用无状态指令路由,无需重置指令状态。"; - if (command == "获取接入码" && !message.IsGroup) return $"你的接入码为 {message.AuthorOpenId},请妥善保存!"; + // 旧版直接回显 OpenID 作为「接入码」已停用:改为 6 位一次性绑定码。 + if ((command is "获取接入码" or "绑定" or "/绑定") && !message.IsGroup) + { + if (message.FunGameUID <= 0) + { + return "身份尚未就绪,请稍后重试或换一条消息触发注册。"; + } + string code = await bindCodes.IssueAsync(message.FunGameUID, "qq_bind", cancellationToken); + return $"你的绑定码为 {code},{bindCodes.TtlSeconds / 60} 分钟内有效且只能使用一次。请在第三方端凭码绑定,切勿公开;旧版直接回显 OpenID 的方式已停用。"; + } if (command == "查询服务器启动时间") return $"OshimaBot 启动时间(UTC):{FunGameRuntime.StartedAt:yyyy-MM-dd HH:mm:ss}"; if (command == "预览魔法卡") return queries.GenerateMagicCard(); diff --git a/OshimaBot/appsettings.json b/OshimaBot/appsettings.json index 3004d41..655f398 100644 --- a/OshimaBot/appsettings.json +++ b/OshimaBot/appsettings.json @@ -30,6 +30,8 @@ }, "Server": { "ApiKey": "", - "MaximumRespawnTimes": 10 + "MaximumRespawnTimes": 10, + "SuperAdminOpenIds": [], + "BindCodeTtlSeconds": 300 } }