feat(S6): add QQ identity resolution, DB-backed API keys and one-time bind codes
This commit is contained in:
@@ -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<QQEventDispatcher>.Instance);
|
||||
dedup, ack, sink, new FakeUserDirectory(), NullLogger<QQEventDispatcher>.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<QQEventDispatcher>.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<BotUserPrincipal> ResolveAsync(ExternalIdentity identity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Calls++;
|
||||
return Task.FromResult(new BotUserPrincipal(42, "U000042", "", [BotRole.Player], false));
|
||||
}
|
||||
|
||||
public Task<IdentityLinkStatus> LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult(IdentityLinkStatus.Linked);
|
||||
}
|
||||
|
||||
private sealed class FakeSink : IBotMessageSink
|
||||
{
|
||||
public List<IBotMessage> Messages { get; } = [];
|
||||
|
||||
@@ -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<IUserDirectory>();
|
||||
|
||||
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<BotDbContext>();
|
||||
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<IUserDirectory>();
|
||||
|
||||
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<BotDbContext>();
|
||||
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<IUserDirectory>().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<IUserDirectory>().ResolveAsync(ExternalIdentity.Qq("HOST"));
|
||||
IBindCodeService codes = db.Get<IBindCodeService>();
|
||||
|
||||
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<BotDbContext>();
|
||||
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<IUserDirectory>();
|
||||
BotUserPrincipal host = await directory.ResolveAsync(ExternalIdentity.Qq("HOST"));
|
||||
BotUserPrincipal other = await directory.ResolveAsync(ExternalIdentity.Qq("TAKEN"));
|
||||
IBindCodeService codes = db.Get<IBindCodeService>();
|
||||
|
||||
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<BotDbContext>();
|
||||
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<ApiKeyAuthenticator>();
|
||||
using (IServiceScope scope = db.Provider.CreateScope())
|
||||
{
|
||||
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||
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<BotDbContext>();
|
||||
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<BotDbContext>();
|
||||
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<IServiceScopeFactory>(),
|
||||
Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }),
|
||||
Options.Create(new ServerOptions { ApiKey = "bootstrap-secret" }),
|
||||
NullLogger<DatabaseInitializer>.Instance);
|
||||
|
||||
await initializer.InitializeAsync(CancellationToken.None);
|
||||
|
||||
ApiKeyAuthenticator authenticator = db.Get<ApiKeyAuthenticator>();
|
||||
Assert.NotNull(await authenticator.AuthenticateAsync("bootstrap-secret"));
|
||||
using IServiceScope scope = db.Provider.CreateScope();
|
||||
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||
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]));
|
||||
}
|
||||
|
||||
/// <summary>共享的 SQLite 内存库 + 真实 DI 容器,保证测的是真实 EF Core 行为。</summary>
|
||||
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<BotDbContext>(options => options.UseSqlite(Connection));
|
||||
services.AddSingleton(Options.Create(serverOptions ?? new ServerOptions()));
|
||||
services.AddSingleton(Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }));
|
||||
services.AddSingleton<IUserDirectory, UserDirectory>();
|
||||
services.AddSingleton<IBindCodeService, BindCodeService>();
|
||||
services.AddSingleton<ApiKeyAuthenticator>();
|
||||
Provider = services.BuildServiceProvider();
|
||||
using IServiceScope scope = Provider.CreateScope();
|
||||
scope.ServiceProvider.GetRequiredService<BotDbContext>().Database.EnsureCreated();
|
||||
}
|
||||
|
||||
public T Get<T>() where T : notnull => Provider.GetRequiredService<T>();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Provider.Dispose();
|
||||
Connection.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<QQBotOptions> options,
|
||||
ILogger<QQBotController> 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<IActionResult> 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<IActionResult> 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);
|
||||
|
||||
@@ -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<DatabaseOptions> options,
|
||||
IOptions<ServerOptions> serverOptions,
|
||||
ILogger<DatabaseInitializer> 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);
|
||||
|
||||
/// <summary>公开以便集成测试直接等待完成(BackgroundService.StartAsync 不会等待 ExecuteAsync)。</summary>
|
||||
public async Task InitializeAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
using IServiceScope scope = scopeFactory.CreateScope();
|
||||
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||
await db.Database.MigrateAsync(stoppingToken);
|
||||
await db.Database.ExecuteSqlRawAsync("PRAGMA journal_mode=WAL;", stoppingToken);
|
||||
await db.Database.ExecuteSqlRawAsync("PRAGMA foreign_keys=ON;", stoppingToken);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 兼容旧配置的过渡:若 Server:ApiKey 非空,首次启动时把 SHA-256 摘要写入 api_keys。
|
||||
/// 认证只查库;写入后应从配置移除明文,后续密钥直接由数据库管理(可吊销/过期/分权)。
|
||||
/// </summary>
|
||||
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 表管理密钥。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace OshimaBot.Models;
|
||||
|
||||
/// <summary>第三方/管理端凭一次性绑定码把 QQ OpenID 绑到内部用户。</summary>
|
||||
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";
|
||||
}
|
||||
@@ -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
|
||||
|
||||
/// <summary>互动事件的被动回复使用 event_id(与 msg_id 互斥);消息事件为 null。</summary>
|
||||
string? EventId { get; set; }
|
||||
|
||||
/// <summary>S6 起由事件管线注入;第三方接口则由 ApiKey ClaimsPrincipal 注入。</summary>
|
||||
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;
|
||||
|
||||
@@ -85,7 +85,14 @@ namespace OshimaBot.Models
|
||||
{
|
||||
public const string SectionName = "Server";
|
||||
|
||||
/// <summary>仅作首次启动引导密钥:启动时把其 SHA-256 写入 api_keys,认证阶段不再读取明文。</summary>
|
||||
public string ApiKey { get; set; } = "";
|
||||
public int MaximumRespawnTimes { get; set; } = 10;
|
||||
|
||||
/// <summary>超管白名单 QQ OpenID,与 user_roles 双轨;数据库清空后仍可恢复管理权限。</summary>
|
||||
public List<string> SuperAdminOpenIds { get; set; } = [];
|
||||
|
||||
/// <summary>一次性绑定码有效期(秒)。</summary>
|
||||
public int BindCodeTtlSeconds { get; set; } = 300;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<QQBotOptions>()
|
||||
builder.Services.AddOptions<ServerOptions>()
|
||||
.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<DatabaseOptions>()
|
||||
.Bind(builder.Configuration.GetSection(DatabaseOptions.SectionName))
|
||||
@@ -38,6 +40,11 @@ builder.Services.AddOptions<DatabaseOptions>()
|
||||
.ValidateOnStart();
|
||||
|
||||
builder.Services.AddSingleton<WebhookSignatureVerifier>();
|
||||
builder.Services.AddAuthentication(ApiKeyDefaults.Scheme)
|
||||
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(ApiKeyDefaults.Scheme, null);
|
||||
builder.Services.AddAuthorization(options => options.AddPolicy(ApiKeyDefaults.Policy, policy => policy
|
||||
.AddAuthenticationSchemes(ApiKeyDefaults.Scheme)
|
||||
.RequireAuthenticatedUser()));
|
||||
|
||||
builder.Services.AddDbContext<BotDbContext>(options =>
|
||||
{
|
||||
@@ -67,6 +74,9 @@ builder.Services.AddSingleton<IBotMessageSink>(sp => sp.GetRequiredService<BotMe
|
||||
builder.Services.AddSingleton<IEventDeduplicationStore, EventDeduplicationStore>();
|
||||
builder.Services.AddSingleton<IInteractionAckService, InteractionAckService>();
|
||||
builder.Services.AddSingleton<IQQEventDispatcher, QQEventDispatcher>();
|
||||
builder.Services.AddSingleton<ApiKeyAuthenticator>();
|
||||
builder.Services.AddSingleton<IUserDirectory, UserDirectory>();
|
||||
builder.Services.AddSingleton<IBindCodeService, BindCodeService>();
|
||||
builder.Services.AddSingleton<IGatewayApiClient, GatewayApiClient>();
|
||||
builder.Services.AddSingleton<IGatewaySessionStore, GatewaySessionStore>();
|
||||
builder.Services.AddSingleton<IGatewayStatus, GatewayStatus>();
|
||||
@@ -81,6 +91,9 @@ app.UseExceptionHandler();
|
||||
// 仅当 QQBot:EnableWebhook=true 时对 POST /QQBot 校验 Ed25519 签名。
|
||||
app.UseMiddleware<WebhookSignatureMiddleware>();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>数据库侧 API Key 校验:只认 api_keys 表中的 SHA-256 摘要,支持吊销/过期/按 key 分权。</summary>
|
||||
public sealed class ApiKeyAuthenticator(IServiceScopeFactory scopeFactory)
|
||||
{
|
||||
public async Task<ApiKeyIdentity?> 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<BotDbContext>();
|
||||
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<int> 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>把 X-API-Key / Bearer 换成标准 ClaimsPrincipal,供 Policy 与 S7 指令权限使用。</summary>
|
||||
public sealed class ApiKeyAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override async Task<AuthenticateResult> 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<ApiKeyAuthenticator>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<string> IssueAsync(long userId, string purpose = "qq_bind", CancellationToken cancellationToken = default);
|
||||
Task<BindRedeemResult> RedeemAsync(string code, ExternalIdentity identity, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>6 位一次性绑定码,替代旧版「获取接入码」直接回显 OpenID。</summary>
|
||||
public sealed class BindCodeService(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IUserDirectory userDirectory,
|
||||
IOptions<ServerOptions> options,
|
||||
ILogger<BindCodeService> logger) : IBindCodeService
|
||||
{
|
||||
private readonly int _ttlSeconds = Math.Max(30, options.Value.BindCodeTtlSeconds);
|
||||
|
||||
public int TtlSeconds => _ttlSeconds;
|
||||
|
||||
public async Task<string> IssueAsync(long userId, string purpose = "qq_bind", CancellationToken cancellationToken = default)
|
||||
{
|
||||
using IServiceScope scope = scopeFactory.CreateScope();
|
||||
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||
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<BindRedeemResult> 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<BotDbContext>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace OshimaBot.Security;
|
||||
|
||||
/// <summary>角色层级:数值越大权限越高,HasRole 按层级比较。</summary>
|
||||
public enum BotRole
|
||||
{
|
||||
Player = 0,
|
||||
Operator = 1,
|
||||
Admin = 2,
|
||||
Owner = 3
|
||||
}
|
||||
|
||||
/// <summary>外部身份坐标:业务代码永远不直接拿 OpenID 当用户主键。</summary>
|
||||
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<BotRole> Roles, bool IsNew)
|
||||
{
|
||||
public const string Scheme = "QQBotEvent";
|
||||
|
||||
public bool HasRole(BotRole required) => Roles.Any(role => role >= required);
|
||||
|
||||
public ClaimsPrincipal ToClaimsPrincipal()
|
||||
{
|
||||
List<Claim> 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<string> Scopes, IReadOnlyList<BotRole> Roles)
|
||||
{
|
||||
public ClaimsPrincipal ToClaimsPrincipal(string scheme)
|
||||
{
|
||||
List<Claim> 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";
|
||||
|
||||
/// <summary>API Key 为高熵随机串,数据库只存 SHA-256 十六进制摘要,不存明文。</summary>
|
||||
public static string Hash(string key)
|
||||
=> Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))).ToLowerInvariant();
|
||||
|
||||
public static IReadOnlyList<string> ParseScopes(string json)
|
||||
{
|
||||
try { return JsonSerializer.Deserialize<List<string>>(json) ?? []; }
|
||||
catch (JsonException) { return []; }
|
||||
}
|
||||
|
||||
public static IReadOnlyList<BotRole> ParseRoles(IEnumerable<int> values)
|
||||
=> values.Select(value => (BotRole)value)
|
||||
.Where(Enum.IsDefined)
|
||||
.Distinct()
|
||||
.ToArray();
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 旧版直接比对全局明文 Server:ApiKey;S6 起改为标准 AuthenticationScheme + Policy,
|
||||
/// 由 ApiKeyAuthenticationHandler 查库校验哈希,支持吊销、过期与分权。
|
||||
/// </summary>
|
||||
[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<IOptions<ServerOptions>>().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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>按 (provider, subject) 解析内部 users.id;首次出现懒注册建档。</summary>
|
||||
Task<BotUserPrincipal> ResolveAsync(ExternalIdentity identity, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>把外部身份绑定到指定内部用户(绑定码兑换时调用)。</summary>
|
||||
Task<IdentityLinkStatus> LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class UserDirectory(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IOptions<ServerOptions> options,
|
||||
ILogger<UserDirectory> logger) : IUserDirectory
|
||||
{
|
||||
private readonly ServerOptions _options = options.Value;
|
||||
|
||||
public async Task<BotUserPrincipal> 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<BotDbContext>();
|
||||
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<BotUserPrincipal> ResolveCoreAsync(ExternalIdentity identity, CancellationToken cancellationToken)
|
||||
{
|
||||
using IServiceScope scope = scopeFactory.CreateScope();
|
||||
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||
|
||||
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<IdentityLinkStatus> LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using IServiceScope scope = scopeFactory.CreateScope();
|
||||
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||
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<int> 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<BotUserPrincipal> BuildPrincipalAsync(
|
||||
BotDbContext db, long userId, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
User user = await db.Users.AsNoTracking().FirstAsync(x => x.Id == userId, cancellationToken);
|
||||
List<int> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<QQEventDispatcher> 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;
|
||||
|
||||
@@ -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<RainBotService> logger)
|
||||
{
|
||||
public async Task<bool> 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();
|
||||
|
||||
@@ -30,6 +30,8 @@
|
||||
},
|
||||
"Server": {
|
||||
"ApiKey": "",
|
||||
"MaximumRespawnTimes": 10
|
||||
"MaximumRespawnTimes": 10,
|
||||
"SuperAdminOpenIds": [],
|
||||
"BindCodeTtlSeconds": 300
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user