diff --git a/.github/workflows/build_ios.yml b/.github/workflows/build_ios.yml index d0539e474..51813a8c6 100644 --- a/.github/workflows/build_ios.yml +++ b/.github/workflows/build_ios.yml @@ -25,6 +25,9 @@ on: permissions: contents: read +env: + SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }} + jobs: build_ios: name: Build_iOS diff --git a/.github/workflows/build_publish.yml b/.github/workflows/build_publish.yml index 3ee1449a7..7258930d1 100644 --- a/.github/workflows/build_publish.yml +++ b/.github/workflows/build_publish.yml @@ -14,6 +14,9 @@ on: permissions: contents: read +env: + SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }} + jobs: # Release publication is gated on metadata.yaml: clients resolve a channel to a release tag there # and reject the release manifest when its tag/channel disagree, so a stale channel entry diff --git a/.github/workflows/codeQL.yml b/.github/workflows/codeQL.yml index 40a107950..73a82f3b0 100644 --- a/.github/workflows/codeQL.yml +++ b/.github/workflows/codeQL.yml @@ -6,6 +6,9 @@ on: schedule: - cron: "0 3 * * 1" +env: + SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }} + jobs: analyze: name: CodeQL 分析 diff --git a/AGENTS.md b/AGENTS.md index eec8c4e9b..1302a4a16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ Maintenance contract: - `docs/project_rules.md` is the source of truth when a convention conflicts with this summary. --> -**Last Update:** 2026-11-01 +**Last Update:** 2026-11-21 **Last Submit:** 51f7f7fd **Last modified model:** MiMoCode @@ -75,6 +75,7 @@ Nested instruction files: | Settings navigation | `SecRandom/Views/SettingsView.axaml.cs` | Default page `settings.overview`; has back stack + restart dialog. General group now includes `settings.general.basic`, `settings.general.privacy`, `settings.general.backup`, and `settings.general.control`. | | Page registration helpers | `SecRandom.Core/Extensions/Registry/` | `AddMainPage`, `AddSettingsPage`, group, and separator helpers. | | ClassIsland notifications | `SecRandom/Services/Notification/`, `SecRandom4Ci.Interface/` | Typed v2 IPC client for the installed SecRandom4Ci ClassIsland plugin. | +| Official SDK integration | `SecRandom/Services/Integration/`, `SecRandom/Views/SettingsPages/Linkage/`, `../SecRandom-Integration-SDK/docs/integration-v1.md` | Local signed-SDK discovery, user-approved result channels, per-channel display name/delivery/linkage management, and floating-window linkage leases; verification requires the compiled ECDSA public key and a matching live IPC peer process. Unverified endpoints cannot be added manually. | | Control-plane node (集控) | `docs/client-protocol.md`, `SecRandom.Core/Services/ControlNode/`, `SecRandom/Services/ControlNode/`, `SecRandom/Views/SettingsPages/General/ControlSettingsPage.axaml(.cs)` | v4.1 集控节点:WebSocket 打 `wss://sectl.cn/control/ws`(凭据放首帧 `hello.payload`,不在 URL/请求头),三分信封 `req`/`res`/`evt`;命令是 `evt cmd` + 两帧回执 `req cmd.ack`/`req cmd.result`(`id` 回填 `command_id`),`expires_at` 为 Unix 毫秒、过期即丢且不补投;期望状态 `evt desired_state` 带单调 `revision` 与 `draw_locked`(缺失按 true),客户端只接受严格更新的 revision 并把 `applied_state_revision` 落盘;接入是双因子「地点ID + 配对码」(`POST /control/api/enroll`),之后 `POST /control/api/device/tree` 拉年级/班级、`POST /control/api/device/assign` 保存,握手成功后用 `class.select`/`class.release` 占班(占班=上课=允许抽取);本地开关 `RemoteControlEnabled`(默认关)仍是最终否决权。协议规范、命令表与错误码以 `../SECTL-auth/docs/control-center-protocol-v4.md` 为唯一事实源;v1 的 `srn_` 令牌 / `group_id` / 单码接入已断代。 | | Crash recovery | `SecRandom/Services/CrashRecovery/`, `SecRandom/Views/CrashRecoveryWindow.axaml.cs` | Fatal/dispatcher crash report prompt, guarded auto-restart, and shared desktop relaunch logic. | | Page registry state | `SecRandom.Core/Services/PagesRegistryService.cs` | Main/settings/group collections. | @@ -113,6 +114,7 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo | `CrashRecoveryRuntime` | app service helper | `SecRandom/Services/CrashRecovery/CrashRecoveryRuntime.cs` | Reads crash recovery mode, writes bounded crash reports, and builds restart process plans. | | `ISecurityService` | app service contract | `SecRandom/Services/Security/` | Owns credential verification, lockout policy, selected-factor authorization, and protected-operation gating. | | `ProtocolCommandRouter` | app service | `SecRandom/Services/Ipc/ProtocolCommandRouter.cs` | Normalizes URL/IPC routes, routes protected commands, and returns structured IPC results. | +| `IntegrationChannelService` | app service | `SecRandom/Services/Integration/IntegrationChannelService.cs` | Verifies official SDK process proofs, discovers and persists approved local notification channels, applies per-channel delivery/linkage switches, forwards committed draws, and tracks IPC linkage leases. | | `DeviceUuidStore` | app service | `SecRandom/Services/Config/DeviceUuidStore.cs` | Persists the pseudo-anonymous device UUID separately in `data/config/device-uuid.json` and migrates legacy settings values. | | `AttachedSettingsRegistryService` | registry | `SecRandom.Core/Services/AttachedSettingsRegistryService.cs` | Static collections for attached-settings controls. | | `ViewModelBase` | base VM | `SecRandom/ViewModels/ViewModelBase.cs` | Base VM exposing `MainConfig`; inherits `ObservableRecipient`. | diff --git a/SecRandom.Core.Tests/IntegrationPublisherProofTests.cs b/SecRandom.Core.Tests/IntegrationPublisherProofTests.cs new file mode 100644 index 000000000..67cf78b21 --- /dev/null +++ b/SecRandom.Core.Tests/IntegrationPublisherProofTests.cs @@ -0,0 +1,68 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using SecRandom.Services.Integration; + +namespace SecRandom.Core.Tests; + +public sealed class IntegrationPublisherProofTests +{ + [Fact] + public void VerifyProof_AcceptsOfficialSignatureAndRejectsTampering() + { + using var signer = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var unsigned = new OfficialSdkProof( + IntegrationChannelService.OfficialPackageId, + "1.0.0", + new string('a', 64), + string.Empty); + var canonical = $"secrandom.integration-sdk/v1\n{unsigned.PackageId}\n{unsigned.SdkVersion}\n{unsigned.AssemblySha256}"; + var proof = unsigned with + { + Signature = Convert.ToBase64String( + signer.SignData(Encoding.UTF8.GetBytes(canonical), HashAlgorithmName.SHA256)) + }; + var publicKey = Convert.ToBase64String(signer.ExportSubjectPublicKeyInfo()); + + Assert.True(IntegrationChannelService.VerifyProof(proof, publicKey)); + Assert.False(IntegrationChannelService.VerifyProof(proof with { SdkVersion = "9.9.9" }, publicKey)); + Assert.False(IntegrationChannelService.VerifyProof(proof with { AssemblySha256 = "not-a-hash" }, publicKey)); + Assert.False(IntegrationChannelService.VerifyProof(proof with { PackageId = "unofficial.package" }, publicKey)); + Assert.False(IntegrationChannelService.VerifyProof(proof, null)); + } + + [Fact] + public void IntegrationChannel_LegacySettings_DefaultBothCapabilitiesToEnabled() + { + const string json = """{"appId":"example.app","displayName":"Example","sdkVersion":"1.0.0","endpoint":"SecRandom_Integration_test","processId":42,"instanceId":"instance","approvedAt":"2026-11-21T00:00:00Z","lastSeen":"2026-11-21T00:00:00Z"}"""; + + var channel = JsonSerializer.Deserialize(json, IntegrationJson.Options); + + Assert.NotNull(channel); + Assert.True(channel.Enabled); + Assert.True(channel.LinkageEnabled); + Assert.Null(channel.CustomName); + Assert.Equal("Example", channel.EffectiveName); + } + + [Fact] + public void IntegrationChannel_CustomSettings_RoundTripAndKeepOfficialDisplayNameSeparate() + { + var channel = new IntegrationChannel("example.app", "Official name", "1.0.0", + "SecRandom_Integration_test", 42, "instance", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow) + { + CustomName = "Classroom display", + Enabled = false, + LinkageEnabled = false + }; + + var restored = JsonSerializer.Deserialize( + JsonSerializer.Serialize(channel, IntegrationJson.Options), IntegrationJson.Options); + + Assert.NotNull(restored); + Assert.Equal("Official name", restored.DisplayName); + Assert.Equal("Classroom display", restored.EffectiveName); + Assert.False(restored.Enabled); + Assert.False(restored.LinkageEnabled); + } +} diff --git a/SecRandom.Core/Abstraction/Services/Messaging/IPluginEventBus.cs b/SecRandom.Core/Abstraction/Services/Messaging/IPluginEventBus.cs index ea07b020a..b57ea6489 100644 --- a/SecRandom.Core/Abstraction/Services/Messaging/IPluginEventBus.cs +++ b/SecRandom.Core/Abstraction/Services/Messaging/IPluginEventBus.cs @@ -1,5 +1,6 @@ using SecRandom.Core.Abstraction.Services.Presentation; using SecRandom.Core.Abstraction.Services.Theming; +using SecRandom.Core.Enums.Configs; using SecRandom.Shared.Models.Profile; namespace SecRandom.Core.Abstraction.Services.Messaging; @@ -39,7 +40,10 @@ public sealed record DrawCompleted( string PrizeListName, string RoundId, DateTime DrawTime, - int RequestedCount); + int RequestedCount) + { + public DrawType? DrawType { get; init; } + } /// 插件加载完成。 public sealed record PluginLoaded(string PluginId, string Name, string Version); diff --git a/SecRandom/AGENTS.md b/SecRandom/AGENTS.md index 04f36e4af..a2292bb33 100644 --- a/SecRandom/AGENTS.md +++ b/SecRandom/AGENTS.md @@ -35,6 +35,7 @@ SecRandom/ │ ├── Platform/ # App-side neutral window-handle adapter for platform feature requests │ ├── Draw/ # DrawAudioService, DrawTemporaryRecordService │ ├── ImportExport/ # Desktop shell + post-import hooks over Core Archive services; diagnostics export; account cloud backup orchestration +│ ├── Integration/ # Official SDK discovery, publisher-proof verification, managed result channels, linkage leases │ ├── Linkage/ # CSES/ClassIsland sources, course state runtime, draw authorization, pre-class reset │ ├── Music/ # Managed local draw-music library and stable track selection resolution │ ├── Notification/ # ClassIsland SecRandom4Ci notification bridge @@ -85,6 +86,7 @@ SecRandom/ | Searchable settings metadata | `Services/Settings/SettingsSearchService.cs` | Reflects `Langs.SettingsPages.*` resources and registered settings pages. Current setting rows use stable `x:Name` IDs; nested targets may be resolved through the visual tree and obsolete resource entries are excluded. | | Account cloud backup | `Services/ImportExport/CloudBackupService.cs`, `Services/ImportExport/CloudAutomaticBackupService.cs`, `Services/Auth/SectlCloudStorageClient.cs`, `Views/SettingsPages/General/BackupSettingsPage.axaml(.cs)` | Desktop and mobile account cloud sync. `CloudBackupService` packages a `CloudBackup` archive, uploads verified 512 KiB parts plus a trailing manifest, lists/groups cloud backups, verifies a download before restore, deletes parts before the manifest, and purges incomplete backups; `SectlCloudStorageClient` owns the `/api/cloud/*` transport and maps service error codes. `CloudAutomaticBackupService` is the hosted service behind `BackupConfig.CloudAutoBackup*`: it uploads on the configured cadence while signed in and calls `CloudBackupService.UploadAutomaticAsync`, which is the only path allowed to free space. Every upload stamps this device's alias (`BackupConfig.CloudDeviceAlias`, default host name) into the backup id, retention trims only this device's own surplus, and only an exhausted quota still removes the account-wide oldest backup. The backup settings page shows the whole cloud tab whenever `SectlAuthService`/`CloudBackupService` resolve, on desktop and mobile, and never caches cloud state in configuration. Cloud backups carry no client-side encryption and no passphrase: the archive is uploaded as produced, so account access is the only key and any signed-in device can list and restore every backup. A package the removed encryption feature uploaded is still recognised by its `-enc` name marker and stays listed — marked 旧版加密,无法恢复 and never restorable (`CloudBackupService.CanRestore` is false) — so the user can see and delete it, but only an older build could open it. | | ClassIsland notifications | `Services/Notification/`, `../SecRandom4Ci.Interface/` | Sends draw-result DTOs to the optional ClassIsland `SecRandom4Ci` plugin through v2 IPC. | +| Official SDK integration | `Services/Integration/`, `Views/SettingsPages/Linkage/`, `../SecRandom-Integration-SDK/docs/integration-v1.md` | Discovers local SDK manifests, verifies the signed official client assembly and IPC peer PID, asks before persisting a notification channel, and lets the user rename, enable/disable result delivery, enable/disable floating-window linkage, rescan, or remove approved channels. Forwarded draws and linkage leases honor those per-channel switches, and floating windows restore when leases end. | | Profile persistence | `../SecRandom.Core/Services/Profiles/ProfileService.cs`, `../SecRandom.Core/Services/Profiles/ProfileCatalogManager.cs` | Current lists/history, active point-call list/history switching, catalog rename/delete/create, and `SaveProfile()`; list items carry hidden `RecordId` identity. | | Roster transfer | `Services/RosterTransfer/`, `Views/SettingsPages/ListManagement/` | Offline QR export pre-generates all manifest/data PNG frames in memory, then loops them. Quick QR and session-code export encrypt the `.xlsx`/`.csv` archive locally with AES-256-GCM and send only its ciphertext to SecRandom Sync; quick QR keeps the random key in the URL fragment, while session mode sends only a SHA-256 code hash. The cloud payload limit is 1 MiB and the offline QR limit is 300 KiB. List-management drawers expose file, quick-QR, offline-QR, and session-code sources; show the three-row preview only after a source has validated, and auto-validate a complete 12-character session code. The settings menu provides these four transport choices only for settings; full-data import/export remains a direct local ZIP operation. Both importers resolve `IRosterQrCameraCaptureFactory` from Host and use its one in-memory frame, permission, error, and disposal workflow. Their `RosterQrCameraPreview` is provider-neutral. On Windows, named DirectShow devices (including OBS virtual cameras) open through OpenCV; Linux derives V4L2 names and indexes, macOS derives AVFoundation names and indexes, and Android surfaces Camera2 device IDs through CameraView facing. The selector is shown only when more than one device is available; iOS keeps default-camera QR scanning and hides it. Every export-drawer close path revokes the active cloud transfer, including a close racing an in-flight upload; every import-drawer close path cancels session-code work, disposes the camera, and deletes the local copy it made for a storage file without a path. Never offer QR-image file selection or persist roster transfer frames. The CameraView Android backend does persist one full-resolution JPEG per shutter release under the app's external files directory and never deletes it, so the QR scan session reclaims those files through the head-injected `IMobileCameraCaptureStore` (`MobilePlatformServiceRoot.CameraCaptureStore`; the Android head implements it with `RosterQrCaptureFiles`, iOS keeps the no-op default because it composes every frame in memory): a session clears leftovers when it starts, after every photo fallback capture, and on disposal (the session-boundary sweeps skip captures younger than five seconds so a sweep cannot delete a file another session's backend still has to read), and the mobile startup path clears everything once in the background, isolated from the startup failure path. The photo fallback itself is capped at three attempts per session, because preview frames stay the primary frame source. Spreadsheet imports pick their range through the shared `RosterImportRegionSelector` (`Views/SettingsPages/ListManagement/`), which owns the worksheet/header-row/data-row controls and the clickable raw row preview; the drawers keep the raw grid from `MiniExcel.Query(..., useHeaderRow: false)`, rebuild column mapping + preview on every region change, and re-read the file by worksheet name because the selector never touches the file system itself. Its row numbers are raw spreadsheet rows (MiniExcel pads missing rows), so they match Excel. `GetSheetNames` is skipped for CSV, which is not a zip package and throws there. | | Voice announcements | `Services/Voice/`, `Controls/AttachedSettings/SpecificAnnouncementAttachedSettingsControl.axaml(.cs)` | App-layer TTS runtime: `ISpeechProvider` implementations enumerate/synthesize system, Edge, or OmniTTS audio; `SpeechAudioPlayer` owns SoundFlow/MiniAudio playback; `VoiceAnnouncementService` builds one batched result announcement and can pre-generate the audio cache in bulk. `OmniTtsSpeechProvider` (engine 2) aggregates OpenAI/FishAudio/MiMo/Custom providers with API-fetched or manually typed models and voices; `OmniTtsCredentialStore` keeps keys in `data/config/voice/omnitts-keys.json`; `MiMoVoiceReferenceStore` keeps authorized WAV clone references privately under `data/config/voice/`. The registered `专属语音` attached setting supplies per-student/per-prize alias, prefix, and suffix. | diff --git a/SecRandom/App.axaml.cs b/SecRandom/App.axaml.cs index a232c22a8..bb2b66b13 100644 --- a/SecRandom/App.axaml.cs +++ b/SecRandom/App.axaml.cs @@ -86,6 +86,7 @@ using SecRandom.Services.RosterTransfer; using SecRandom.Services.Ipc; using SecRandom.Services.ImportExport; +using SecRandom.Services.Integration; using SecRandom.Services.FirstRun; using SecRandom.Services.Feedback; using SecRandom.Services.Linkage; @@ -145,6 +146,8 @@ public partial class App : Application { private static FloatingWindow? _floatingWindow; private static FloatingWindow? _secondaryFloatingWindow; + private static readonly HashSet _integrationLinkageLeases = new(StringComparer.Ordinal); + private static readonly List _integrationSuppressedWindows = []; private static Window? _quickDrawWindow; private static NotificationChannelSettings? _quickDrawNotificationSettings; private static bool _positioningQuickDrawWindow; @@ -195,6 +198,31 @@ public TopLevel GetRootWindow() throw new InvalidOperationException("No active application TopLevel is available."); } + internal async Task ConfirmIntegrationChannelAsync(IntegrationChannel channel) + { + var root = _settingsWindow as TopLevel ?? _mainWindow as TopLevel ?? _floatingWindow as TopLevel; + if (root is null) + return null; + + var resources = Langs.SettingsPages.Linkage.Resources.ResourceManager; + var culture = Langs.SettingsPages.Linkage.Resources.Culture; + var content = string.Format( + System.Globalization.CultureInfo.CurrentCulture, + resources.GetString("M_IntegrationApprovalContent", culture) + ?? "Allow {0} ({1}) to receive draw results?", + channel.DisplayName, + channel.AppId); + var result = await new FAContentDialog + { + Title = resources.GetString("M_IntegrationApprovalTitle", culture) ?? "Save integration channel", + Content = content, + PrimaryButtonText = resources.GetString("C_Confirm", culture) ?? "Confirm", + CloseButtonText = resources.GetString("C_Cancel", culture) ?? "Cancel", + DefaultButton = FAContentDialogButton.Close + }.ShowAsync(root); + return result == FAContentDialogResult.Primary; + } + public event EventHandler? AppStarted; public event EventHandler? AppStopping; @@ -776,6 +804,43 @@ private static void HideFloatingWindows() window.Hide(); } + /// 由已验证的 SDK 联动租约调用:暂时隐藏当前可见的悬浮窗。 + public static void AcquireIntegrationLinkage(string leaseId) + { + Dispatcher.UIThread.Post(() => + { + if (!_integrationLinkageLeases.Add(leaseId) || _integrationLinkageLeases.Count != 1) + return; + + _integrationSuppressedWindows.Clear(); + foreach (var window in FloatingWindows()) + { + if (!window.IsVisible) + continue; + _integrationSuppressedWindows.Add(window); + window.Hide(); + } + }); + } + + /// 释放联动租约;所有租约结束后按联动开始前的状态恢复悬浮窗。 + public static void ReleaseIntegrationLinkage(string leaseId) + { + Dispatcher.UIThread.Post(() => + { + if (!_integrationLinkageLeases.Remove(leaseId) || _integrationLinkageLeases.Count != 0) + return; + + var restore = _integrationSuppressedWindows.ToArray(); + _integrationSuppressedWindows.Clear(); + foreach (var window in restore) + { + if (!window.IsVisible && window.UserWantsVisible && !window.IsHiddenByCourseLinkage) + RestoreWithoutActivating(window); + } + }); + } + /// /// 订阅悬浮窗设置(并跟踪配置重载),用于实时响应"左右两侧同时显示"的开关。 /// @@ -1812,6 +1877,11 @@ private void BuildHost(IPlatformServiceRoot platform) // 插件扩展点(第二批):事件总线 / UI 线程 / 私有存储 / 名单查询 / 忙碌指示 / // 抽签流水线 / 主题色板 / 通知与对话框 / 窗口 / 弹层 / 本地化 / 能力与权限 / 诊断 services.AddSingleton(); + if (!isMobile) + { + services.AddSingleton(); + services.AddHostedService(provider => provider.GetRequiredService()); + } services.AddSingleton(); services.AddSingleton(_ => new PluginStorageFactory(PluginManager.PluginConfigsDirectory)); diff --git a/SecRandom/Langs/SettingsPages/Linkage/Resources.en-US.resx b/SecRandom/Langs/SettingsPages/Linkage/Resources.en-US.resx index 8355b66ea..0c090c20b 100644 --- a/SecRandom/Langs/SettingsPages/Linkage/Resources.en-US.resx +++ b/SecRandom/Langs/SettingsPages/Linkage/Resources.en-US.resx @@ -157,4 +157,27 @@ ClassIsland has not loaded today's timetable ClassIsland returned an unsupported current state: {0} Unable to read the ClassIsland class state + SDK notification channels + Manage approved SDK channels, result delivery, and floating-window linkage + Scan now + Remove + Rename + Save notification channel + Official SecRandom Integration SDK application “{0}” ({1}) was found. Saving it allows result delivery and lets it request floating-window hiding when linkage is enabled + No saved SDK notification channels + Online + Offline + Result delivery + Window linkage + Allow draw result delivery + Draw result delivery paused + Allow the SDK to hide the floating window + Floating-window linkage disabled + Notification channels scanned + Rename notification channel + Leave empty to use the official name + Notification channel renamed + Remove notification channel + SecRandom will stop sending draw results to “{0}” + Notification channel removed diff --git a/SecRandom/Langs/SettingsPages/Linkage/Resources.ja-JP.resx b/SecRandom/Langs/SettingsPages/Linkage/Resources.ja-JP.resx index e42079a3f..4fc52152a 100644 --- a/SecRandom/Langs/SettingsPages/Linkage/Resources.ja-JP.resx +++ b/SecRandom/Langs/SettingsPages/Linkage/Resources.ja-JP.resx @@ -157,4 +157,27 @@ ClassIsland が当日の時間割を読み込んでいません ClassIsland から未対応の現在状態が返されました: {0} ClassIsland の授業状態を読み取れません + SDK 通知チャネル + 承認済み SDK チャネル、結果送信、フローティングウィンドウ連携を管理します + 今すぐスキャン + 削除 + 名前を変更 + 通知チャネルを保存 + 公式 SecRandom Integration SDK アプリ「{0}」({1})が見つかりました。保存すると結果を受信でき、連携が有効な場合はフローティングウィンドウの非表示を要求できます + 保存済みの SDK 通知チャネルはありません + オンライン + オフライン + 結果送信 + ウィンドウ連携 + 抽選結果の送信を許可 + 抽選結果の送信を停止 + SDK によるフローティングウィンドウの非表示を許可 + ウィンドウ連携は無効です + 通知チャネルをスキャンしました + 通知チャネル名を変更 + 空欄の場合は公式名を使用します + 通知チャネル名を変更しました + 通知チャネルを削除 + 「{0}」への抽選結果の送信を停止します + 通知チャネルを削除しました diff --git a/SecRandom/Langs/SettingsPages/Linkage/Resources.resx b/SecRandom/Langs/SettingsPages/Linkage/Resources.resx index 13f1595f3..654cd4849 100644 --- a/SecRandom/Langs/SettingsPages/Linkage/Resources.resx +++ b/SecRandom/Langs/SettingsPages/Linkage/Resources.resx @@ -172,4 +172,27 @@ ClassIsland 尚未加载当天课程表 ClassIsland 返回了未支持的当前状态:{0} 无法读取 ClassIsland 的课程状态 + SDK 通知渠道 + 管理已批准的 SDK 渠道、结果发送和浮窗联动 + 立即扫描 + 删除 + 重命名 + 保存通知渠道 + 发现官方 SecRandom 集成 SDK 应用“{0}”({1})。保存后可以接收抽取结果,并可按下方设置请求隐藏本体浮窗 + 暂无已保存的 SDK 通知渠道 + 在线 + 离线 + 结果发送 + 浮窗联动 + 允许发送抽取结果 + 已暂停结果发送 + 允许 SDK 隐藏本体浮窗 + 已停用浮窗联动 + 已扫描通知渠道 + 重命名通知渠道 + 留空则使用官方名称 + 通知渠道已重命名 + 删除通知渠道 + 删除“{0}”后,本体不再向它发送抽取结果 + 通知渠道已删除 diff --git a/SecRandom/SecRandom.csproj b/SecRandom/SecRandom.csproj index b95129f73..0de9d08f2 100644 --- a/SecRandom/SecRandom.csproj +++ b/SecRandom/SecRandom.csproj @@ -6,6 +6,7 @@ true true True + $(SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64) $(NoWarn);AVLN3001 @@ -569,4 +570,17 @@ + + + + <_IntegrationTrustMetadataPath>$(IntermediateOutputPath)IntegrationTrustMetadata.g.cs + + + + + + diff --git a/SecRandom/Services/Draw/SharedDrawServices.cs b/SecRandom/Services/Draw/SharedDrawServices.cs index 95f47333c..270e3d1a5 100644 --- a/SecRandom/Services/Draw/SharedDrawServices.cs +++ b/SecRandom/Services/Draw/SharedDrawServices.cs @@ -176,7 +176,10 @@ public void SwitchList(string name) string.Empty, drawRoundId, DateTime.Now, - count)); + count) + { + DrawType = configHandler.Data.EffectiveRollCallSettings.DrawType + }); return new RollCallDrawResult(outcome.Winners, outcome.Proof.ProofId, drawRoundId, outcome.FrozenWeights, edit?.Note, edit?.SuppressPresentation ?? false); } @@ -247,7 +250,10 @@ public RollCallNumberSnapshot GetNumberSnapshot(int rangeStart, int rangeEnd) string.Empty, drawRoundId, DateTime.Now, - count)); + count) + { + DrawType = configHandler.Data.EffectiveRollCallSettings.DrawType + }); return new RollCallNumberDrawResult(outcome.Winners, outcome.Proof.ProofId, drawRoundId, outcome.FrozenWeights); } diff --git a/SecRandom/Services/Integration/IntegrationChannelService.cs b/SecRandom/Services/Integration/IntegrationChannelService.cs new file mode 100644 index 000000000..8fc360072 --- /dev/null +++ b/SecRandom/Services/Integration/IntegrationChannelService.cs @@ -0,0 +1,718 @@ +using System.Diagnostics; +using System.IO.Pipes; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Avalonia.Threading; +using FluentAvalonia.UI.Controls; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using SecRandom.Core.Abstraction.Services.Messaging; +using SecRandom.Core.Enums.Configs; +using SecRandom.Shared.Models.Profile; +using SecRandom.Core.Abstraction.Services.Presentation; +using SecRandom.Shared; +using SecRandom.Services.Draw; + +namespace SecRandom.Services.Integration; + +/// +/// Official SDK discovery and result delivery. The service owns only local IPC and persistence; +/// UI approval is raised as an event so the settings shell can show the confirmation dialog. +/// +public sealed class IntegrationChannelService( + IPluginEventBus eventBus, + ILogger logger) : IHostedService, IDisposable +{ + internal const string OfficialPackageId = "SecRandom.Integration.Client"; + private const string AppId = "secrandom.app"; + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + private readonly object _gate = new(); + private readonly object _saveGate = new(); + private readonly string _directory = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SecRandom", "integrations"); + private readonly string _channelsPath = Utils.GetFilePath("config", "integration-channels.json"); + private readonly string _instanceId = Guid.NewGuid().ToString("N"); + private readonly Dictionary _channels = new(StringComparer.Ordinal); + private readonly HashSet _seenInstances = new(StringComparer.Ordinal); + private readonly HashSet _offlineChannels = new(StringComparer.Ordinal); + private readonly Dictionary _leases = new(StringComparer.Ordinal); + private readonly CancellationTokenSource _cts = new(); + private IDisposable? _drawSubscription; + private Task? _serverTask; + private Task? _discoveryTask; + private string? _hostManifestPath; + private int _discoveryRunning; + + public string HostPipeName { get; } = "SecRandom_Integration_Host_" + Guid.NewGuid().ToString("N"); + public event Action? Changed; + public event Action? ChannelDiscovered; + public IReadOnlyList Channels + { + get { lock (_gate) return _channels.Values.OrderBy(x => x.EffectiveName, StringComparer.CurrentCultureIgnoreCase).ToArray(); } + } + + public Task StartAsync(CancellationToken cancellationToken) + { + Directory.CreateDirectory(_directory); + LoadChannels(); + WriteHostManifest(); + _drawSubscription = eventBus.Subscribe(OnDrawCompleted); + _serverTask = Task.Run(() => HostPipeLoopAsync(_cts.Token), CancellationToken.None); + _discoveryTask = Task.Run(() => DiscoveryLoopAsync(_cts.Token), CancellationToken.None); + return Task.CompletedTask; + } + + public async Task StopAsync(CancellationToken cancellationToken) + { + _cts.Cancel(); + if (_serverTask is not null) + { + try { await _serverTask.WaitAsync(TimeSpan.FromSeconds(3), cancellationToken).ConfigureAwait(false); } + catch (Exception exception) when (exception is OperationCanceledException or TimeoutException) { } + } + if (_discoveryTask is not null) + { + try { await _discoveryTask.WaitAsync(TimeSpan.FromSeconds(3), cancellationToken).ConfigureAwait(false); } + catch (Exception exception) when (exception is OperationCanceledException or TimeoutException) { } + } + _drawSubscription?.Dispose(); + _drawSubscription = null; + if (_hostManifestPath is not null) + { + try { File.Delete(_hostManifestPath); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + ReleaseAllLeases(); + } + + public void Dispose() => _cts.Dispose(); + + public void DiscoverNow() + { + if (Interlocked.Exchange(ref _discoveryRunning, 1) != 0) + return; + + try + { + var changed = false; + var now = DateTimeOffset.UtcNow; + foreach (var manifest in ReadManifests()) + { + if (!VerifyOfficialManifest(manifest)) + continue; + + lock (_gate) + { + if (_channels.TryGetValue(manifest.AppId, out var approved)) + { + changed |= approved.ProcessId != manifest.ProcessId + || !string.Equals(approved.InstanceId, manifest.InstanceId, StringComparison.Ordinal) + || !string.Equals(approved.Endpoint, manifest.Endpoint, StringComparison.Ordinal) + || !string.Equals(approved.DisplayName, manifest.DisplayName, StringComparison.Ordinal) + || !string.Equals(approved.SdkVersion, manifest.SdkVersion, StringComparison.Ordinal); + changed |= _offlineChannels.Remove(manifest.AppId); + _channels[manifest.AppId] = approved with + { + DisplayName = manifest.DisplayName, + Endpoint = manifest.Endpoint, + ProcessId = manifest.ProcessId, + InstanceId = manifest.InstanceId, + SdkVersion = manifest.SdkVersion, + LastSeen = now + }; + continue; + } + + if (!_seenInstances.Add(manifest.AppId + "\n" + manifest.InstanceId)) + continue; + } + + var channel = new IntegrationChannel(manifest.AppId, manifest.DisplayName, manifest.SdkVersion, + manifest.Endpoint, manifest.ProcessId, manifest.InstanceId, now, now); + ChannelDiscovered?.Invoke(channel); + QueueApprovalPrompt(channel); + } + + lock (_gate) + { + foreach (var channel in _channels.Values) + { + if (now - channel.LastSeen > TimeSpan.FromSeconds(8)) + changed |= _offlineChannels.Add(channel.AppId); + } + } + + if (changed) + { + SaveChannels(); + Changed?.Invoke(); + } + } + finally + { + Volatile.Write(ref _discoveryRunning, 0); + } + } + + public void Approve(IntegrationChannel channel) + { + lock (_gate) + _channels[channel.AppId] = channel; + SaveChannels(); + Changed?.Invoke(); + } + + public bool Remove(string appId) + { + bool removed; + lock (_gate) + { + removed = _channels.Remove(appId); + _offlineChannels.Remove(appId); + } + if (removed) + { + ReleaseLeasesFor(appId); + SaveChannels(); + Changed?.Invoke(); + } + return removed; + } + + public bool SetEnabled(string appId, bool enabled) + { + var changed = false; + lock (_gate) + { + if (!_channels.TryGetValue(appId, out var channel)) + return false; + if (channel.Enabled != enabled) + { + _channels[appId] = channel with { Enabled = enabled }; + changed = true; + } + } + + if (changed) + { + SaveChannels(); + Changed?.Invoke(); + } + return true; + } + + public bool SetLinkageEnabled(string appId, bool enabled) + { + var changed = false; + lock (_gate) + { + if (!_channels.TryGetValue(appId, out var channel)) + return false; + if (channel.LinkageEnabled != enabled) + { + _channels[appId] = channel with { LinkageEnabled = enabled }; + changed = true; + } + } + + if (!enabled) + ReleaseLeasesFor(appId); + if (changed) + { + SaveChannels(); + Changed?.Invoke(); + } + return true; + } + + public bool SetCustomName(string appId, string? customName) + { + var changed = false; + lock (_gate) + { + if (!_channels.TryGetValue(appId, out var channel)) + return false; + + var normalized = NormalizeCustomName(customName); + if (!string.Equals(channel.CustomName, normalized, StringComparison.Ordinal)) + { + _channels[appId] = channel with { CustomName = normalized }; + changed = true; + } + } + + if (changed) + { + SaveChannels(); + Changed?.Invoke(); + } + return true; + } + + public bool IsOnline(IntegrationChannel channel) => + IsProcessAlive(channel.ProcessId) + && DateTimeOffset.UtcNow - channel.LastSeen <= TimeSpan.FromSeconds(8); + + private async Task DiscoveryLoopAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + DiscoverNow(); + RemoveDeadLeases(); + await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { break; } + catch (Exception exception) { logger.LogDebug(exception, "Integration discovery failed."); } + } + } + + private async Task HostPipeLoopAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + await using var server = new NamedPipeServerStream(HostPipeName, PipeDirection.InOut, 8, + PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + try + { + await server.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false); + await HandleHostRequestAsync(server, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { break; } + catch (IOException) { } + catch (Exception exception) { logger.LogDebug(exception, "Integration host pipe failed."); } + } + } + + private async Task HandleHostRequestAsync(NamedPipeServerStream server, CancellationToken cancellationToken) + { + using var reader = new StreamReader(server, StrictUtf8, false, 4096, true); + await using var writer = new StreamWriter(server, StrictUtf8, 4096, true); + var line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false); + if (line is null || Encoding.UTF8.GetByteCount(line) > IntegrationProtocol.MaxFrameBytes) + { + await WriteResponseAsync(writer, null, null, new IntegrationError("invalid_request", "Invalid frame.")).ConfigureAwait(false); + return; + } + + IntegrationFrame? request; + try { request = JsonSerializer.Deserialize(line, IntegrationJson.Options); } + catch (JsonException) { request = null; } + if (request is null || request.Version != IntegrationProtocol.Version || request.Type != "rpc") + { + await WriteResponseAsync(writer, request?.Id, null, new IntegrationError("invalid_request", "Invalid request.")).ConfigureAwait(false); + return; + } + + if (request.Method is "system.ping") + { + await WriteResponseAsync(writer, request.Id, new { pong = true }, null).ConfigureAwait(false); + return; + } + + if (request.Method is "linkage.acquire" or "linkage.release" + && request.Params is { ValueKind: JsonValueKind.Object } parameters) + { + var linkage = parameters.Deserialize(IntegrationJson.Options); + if (linkage is null || string.IsNullOrWhiteSpace(linkage.LeaseId)) + { + await WriteResponseAsync(writer, request.Id, null, + new IntegrationError("invalid_request", "A linkage lease is required.")).ConfigureAwait(false); + return; + } + + if (request.Method == "linkage.acquire") + { + if (!IsPipeClientProcess(server, linkage.ProcessId)) + { + await WriteResponseAsync(writer, request.Id, null, + new IntegrationError("authorization_denied", "The SDK channel is not approved.")).ConfigureAwait(false); + return; + } + + bool approved; + lock (_gate) + { + approved = IsApprovedRequester(linkage); + if (approved) + { + _leases[linkage.LeaseId] = linkage; + // Queue acquisition under the same gate as removal/revocation so their + // UI dispatcher callbacks preserve the lease's state transition order. + App.AcquireIntegrationLinkage(linkage.LeaseId); + } + } + if (!approved) + { + await WriteResponseAsync(writer, request.Id, null, + new IntegrationError("authorization_denied", "The SDK channel is not approved.")).ConfigureAwait(false); + return; + } + } + else + { + if (!IsOwnedLease(linkage) || !IsPipeClientProcess(server, linkage.ProcessId)) + { + await WriteResponseAsync(writer, request.Id, null, + new IntegrationError("authorization_denied", "The linkage lease does not belong to this process.")).ConfigureAwait(false); + return; + } + lock (_gate) _leases.Remove(linkage.LeaseId); + App.ReleaseIntegrationLinkage(linkage.LeaseId); + } + + await WriteResponseAsync(writer, request.Id, new { accepted = true }, null).ConfigureAwait(false); + return; + } + + await WriteResponseAsync(writer, request.Id, null, + new IntegrationError("unsupported_method", "The method is not supported.")).ConfigureAwait(false); + } + + private void OnDrawCompleted(HostEvents.DrawCompleted completed) => _ = ForwardDrawCompletedAsync(completed); + + private async Task ForwardDrawCompletedAsync(HostEvents.DrawCompleted completed) + { + if (string.Equals(completed.ListName, RollCallDrawService.NumberListName, StringComparison.Ordinal) + || string.Equals(completed.PrizeListName, LotteryDrawService.NumberPrizePoolName, StringComparison.Ordinal)) + return; + + IntegrationChannel[] channels; + lock (_gate) channels = _channels.Values.Where(x => x.Enabled).ToArray(); + var members = completed.Channel == DrawPresentationChannel.Lottery + ? completed.Prizes.Select(prize => new { id = prize.RecordId.ToString("N"), name = prize.Name, + gender = (string?)null, group = (string?)null, enabled = prize.Exists, weight = prize.Weight }).ToArray() + : completed.Students.Select(student => new { id = student.RecordId.ToString("N"), name = student.Name, + gender = (string?)student.Gender, group = (string?)student.Group, enabled = student.Exists, weight = 1d }).ToArray(); + var result = new + { + round_id = completed.RoundId, + roster_id = completed.Channel == DrawPresentationChannel.Lottery ? completed.PrizeListName : completed.ListName, + mode = completed.DrawType switch + { + DrawType.Random => 0, + DrawType.Fair => 1, + _ => (int?)null + }, + members, + at = new DateTimeOffset(completed.DrawTime).ToUniversalTime(), + idempotency_key = completed.RoundId, + source_app_id = AppId, + roster_kind = completed.Channel == DrawPresentationChannel.Lottery ? 1 : 0 + }; + + foreach (var channel in channels) + { + try + { + var manifest = ReadManifests().FirstOrDefault(x => + string.Equals(x.AppId, channel.AppId, StringComparison.Ordinal) + && x.ProcessId == channel.ProcessId + && string.Equals(x.InstanceId, channel.InstanceId, StringComparison.Ordinal) + && string.Equals(x.Endpoint, channel.Endpoint, StringComparison.Ordinal)); + if (manifest is null || !VerifyOfficialManifest(manifest)) + continue; + await SendResultAsync(manifest.Endpoint, manifest.ProcessId, result).ConfigureAwait(false); + } + catch (Exception exception) { logger.LogDebug(exception, "Integration result delivery failed for {AppId}.", channel.AppId); } + } + } + + private static async Task SendResultAsync(string pipeName, int expectedProcessId, object result) + { + using var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + await pipe.ConnectAsync(2000).ConfigureAwait(false); + if (!TryGetPipePeerProcessId(pipe.SafePipeHandle.DangerousGetHandle(), localIsServer: false, + out var serverProcessId) + || serverProcessId != (uint)expectedProcessId) + throw new IOException("The SDK notification pipe belongs to a different process."); + using var writer = new StreamWriter(pipe, StrictUtf8, 4096, true); + using var reader = new StreamReader(pipe, StrictUtf8, false, 4096, true); + var request = new IntegrationFrame(IntegrationProtocol.Version, "rpc", Guid.NewGuid().ToString("N"), + "notification.result", JsonSerializer.SerializeToElement(result, IntegrationJson.Options)); + await writer.WriteLineAsync(JsonSerializer.Serialize(request, IntegrationJson.Options)).ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + _ = await reader.ReadLineAsync().ConfigureAwait(false); + } + + private void RemoveDeadLeases() + { + string[] dead; + lock (_gate) dead = _leases.Values.Where(x => !IsProcessAlive(x.ProcessId)).Select(x => x.LeaseId).ToArray(); + foreach (var leaseId in dead) + { + lock (_gate) _leases.Remove(leaseId); + App.ReleaseIntegrationLinkage(leaseId); + } + } + + private void ReleaseAllLeases() + { + string[] leases; + lock (_gate) { leases = _leases.Keys.ToArray(); _leases.Clear(); } + foreach (var lease in leases) App.ReleaseIntegrationLinkage(lease); + } + + private IReadOnlyList ReadManifests() + { + if (!Directory.Exists(_directory)) return []; + var manifests = new List(); + foreach (var file in Directory.EnumerateFiles(_directory, "*.json")) + { + if (string.Equals(Path.GetFileName(file), "host.json", StringComparison.OrdinalIgnoreCase)) continue; + try + { + var manifest = JsonSerializer.Deserialize(File.ReadAllText(file), IntegrationJson.Options); + if (manifest is not null) manifests.Add(manifest); + } + catch (Exception exception) when (exception is IOException or JsonException) { } + } + return manifests; + } + + private bool VerifyOfficialManifest(IntegrationManifest manifest) + { + if (manifest.Protocol != IntegrationProtocol.Name || !IsValidEndpoint(manifest.Endpoint) + || !IsProcessAlive(manifest.ProcessId) || string.IsNullOrWhiteSpace(manifest.PublisherProof)) + return false; + try + { + var proof = JsonSerializer.Deserialize(manifest.PublisherProof, IntegrationJson.Options); + if (proof is null || proof.PackageId != OfficialPackageId || proof.SdkVersion != manifest.SdkVersion) + return false; + var key = typeof(IntegrationChannelService).Assembly.GetCustomAttributes() + .FirstOrDefault(x => x.Key == "SecRandomIntegrationPublicKey")?.Value; + if (!VerifyProof(proof, key)) return false; + using var process = Process.GetProcessById(manifest.ProcessId); + foreach (ProcessModule module in process.Modules) + { + try + { + if (Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(module.FileName))).Equals( + proof.AssemblySha256, StringComparison.OrdinalIgnoreCase)) return true; + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } + catch (Exception exception) when (exception is JsonException or FormatException or CryptographicException + or InvalidOperationException or NotSupportedException + or System.ComponentModel.Win32Exception) + { + logger.LogDebug(exception, "SDK manifest verification failed for {AppId}.", manifest.AppId); + } + return false; + } + + internal static bool VerifyProof(OfficialSdkProof proof, string? publicKey) + { + if (proof.PackageId != OfficialPackageId || string.IsNullOrWhiteSpace(proof.SdkVersion) + || string.IsNullOrWhiteSpace(proof.AssemblySha256) || string.IsNullOrWhiteSpace(proof.Signature) + || string.IsNullOrWhiteSpace(publicKey) || proof.AssemblySha256.Length != 64 || + proof.AssemblySha256.Any(x => !Uri.IsHexDigit(x))) return false; + var canonical = $"secrandom.integration-sdk/v1\n{proof.PackageId}\n{proof.SdkVersion}\n{proof.AssemblySha256.ToLowerInvariant()}"; + try + { + using var ecdsa = ECDsa.Create(); + ecdsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(publicKey), out _); + return ecdsa.VerifyData(Encoding.UTF8.GetBytes(canonical), Convert.FromBase64String(proof.Signature), HashAlgorithmName.SHA256); + } + catch (FormatException) { return false; } + catch (CryptographicException) { return false; } + } + + private void LoadChannels() + { + try + { + var loaded = File.Exists(_channelsPath) + ? JsonSerializer.Deserialize>(File.ReadAllText(_channelsPath), IntegrationJson.Options) + : null; + if (loaded is null) return; + lock (_gate) foreach (var channel in loaded.Where(x => !string.IsNullOrWhiteSpace(x.AppId))) _channels[channel.AppId] = channel; + } + catch (Exception exception) when (exception is IOException or JsonException) { logger.LogWarning(exception, "Unable to load integration channels."); } + } + + private void SaveChannels() + { + lock (_saveGate) + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(_channelsPath)!); + IntegrationChannel[] channels; + lock (_gate) channels = _channels.Values.ToArray(); + var temporary = _channelsPath + ".tmp"; + File.WriteAllText(temporary, JsonSerializer.Serialize(channels, IntegrationJson.Options)); + File.Move(temporary, _channelsPath, true); + } + catch (IOException exception) { logger.LogWarning(exception, "Unable to save integration channels."); } + } + } + + private void WriteHostManifest() + { + var manifest = new { app_id = AppId, endpoint = HostPipeName, pid = Environment.ProcessId, + instance_id = _instanceId, protocol = IntegrationProtocol.Name }; + _hostManifestPath = Path.Combine(_directory, "host.json"); + var temporary = _hostManifestPath + ".tmp"; + File.WriteAllText(temporary, JsonSerializer.Serialize(manifest, IntegrationJson.Options)); + File.Move(temporary, _hostManifestPath, true); + } + + private static bool IsProcessAlive(int processId) + { + try { return Process.GetProcessById(processId) is { HasExited: false }; } + catch (ArgumentException) { return false; } + catch (InvalidOperationException) { return false; } + } + + private bool IsApprovedRequester(LinkageLeaseRequest request) + { + lock (_gate) + return _channels.TryGetValue(request.AppId, out var channel) + && channel.ProcessId == request.ProcessId + && string.Equals(channel.InstanceId, request.InstanceId, StringComparison.Ordinal) + && channel.LinkageEnabled + && DateTimeOffset.UtcNow - channel.LastSeen < TimeSpan.FromSeconds(8) + && IsProcessAlive(request.ProcessId); + } + + private bool IsOwnedLease(LinkageLeaseRequest request) + { + lock (_gate) + return _leases.TryGetValue(request.LeaseId, out var lease) + && lease.ProcessId == request.ProcessId + && string.Equals(lease.AppId, request.AppId, StringComparison.Ordinal) + && string.Equals(lease.InstanceId, request.InstanceId, StringComparison.Ordinal); + } + + private void ReleaseLeasesFor(string appId) + { + string[] leases; + lock (_gate) + { + leases = _leases.Values.Where(x => string.Equals(x.AppId, appId, StringComparison.Ordinal)) + .Select(x => x.LeaseId) + .ToArray(); + foreach (var lease in leases) + _leases.Remove(lease); + } + + foreach (var lease in leases) + App.ReleaseIntegrationLinkage(lease); + } + + private static string? NormalizeCustomName(string? customName) + { + var value = customName?.Trim(); + if (string.IsNullOrEmpty(value)) + return null; + return value.Length <= 64 ? value : value[..64]; + } + + private static bool IsPipeClientProcess(NamedPipeServerStream server, int expectedProcessId) + { + return TryGetPipePeerProcessId(server.SafePipeHandle.DangerousGetHandle(), localIsServer: true, + out var processId) + && processId == (uint)expectedProcessId; + } + + private static bool TryGetPipePeerProcessId(IntPtr pipeHandle, bool localIsServer, out uint processId) + { + if (OperatingSystem.IsWindows()) + return localIsServer + ? GetNamedPipeClientProcessId(pipeHandle, out processId) + : GetNamedPipeServerProcessId(pipeHandle, out processId); + + if (OperatingSystem.IsLinux()) + { + var length = (uint)System.Runtime.InteropServices.Marshal.SizeOf(); + UnixPeerCredentials credentials; + if (GetSocketOption(pipeHandle.ToInt32(), 1, 17, out credentials, ref length) == 0 + && credentials.ProcessId > 0) + { + processId = (uint)credentials.ProcessId; + return true; + } + } + else if (OperatingSystem.IsMacOS()) + { + var length = (uint)sizeof(int); + int peerProcessId; + if (GetSocketOption(pipeHandle.ToInt32(), 0, 2, out peerProcessId, ref length) == 0 + && peerProcessId > 0) + { + processId = (uint)peerProcessId; + return true; + } + } + + processId = 0; + return false; + } + + [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + private struct UnixPeerCredentials + { + public int ProcessId; + public uint UserId; + public uint GroupId; + } + + private void QueueApprovalPrompt(IntegrationChannel channel) + { + Dispatcher.UIThread.Post(() => _ = PromptForChannelAsync(channel)); + } + + private async Task PromptForChannelAsync(IntegrationChannel channel) + { + try + { + var accepted = await Dispatcher.UIThread.InvokeAsync( + () => App.Current.ConfirmIntegrationChannelAsync(channel)); + if (accepted is true) + Approve(channel); + else if (accepted is null) + lock (_gate) _seenInstances.Remove(channel.AppId + "\n" + channel.InstanceId); + } + catch (Exception exception) + { + lock (_gate) _seenInstances.Remove(channel.AppId + "\n" + channel.InstanceId); + logger.LogDebug(exception, "Integration channel confirmation was unavailable."); + } + } + + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] + private static extern bool GetNamedPipeClientProcessId(IntPtr pipe, out uint clientProcessId); + + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] + [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(IntPtr pipe, out uint serverProcessId); + + [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "getsockopt", SetLastError = true)] + private static extern int GetSocketOption(int socket, int level, int option, + out UnixPeerCredentials value, ref uint optionLength); + + [System.Runtime.InteropServices.DllImport("libc", EntryPoint = "getsockopt", SetLastError = true)] + private static extern int GetSocketOption(int socket, int level, int option, + out int value, ref uint optionLength); + + private static bool IsValidEndpoint(string endpoint) => endpoint.StartsWith("SecRandom_Integration_", StringComparison.Ordinal) + && endpoint.Length <= 96 + && endpoint.All(character => char.IsAsciiLetterOrDigit(character) || character == '_'); + + private static async Task WriteResponseAsync(StreamWriter writer, string? id, object? result, IntegrationError? error) + { + var response = new IntegrationFrame(IntegrationProtocol.Version, "rpc", id, null, null, result, error); + await writer.WriteLineAsync(JsonSerializer.Serialize(response, IntegrationJson.Options)).ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + } +} diff --git a/SecRandom/Services/Integration/IntegrationContracts.cs b/SecRandom/Services/Integration/IntegrationContracts.cs new file mode 100644 index 000000000..87875a984 --- /dev/null +++ b/SecRandom/Services/Integration/IntegrationContracts.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace SecRandom.Services.Integration; + +internal static class IntegrationProtocol +{ + public const int Version = 1; + public const int MaxFrameBytes = 256 * 1024; + public const string Name = "secrandom.integration.v1"; +} + +internal sealed record IntegrationManifest( + [property: JsonPropertyName("app_id")] string AppId, + [property: JsonPropertyName("display_name")] string DisplayName, + [property: JsonPropertyName("sdk_version")] string SdkVersion, + [property: JsonPropertyName("protocol")] string Protocol, + [property: JsonPropertyName("endpoint")] string Endpoint, + [property: JsonPropertyName("pid")] int ProcessId, + [property: JsonPropertyName("instance_id")] string InstanceId, + [property: JsonPropertyName("capabilities")] IReadOnlyList Capabilities, + [property: JsonPropertyName("published_at")] DateTimeOffset PublishedAt, + [property: JsonPropertyName("publisher_proof")] string? PublisherProof); + +internal sealed record OfficialSdkProof( + [property: JsonPropertyName("package_id")] string PackageId, + [property: JsonPropertyName("sdk_version")] string SdkVersion, + [property: JsonPropertyName("assembly_sha256")] string AssemblySha256, + [property: JsonPropertyName("signature")] string Signature); + +internal sealed record IntegrationFrame( + [property: JsonPropertyName("version")] int Version, + [property: JsonPropertyName("type")] string Type, + [property: JsonPropertyName("id")] string? Id, + [property: JsonPropertyName("method")] string? Method, + [property: JsonPropertyName("params")] JsonElement? Params, + [property: JsonPropertyName("result")] object? Result = null, + [property: JsonPropertyName("error")] IntegrationError? Error = null); + +internal sealed record IntegrationError( + [property: JsonPropertyName("code")] string Code, + [property: JsonPropertyName("message")] string Message, + [property: JsonPropertyName("retryable")] bool Retryable = false); + +internal sealed record LinkageLeaseRequest( + [property: JsonPropertyName("app_id")] string AppId, + [property: JsonPropertyName("process_id")] int ProcessId, + [property: JsonPropertyName("instance_id")] string InstanceId, + [property: JsonPropertyName("lease_id")] string LeaseId); + +internal static class IntegrationJson +{ + public static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; +} + +public sealed record IntegrationChannel( + string AppId, + string DisplayName, + string SdkVersion, + string Endpoint, + int ProcessId, + string InstanceId, + DateTimeOffset ApprovedAt, + DateTimeOffset LastSeen) +{ + public string? CustomName { get; init; } + public bool Enabled { get; init; } = true; + public bool LinkageEnabled { get; init; } = true; + + /// 用户可改的显示名只影响设置页,不参与身份验证或 IPC 协议。 + public string EffectiveName => string.IsNullOrWhiteSpace(CustomName) ? DisplayName : CustomName; +} + diff --git a/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs b/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs index 1ebd88f66..3c2ebf95b 100644 --- a/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs +++ b/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs @@ -14,6 +14,8 @@ using Microsoft.Extensions.Logging; using SecRandom.Core; using SecRandom.Core.Abstraction.Services; +using SecRandom.Core.Abstraction.Services.Messaging; +using SecRandom.Core.Abstraction.Services.Presentation; using SecRandom.Core.Enums; using SecRandom.Core.Enums.Configs; using SecRandom.Core.Models.AttachedSettings; @@ -51,6 +53,7 @@ public sealed partial class QuickDrawPageViewModel : ViewModelBase, IDisposable private readonly LinkageDrawCoordinator _linkageDrawCoordinator; private readonly VerificationDrawCoordinator _verificationDrawCoordinator; private readonly IHistoryGroupCatalog _historyGroupCatalog; + private readonly IPluginEventBus? _eventBus; private readonly IVoiceAnnouncementService? _voiceAnnouncementService; private readonly NotificationService? _notificationService; private bool _isDrawCommandRunning; @@ -81,7 +84,8 @@ public QuickDrawPageViewModel( VerificationDrawCoordinator verificationDrawCoordinator, IHistoryGroupCatalog historyGroupCatalog, IVoiceAnnouncementService? voiceAnnouncementService = null, - NotificationService? notificationService = null) + NotificationService? notificationService = null, + IPluginEventBus? eventBus = null) : base(configHandler) { _configHandler = configHandler; @@ -95,6 +99,7 @@ public QuickDrawPageViewModel( _linkageDrawCoordinator = linkageDrawCoordinator; _verificationDrawCoordinator = verificationDrawCoordinator; _historyGroupCatalog = historyGroupCatalog; + _eventBus = eventBus; _voiceAnnouncementService = voiceAnnouncementService; _notificationService = notificationService; ResultItems.CollectionChanged += (_, _) => OnPropertyChanged(nameof(ResultFontSize)); @@ -349,7 +354,7 @@ await _drawAudioService.StartAnimationMusicAsync( } var weights = BuildWeightSnapshot(drawn, drawOutcome.FrozenWeights); - _drawCommitService.CommitStudentDraw(new StudentDrawCommit( + var drawRoundId = _drawCommitService.CommitStudentDraw(new StudentDrawCommit( drawn, DateTime.Now, count, @@ -358,6 +363,18 @@ await _drawAudioService.StartAnimationMusicAsync( Weights: weights, CourseName: courseName, HistoryGroup: historyGroup)); + _eventBus?.Publish(new HostEvents.DrawCompleted( + DrawPresentationChannel.RollCall, + drawn, + [], + SelectedStudentListName, + string.Empty, + drawRoundId, + DateTime.Now, + count) + { + DrawType = Config.EffectiveQuickDrawSettings.DrawType + }); try { _verificationDrawCoordinator.Publish(drawOutcome); diff --git a/SecRandom/Views/SettingsPages/Linkage/LinkageSettingsPage.axaml b/SecRandom/Views/SettingsPages/Linkage/LinkageSettingsPage.axaml index 74058e570..e85765936 100644 --- a/SecRandom/Views/SettingsPages/Linkage/LinkageSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/Linkage/LinkageSettingsPage.axaml @@ -171,6 +171,56 @@ + + + + + +