Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/build_ios.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/build_publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/codeQL.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 分析
Expand Down
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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. |
Expand Down Expand Up @@ -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`. |
Expand Down
68 changes: 68 additions & 0 deletions SecRandom.Core.Tests/IntegrationPublisherProofTests.cs
Original file line number Diff line number Diff line change
@@ -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<IntegrationChannel>(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<IntegrationChannel>(
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);
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -39,7 +40,10 @@ public sealed record DrawCompleted(
string PrizeListName,
string RoundId,
DateTime DrawTime,
int RequestedCount);
int RequestedCount)
{
public DrawType? DrawType { get; init; }
}

/// <summary>插件加载完成。</summary>
public sealed record PluginLoaded(string PluginId, string Name, string Version);
Expand Down
2 changes: 2 additions & 0 deletions SecRandom/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. |
Expand Down
Loading
Loading