From c4233900a6796304f87a991c674edc141bcde425 Mon Sep 17 00:00:00 2001 From: biss Date: Mon, 16 Nov 2026 15:54:58 +0800 Subject: [PATCH] Improve license activation and provider tracking --- docs/license-activation.md | 4 +- .../Controllers/LicensesController.cs | 43 ++++++++++++++++--- src/Jiaowu.Api/Program.cs | 1 + src/Jiaowu.LicenseApi/Program.cs | 8 ++-- src/Jiaowu.Licensing/LicenseCryptography.cs | 2 +- web/src/views/LicensesView.vue | 28 +++++++++++- 6 files changed, 73 insertions(+), 13 deletions(-) diff --git a/docs/license-activation.md b/docs/license-activation.md index ea0d337..e6f017e 100644 --- a/docs/license-activation.md +++ b/docs/license-activation.md @@ -40,9 +40,9 @@ Licensing__ApiKey= The service exposes `GET /health` and `POST /api/licenses/issue`. The issue endpoint requires `X-License-Api-Key` and accepts JSON such as: ```json -{"machineCode":"JW-ABCDEF-123456-789ABC-DEF012","years":1,"isAnnual":true} +{"machineCode":"JW-ABCDEF-123456-789ABC-DEF012","years":1,"isAnnual":true,"maintenanceOrganization":"示例维护机构"} ``` -It returns a signed activation code for the supplied machine. A customer-facing portal or order system should call this endpoint from its server after checking the customer's purchase, then present the activation code for pasting into Jiaowu. Do not expose the API key in browser code. The API service can use the same public/private key pair as offline issuance, while only the public key is installed on Jiaowu. +It returns a signed activation code for the supplied machine. The optional maintenance organization is included in the signature and shown in Jiaowu's authorization status after activation. Configure Jiaowu's server with `Licensing__OnlineApiUrl` (HTTPS base URL) and `Licensing__OnlineApiKey`; super administrators can then issue and activate directly from **System authorization**. The API key stays on the server. The API service can use the same public/private key pair as offline issuance, while only the public key is installed on Jiaowu. For Docker or virtualized installations, set `JIAOWU_LICENSE_MACHINE_ID` to a stable deployment identifier before taking the machine code. Keep that value unchanged for the life of the installation; changing it changes the machine code and invalidates its machine binding. diff --git a/src/Jiaowu.Api/Controllers/LicensesController.cs b/src/Jiaowu.Api/Controllers/LicensesController.cs index 62b352d..fbf9f2a 100644 --- a/src/Jiaowu.Api/Controllers/LicensesController.cs +++ b/src/Jiaowu.Api/Controllers/LicensesController.cs @@ -10,7 +10,7 @@ namespace Jiaowu.Api.Controllers; [ApiController] [Route("api/licenses")] -public sealed class LicensesController(AppDbContext db, IConfiguration configuration) : ControllerBase +public sealed class LicensesController(AppDbContext db, IConfiguration configuration, IHttpClientFactory httpClientFactory) : ControllerBase { private const string StoredCodePrefix = "JWL:"; private const int CodeChunkSize = 70; @@ -23,11 +23,40 @@ public sealed class LicensesController(AppDbContext db, IConfiguration configura var code = await ReadStoredCode(cancellationToken); var publicKey = GetPublicKey(); if (code is null || publicKey is null || !LicenseCryptography.TryVerify(code, publicKey, out var payload) || payload is null) - return Ok(new LicenseStatus(machineCode, false, null, null, false)); + return Ok(new LicenseStatus(machineCode, false, null, null, false, null)); var bound = string.Equals(payload.MachineCode, machineCode, StringComparison.Ordinal); var expired = payload.ExpiresAtUtc <= DateTime.UtcNow; - return Ok(new LicenseStatus(machineCode, bound, payload.ExpiresAtUtc, payload.Type, expired)); + return Ok(new LicenseStatus(machineCode, bound, payload.ExpiresAtUtc, payload.Type, expired, payload.MaintenanceOrganization)); + } + + [Authorize(Roles = SystemRoles.SuperAdmin)] + [HttpPost("online-activate")] + public async Task> OnlineActivate(OnlineLicenseRequest request, CancellationToken cancellationToken) + { + var endpoint = configuration["Licensing:OnlineApiUrl"]; + var apiKey = configuration["Licensing:OnlineApiKey"]; + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps || string.IsNullOrWhiteSpace(apiKey)) + return StatusCode(StatusCodes.Status503ServiceUnavailable, new { message = "在线授权服务未配置(需要 HTTPS 地址和 API 密钥)。" }); + var organization = request.MaintenanceOrganization?.Trim(); + if (string.IsNullOrWhiteSpace(organization) || organization.Length > 200) + return BadRequest(new { message = "请填写维护机构名称(最多 200 个字符)。" }); + using var message = new HttpRequestMessage(HttpMethod.Post, new Uri(uri, "/api/licenses/issue")); + message.Headers.Add("X-License-Api-Key", apiKey); + message.Content = System.Net.Http.Json.JsonContent.Create(new OnlineLicenseIssueRequest( + LicenseCryptography.GetMachineCode(), request.Years, request.IsAnnual, organization)); + using var response = await httpClientFactory.CreateClient("LicenseIssuance").SendAsync(message, cancellationToken); + if (!response.IsSuccessStatusCode) + { + var responseText = await response.Content.ReadAsStringAsync(cancellationToken); + return StatusCode(StatusCodes.Status502BadGateway, new { message = $"在线授权服务返回错误({(int)response.StatusCode}):{responseText}" }); + } + var issued = await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken); + if (issued is null || string.IsNullOrWhiteSpace(issued.ActivationCode)) + return StatusCode(StatusCodes.Status502BadGateway, new { message = "在线授权服务没有返回激活码。" }); + var activated = await Activate(new ActivateLicenseRequest(issued.ActivationCode), cancellationToken); + if (activated.Result is not null) return activated.Result; + return Ok(new OnlineLicenseActivationResult(issued.ActivationCode, activated.Value!)); } [Authorize(Roles = SystemRoles.SuperAdmin)] @@ -62,7 +91,7 @@ public sealed class LicensesController(AppDbContext db, IConfiguration configura } await db.SaveChangesAsync(cancellationToken); return Ok(new LicenseStatus(LicenseCryptography.GetMachineCode(), true, - payload.ExpiresAtUtc, payload.Type, false)); + payload.ExpiresAtUtc, payload.Type, false, payload.MaintenanceOrganization)); } private string? GetPublicKey() @@ -88,4 +117,8 @@ public sealed class LicensesController(AppDbContext db, IConfiguration configura public sealed record ActivateLicenseRequest(string Code); public sealed record LicenseStatus(string MachineCode, bool IsLicensed, DateTime? ExpiresAt, - string? Type, bool IsExpired); + string? Type, bool IsExpired, string? MaintenanceOrganization); +public sealed record OnlineLicenseRequest(int Years = 1, bool IsAnnual = true, string? MaintenanceOrganization = null); +public sealed record OnlineLicenseIssueRequest(string MachineCode, int Years, bool IsAnnual, string MaintenanceOrganization); +public sealed record OnlineLicenseIssueResponse(string ActivationCode, string Type, DateTime ExpiresAtUtc); +public sealed record OnlineLicenseActivationResult(string ActivationCode, LicenseStatus Status); diff --git a/src/Jiaowu.Api/Program.cs b/src/Jiaowu.Api/Program.cs index 89026af..4bcc66d 100644 --- a/src/Jiaowu.Api/Program.cs +++ b/src/Jiaowu.Api/Program.cs @@ -362,6 +362,7 @@ builder.Services.AddSingleton(clickHouseAnalyticsOptions); builder.Services.AddSingleton(rabbitMqOptions); builder.Services.AddSingleton(); builder.Services.AddHttpContextAccessor(); +builder.Services.AddHttpClient("LicenseIssuance", client => client.Timeout = TimeSpan.FromSeconds(20)); builder.Services.AddMemoryCache(); builder.Services.AddHttpClient((services, client) => { diff --git a/src/Jiaowu.LicenseApi/Program.cs b/src/Jiaowu.LicenseApi/Program.cs index 956fabb..9c424b2 100644 --- a/src/Jiaowu.LicenseApi/Program.cs +++ b/src/Jiaowu.LicenseApi/Program.cs @@ -12,8 +12,8 @@ app.MapPost("/api/licenses/issue", async (HttpRequest request, LicenseIssueReque var supplied = request.Headers["X-License-Api-Key"].ToString(); if (string.IsNullOrWhiteSpace(expected) || !FixedTimeEquals(supplied, expected)) return Results.Unauthorized(); - if (string.IsNullOrWhiteSpace(input.MachineCode) || input.MachineCode.Length > 64 || input.Years is < 1 or > 30) - return Results.BadRequest(new { message = "MachineCode is required and years must be 1 through 30." }); + if (string.IsNullOrWhiteSpace(input.MachineCode) || input.MachineCode.Length > 64 || input.Years is < 1 or > 30 || input.MaintenanceOrganization?.Length > 200) + return Results.BadRequest(new { message = "MachineCode is required, years must be 1 through 30, and maintenance organization must be at most 200 characters." }); var keyPath = config["Licensing:PrivateKeyPath"]; if (string.IsNullOrWhiteSpace(keyPath) || !File.Exists(keyPath)) @@ -22,7 +22,7 @@ app.MapPost("/api/licenses/issue", async (HttpRequest request, LicenseIssueReque var now = DateTime.UtcNow; var type = input.IsAnnual ? "Annual" : "Custom"; var code = LicenseCryptography.CreateCode( - new LicensePayload(input.MachineCode, now, now.AddYears(input.IsAnnual ? 1 : input.Years), type), + new LicensePayload(input.MachineCode, now, now.AddYears(input.IsAnnual ? 1 : input.Years), type, input.MaintenanceOrganization?.Trim()), await File.ReadAllTextAsync(keyPath)); return Results.Ok(new LicenseIssueResponse(code, type, now.AddYears(input.IsAnnual ? 1 : input.Years))); }); @@ -36,5 +36,5 @@ static bool FixedTimeEquals(string supplied, string expected) return left.Length == right.Length && CryptographicOperations.FixedTimeEquals(left, right); } -public sealed record LicenseIssueRequest(string MachineCode, int Years, bool IsAnnual = false); +public sealed record LicenseIssueRequest(string MachineCode, int Years, bool IsAnnual = false, string? MaintenanceOrganization = null); public sealed record LicenseIssueResponse(string ActivationCode, string Type, DateTime ExpiresAtUtc); diff --git a/src/Jiaowu.Licensing/LicenseCryptography.cs b/src/Jiaowu.Licensing/LicenseCryptography.cs index 9abedad..dc0e4b6 100644 --- a/src/Jiaowu.Licensing/LicenseCryptography.cs +++ b/src/Jiaowu.Licensing/LicenseCryptography.cs @@ -4,7 +4,7 @@ using System.Text.Json; namespace Jiaowu.Licensing; -public sealed record LicensePayload(string MachineCode, DateTime IssuedAtUtc, DateTime ExpiresAtUtc, string Type); +public sealed record LicensePayload(string MachineCode, DateTime IssuedAtUtc, DateTime ExpiresAtUtc, string Type, string? MaintenanceOrganization = null); public static class LicenseCryptography { diff --git a/web/src/views/LicensesView.vue b/web/src/views/LicensesView.vue index 21da0fc..ebe7d5d 100644 --- a/web/src/views/LicensesView.vue +++ b/web/src/views/LicensesView.vue @@ -3,9 +3,12 @@ import { onMounted, ref } from 'vue' import { ElMessage } from 'element-plus' import http, { apiErrorMessage } from '../api/http' -interface LicenseStatus { machineCode: string; isLicensed: boolean; expiresAt: string | null; type: string | null; isExpired: boolean } +interface LicenseStatus { machineCode: string; isLicensed: boolean; expiresAt: string | null; type: string | null; isExpired: boolean; maintenanceOrganization: string | null } const status = ref(null) const code = ref('') +const maintenanceOrganization = ref('') +const years = ref(1) +const isAnnual = ref(true) const loading = ref(false) async function load() { const { data } = await http.get('/licenses/status') @@ -24,6 +27,17 @@ async function activate() { ElMessage.success('授权激活成功。') } catch (error) { ElMessage.error(apiErrorMessage(error)) } finally { loading.value = false } } +async function onlineActivate() { + loading.value = true + try { + const { data } = await http.post<{ status: LicenseStatus; activationCode: string }>('/licenses/online-activate', { + maintenanceOrganization: maintenanceOrganization.value.trim(), years: years.value, isAnnual: isAnnual.value, + }) + status.value = data.status + code.value = data.activationCode + ElMessage.success('在线授权成功,激活码已显示并保存。') + } catch (error) { ElMessage.error(apiErrorMessage(error)) } finally { loading.value = false } +} onMounted(() => load().catch(error => ElMessage.error(apiErrorMessage(error)))) @@ -34,6 +48,17 @@ onMounted(() => load().catch(error => ElMessage.error(apiErrorMessage(error))))

当前授权

{{ status.isExpired ? '已过期' : '有效' }} · 到期时间:{{ new Date(status.expiresAt!).toLocaleString() }}

尚未激活有效授权

+

购买的维护机构:{{ status.maintenanceOrganization }}

+ + +

在线激活

+

填写购买时对应的维护机构,系统将向已配置的在线授权服务申请并保存激活码。

+ +
+ + +
+ 在线申请并激活

本机机器码

@@ -55,4 +80,5 @@ onMounted(() => load().catch(error => ElMessage.error(apiErrorMessage(error)))) h1, h2 { margin-top: 0; } .el-button { margin-top: 12px; } .machine-code { display: inline-block; margin-right: 14px; padding: 10px 12px; border-radius: var(--radius-control); background: #f2f5f7; font-size: 17px; letter-spacing: 1px; } +.online-options { display: flex; align-items: center; gap: 16px; margin-top: 12px; }