feat(p01): add secure profile foundation and management UI #2
共有 23 个文件被更改,包括 2236 次插入 和 94 次删除
10
CHANGELOG.md
10
CHANGELOG.md
|
|
@ -18,9 +18,19 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
|
||||||
- Provisional desktop-v1alpha1 Rust types, TypeScript exports, ten JSON Schemas, drift checks, and two loopback-only Mock Gateway instances.
|
- Provisional desktop-v1alpha1 Rust types, TypeScript exports, ten JSON Schemas, drift checks, and two loopback-only Mock Gateway instances.
|
||||||
- Frontend, browser, Rust, integration, Windows provider, soak, and Forgejo CI test entry points.
|
- Frontend, browser, Rust, integration, Windows provider, soak, and Forgejo CI test entry points.
|
||||||
- P00 dependency review and durable Spike result records.
|
- P00 dependency review and durable Spike result records.
|
||||||
|
- Persistent SQLite application-data initialization with transactional `user_version` migration and future-version rejection.
|
||||||
|
- Strict Zod validation for the Rust bootstrap IPC payload, including the active database schema version.
|
||||||
|
- Redacting tracing output writer with structured-field, bearer-token, URL-credential, private-key, and known-secret coverage.
|
||||||
|
- P01 migration, logging, IPC validation, real Tauri startup, and production-build verification.
|
||||||
|
- SQLite schema v2 for persistent non-sensitive ConnectionProfile metadata.
|
||||||
|
- Bounded Rust-owned Profile list/create/update/delete IPC with generated UUIDs and timestamps.
|
||||||
|
- Strict frontend ConnectionProfile Schemas and a basic Profile management UI.
|
||||||
|
- Migration, five-Profile CRUD, persistent reopen, secret-field rejection, and browser fallback tests.
|
||||||
|
|
||||||
### Security
|
### Security
|
||||||
|
|
||||||
- Kept credentials and native capabilities in Rust; the React capability set remains `core:default` only.
|
- Kept credentials and native capabilities in Rust; the React capability set remains `core:default` only.
|
||||||
- Added secret redaction and repository scans; no arbitrary PowerShell, CMD, shell, input-injection, registry-write, or unrestricted filesystem API is exposed.
|
- Added secret redaction and repository scans; no arbitrary PowerShell, CMD, shell, input-injection, registry-write, or unrestricted filesystem API is exposed.
|
||||||
- Kept real UNC writes, signing keys, updater keys, and release secrets outside P00.
|
- Kept real UNC writes, signing keys, updater keys, and release secrets outside P00.
|
||||||
|
- Rejected Token, password, API Key, URL credential, query-string credential, and unknown fields at the Profile IPC boundary.
|
||||||
|
- Required explicit approval for insecure HTTP and kept slots, connections, and credential enrollment outside P01.
|
||||||
|
|
|
||||||
6
Cargo.lock
自动生成
6
Cargo.lock
自动生成
|
|
@ -105,7 +105,7 @@ checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "astrbot-desktop"
|
name = "astrbot-desktop"
|
||||||
version = "0.1.0-alpha.0"
|
version = "0.1.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"desktop-protocol",
|
"desktop-protocol",
|
||||||
"eventsource-stream",
|
"eventsource-stream",
|
||||||
|
|
@ -989,7 +989,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "desktop-protocol"
|
name = "desktop-protocol"
|
||||||
version = "0.1.0-alpha.0"
|
version = "0.1.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"schemars 1.2.1",
|
"schemars 1.2.1",
|
||||||
"serde",
|
"serde",
|
||||||
|
|
@ -2470,7 +2470,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mock-gateway"
|
name = "mock-gateway"
|
||||||
version = "0.1.0-alpha.0"
|
version = "0.1.0-alpha.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-stream",
|
"async-stream",
|
||||||
"axum",
|
"axum",
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ members = [
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0-alpha.0"
|
version = "0.1.0-alpha.1"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.97.1"
|
rust-version = "1.97.1"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,64 @@
|
||||||
|
# ADR-0004: Profile lifecycle and secret boundary
|
||||||
|
|
||||||
|
- Status: accepted
|
||||||
|
- Date: 2026-07-18
|
||||||
|
- Decision owner: project owner
|
||||||
|
|
||||||
|
## Background
|
||||||
|
|
||||||
|
The architecture document assigns Profile CRUD to stage 1, while the implementation task document groups ConnectionProfile CRUD with the stage 2 dual-connection slots. The conflict affects the SQLite schema, Tauri IPC surface, frontend state, and stage acceptance boundary.
|
||||||
|
|
||||||
|
The project owner selected option A from PD-0008:
|
||||||
|
|
||||||
|
- P01 owns basic ConnectionProfile metadata CRUD.
|
||||||
|
- P02 owns active slot assignment and all runtime connection behavior.
|
||||||
|
|
||||||
|
## Options considered
|
||||||
|
|
||||||
|
### Option A: basic metadata CRUD in P01
|
||||||
|
|
||||||
|
Create, list, update, and delete non-sensitive Profile metadata in P01. Keep companion/operations slot assignment, active connections, auto-connect validation, switching protection, and duplicate server-instance detection in P02.
|
||||||
|
|
||||||
|
### Option B: defer all Profile CRUD to P02
|
||||||
|
|
||||||
|
Keep P01 limited to application bootstrap, persistent SQLite, logging, tray, single-instance, and tests.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Use option A.
|
||||||
|
|
||||||
|
P01 persists the canonical non-sensitive ConnectionProfile fields and exposes bounded Tauri commands for:
|
||||||
|
|
||||||
|
- listing Profiles;
|
||||||
|
- creating a Profile;
|
||||||
|
- updating user-editable metadata;
|
||||||
|
- deleting a Profile.
|
||||||
|
|
||||||
|
The P01 IPC input does not accept Token, password, API Key, Cookie, Authorization header, NAS credential, or arbitrary extra fields. Rust creates Profile IDs and timestamps. React may receive only non-sensitive metadata and an opaque credential reference.
|
||||||
|
|
||||||
|
The following remain explicitly out of P01:
|
||||||
|
|
||||||
|
- credential value enrollment or retrieval;
|
||||||
|
- companion/operations slot assignment;
|
||||||
|
- connection activation and cancellation;
|
||||||
|
- auto-connect behavior;
|
||||||
|
- switching protection;
|
||||||
|
- server_instance_id conflict detection;
|
||||||
|
- REST/SSE runtime state.
|
||||||
|
|
||||||
|
## Reasons
|
||||||
|
|
||||||
|
- AGENTS.md gives the architecture document higher priority.
|
||||||
|
- A saved Profile is a durable application-foundation concept and can be implemented without activating a connection.
|
||||||
|
- Separating metadata from runtime connection state preserves the Rust-owned security boundary.
|
||||||
|
- The narrow IPC input makes accidental secret transfer to React or SQLite rejectable at deserialization time.
|
||||||
|
|
||||||
|
## Trade-offs
|
||||||
|
|
||||||
|
- P01 can select an authentication type but cannot enroll the corresponding credential value.
|
||||||
|
- The UI is intentionally a foundation form, not a full connection settings experience.
|
||||||
|
- Credential deletion and transactional cleanup must be added with the formal credential lifecycle before credential references can be created by production flows.
|
||||||
|
|
||||||
|
## Follow-up
|
||||||
|
|
||||||
|
P02 must consume this metadata model without widening the P01 commands to accept secret values. It must add slots, connection state, auto-connect rules, profile-switch guards, duplicate server-instance warnings, and credential lifecycle integration as separate reviewed increments.
|
||||||
|
|
@ -50,3 +50,14 @@
|
||||||
- Implementation: the identity is configured only in this repository.
|
- Implementation: the identity is configured only in this repository.
|
||||||
- Result: two Conventional Commit baseline commits were created on `main`, pushed normally, and followed by scoped feature-branch commits.
|
- Result: two Conventional Commit baseline commits were created on `main`, pushed normally, and followed by scoped feature-branch commits.
|
||||||
- Safety impact: no global Git identity was changed.
|
- Safety impact: no global Git identity was changed.
|
||||||
|
|
||||||
|
## PD-0008: Profile CRUD stage ownership
|
||||||
|
|
||||||
|
- Status: resolved; option A selected by the project owner on 2026-07-18
|
||||||
|
- Conflict: `docs/01_Architecture_Design.md` lists Profile CRUD in stage 1, while `docs/02_Codex_Implementation_Tasks.md` lists ConnectionProfile CRUD in Batch 2.
|
||||||
|
- Decision: implement basic non-sensitive Profile metadata CRUD in P01.
|
||||||
|
- P01 scope: Profile list, create, update, and delete; SQLite schema v2; bounded Tauri IPC; strict frontend Schema; basic management UI.
|
||||||
|
- P02 scope: companion/operations slot assignment, active connection state, auto-connect validation, switching protection, and `server_instance_id` conflict detection.
|
||||||
|
- Secret boundary: P01 commands accept no Token, password, API Key, Cookie, Authorization header, or NAS credential fields. SQLite stores only non-sensitive metadata and future opaque credential references.
|
||||||
|
- Rationale: AGENTS.md gives the architecture document higher priority, and the selected split keeps runtime connection behavior out of P01.
|
||||||
|
- ADR: `ADR-0004-profile-lifecycle-and-secret-boundary.md`.
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
# P00 Bootstrap Implementation Plan
|
# Implementation Plan
|
||||||
|
|
||||||
|
## P00 Bootstrap (completed)
|
||||||
|
|
||||||
## Objective
|
## Objective
|
||||||
|
|
||||||
|
|
@ -30,7 +32,43 @@ Establish a reproducible Tauri 2 + React + TypeScript + Rust baseline and comple
|
||||||
|
|
||||||
- Rust/MSVC/Tauri are verified and no longer block local work.
|
- Rust/MSVC/Tauri are verified and no longer block local work.
|
||||||
- Git Credential Manager reauthentication succeeded and the non-forced HTTP push created the remote `main` baseline at `0d12b94`.
|
- Git Credential Manager reauthentication succeeded and the non-forced HTTP push created the remote `main` baseline at `0d12b94`.
|
||||||
- Development is active on `feat/p00-bootstrap`; the remaining repository handoff step is a normal push of this feature branch.
|
- Forgejo PR #1 merged P00 into `main` at `b3420e4`; development now continues on `feat/p01-foundation`.
|
||||||
- The configured SSH fetch endpoint still refuses connections and the LAN SSH endpoint rejects the available key, but the approved HTTP push URL is operational.
|
- The configured SSH fetch endpoint still refuses connections and the LAN SSH endpoint rejects the available key, but the approved HTTP push URL is operational.
|
||||||
- Forgejo runner labels/jobs remain unverified, so the committed workflow is not claimed successful.
|
- Forgejo runner labels/jobs remain unverified, so the committed workflow is not claimed successful.
|
||||||
- Real UNC execution still requires a user-authorized disposable fixture.
|
- Real UNC execution still requires a user-authorized disposable fixture.
|
||||||
|
|
||||||
|
## P01 Foundation (active)
|
||||||
|
|
||||||
|
### Objective
|
||||||
|
|
||||||
|
Turn the P00 Spike skeleton into a durable application foundation. Under the project owner's option A decision, P01 includes basic non-sensitive Profile metadata CRUD while P02 retains all slot and runtime connection behavior.
|
||||||
|
|
||||||
|
### Ordered work
|
||||||
|
|
||||||
|
1. Initialize a persistent SQLite database in the Tauri application-data directory.
|
||||||
|
2. Apply versioned, transactional, idempotent migrations and refuse unknown future schema versions.
|
||||||
|
3. Validate Rust-to-TypeScript bootstrap payloads at runtime.
|
||||||
|
4. Ensure tracing output passes through the shared redaction rules before it reaches a writer.
|
||||||
|
5. Add SQLite schema v2 for canonical non-sensitive ConnectionProfile metadata.
|
||||||
|
6. Add bounded Tauri list/create/update/delete commands that generate IDs and timestamps in Rust.
|
||||||
|
7. Reject secret values, URL credentials, query-string credentials, unknown IPC fields, and implicit insecure HTTP.
|
||||||
|
8. Add strict frontend Profile Schemas and a basic management UI without Token/password/API Key inputs.
|
||||||
|
9. Test five saved Profiles, CRUD, persistent reopen, v1-to-v2 migration, future-version rejection, and browser fallback.
|
||||||
|
10. Re-verify tray, single-instance, explicit exit, frontend, Rust, E2E, development startup, Schema export, and production build behavior.
|
||||||
|
11. Record the decision in PD-0008 and ADR-0004, then commit and push the verified branch normally.
|
||||||
|
|
||||||
|
### P01 boundary
|
||||||
|
|
||||||
|
- Included: durable application database, schema migration, redacted logging, validated bootstrap IPC, basic Profile metadata CRUD, basic Profile management UI, tray, single-instance, and build/test foundations.
|
||||||
|
- Excluded: slot assignment, active REST/SSE connections, auto-connect behavior, Profile switching protection, duplicate `server_instance_id` handling, and formal credential enrollment.
|
||||||
|
|
||||||
|
### Verification status
|
||||||
|
|
||||||
|
- Frontend formatting, ESLint, TypeScript, 3 Vitest tests, and Vite production build passed.
|
||||||
|
- Playwright Chromium passed 1/1.
|
||||||
|
- Rust fmt, Clippy with warnings denied, tests, and check passed.
|
||||||
|
- Rust test suite passed 50 normal tests; 2 explicit manual tests remained ignored.
|
||||||
|
- Protocol Schema export completed without drift.
|
||||||
|
- Real Tauri development startup reached the Windows executable and was then deliberately terminated.
|
||||||
|
- Windows release and NSIS bundling passed.
|
||||||
|
- Forgejo CI remains unverified because a compatible runner/jobs endpoint is unavailable.
|
||||||
|
|
|
||||||
|
|
@ -2,35 +2,40 @@
|
||||||
|
|
||||||
## Current phase
|
## Current phase
|
||||||
|
|
||||||
P00 bootstrap implementation and high-risk Spike verification is complete; the feature branch is published and awaiting user PR review.
|
P01 foundation is complete and published on `feat/p01-foundation`. The option A boundary is resolved: basic non-sensitive Profile metadata CRUD belongs to P01, while slots and runtime connection behavior remain in P02.
|
||||||
|
|
||||||
## Completed
|
## Completed
|
||||||
|
|
||||||
- Read `AGENTS.md` and all authoritative architecture, implementation, and Forgejo workflow documents.
|
- Read `AGENTS.md`, the architecture, implementation task, and Forgejo predevelopment workflow documents in full.
|
||||||
- Verified the Windows, Git, Node.js, package-manager, WebView2, Rust, Tauri, and MSVC environment.
|
- Verified the Windows, Git, Node.js, package-manager, WebView2, Rust, Tauri, and MSVC environment.
|
||||||
- Initialized a local Git repository on `main`.
|
- Initialized and normalized Git, established `main`, and pushed the baseline without force.
|
||||||
- Configured `origin` as `ssh://git@localhost:18086/YokiiroBW/AstrBot-Desktop.git`.
|
- Completed and merged P00 through Forgejo PR #1 at `b3420e4`.
|
||||||
- Verified through authenticated Forgejo API and HTTP Git that the remote repository existed, was empty, used `main`, and granted push permission before the baseline push.
|
- Created `feat/p01-foundation` from the merged `main`.
|
||||||
- Reauthenticated through Git Credential Manager and non-forced pushed the `main` baseline to Forgejo at `0d12b94`.
|
- Added persistent SQLite startup initialization with WAL, busy timeout, foreign-key enforcement, and transactional migrations.
|
||||||
- Created and switched to `feat/p00-bootstrap` from the pushed `main` baseline.
|
- Added schema v2 with canonical non-sensitive `connection_profiles` metadata.
|
||||||
- Built the Tauri 2 + React + TypeScript + Rust skeleton with tray, single-instance, CSP, and minimal `core:default` capability.
|
- Added fresh-database, v1-to-v2, future-version, idempotent reopen, five-Profile, CRUD, and persistent-reopen coverage.
|
||||||
- Implemented independent companion/operations REST and SSE clients and passed the corrected 30-minute soak.
|
- Added bounded Tauri Profile list/create/update/delete commands.
|
||||||
- Implemented and tested Windows Credential Manager, UI Automation, selected-window capture, Event Log, process, port, foreground-window, authorized log-tail, configuration parsing, and redaction Spikes.
|
- Kept UUID and timestamp creation in Rust.
|
||||||
- Implemented and tested composite-key SQLite isolation and recoverable local file transactions with source preservation.
|
- Rejected credential-bearing URLs, URL query/fragment data, implicit HTTP, invalid certificate fingerprints, malformed IDs, unknown fields, and Token/password/API Key fields.
|
||||||
- Added provisional protocol types, ten JSON Schemas, TypeScript exports, drift checks, and two loopback-only Mock Gateway instances.
|
- Preserved credential references and runtime-managed fields outside the editable P01 input.
|
||||||
- Added frontend, Playwright, Rust, integration, Windows-provider, soak, and Forgejo CI entry points.
|
- Added strict Zod Schemas for bootstrap and ConnectionProfile IPC payloads.
|
||||||
- Built the Windows release executable and SHA-256-recorded NSIS installer.
|
- Added a basic React Profile management UI for non-sensitive metadata only.
|
||||||
- Added dependency, Spike, progress, changelog, and pending-decision records.
|
- Added explicit deletion confirmation and browser-safe Tauri IPC fallback.
|
||||||
- Committed the implementation, test, and CI increments with Conventional Commit subjects.
|
- Added a redacting tracing writer that sanitizes structured fields and rendered message content.
|
||||||
|
- Retained tray, close-to-tray, explicit quit, and single-instance behavior.
|
||||||
|
- Re-exported protocol Schemas without drift.
|
||||||
|
- Re-ran a real Tauri development startup and reached the Windows executable.
|
||||||
|
- Rebuilt the Windows release executable and NSIS installer.
|
||||||
|
- Recorded the Profile boundary in PD-0008 and ADR-0004.
|
||||||
|
|
||||||
## In progress
|
## In progress
|
||||||
|
|
||||||
- Preparing the final PR draft and handoff report without merging `main`.
|
- No code implementation is in progress; the branch is awaiting Forgejo PR review.
|
||||||
|
|
||||||
## Remaining
|
## Remaining
|
||||||
|
|
||||||
- Open and review the Forgejo PR from `feat/p00-bootstrap` to `main`; do not merge automatically.
|
- Create and review the P01 Forgejo PR; do not automatically merge `main`.
|
||||||
- Run the Forgejo workflow when a compatible runner is available.
|
- Run Forgejo CI when a compatible runner is available.
|
||||||
- Execute a real UNC transaction only after an authorized disposable fixture is supplied.
|
- Execute a real UNC transaction only after an authorized disposable fixture is supplied.
|
||||||
- Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray.
|
- Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray.
|
||||||
|
|
||||||
|
|
@ -38,35 +43,39 @@ P00 bootstrap implementation and high-risk Spike verification is complete; the f
|
||||||
|
|
||||||
- Configured Forgejo SSH `localhost:18086` refuses connections.
|
- Configured Forgejo SSH `localhost:18086` refuses connections.
|
||||||
- LAN SSH `192.168.31.210:18086` responds but rejects the available public key.
|
- LAN SSH `192.168.31.210:18086` responds but rejects the available public key.
|
||||||
- HTTP Git push is operational after Git Credential Manager reauthentication and is no longer a blocker.
|
- Approved HTTP Git push remains operational and is not blocked.
|
||||||
- Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404.
|
- Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404.
|
||||||
|
- No blocker remains for the selected P01 scope.
|
||||||
|
|
||||||
## Test status
|
## Test status
|
||||||
|
|
||||||
- `pnpm check:frontend`: passed; 1 Vitest test and production Vite build.
|
- `npm run check:frontend`: passed; Prettier, ESLint, TypeScript, 3 Vitest tests, and Vite production build.
|
||||||
- `pnpm test:e2e`: passed; 1 Chromium smoke test.
|
- `npm run test:e2e`: passed; 1 Chromium smoke test.
|
||||||
- Rust fmt/check/Clippy with warnings denied: passed.
|
- Rust fmt/check/Clippy with warnings denied: passed.
|
||||||
- `cargo test --workspace`: 40 passed, 2 explicit manual tests ignored.
|
- `cargo test --workspace`: passed; 50 normal tests, 2 explicit manual tests ignored.
|
||||||
- Controlled Windows UIA/PrintWindow smoke: 1 passed.
|
- Profile persistence: passed; five Profile CRUD, close/reopen persistence, and v1-to-v2 migration preserve existing messages.
|
||||||
- Corrected dual-SSE soak: 1800.02 seconds, 1800 companion events, 1801 operations events, passed.
|
- Secret boundary: passed; unknown Token, password, and API Key input fields are rejected.
|
||||||
- Protocol Schema drift check: passed.
|
- Protocol Schema export: passed; no generated drift.
|
||||||
- Tauri development smoke, release executable, and NSIS installer build: passed.
|
- Tauri development startup: passed; executable launched, then was deliberately terminated after verification.
|
||||||
- pnpm 11.9.0 frozen lockfile-only validation: passed using a local temporary store to avoid the pnpm UNC project-registry limitation.
|
- Tauri Windows release executable: passed.
|
||||||
|
- NSIS installer: passed; `0.1.0-alpha.1`, 3,827,899 bytes.
|
||||||
|
- NSIS SHA-256: `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740`.
|
||||||
- Forgejo CI and a real UNC transaction were not executed and are not claimed successful.
|
- Forgejo CI and a real UNC transaction were not executed and are not claimed successful.
|
||||||
|
|
||||||
## Current branch
|
## Current branch
|
||||||
|
|
||||||
`feat/p00-bootstrap`
|
`feat/p01-foundation`
|
||||||
|
|
||||||
## Recent commits
|
## Recent commits
|
||||||
|
|
||||||
- `5e6e8d5 docs(project): add architecture and implementation specifications`
|
- `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)`
|
||||||
- `0d12b94 chore(repo): initialize repository and ignore rules`
|
- `ed74342 feat(foundation): add persistent bootstrap safeguards`
|
||||||
- `01607c6 feat(p00): add Tauri desktop spike foundation`
|
- `6a1eeab docs(p01): record foundation progress and profile boundary`
|
||||||
- `69b432b test(p00): add frontend browser rust and windows checks`
|
- `02fd25a feat(profile): add secure profile persistence and IPC`
|
||||||
- `d4af979 ci(forgejo): add portable and windows quality workflows`
|
- `907a8a3 feat(profile-ui): add basic profile management`
|
||||||
- `353a439 docs(p00): record spike results and unresolved boundaries`
|
- `5672585 chore(version): set P01 alpha version`
|
||||||
|
- `2154c3b docs(p01): resolve profile boundary and record verification`
|
||||||
|
|
||||||
## Next step
|
## Next step
|
||||||
|
|
||||||
Provide the verified test report and PR draft. The user can then review the Forgejo diff and decide whether to merge; `main` remains unchanged by this workflow.
|
Open `feat/p01-foundation → main` as a Forgejo PR, review the recorded local verification, and run CI only when a compatible runner is available.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,88 @@
|
||||||
|
# P01 Foundation Progress Report
|
||||||
|
|
||||||
|
Date: 2026-07-18
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
P01 implementation, local verification, focused commits, and normal Forgejo branch publication are complete. The stage is ready for a `feat/p01-foundation → main` PR review.
|
||||||
|
|
||||||
|
PD-0008 was resolved by the project owner with option A:
|
||||||
|
|
||||||
|
- P01 includes basic non-sensitive Profile metadata CRUD.
|
||||||
|
- P02 retains slots, active connections, auto-connect, switching protection, duplicate server-instance handling, and credential enrollment.
|
||||||
|
|
||||||
|
## Completed
|
||||||
|
|
||||||
|
- Verified P00 PR #1 merged into `main` at `b3420e4`.
|
||||||
|
- Created `feat/p01-foundation` from the merged baseline.
|
||||||
|
- Added persistent SQLite under the Tauri application-data directory.
|
||||||
|
- Added WAL, a bounded busy timeout, foreign-key enforcement, and transactional `user_version` migrations.
|
||||||
|
- Added schema v2 for `connection_profiles`.
|
||||||
|
- Verified fresh creation and v1-to-v2 migration without losing existing messages.
|
||||||
|
- Verified five saved Profiles, full CRUD, and persistence after reopening the database.
|
||||||
|
- Added bounded Tauri list/create/update/delete commands.
|
||||||
|
- Added Rust-owned UUIDs and RFC 3339 timestamps.
|
||||||
|
- Added URL normalization and rejection of embedded credentials, query strings, fragments, implicit HTTP, and invalid fingerprints.
|
||||||
|
- Added strict IPC rejection for unknown Token, password, and API Key fields.
|
||||||
|
- Added strict frontend ConnectionProfile Schemas.
|
||||||
|
- Added a basic React Profile manager with list/create/edit/delete and explicit deletion confirmation.
|
||||||
|
- Added no Token, password, API Key, Cookie, or NAS credential input.
|
||||||
|
- Added a tracing writer that redacts output before writing.
|
||||||
|
- Retained tray, close-to-tray, explicit quit, and single-instance focus behavior.
|
||||||
|
- Added ADR-0004 for the Profile lifecycle and secret boundary.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
| Check | Result |
|
||||||
|
| ------------------------------------------------------- | --------------------------------------------------------------------------- |
|
||||||
|
| Frontend format, ESLint, TypeScript, Vitest, Vite build | Passed; 3 Vitest tests |
|
||||||
|
| Playwright Chromium | Passed; 1 test |
|
||||||
|
| Rust fmt, Clippy with warnings denied, check | Passed |
|
||||||
|
| Rust tests | Passed; 50 normal tests, 2 explicit manual tests ignored |
|
||||||
|
| SQLite fresh schema v2 | Passed |
|
||||||
|
| SQLite v1-to-v2 migration | Passed; existing message preserved |
|
||||||
|
| Five Profile CRUD | Passed |
|
||||||
|
| Profile close/reopen persistence | Passed |
|
||||||
|
| Unknown secret IPC fields | Passed; rejected |
|
||||||
|
| Protocol Schema export | Passed; no drift |
|
||||||
|
| Tauri development startup | Passed; executable launched and was deliberately stopped after verification |
|
||||||
|
| Tauri release executable | Passed |
|
||||||
|
| NSIS installer | Passed; `0.1.0-alpha.1`, 3,827,899 bytes |
|
||||||
|
| NSIS SHA-256 | `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740` |
|
||||||
|
| Forgejo feature branch | Passed; normal push through `2154c3b`, no force and no `main` merge |
|
||||||
|
|
||||||
|
## Security boundary
|
||||||
|
|
||||||
|
- React never receives or submits credential values.
|
||||||
|
- P01 IPC accepts only non-sensitive Profile fields.
|
||||||
|
- Unknown input fields are rejected by Serde.
|
||||||
|
- SQLite stores non-sensitive Profile metadata and reserves only an opaque `credential_reference`.
|
||||||
|
- HTTP requires an explicit insecure-transport flag.
|
||||||
|
- URLs containing credentials, query strings, or fragments are rejected.
|
||||||
|
- No arbitrary command, unrestricted filesystem, registry-write, input-injection, or destructive file API was added.
|
||||||
|
|
||||||
|
## Build environment note
|
||||||
|
|
||||||
|
The prior P01 release attempt found a missing generated `bindgen.rs` in the local `libsqlite3-sys 0.38.1` release cache. The official cached `bindgen_bundled_version.rs` was copied to the exact expected build-cache location, and the matching SHA-256 was recorded:
|
||||||
|
|
||||||
|
`5B5A37A74DC728FB0BCD041867EB577C03C95E2FE46285262C589A3B1CD4BBAC`
|
||||||
|
|
||||||
|
This was an environment cache repair only. No repository file or dependency version was changed. The current production build completed successfully using the repaired cache.
|
||||||
|
|
||||||
|
## Deferred to P02
|
||||||
|
|
||||||
|
- companion and operations slot assignment;
|
||||||
|
- maximum two active connections;
|
||||||
|
- REST/SSE activation and cancellation;
|
||||||
|
- auto-connect validation;
|
||||||
|
- Profile switching protection;
|
||||||
|
- duplicate `server_instance_id` warnings;
|
||||||
|
- formal credential enrollment, lookup, rotation, and deletion.
|
||||||
|
|
||||||
|
## Not claimed
|
||||||
|
|
||||||
|
- Forgejo CI has not run.
|
||||||
|
- No real AstrBot gateway compatibility is claimed.
|
||||||
|
- No real credential was used.
|
||||||
|
- No real UNC file transaction was executed.
|
||||||
|
- No automatic merge to `main` was performed.
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "astrbot-desktop",
|
"name": "astrbot-desktop",
|
||||||
"version": "0.1.0-alpha.0",
|
"version": "0.1.0-alpha.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "pnpm@11.9.0",
|
"packageManager": "pnpm@11.9.0",
|
||||||
|
|
|
||||||
|
|
@ -1,33 +1,64 @@
|
||||||
|
mod profiles;
|
||||||
|
|
||||||
|
use std::{path::Path, sync::Mutex, time::Duration};
|
||||||
|
|
||||||
use rusqlite::{Connection, OptionalExtension, params};
|
use rusqlite::{Connection, OptionalExtension, params};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
pub const CURRENT_SCHEMA_VERSION: u32 = 2;
|
||||||
|
|
||||||
|
pub struct ApplicationDatabase {
|
||||||
|
store: Mutex<ProfileMessageStore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationDatabase {
|
||||||
|
pub fn open(path: impl AsRef<Path>) -> Result<Self, DatabaseError> {
|
||||||
|
Ok(Self {
|
||||||
|
store: Mutex::new(ProfileMessageStore::open(path)?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) fn in_memory() -> Result<Self, DatabaseError> {
|
||||||
|
Ok(Self {
|
||||||
|
store: Mutex::new(ProfileMessageStore::in_memory()?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn schema_version(&self) -> Result<u32, DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.schema_version()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct ProfileMessageStore {
|
pub struct ProfileMessageStore {
|
||||||
connection: Connection,
|
connection: Connection,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProfileMessageStore {
|
impl ProfileMessageStore {
|
||||||
pub fn in_memory() -> Result<Self, DatabaseError> {
|
pub fn open(path: impl AsRef<Path>) -> Result<Self, DatabaseError> {
|
||||||
let connection = Connection::open_in_memory()?;
|
Self::from_connection(Connection::open(path)?, true)
|
||||||
let store = Self { connection };
|
|
||||||
store.migrate()?;
|
|
||||||
Ok(store)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn migrate(&self) -> Result<(), DatabaseError> {
|
pub fn in_memory() -> Result<Self, DatabaseError> {
|
||||||
self.connection.execute_batch(
|
Self::from_connection(Connection::open_in_memory()?, false)
|
||||||
"
|
}
|
||||||
PRAGMA foreign_keys = ON;
|
|
||||||
CREATE TABLE IF NOT EXISTS messages (
|
fn from_connection(
|
||||||
profile_id TEXT NOT NULL,
|
mut connection: Connection,
|
||||||
server_instance_id TEXT NOT NULL,
|
persistent: bool,
|
||||||
conversation_id TEXT NOT NULL,
|
) -> Result<Self, DatabaseError> {
|
||||||
message_id TEXT NOT NULL,
|
configure_connection(&connection, persistent)?;
|
||||||
content TEXT NOT NULL,
|
migrate(&mut connection)?;
|
||||||
PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id)
|
Ok(Self { connection })
|
||||||
);
|
}
|
||||||
",
|
|
||||||
)?;
|
pub fn schema_version(&self) -> Result<u32, DatabaseError> {
|
||||||
Ok(())
|
Ok(self
|
||||||
|
.connection
|
||||||
|
.pragma_query_value(None, "user_version", |row| row.get(0))?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn insert_message(
|
pub fn insert_message(
|
||||||
|
|
@ -84,16 +115,220 @@ impl ProfileMessageStore {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> {
|
||||||
|
connection.pragma_update(None, "foreign_keys", "ON")?;
|
||||||
|
connection.busy_timeout(Duration::from_secs(5))?;
|
||||||
|
if persistent {
|
||||||
|
connection.pragma_update(None, "journal_mode", "WAL")?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
|
||||||
|
let found: u32 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?;
|
||||||
|
|
||||||
|
if found > CURRENT_SCHEMA_VERSION {
|
||||||
|
return Err(DatabaseError::UnsupportedSchemaVersion {
|
||||||
|
found,
|
||||||
|
supported: CURRENT_SCHEMA_VERSION,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if found == 0 {
|
||||||
|
let transaction = connection.transaction()?;
|
||||||
|
transaction.execute_batch(
|
||||||
|
"
|
||||||
|
CREATE TABLE messages (
|
||||||
|
profile_id TEXT NOT NULL,
|
||||||
|
server_instance_id TEXT NOT NULL,
|
||||||
|
conversation_id TEXT NOT NULL,
|
||||||
|
message_id TEXT NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id)
|
||||||
|
);
|
||||||
|
PRAGMA user_version = 1;
|
||||||
|
",
|
||||||
|
)?;
|
||||||
|
transaction.commit()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if found <= 1 {
|
||||||
|
let transaction = connection.transaction()?;
|
||||||
|
transaction.execute_batch(
|
||||||
|
"
|
||||||
|
CREATE TABLE connection_profiles (
|
||||||
|
id TEXT PRIMARY KEY NOT NULL,
|
||||||
|
display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 80),
|
||||||
|
role TEXT NOT NULL CHECK(role IN ('companion', 'operations', 'general')),
|
||||||
|
base_url TEXT NOT NULL,
|
||||||
|
event_stream_url TEXT,
|
||||||
|
authentication_type TEXT NOT NULL CHECK(authentication_type IN ('device-token', 'api-key')),
|
||||||
|
credential_reference TEXT,
|
||||||
|
allow_insecure_http INTEGER NOT NULL DEFAULT 0 CHECK(allow_insecure_http IN (0, 1)),
|
||||||
|
pinned_certificate_fingerprint TEXT,
|
||||||
|
auto_connect_slot TEXT CHECK(auto_connect_slot IS NULL OR auto_connect_slot IN ('companion', 'operations')),
|
||||||
|
auto_connect INTEGER NOT NULL DEFAULT 0 CHECK(auto_connect IN (0, 1)),
|
||||||
|
server_instance_id TEXT,
|
||||||
|
server_version TEXT,
|
||||||
|
protocol_version TEXT,
|
||||||
|
local_tool_policy_id TEXT,
|
||||||
|
last_connected_at TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX connection_profiles_role_idx
|
||||||
|
ON connection_profiles(role);
|
||||||
|
PRAGMA user_version = 2;
|
||||||
|
",
|
||||||
|
)?;
|
||||||
|
transaction.commit()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum DatabaseError {
|
pub enum DatabaseError {
|
||||||
#[error("SQLite operation failed")]
|
#[error("SQLite operation failed")]
|
||||||
Sqlite(#[from] rusqlite::Error),
|
Sqlite(#[from] rusqlite::Error),
|
||||||
|
#[error("database schema version {found} is newer than supported version {supported}")]
|
||||||
|
UnsupportedSchemaVersion { found: u32, supported: u32 },
|
||||||
|
#[error("database state lock is unavailable")]
|
||||||
|
LockPoisoned,
|
||||||
|
#[error("database contains invalid profile data")]
|
||||||
|
InvalidStoredProfile,
|
||||||
|
#[error("connection profile was not found")]
|
||||||
|
ProfileNotFound,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn creates_and_reopens_a_persistent_migrated_database() {
|
||||||
|
let directory = tempfile::tempdir().expect("temporary directory");
|
||||||
|
let path = directory.path().join("desktop.sqlite3");
|
||||||
|
|
||||||
|
{
|
||||||
|
let store = ProfileMessageStore::open(&path).expect("open database");
|
||||||
|
assert_eq!(
|
||||||
|
store.schema_version().expect("schema version"),
|
||||||
|
CURRENT_SCHEMA_VERSION
|
||||||
|
);
|
||||||
|
store
|
||||||
|
.insert_message(
|
||||||
|
"profile-a",
|
||||||
|
"server-a",
|
||||||
|
"conversation-a",
|
||||||
|
"message-a",
|
||||||
|
"persisted",
|
||||||
|
)
|
||||||
|
.expect("insert message");
|
||||||
|
}
|
||||||
|
|
||||||
|
let reopened = ProfileMessageStore::open(&path).expect("reopen database");
|
||||||
|
assert_eq!(
|
||||||
|
reopened.schema_version().expect("schema version"),
|
||||||
|
CURRENT_SCHEMA_VERSION
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
reopened
|
||||||
|
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
||||||
|
.expect("query message")
|
||||||
|
.as_deref(),
|
||||||
|
Some("persisted")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn migrates_v1_to_v2_without_losing_messages() {
|
||||||
|
let directory = tempfile::tempdir().expect("temporary directory");
|
||||||
|
let path = directory.path().join("v1.sqlite3");
|
||||||
|
let connection = Connection::open(&path).expect("create v1 database");
|
||||||
|
connection
|
||||||
|
.execute_batch(
|
||||||
|
"
|
||||||
|
CREATE TABLE messages (
|
||||||
|
profile_id TEXT NOT NULL,
|
||||||
|
server_instance_id TEXT NOT NULL,
|
||||||
|
conversation_id TEXT NOT NULL,
|
||||||
|
message_id TEXT NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id)
|
||||||
|
);
|
||||||
|
INSERT INTO messages (
|
||||||
|
profile_id,
|
||||||
|
server_instance_id,
|
||||||
|
conversation_id,
|
||||||
|
message_id,
|
||||||
|
content
|
||||||
|
) VALUES (
|
||||||
|
'profile-a',
|
||||||
|
'server-a',
|
||||||
|
'conversation-a',
|
||||||
|
'message-a',
|
||||||
|
'preserved'
|
||||||
|
);
|
||||||
|
PRAGMA user_version = 1;
|
||||||
|
",
|
||||||
|
)
|
||||||
|
.expect("create v1 schema");
|
||||||
|
drop(connection);
|
||||||
|
|
||||||
|
let store = ProfileMessageStore::open(&path).expect("migrate database");
|
||||||
|
assert_eq!(store.schema_version().expect("schema version"), 2);
|
||||||
|
assert_eq!(
|
||||||
|
store
|
||||||
|
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
||||||
|
.expect("query preserved message")
|
||||||
|
.as_deref(),
|
||||||
|
Some("preserved")
|
||||||
|
);
|
||||||
|
let profile_table_count: u32 = store
|
||||||
|
.connection
|
||||||
|
.query_row(
|
||||||
|
"SELECT COUNT(*) FROM sqlite_master
|
||||||
|
WHERE type = 'table' AND name = 'connection_profiles'",
|
||||||
|
[],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.expect("query profile table");
|
||||||
|
assert_eq!(profile_table_count, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_a_database_from_a_newer_schema_version() {
|
||||||
|
let directory = tempfile::tempdir().expect("temporary directory");
|
||||||
|
let path = directory.path().join("future.sqlite3");
|
||||||
|
let connection = Connection::open(&path).expect("create database");
|
||||||
|
connection
|
||||||
|
.pragma_update(None, "user_version", CURRENT_SCHEMA_VERSION + 1)
|
||||||
|
.expect("set future version");
|
||||||
|
drop(connection);
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
ProfileMessageStore::open(path),
|
||||||
|
Err(DatabaseError::UnsupportedSchemaVersion {
|
||||||
|
found: 3,
|
||||||
|
supported: CURRENT_SCHEMA_VERSION
|
||||||
|
})
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeated_migration_is_idempotent() {
|
||||||
|
let store = ProfileMessageStore::in_memory().expect("store");
|
||||||
|
assert_eq!(
|
||||||
|
store.schema_version().expect("schema version"),
|
||||||
|
CURRENT_SCHEMA_VERSION
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
store.schema_version().expect("schema version"),
|
||||||
|
CURRENT_SCHEMA_VERSION
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn identical_remote_ids_remain_isolated_by_profile_and_server() {
|
fn identical_remote_ids_remain_isolated_by_profile_and_server() {
|
||||||
let store = ProfileMessageStore::in_memory().expect("store");
|
let store = ProfileMessageStore::in_memory().expect("store");
|
||||||
|
|
|
||||||
349
src-tauri/src/database/profiles.rs
普通文件
349
src-tauri/src/database/profiles.rs
普通文件
|
|
@ -0,0 +1,349 @@
|
||||||
|
use desktop_protocol::{ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile};
|
||||||
|
use rusqlite::{Row, params};
|
||||||
|
|
||||||
|
use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore};
|
||||||
|
|
||||||
|
const PROFILE_COLUMNS: &str = "
|
||||||
|
id,
|
||||||
|
display_name,
|
||||||
|
role,
|
||||||
|
base_url,
|
||||||
|
event_stream_url,
|
||||||
|
authentication_type,
|
||||||
|
credential_reference,
|
||||||
|
allow_insecure_http,
|
||||||
|
pinned_certificate_fingerprint,
|
||||||
|
auto_connect_slot,
|
||||||
|
auto_connect,
|
||||||
|
server_instance_id,
|
||||||
|
server_version,
|
||||||
|
protocol_version,
|
||||||
|
local_tool_policy_id,
|
||||||
|
last_connected_at,
|
||||||
|
created_at,
|
||||||
|
updated_at
|
||||||
|
";
|
||||||
|
|
||||||
|
impl ApplicationDatabase {
|
||||||
|
pub fn list_profiles(&self) -> Result<Vec<ConnectionProfile>, DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.list_profiles()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn profile(&self, id: &str) -> Result<Option<ConnectionProfile>, DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.profile(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.create_profile(profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.update_profile(profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.delete_profile(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProfileMessageStore {
|
||||||
|
fn list_profiles(&self) -> Result<Vec<ConnectionProfile>, DatabaseError> {
|
||||||
|
let mut statement = self.connection.prepare(&format!(
|
||||||
|
"SELECT {PROFILE_COLUMNS}
|
||||||
|
FROM connection_profiles
|
||||||
|
ORDER BY display_name COLLATE NOCASE, id"
|
||||||
|
))?;
|
||||||
|
let mut rows = statement.query([])?;
|
||||||
|
let mut profiles = Vec::new();
|
||||||
|
while let Some(row) = rows.next()? {
|
||||||
|
profiles.push(profile_from_row(row)?);
|
||||||
|
}
|
||||||
|
Ok(profiles)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profile(&self, id: &str) -> Result<Option<ConnectionProfile>, DatabaseError> {
|
||||||
|
let mut statement = self.connection.prepare(&format!(
|
||||||
|
"SELECT {PROFILE_COLUMNS}
|
||||||
|
FROM connection_profiles
|
||||||
|
WHERE id = ?1"
|
||||||
|
))?;
|
||||||
|
let mut rows = statement.query(params![id])?;
|
||||||
|
match rows.next()? {
|
||||||
|
Some(row) => Ok(Some(profile_from_row(row)?)),
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||||
|
self.connection.execute(
|
||||||
|
"
|
||||||
|
INSERT INTO connection_profiles (
|
||||||
|
id,
|
||||||
|
display_name,
|
||||||
|
role,
|
||||||
|
base_url,
|
||||||
|
event_stream_url,
|
||||||
|
authentication_type,
|
||||||
|
credential_reference,
|
||||||
|
allow_insecure_http,
|
||||||
|
pinned_certificate_fingerprint,
|
||||||
|
auto_connect_slot,
|
||||||
|
auto_connect,
|
||||||
|
server_instance_id,
|
||||||
|
server_version,
|
||||||
|
protocol_version,
|
||||||
|
local_tool_policy_id,
|
||||||
|
last_connected_at,
|
||||||
|
created_at,
|
||||||
|
updated_at
|
||||||
|
) VALUES (
|
||||||
|
?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9,
|
||||||
|
?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18
|
||||||
|
)
|
||||||
|
",
|
||||||
|
params![
|
||||||
|
profile.id,
|
||||||
|
profile.display_name,
|
||||||
|
role_to_str(profile.role),
|
||||||
|
profile.base_url,
|
||||||
|
profile.event_stream_url,
|
||||||
|
authentication_to_str(profile.authentication_type),
|
||||||
|
profile.credential_reference,
|
||||||
|
profile.allow_insecure_http,
|
||||||
|
profile.pinned_certificate_fingerprint,
|
||||||
|
profile.auto_connect_slot.map(slot_to_str),
|
||||||
|
profile.auto_connect,
|
||||||
|
profile.server_instance_id,
|
||||||
|
profile.server_version,
|
||||||
|
profile.protocol_version,
|
||||||
|
profile.local_tool_policy_id,
|
||||||
|
profile.last_connected_at,
|
||||||
|
profile.created_at,
|
||||||
|
profile.updated_at,
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||||
|
let changed = self.connection.execute(
|
||||||
|
"
|
||||||
|
UPDATE connection_profiles
|
||||||
|
SET display_name = ?2,
|
||||||
|
role = ?3,
|
||||||
|
base_url = ?4,
|
||||||
|
event_stream_url = ?5,
|
||||||
|
authentication_type = ?6,
|
||||||
|
credential_reference = ?7,
|
||||||
|
allow_insecure_http = ?8,
|
||||||
|
pinned_certificate_fingerprint = ?9,
|
||||||
|
auto_connect_slot = ?10,
|
||||||
|
auto_connect = ?11,
|
||||||
|
server_instance_id = ?12,
|
||||||
|
server_version = ?13,
|
||||||
|
protocol_version = ?14,
|
||||||
|
local_tool_policy_id = ?15,
|
||||||
|
last_connected_at = ?16,
|
||||||
|
created_at = ?17,
|
||||||
|
updated_at = ?18
|
||||||
|
WHERE id = ?1
|
||||||
|
",
|
||||||
|
params![
|
||||||
|
profile.id,
|
||||||
|
profile.display_name,
|
||||||
|
role_to_str(profile.role),
|
||||||
|
profile.base_url,
|
||||||
|
profile.event_stream_url,
|
||||||
|
authentication_to_str(profile.authentication_type),
|
||||||
|
profile.credential_reference,
|
||||||
|
profile.allow_insecure_http,
|
||||||
|
profile.pinned_certificate_fingerprint,
|
||||||
|
profile.auto_connect_slot.map(slot_to_str),
|
||||||
|
profile.auto_connect,
|
||||||
|
profile.server_instance_id,
|
||||||
|
profile.server_version,
|
||||||
|
profile.protocol_version,
|
||||||
|
profile.local_tool_policy_id,
|
||||||
|
profile.last_connected_at,
|
||||||
|
profile.created_at,
|
||||||
|
profile.updated_at,
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
if changed == 0 {
|
||||||
|
return Err(DatabaseError::ProfileNotFound);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> {
|
||||||
|
if self
|
||||||
|
.connection
|
||||||
|
.execute("DELETE FROM connection_profiles WHERE id = ?1", params![id])?
|
||||||
|
== 0
|
||||||
|
{
|
||||||
|
return Err(DatabaseError::ProfileNotFound);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profile_from_row(row: &Row<'_>) -> Result<ConnectionProfile, DatabaseError> {
|
||||||
|
let role = match row.get::<_, String>(2)?.as_str() {
|
||||||
|
"companion" => AstrBotProfileRole::Companion,
|
||||||
|
"operations" => AstrBotProfileRole::Operations,
|
||||||
|
"general" => AstrBotProfileRole::General,
|
||||||
|
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||||
|
};
|
||||||
|
let authentication_type = match row.get::<_, String>(5)?.as_str() {
|
||||||
|
"device-token" => AuthenticationType::DeviceToken,
|
||||||
|
"api-key" => AuthenticationType::ApiKey,
|
||||||
|
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||||
|
};
|
||||||
|
let auto_connect_slot = match row.get::<_, Option<String>>(9)?.as_deref() {
|
||||||
|
Some("companion") => Some(ActiveSlotKind::Companion),
|
||||||
|
Some("operations") => Some(ActiveSlotKind::Operations),
|
||||||
|
Some(_) => return Err(DatabaseError::InvalidStoredProfile),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(ConnectionProfile {
|
||||||
|
id: row.get(0)?,
|
||||||
|
display_name: row.get(1)?,
|
||||||
|
role,
|
||||||
|
base_url: row.get(3)?,
|
||||||
|
event_stream_url: row.get(4)?,
|
||||||
|
authentication_type,
|
||||||
|
credential_reference: row.get(6)?,
|
||||||
|
allow_insecure_http: row.get(7)?,
|
||||||
|
pinned_certificate_fingerprint: row.get(8)?,
|
||||||
|
auto_connect_slot,
|
||||||
|
auto_connect: row.get(10)?,
|
||||||
|
server_instance_id: row.get(11)?,
|
||||||
|
server_version: row.get(12)?,
|
||||||
|
protocol_version: row.get(13)?,
|
||||||
|
local_tool_policy_id: row.get(14)?,
|
||||||
|
last_connected_at: row.get(15)?,
|
||||||
|
created_at: row.get(16)?,
|
||||||
|
updated_at: row.get(17)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn role_to_str(role: AstrBotProfileRole) -> &'static str {
|
||||||
|
match role {
|
||||||
|
AstrBotProfileRole::Companion => "companion",
|
||||||
|
AstrBotProfileRole::Operations => "operations",
|
||||||
|
AstrBotProfileRole::General => "general",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn authentication_to_str(authentication_type: AuthenticationType) -> &'static str {
|
||||||
|
match authentication_type {
|
||||||
|
AuthenticationType::DeviceToken => "device-token",
|
||||||
|
AuthenticationType::ApiKey => "api-key",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn slot_to_str(slot: ActiveSlotKind) -> &'static str {
|
||||||
|
match slot {
|
||||||
|
ActiveSlotKind::Companion => "companion",
|
||||||
|
ActiveSlotKind::Operations => "operations",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn profile(index: usize) -> ConnectionProfile {
|
||||||
|
ConnectionProfile {
|
||||||
|
id: format!("00000000-0000-4000-8000-{index:012}"),
|
||||||
|
display_name: format!("Profile {index}"),
|
||||||
|
role: AstrBotProfileRole::General,
|
||||||
|
base_url: format!("https://example-{index}.test/"),
|
||||||
|
event_stream_url: None,
|
||||||
|
authentication_type: AuthenticationType::DeviceToken,
|
||||||
|
credential_reference: None,
|
||||||
|
allow_insecure_http: false,
|
||||||
|
pinned_certificate_fingerprint: None,
|
||||||
|
auto_connect_slot: None,
|
||||||
|
auto_connect: false,
|
||||||
|
server_instance_id: None,
|
||||||
|
server_version: None,
|
||||||
|
protocol_version: None,
|
||||||
|
local_tool_policy_id: None,
|
||||||
|
last_connected_at: None,
|
||||||
|
created_at: "2026-07-18T00:00:00Z".into(),
|
||||||
|
updated_at: "2026-07-18T00:00:00Z".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stores_lists_updates_and_deletes_five_profiles() {
|
||||||
|
let database = ApplicationDatabase::in_memory().expect("database");
|
||||||
|
for index in 0..5 {
|
||||||
|
database
|
||||||
|
.create_profile(&profile(index))
|
||||||
|
.expect("create profile");
|
||||||
|
}
|
||||||
|
assert_eq!(database.list_profiles().expect("list profiles").len(), 5);
|
||||||
|
|
||||||
|
let mut updated = database
|
||||||
|
.profile(&profile(2).id)
|
||||||
|
.expect("read profile")
|
||||||
|
.expect("existing profile");
|
||||||
|
updated.display_name = "Updated Profile".into();
|
||||||
|
updated.updated_at = "2026-07-18T01:00:00Z".into();
|
||||||
|
database.update_profile(&updated).expect("update profile");
|
||||||
|
assert_eq!(
|
||||||
|
database
|
||||||
|
.profile(&updated.id)
|
||||||
|
.expect("read updated profile")
|
||||||
|
.expect("existing profile")
|
||||||
|
.display_name,
|
||||||
|
"Updated Profile"
|
||||||
|
);
|
||||||
|
|
||||||
|
database
|
||||||
|
.delete_profile(&updated.id)
|
||||||
|
.expect("delete profile");
|
||||||
|
assert_eq!(database.list_profiles().expect("list profiles").len(), 4);
|
||||||
|
assert!(matches!(
|
||||||
|
database.delete_profile(&updated.id),
|
||||||
|
Err(DatabaseError::ProfileNotFound)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profile_metadata_persists_after_reopening_database() {
|
||||||
|
let directory = tempfile::tempdir().expect("temporary directory");
|
||||||
|
let path = directory.path().join("profiles.sqlite3");
|
||||||
|
let expected = profile(7);
|
||||||
|
|
||||||
|
{
|
||||||
|
let store = ProfileMessageStore::open(&path).expect("open database");
|
||||||
|
store.create_profile(&expected).expect("create profile");
|
||||||
|
}
|
||||||
|
|
||||||
|
let reopened = ProfileMessageStore::open(&path).expect("reopen database");
|
||||||
|
let actual = reopened
|
||||||
|
.profile(&expected.id)
|
||||||
|
.expect("read profile")
|
||||||
|
.expect("persisted profile");
|
||||||
|
assert_eq!(actual, expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,11 +1,15 @@
|
||||||
pub mod database;
|
pub mod database;
|
||||||
pub mod diagnostics;
|
pub mod diagnostics;
|
||||||
pub mod file_transfer;
|
pub mod file_transfer;
|
||||||
|
pub mod logging;
|
||||||
pub mod networking;
|
pub mod networking;
|
||||||
|
pub mod profiles;
|
||||||
pub mod secure_store;
|
pub mod secure_store;
|
||||||
pub mod windows;
|
pub mod windows;
|
||||||
|
|
||||||
|
use database::ApplicationDatabase;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use tauri::{
|
use tauri::{
|
||||||
Manager, WindowEvent,
|
Manager, WindowEvent,
|
||||||
menu::{Menu, MenuItem},
|
menu::{Menu, MenuItem},
|
||||||
|
|
@ -16,30 +20,31 @@ use tauri::{
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct BootstrapStatus {
|
struct BootstrapStatus {
|
||||||
app_version: &'static str,
|
app_version: &'static str,
|
||||||
|
database_schema_version: u32,
|
||||||
platform: &'static str,
|
platform: &'static str,
|
||||||
rust_core: &'static str,
|
rust_core: &'static str,
|
||||||
protocol_version: &'static str,
|
protocol_version: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn bootstrap_status() -> BootstrapStatus {
|
fn bootstrap_status(
|
||||||
BootstrapStatus {
|
database: tauri::State<'_, ApplicationDatabase>,
|
||||||
|
) -> Result<BootstrapStatus, String> {
|
||||||
|
let database_schema_version = database
|
||||||
|
.schema_version()
|
||||||
|
.map_err(|_| "database status is unavailable".to_owned())?;
|
||||||
|
|
||||||
|
Ok(BootstrapStatus {
|
||||||
app_version: env!("CARGO_PKG_VERSION"),
|
app_version: env!("CARGO_PKG_VERSION"),
|
||||||
platform: "windows",
|
platform: "windows",
|
||||||
rust_core: "ready",
|
rust_core: "ready",
|
||||||
protocol_version: desktop_protocol::PROTOCOL_VERSION,
|
protocol_version: desktop_protocol::PROTOCOL_VERSION,
|
||||||
}
|
database_schema_version,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run() {
|
pub fn run() {
|
||||||
tracing_subscriber::fmt()
|
logging::init();
|
||||||
.with_env_filter(
|
|
||||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
|
||||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
|
||||||
)
|
|
||||||
.with_target(false)
|
|
||||||
.compact()
|
|
||||||
.init();
|
|
||||||
|
|
||||||
tauri::Builder::default()
|
tauri::Builder::default()
|
||||||
.plugin(tauri_plugin_single_instance::init(|app, _, _| {
|
.plugin(tauri_plugin_single_instance::init(|app, _, _| {
|
||||||
|
|
@ -49,6 +54,12 @@ pub fn run() {
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
|
let app_data_dir = app.path().app_data_dir()?;
|
||||||
|
std::fs::create_dir_all(&app_data_dir)?;
|
||||||
|
app.manage(ApplicationDatabase::open(
|
||||||
|
app_data_dir.join("astrbot-desktop.sqlite3"),
|
||||||
|
)?);
|
||||||
|
|
||||||
let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?;
|
let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?;
|
||||||
let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
|
let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
|
||||||
let menu = Menu::with_items(app, &[&show, &quit])?;
|
let menu = Menu::with_items(app, &[&show, &quit])?;
|
||||||
|
|
@ -75,7 +86,13 @@ pub fn run() {
|
||||||
let _ = window.hide();
|
let _ = window.hide();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![bootstrap_status])
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
bootstrap_status,
|
||||||
|
profiles::list_connection_profiles,
|
||||||
|
profiles::create_connection_profile,
|
||||||
|
profiles::update_connection_profile,
|
||||||
|
profiles::delete_connection_profile,
|
||||||
|
])
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("failed to run AstrBot Desktop");
|
.expect("failed to run AstrBot Desktop");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
170
src-tauri/src/logging.rs
普通文件
170
src-tauri/src/logging.rs
普通文件
|
|
@ -0,0 +1,170 @@
|
||||||
|
use std::io::{self, Write};
|
||||||
|
|
||||||
|
use tracing_subscriber::fmt::MakeWriter;
|
||||||
|
|
||||||
|
use crate::diagnostics::redaction::Redactor;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct RedactingMakeWriter<M> {
|
||||||
|
inner: M,
|
||||||
|
redactor: Redactor,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<M> RedactingMakeWriter<M> {
|
||||||
|
pub fn new(inner: M) -> Self {
|
||||||
|
Self {
|
||||||
|
inner,
|
||||||
|
redactor: Redactor::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn with_redactor(inner: M, redactor: Redactor) -> Self {
|
||||||
|
Self { inner, redactor }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'writer, M> MakeWriter<'writer> for RedactingMakeWriter<M>
|
||||||
|
where
|
||||||
|
M: MakeWriter<'writer>,
|
||||||
|
M::Writer: Write,
|
||||||
|
{
|
||||||
|
type Writer = RedactingWriter<M::Writer>;
|
||||||
|
|
||||||
|
fn make_writer(&'writer self) -> Self::Writer {
|
||||||
|
RedactingWriter {
|
||||||
|
inner: self.inner.make_writer(),
|
||||||
|
redactor: self.redactor.clone(),
|
||||||
|
buffer: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RedactingWriter<W: Write> {
|
||||||
|
inner: W,
|
||||||
|
redactor: Redactor,
|
||||||
|
buffer: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Write> RedactingWriter<W> {
|
||||||
|
fn flush_redacted(&mut self) -> io::Result<()> {
|
||||||
|
if self.buffer.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let rendered = String::from_utf8_lossy(&self.buffer);
|
||||||
|
let redacted = self.redactor.redact(&rendered);
|
||||||
|
self.inner.write_all(redacted.as_bytes())?;
|
||||||
|
self.buffer.clear();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Write> Write for RedactingWriter<W> {
|
||||||
|
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
|
||||||
|
self.buffer.extend_from_slice(buffer);
|
||||||
|
Ok(buffer.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
self.flush_redacted()?;
|
||||||
|
self.inner.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Write> Drop for RedactingWriter<W> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = self.flush_redacted();
|
||||||
|
let _ = self.inner.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init() {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(
|
||||||
|
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||||
|
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
||||||
|
)
|
||||||
|
.with_target(false)
|
||||||
|
.compact()
|
||||||
|
.with_writer(RedactingMakeWriter::new(std::io::stderr))
|
||||||
|
.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct SharedMakeWriter {
|
||||||
|
output: Arc<Mutex<Vec<u8>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SharedMakeWriter {
|
||||||
|
fn contents(&self) -> String {
|
||||||
|
String::from_utf8(self.output.lock().expect("output lock").clone())
|
||||||
|
.expect("UTF-8 output")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SharedWriter {
|
||||||
|
output: Arc<Mutex<Vec<u8>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Write for SharedWriter {
|
||||||
|
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
|
||||||
|
self.output
|
||||||
|
.lock()
|
||||||
|
.expect("output lock")
|
||||||
|
.extend_from_slice(buffer);
|
||||||
|
Ok(buffer.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'writer> MakeWriter<'writer> for SharedMakeWriter {
|
||||||
|
type Writer = SharedWriter;
|
||||||
|
|
||||||
|
fn make_writer(&'writer self) -> Self::Writer {
|
||||||
|
SharedWriter {
|
||||||
|
output: self.output.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn redacts_structured_fields_and_message_content_before_writing() {
|
||||||
|
let sink = SharedMakeWriter::default();
|
||||||
|
let known_secret = format!("canary-{}", uuid::Uuid::new_v4());
|
||||||
|
let subscriber = tracing_subscriber::fmt()
|
||||||
|
.without_time()
|
||||||
|
.with_ansi(false)
|
||||||
|
.with_target(false)
|
||||||
|
.with_writer(RedactingMakeWriter::with_redactor(
|
||||||
|
sink.clone(),
|
||||||
|
Redactor::new([&known_secret]),
|
||||||
|
))
|
||||||
|
.finish();
|
||||||
|
|
||||||
|
tracing::subscriber::with_default(subscriber, || {
|
||||||
|
tracing::info!(
|
||||||
|
password = "test-password",
|
||||||
|
authorization = "Bearer abcdefghijklmnop",
|
||||||
|
endpoint = "https://alice:password@example.test/path",
|
||||||
|
"known={known_secret}"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = sink.contents();
|
||||||
|
assert!(!output.contains("test-password"));
|
||||||
|
assert!(!output.contains("abcdefghijklmnop"));
|
||||||
|
assert!(!output.contains("alice:password"));
|
||||||
|
assert!(!output.contains(&known_secret));
|
||||||
|
assert!(output.contains(crate::diagnostics::redaction::REDACTED));
|
||||||
|
}
|
||||||
|
}
|
||||||
353
src-tauri/src/profiles.rs
普通文件
353
src-tauri/src/profiles.rs
普通文件
|
|
@ -0,0 +1,353 @@
|
||||||
|
use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||||
|
use url::Url;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::database::{ApplicationDatabase, DatabaseError};
|
||||||
|
|
||||||
|
const MAX_DISPLAY_NAME_CHARS: usize = 80;
|
||||||
|
const MAX_URL_CHARS: usize = 2048;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct ConnectionProfileInput {
|
||||||
|
pub display_name: String,
|
||||||
|
pub role: AstrBotProfileRole,
|
||||||
|
pub base_url: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub event_stream_url: Option<String>,
|
||||||
|
pub authentication_type: AuthenticationType,
|
||||||
|
#[serde(default)]
|
||||||
|
pub allow_insecure_http: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub pinned_certificate_fingerprint: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct UpdateConnectionProfileRequest {
|
||||||
|
pub id: String,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub profile: ConnectionProfileInput,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ProfileCommandError {
|
||||||
|
code: &'static str,
|
||||||
|
message: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProfileCommandError {
|
||||||
|
fn validation(message: &'static str) -> Self {
|
||||||
|
Self {
|
||||||
|
code: "validationFailed",
|
||||||
|
message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn database(error: DatabaseError) -> Self {
|
||||||
|
match error {
|
||||||
|
DatabaseError::ProfileNotFound => Self {
|
||||||
|
code: "notFound",
|
||||||
|
message: "The connection profile no longer exists.",
|
||||||
|
},
|
||||||
|
_ => Self {
|
||||||
|
code: "databaseUnavailable",
|
||||||
|
message: "The local profile database is unavailable.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn list_connection_profiles(
|
||||||
|
database: tauri::State<'_, ApplicationDatabase>,
|
||||||
|
) -> Result<Vec<ConnectionProfile>, ProfileCommandError> {
|
||||||
|
list_profiles(&database)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn create_connection_profile(
|
||||||
|
database: tauri::State<'_, ApplicationDatabase>,
|
||||||
|
request: ConnectionProfileInput,
|
||||||
|
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||||
|
create_profile(&database, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn update_connection_profile(
|
||||||
|
database: tauri::State<'_, ApplicationDatabase>,
|
||||||
|
request: UpdateConnectionProfileRequest,
|
||||||
|
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||||
|
update_profile(&database, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn delete_connection_profile(
|
||||||
|
database: tauri::State<'_, ApplicationDatabase>,
|
||||||
|
id: String,
|
||||||
|
) -> Result<(), ProfileCommandError> {
|
||||||
|
delete_profile(&database, &id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_profiles(
|
||||||
|
database: &ApplicationDatabase,
|
||||||
|
) -> Result<Vec<ConnectionProfile>, ProfileCommandError> {
|
||||||
|
database
|
||||||
|
.list_profiles()
|
||||||
|
.map_err(ProfileCommandError::database)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_profile(
|
||||||
|
database: &ApplicationDatabase,
|
||||||
|
request: ConnectionProfileInput,
|
||||||
|
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||||
|
let normalized = normalize_input(request)?;
|
||||||
|
let now = timestamp()?;
|
||||||
|
let profile = ConnectionProfile {
|
||||||
|
id: Uuid::new_v4().to_string(),
|
||||||
|
display_name: normalized.display_name,
|
||||||
|
role: normalized.role,
|
||||||
|
base_url: normalized.base_url,
|
||||||
|
event_stream_url: normalized.event_stream_url,
|
||||||
|
authentication_type: normalized.authentication_type,
|
||||||
|
credential_reference: None,
|
||||||
|
allow_insecure_http: normalized.allow_insecure_http,
|
||||||
|
pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint,
|
||||||
|
auto_connect_slot: None,
|
||||||
|
auto_connect: false,
|
||||||
|
server_instance_id: None,
|
||||||
|
server_version: None,
|
||||||
|
protocol_version: None,
|
||||||
|
local_tool_policy_id: None,
|
||||||
|
last_connected_at: None,
|
||||||
|
created_at: now.clone(),
|
||||||
|
updated_at: now,
|
||||||
|
};
|
||||||
|
database
|
||||||
|
.create_profile(&profile)
|
||||||
|
.map_err(ProfileCommandError::database)?;
|
||||||
|
Ok(profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_profile(
|
||||||
|
database: &ApplicationDatabase,
|
||||||
|
request: UpdateConnectionProfileRequest,
|
||||||
|
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||||
|
validate_id(&request.id)?;
|
||||||
|
let normalized = normalize_input(request.profile)?;
|
||||||
|
let mut profile = database
|
||||||
|
.profile(&request.id)
|
||||||
|
.map_err(ProfileCommandError::database)?
|
||||||
|
.ok_or_else(|| ProfileCommandError::database(DatabaseError::ProfileNotFound))?;
|
||||||
|
|
||||||
|
profile.display_name = normalized.display_name;
|
||||||
|
profile.role = normalized.role;
|
||||||
|
profile.base_url = normalized.base_url;
|
||||||
|
profile.event_stream_url = normalized.event_stream_url;
|
||||||
|
profile.authentication_type = normalized.authentication_type;
|
||||||
|
profile.allow_insecure_http = normalized.allow_insecure_http;
|
||||||
|
profile.pinned_certificate_fingerprint = normalized.pinned_certificate_fingerprint;
|
||||||
|
profile.updated_at = timestamp()?;
|
||||||
|
|
||||||
|
database
|
||||||
|
.update_profile(&profile)
|
||||||
|
.map_err(ProfileCommandError::database)?;
|
||||||
|
Ok(profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn delete_profile(database: &ApplicationDatabase, id: &str) -> Result<(), ProfileCommandError> {
|
||||||
|
validate_id(id)?;
|
||||||
|
database
|
||||||
|
.delete_profile(id)
|
||||||
|
.map_err(ProfileCommandError::database)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_input(
|
||||||
|
request: ConnectionProfileInput,
|
||||||
|
) -> Result<ConnectionProfileInput, ProfileCommandError> {
|
||||||
|
let display_name = request.display_name.trim().to_owned();
|
||||||
|
if display_name.is_empty()
|
||||||
|
|| display_name.chars().count() > MAX_DISPLAY_NAME_CHARS
|
||||||
|
|| display_name.chars().any(char::is_control)
|
||||||
|
{
|
||||||
|
return Err(ProfileCommandError::validation(
|
||||||
|
"Display name must contain 1 to 80 visible characters.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let base_url = normalize_url(&request.base_url, request.allow_insecure_http)?;
|
||||||
|
let event_stream_url = request
|
||||||
|
.event_stream_url
|
||||||
|
.as_deref()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(|value| normalize_url(value, request.allow_insecure_http))
|
||||||
|
.transpose()?;
|
||||||
|
let pinned_certificate_fingerprint =
|
||||||
|
normalize_fingerprint(request.pinned_certificate_fingerprint)?;
|
||||||
|
|
||||||
|
Ok(ConnectionProfileInput {
|
||||||
|
display_name,
|
||||||
|
role: request.role,
|
||||||
|
base_url,
|
||||||
|
event_stream_url,
|
||||||
|
authentication_type: request.authentication_type,
|
||||||
|
allow_insecure_http: request.allow_insecure_http,
|
||||||
|
pinned_certificate_fingerprint,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_url(value: &str, allow_insecure_http: bool) -> Result<String, ProfileCommandError> {
|
||||||
|
let value = value.trim();
|
||||||
|
if value.is_empty() || value.chars().count() > MAX_URL_CHARS {
|
||||||
|
return Err(ProfileCommandError::validation(
|
||||||
|
"Connection URL is empty or too long.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut url = Url::parse(value)
|
||||||
|
.map_err(|_| ProfileCommandError::validation("Connection URL is invalid."))?;
|
||||||
|
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||||
|
return Err(ProfileCommandError::validation(
|
||||||
|
"Connection URL must use HTTP or HTTPS and include a host.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !url.username().is_empty() || url.password().is_some() {
|
||||||
|
return Err(ProfileCommandError::validation(
|
||||||
|
"Credentials must not be embedded in a connection URL.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if url.query().is_some() || url.fragment().is_some() {
|
||||||
|
return Err(ProfileCommandError::validation(
|
||||||
|
"Connection URLs must not contain query parameters or fragments.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if url.scheme() == "http" && !allow_insecure_http {
|
||||||
|
return Err(ProfileCommandError::validation(
|
||||||
|
"HTTP requires explicit insecure-transport approval.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
url.set_fragment(None);
|
||||||
|
Ok(url.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_fingerprint(value: Option<String>) -> Result<Option<String>, ProfileCommandError> {
|
||||||
|
let Some(value) = value else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let normalized = value
|
||||||
|
.trim()
|
||||||
|
.chars()
|
||||||
|
.filter(|character| *character != ':')
|
||||||
|
.flat_map(char::to_uppercase)
|
||||||
|
.collect::<String>();
|
||||||
|
if normalized.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
if normalized.len() != 64
|
||||||
|
|| !normalized
|
||||||
|
.chars()
|
||||||
|
.all(|character| character.is_ascii_hexdigit())
|
||||||
|
{
|
||||||
|
return Err(ProfileCommandError::validation(
|
||||||
|
"Pinned certificate fingerprint must be a SHA-256 hex value.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(Some(normalized))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_id(id: &str) -> Result<(), ProfileCommandError> {
|
||||||
|
if Uuid::parse_str(id).is_err() {
|
||||||
|
return Err(ProfileCommandError::validation(
|
||||||
|
"Connection profile ID is invalid.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timestamp() -> Result<String, ProfileCommandError> {
|
||||||
|
OffsetDateTime::now_utc()
|
||||||
|
.format(&Rfc3339)
|
||||||
|
.map_err(|_| ProfileCommandError {
|
||||||
|
code: "clockUnavailable",
|
||||||
|
message: "The system clock could not produce a profile timestamp.",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn request(base_url: &str) -> ConnectionProfileInput {
|
||||||
|
ConnectionProfileInput {
|
||||||
|
display_name: " Test Profile ".into(),
|
||||||
|
role: AstrBotProfileRole::General,
|
||||||
|
base_url: base_url.into(),
|
||||||
|
event_stream_url: None,
|
||||||
|
authentication_type: AuthenticationType::DeviceToken,
|
||||||
|
allow_insecure_http: false,
|
||||||
|
pinned_certificate_fingerprint: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn creates_updates_lists_and_deletes_profile_metadata() {
|
||||||
|
let database = ApplicationDatabase::in_memory().expect("database");
|
||||||
|
let created =
|
||||||
|
create_profile(&database, request("https://example.test")).expect("create profile");
|
||||||
|
assert_eq!(created.display_name, "Test Profile");
|
||||||
|
assert_eq!(created.base_url, "https://example.test/");
|
||||||
|
assert!(created.credential_reference.is_none());
|
||||||
|
assert!(!created.auto_connect);
|
||||||
|
assert!(created.auto_connect_slot.is_none());
|
||||||
|
|
||||||
|
let updated = update_profile(
|
||||||
|
&database,
|
||||||
|
UpdateConnectionProfileRequest {
|
||||||
|
id: created.id.clone(),
|
||||||
|
profile: ConnectionProfileInput {
|
||||||
|
display_name: "Updated".into(),
|
||||||
|
role: AstrBotProfileRole::Companion,
|
||||||
|
base_url: "https://updated.example.test".into(),
|
||||||
|
event_stream_url: Some("https://updated.example.test/events".into()),
|
||||||
|
authentication_type: AuthenticationType::ApiKey,
|
||||||
|
allow_insecure_http: false,
|
||||||
|
pinned_certificate_fingerprint: None,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("update profile");
|
||||||
|
assert_eq!(updated.display_name, "Updated");
|
||||||
|
assert_eq!(list_profiles(&database).expect("list profiles").len(), 1);
|
||||||
|
|
||||||
|
delete_profile(&database, &created.id).expect("delete profile");
|
||||||
|
assert!(list_profiles(&database).expect("list profiles").is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_insecure_or_credential_bearing_urls() {
|
||||||
|
let database = ApplicationDatabase::in_memory().expect("database");
|
||||||
|
assert!(create_profile(&database, request("http://example.test")).is_err());
|
||||||
|
assert!(create_profile(&database, request("https://user:password@example.test")).is_err());
|
||||||
|
assert!(create_profile(&database, request("https://example.test?token=fake")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_secret_values_and_unknown_fields_at_the_ipc_boundary() {
|
||||||
|
let result = serde_json::from_value::<ConnectionProfileInput>(serde_json::json!({
|
||||||
|
"displayName": "Test Profile",
|
||||||
|
"role": "general",
|
||||||
|
"baseUrl": "https://example.test",
|
||||||
|
"authenticationType": "device-token",
|
||||||
|
"allowInsecureHttp": false,
|
||||||
|
"token": "[REDACTED]",
|
||||||
|
"password": "[REDACTED]",
|
||||||
|
"apiKey": "[REDACTED]"
|
||||||
|
}));
|
||||||
|
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "AstrBot Desktop",
|
"productName": "AstrBot Desktop",
|
||||||
"version": "0.1.0-alpha.0",
|
"version": "0.1.0-alpha.1",
|
||||||
"identifier": "com.yokiirobw.astrbot-desktop",
|
"identifier": "com.yokiirobw.astrbot-desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm run dev",
|
"beforeDevCommand": "npm run dev",
|
||||||
|
|
|
||||||
143
src/App.test.tsx
143
src/App.test.tsx
|
|
@ -1,20 +1,36 @@
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { render, screen } from "@testing-library/react";
|
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { App } from "./App";
|
import { App } from "./App";
|
||||||
|
import type {
|
||||||
|
ConnectionProfile,
|
||||||
|
ConnectionProfileInput,
|
||||||
|
UpdateConnectionProfileRequest,
|
||||||
|
} from "./types/profile";
|
||||||
|
|
||||||
vi.mock("@tauri-apps/api/core", () => ({
|
vi.mock("@tauri-apps/api/core", () => ({
|
||||||
invoke: vi.fn(),
|
invoke: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const bootstrapStatus = {
|
||||||
|
appVersion: "0.1.0-alpha.0",
|
||||||
|
platform: "windows",
|
||||||
|
rustCore: "ready",
|
||||||
|
protocolVersion: "desktop-v1alpha1",
|
||||||
|
databaseSchemaVersion: 2,
|
||||||
|
};
|
||||||
|
|
||||||
describe("App", () => {
|
describe("App", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.mocked(invoke).mockResolvedValue({
|
vi.mocked(invoke).mockImplementation(async (command) => {
|
||||||
appVersion: "0.1.0-alpha.0",
|
if (command === "bootstrap_status") {
|
||||||
platform: "windows",
|
return bootstrapStatus;
|
||||||
rustCore: "ready",
|
}
|
||||||
protocolVersion: "desktop-v1alpha1",
|
if (command === "list_connection_profiles") {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected command: ${command}`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -23,5 +39,120 @@ describe("App", () => {
|
||||||
|
|
||||||
expect(await screen.findByText("ready")).toBeInTheDocument();
|
expect(await screen.findByText("ready")).toBeInTheDocument();
|
||||||
expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument();
|
expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("连接 Profile")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an invalid Rust IPC payload", async () => {
|
||||||
|
vi.mocked(invoke).mockImplementation(async (command) => {
|
||||||
|
if (command === "bootstrap_status") {
|
||||||
|
return {
|
||||||
|
...bootstrapStatus,
|
||||||
|
rustCore: "unexpected",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (command === "list_connection_profiles") {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected command: ${command}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
render(<App />);
|
||||||
|
|
||||||
|
expect(await screen.findByText(/IPC unavailable:/)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText("unexpected")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("creates, edits, and deletes non-sensitive profile metadata", async () => {
|
||||||
|
let profiles: ConnectionProfile[] = [];
|
||||||
|
vi.mocked(invoke).mockImplementation(async (command, args) => {
|
||||||
|
if (command === "bootstrap_status") {
|
||||||
|
return bootstrapStatus;
|
||||||
|
}
|
||||||
|
if (command === "list_connection_profiles") {
|
||||||
|
return profiles;
|
||||||
|
}
|
||||||
|
if (command === "create_connection_profile") {
|
||||||
|
const { request } = args as { request: ConnectionProfileInput };
|
||||||
|
const created: ConnectionProfile = {
|
||||||
|
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
|
||||||
|
...request,
|
||||||
|
autoConnect: false,
|
||||||
|
createdAt: "2026-07-18T02:00:00Z",
|
||||||
|
updatedAt: "2026-07-18T02:00:00Z",
|
||||||
|
};
|
||||||
|
profiles = [created];
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
if (command === "update_connection_profile") {
|
||||||
|
const { request } = args as {
|
||||||
|
request: UpdateConnectionProfileRequest;
|
||||||
|
};
|
||||||
|
const existing = profiles.find((profile) => profile.id === request.id);
|
||||||
|
if (!existing) {
|
||||||
|
throw new Error("Profile not found");
|
||||||
|
}
|
||||||
|
const updated: ConnectionProfile = {
|
||||||
|
...existing,
|
||||||
|
...request.profile,
|
||||||
|
updatedAt: "2026-07-18T02:10:00Z",
|
||||||
|
};
|
||||||
|
profiles = [updated];
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
if (command === "delete_connection_profile") {
|
||||||
|
const { id } = args as { id: string };
|
||||||
|
profiles = profiles.filter((profile) => profile.id !== id);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected command: ${command}`);
|
||||||
|
});
|
||||||
|
vi.spyOn(window, "confirm").mockReturnValue(true);
|
||||||
|
|
||||||
|
render(<App />);
|
||||||
|
expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText("显示名称"), {
|
||||||
|
target: { value: "家庭运维" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText("角色"), {
|
||||||
|
target: { value: "operations" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText("REST 基础 URL"), {
|
||||||
|
target: { value: "https://ops.example.test" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "保存 Profile" }));
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await screen.findByText("已创建 Profile:家庭运维"),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(screen.getByLabelText("编辑 家庭运维")).toBeEnabled();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByLabelText("编辑 家庭运维"));
|
||||||
|
fireEvent.change(screen.getByLabelText("显示名称"), {
|
||||||
|
target: { value: "家庭运维(主)" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "更新 Profile" }));
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await screen.findByText("已更新 Profile:家庭运维(主)"),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByLabelText("删除 家庭运维(主)"));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(
|
||||||
|
screen.getByText("已删除 Profile:家庭运维(主)"),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
expect(screen.getByText("尚未保存 Profile。")).toBeInTheDocument();
|
||||||
|
expect(invoke).toHaveBeenCalledWith(
|
||||||
|
"create_connection_profile",
|
||||||
|
expect.objectContaining({
|
||||||
|
request: expect.not.objectContaining({
|
||||||
|
token: expect.anything(),
|
||||||
|
password: expect.anything(),
|
||||||
|
apiKey: expect.anything(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
15
src/App.tsx
15
src/App.tsx
|
|
@ -1,13 +1,15 @@
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
|
||||||
import type { BootstrapStatus } from "./types/bootstrap";
|
import { ProfileManager } from "./features/profiles/ProfileManager";
|
||||||
|
import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap";
|
||||||
|
|
||||||
const initialStatus: BootstrapStatus = {
|
const initialStatus: BootstrapStatus = {
|
||||||
appVersion: "unknown",
|
appVersion: "unknown",
|
||||||
platform: "unknown",
|
platform: "unknown",
|
||||||
rustCore: "pending",
|
rustCore: "pending",
|
||||||
protocolVersion: "desktop-v1alpha1",
|
protocolVersion: "desktop-v1alpha1",
|
||||||
|
databaseSchemaVersion: 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
|
|
@ -16,8 +18,8 @@ export function App() {
|
||||||
|
|
||||||
const refreshStatus = useCallback(async () => {
|
const refreshStatus = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const result = await invoke<BootstrapStatus>("bootstrap_status");
|
const result = await invoke<unknown>("bootstrap_status");
|
||||||
setStatus(result);
|
setStatus(bootstrapStatusSchema.parse(result));
|
||||||
setError(null);
|
setError(null);
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
setError(reason instanceof Error ? reason.message : String(reason));
|
setError(reason instanceof Error ? reason.message : String(reason));
|
||||||
|
|
@ -31,7 +33,7 @@ export function App() {
|
||||||
return (
|
return (
|
||||||
<main className="app-shell">
|
<main className="app-shell">
|
||||||
<header className="hero">
|
<header className="hero">
|
||||||
<p className="eyebrow">P00 · bootstrap</p>
|
<p className="eyebrow">P01 · foundation</p>
|
||||||
<h1>AstrBot Desktop</h1>
|
<h1>AstrBot Desktop</h1>
|
||||||
<p className="subtitle">
|
<p className="subtitle">
|
||||||
双实例陪伴与本机助手的安全 Windows 客户端工程底座。
|
双实例陪伴与本机助手的安全 Windows 客户端工程底座。
|
||||||
|
|
@ -44,6 +46,10 @@ export function App() {
|
||||||
<StatusCard label="App Version" value={status.appVersion} />
|
<StatusCard label="App Version" value={status.appVersion} />
|
||||||
<StatusCard label="Protocol" value={status.protocolVersion} />
|
<StatusCard label="Protocol" value={status.protocolVersion} />
|
||||||
</section>
|
</section>
|
||||||
|
<StatusCard
|
||||||
|
label="Database Schema"
|
||||||
|
value={String(status.databaseSchemaVersion)}
|
||||||
|
/>
|
||||||
|
|
||||||
{error ? <p className="error-banner">IPC unavailable: {error}</p> : null}
|
{error ? <p className="error-banner">IPC unavailable: {error}</p> : null}
|
||||||
|
|
||||||
|
|
@ -56,6 +62,7 @@ export function App() {
|
||||||
<li>文件事务默认保留源文件,且不会静默覆盖。</li>
|
<li>文件事务默认保留源文件,且不会静默覆盖。</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
<ProfileManager />
|
||||||
|
|
||||||
<button type="button" onClick={() => void refreshStatus()}>
|
<button type="button" onClick={() => void refreshStatus()}>
|
||||||
重新检查 IPC
|
重新检查 IPC
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,396 @@
|
||||||
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
connectionProfileListSchema,
|
||||||
|
connectionProfileSchema,
|
||||||
|
type AuthenticationType,
|
||||||
|
type ConnectionProfile,
|
||||||
|
type ConnectionProfileInput,
|
||||||
|
type ProfileRole,
|
||||||
|
type UpdateConnectionProfileRequest,
|
||||||
|
} from "../../types/profile";
|
||||||
|
|
||||||
|
interface ProfileFormState {
|
||||||
|
displayName: string;
|
||||||
|
role: ProfileRole;
|
||||||
|
baseUrl: string;
|
||||||
|
eventStreamUrl: string;
|
||||||
|
authenticationType: AuthenticationType;
|
||||||
|
allowInsecureHttp: boolean;
|
||||||
|
pinnedCertificateFingerprint: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyForm: ProfileFormState = {
|
||||||
|
displayName: "",
|
||||||
|
role: "general",
|
||||||
|
baseUrl: "https://",
|
||||||
|
eventStreamUrl: "",
|
||||||
|
authenticationType: "device-token",
|
||||||
|
allowInsecureHttp: false,
|
||||||
|
pinnedCertificateFingerprint: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ProfileManager() {
|
||||||
|
const [profiles, setProfiles] = useState<ConnectionProfile[]>([]);
|
||||||
|
const [form, setForm] = useState<ProfileFormState>(emptyForm);
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [notice, setNotice] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const loadProfiles = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const result = await invoke<unknown>("list_connection_profiles");
|
||||||
|
setProfiles(connectionProfileListSchema.parse(result));
|
||||||
|
setError(null);
|
||||||
|
} catch (reason) {
|
||||||
|
setError(`Profile storage unavailable: ${errorMessage(reason)}`);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadProfiles();
|
||||||
|
}, [loadProfiles]);
|
||||||
|
|
||||||
|
async function submitProfile(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setNotice(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const profileInput = toProfileInput(form);
|
||||||
|
const result = editingId
|
||||||
|
? await invoke<unknown>("update_connection_profile", {
|
||||||
|
request: {
|
||||||
|
id: editingId,
|
||||||
|
profile: profileInput,
|
||||||
|
} satisfies UpdateConnectionProfileRequest,
|
||||||
|
})
|
||||||
|
: await invoke<unknown>("create_connection_profile", {
|
||||||
|
request: profileInput,
|
||||||
|
});
|
||||||
|
const saved = connectionProfileSchema.parse(result);
|
||||||
|
setProfiles((current) =>
|
||||||
|
sortProfiles([
|
||||||
|
...current.filter((profile) => profile.id !== saved.id),
|
||||||
|
saved,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
setNotice(
|
||||||
|
editingId
|
||||||
|
? `已更新 Profile:${saved.displayName}`
|
||||||
|
: `已创建 Profile:${saved.displayName}`,
|
||||||
|
);
|
||||||
|
resetForm();
|
||||||
|
} catch (reason) {
|
||||||
|
setError(`Profile save failed: ${errorMessage(reason)}`);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function editProfile(profile: ConnectionProfile) {
|
||||||
|
setEditingId(profile.id);
|
||||||
|
setForm({
|
||||||
|
displayName: profile.displayName,
|
||||||
|
role: profile.role,
|
||||||
|
baseUrl: profile.baseUrl,
|
||||||
|
eventStreamUrl: profile.eventStreamUrl ?? "",
|
||||||
|
authenticationType: profile.authenticationType,
|
||||||
|
allowInsecureHttp: profile.allowInsecureHttp,
|
||||||
|
pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "",
|
||||||
|
});
|
||||||
|
setError(null);
|
||||||
|
setNotice(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteProfile(profile: ConnectionProfile) {
|
||||||
|
if (
|
||||||
|
!window.confirm(
|
||||||
|
`删除 Profile“${profile.displayName}”?此操作不会删除凭据值,因为 P01 不接触凭据。`,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setNotice(null);
|
||||||
|
try {
|
||||||
|
await invoke("delete_connection_profile", { id: profile.id });
|
||||||
|
setProfiles((current) =>
|
||||||
|
current.filter((item) => item.id !== profile.id),
|
||||||
|
);
|
||||||
|
if (editingId === profile.id) {
|
||||||
|
resetForm();
|
||||||
|
}
|
||||||
|
setNotice(`已删除 Profile:${profile.displayName}`);
|
||||||
|
} catch (reason) {
|
||||||
|
setError(`Profile deletion failed: ${errorMessage(reason)}`);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetForm() {
|
||||||
|
setEditingId(null);
|
||||||
|
setForm(emptyForm);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="profile-manager" aria-labelledby="profile-heading">
|
||||||
|
<div className="section-heading">
|
||||||
|
<div>
|
||||||
|
<p className="eyebrow">P01 · foundation</p>
|
||||||
|
<h2 id="profile-heading">连接 Profile</h2>
|
||||||
|
</div>
|
||||||
|
<p>
|
||||||
|
这里只管理非敏感连接元数据。Token、密码和 API Key 不会进入 React 或
|
||||||
|
SQLite 普通字段。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="profile-layout">
|
||||||
|
<form className="profile-form" onSubmit={submitProfile}>
|
||||||
|
<h3>{editingId ? "编辑 Profile" : "新建 Profile"}</h3>
|
||||||
|
|
||||||
|
<label>
|
||||||
|
<span>显示名称</span>
|
||||||
|
<input
|
||||||
|
name="displayName"
|
||||||
|
required
|
||||||
|
maxLength={80}
|
||||||
|
value={form.displayName}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((current) => ({
|
||||||
|
...current,
|
||||||
|
displayName: event.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label>
|
||||||
|
<span>角色</span>
|
||||||
|
<select
|
||||||
|
name="role"
|
||||||
|
value={form.role}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((current) => ({
|
||||||
|
...current,
|
||||||
|
role: event.target.value as ProfileRole,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="general">通用</option>
|
||||||
|
<option value="companion">陪伴</option>
|
||||||
|
<option value="operations">运维</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label>
|
||||||
|
<span>REST 基础 URL</span>
|
||||||
|
<input
|
||||||
|
name="baseUrl"
|
||||||
|
type="url"
|
||||||
|
required
|
||||||
|
value={form.baseUrl}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((current) => ({
|
||||||
|
...current,
|
||||||
|
baseUrl: event.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label>
|
||||||
|
<span>SSE URL(可选)</span>
|
||||||
|
<input
|
||||||
|
name="eventStreamUrl"
|
||||||
|
type="url"
|
||||||
|
value={form.eventStreamUrl}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((current) => ({
|
||||||
|
...current,
|
||||||
|
eventStreamUrl: event.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label>
|
||||||
|
<span>认证类型</span>
|
||||||
|
<select
|
||||||
|
name="authenticationType"
|
||||||
|
value={form.authenticationType}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((current) => ({
|
||||||
|
...current,
|
||||||
|
authenticationType: event.target.value as AuthenticationType,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="device-token">设备 Token</option>
|
||||||
|
<option value="api-key">API Key</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label>
|
||||||
|
<span>证书 SHA-256 指纹(可选)</span>
|
||||||
|
<input
|
||||||
|
name="pinnedCertificateFingerprint"
|
||||||
|
inputMode="text"
|
||||||
|
placeholder="64 位十六进制"
|
||||||
|
value={form.pinnedCertificateFingerprint}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((current) => ({
|
||||||
|
...current,
|
||||||
|
pinnedCertificateFingerprint: event.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="checkbox-field">
|
||||||
|
<input
|
||||||
|
name="allowInsecureHttp"
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.allowInsecureHttp}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((current) => ({
|
||||||
|
...current,
|
||||||
|
allowInsecureHttp: event.target.checked,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<span>明确允许不安全 HTTP(仅限受信任网络)</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<p className="form-note">
|
||||||
|
槽位分配、自动连接和连接切换保护将在 P02 实现。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="button-row">
|
||||||
|
<button type="submit" disabled={busy}>
|
||||||
|
{editingId ? "更新 Profile" : "保存 Profile"}
|
||||||
|
</button>
|
||||||
|
{editingId ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button-secondary"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={resetForm}
|
||||||
|
>
|
||||||
|
取消编辑
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className="profile-list" aria-label="已保存 Profile">
|
||||||
|
<h3>已保存 ({profiles.length})</h3>
|
||||||
|
{profiles.length === 0 ? (
|
||||||
|
<p className="empty-state">尚未保存 Profile。</p>
|
||||||
|
) : (
|
||||||
|
profiles.map((profile) => (
|
||||||
|
<article className="profile-card" key={profile.id}>
|
||||||
|
<div>
|
||||||
|
<strong>{profile.displayName}</strong>
|
||||||
|
<span>{roleLabel(profile.role)}</span>
|
||||||
|
</div>
|
||||||
|
<code>{profile.baseUrl}</code>
|
||||||
|
<p>
|
||||||
|
{profile.authenticationType === "api-key"
|
||||||
|
? "API Key 引用"
|
||||||
|
: "设备 Token 引用"}
|
||||||
|
{" · "}
|
||||||
|
{profile.credentialReference ? "已登记" : "待登记"}
|
||||||
|
</p>
|
||||||
|
<div className="button-row">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button-secondary"
|
||||||
|
disabled={busy}
|
||||||
|
aria-label={`编辑 ${profile.displayName}`}
|
||||||
|
onClick={() => editProfile(profile)}
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button-danger"
|
||||||
|
disabled={busy}
|
||||||
|
aria-label={`删除 ${profile.displayName}`}
|
||||||
|
onClick={() => void deleteProfile(profile)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{notice ? (
|
||||||
|
<p className="notice-banner" aria-live="polite">
|
||||||
|
{notice}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
{error ? (
|
||||||
|
<p className="error-banner" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toProfileInput(form: ProfileFormState): ConnectionProfileInput {
|
||||||
|
const eventStreamUrl = form.eventStreamUrl.trim();
|
||||||
|
const fingerprint = form.pinnedCertificateFingerprint.trim();
|
||||||
|
return {
|
||||||
|
displayName: form.displayName.trim(),
|
||||||
|
role: form.role,
|
||||||
|
baseUrl: form.baseUrl.trim(),
|
||||||
|
eventStreamUrl: eventStreamUrl || undefined,
|
||||||
|
authenticationType: form.authenticationType,
|
||||||
|
allowInsecureHttp: form.allowInsecureHttp,
|
||||||
|
pinnedCertificateFingerprint: fingerprint || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortProfiles(profiles: ConnectionProfile[]) {
|
||||||
|
return [...profiles].sort((left, right) =>
|
||||||
|
left.displayName.localeCompare(right.displayName, "zh-CN"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function roleLabel(role: ProfileRole) {
|
||||||
|
switch (role) {
|
||||||
|
case "companion":
|
||||||
|
return "陪伴";
|
||||||
|
case "operations":
|
||||||
|
return "运维";
|
||||||
|
case "general":
|
||||||
|
return "通用";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorMessage(reason: unknown) {
|
||||||
|
if (reason instanceof Error) {
|
||||||
|
return reason.message;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
typeof reason === "object" &&
|
||||||
|
reason !== null &&
|
||||||
|
"message" in reason &&
|
||||||
|
typeof reason.message === "string"
|
||||||
|
) {
|
||||||
|
return reason.message;
|
||||||
|
}
|
||||||
|
return String(reason);
|
||||||
|
}
|
||||||
190
src/styles.css
190
src/styles.css
|
|
@ -43,8 +43,13 @@ button:hover {
|
||||||
background: #204b88;
|
background: #204b88;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
button:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.58;
|
||||||
|
}
|
||||||
|
|
||||||
.app-shell {
|
.app-shell {
|
||||||
width: min(920px, calc(100% - 2rem));
|
width: min(1120px, calc(100% - 2rem));
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: 4rem 0;
|
padding: 4rem 0;
|
||||||
}
|
}
|
||||||
|
|
@ -123,6 +128,158 @@ h1 {
|
||||||
border-color: rgb(255 115 115 / 45%);
|
border-color: rgb(255 115 115 / 45%);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.profile-manager {
|
||||||
|
margin: 2rem 0;
|
||||||
|
padding: 1.5rem;
|
||||||
|
border: 1px solid rgb(137 175 232 / 28%);
|
||||||
|
border-radius: 1rem;
|
||||||
|
background: rgb(13 29 52 / 78%);
|
||||||
|
box-shadow: 0 1rem 3rem rgb(0 0 0 / 18%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-heading {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 0.8fr) minmax(280px, 1.2fr);
|
||||||
|
gap: 2rem;
|
||||||
|
align-items: end;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-heading h2,
|
||||||
|
.profile-form h3,
|
||||||
|
.profile-list h3 {
|
||||||
|
margin: 0.3rem 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-heading > p,
|
||||||
|
.form-note,
|
||||||
|
.empty-state,
|
||||||
|
.profile-card p {
|
||||||
|
color: #aebfda;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(300px, 0.95fr) minmax(320px, 1.05fr);
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-form,
|
||||||
|
.profile-list {
|
||||||
|
padding: 1.2rem;
|
||||||
|
border: 1px solid rgb(137 175 232 / 24%);
|
||||||
|
border-radius: 0.9rem;
|
||||||
|
background: rgb(7 18 34 / 52%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-form {
|
||||||
|
display: grid;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-form label:not(.checkbox-field) {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.45rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-form label > span {
|
||||||
|
color: #c7d4e9;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.72rem 0.8rem;
|
||||||
|
border: 1px solid rgb(137 175 232 / 38%);
|
||||||
|
border-radius: 0.65rem;
|
||||||
|
color: inherit;
|
||||||
|
background: #0b1b31;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus,
|
||||||
|
select:focus {
|
||||||
|
outline: 2px solid #6aa3ff;
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-field {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.7rem;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-field input {
|
||||||
|
width: auto;
|
||||||
|
margin-top: 0.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-note {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.65rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-secondary {
|
||||||
|
border-color: rgb(157 181 218 / 48%);
|
||||||
|
background: #20314b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-danger {
|
||||||
|
border-color: rgb(255 122 122 / 65%);
|
||||||
|
background: #5a2430;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-list {
|
||||||
|
display: grid;
|
||||||
|
align-content: start;
|
||||||
|
gap: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-card {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.7rem;
|
||||||
|
padding: 1rem;
|
||||||
|
border: 1px solid rgb(137 175 232 / 22%);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
background: rgb(20 42 72 / 72%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-card > div:first-child {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-card span {
|
||||||
|
color: #8db9ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-card code {
|
||||||
|
color: #dbe8ff;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-card p {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notice-banner {
|
||||||
|
padding: 1rem;
|
||||||
|
border: 1px solid rgb(96 211 153 / 42%);
|
||||||
|
border-radius: 0.8rem;
|
||||||
|
color: #c8f7dc;
|
||||||
|
background: rgb(20 83 57 / 45%);
|
||||||
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: light) {
|
@media (prefers-color-scheme: light) {
|
||||||
:root {
|
:root {
|
||||||
color: #102039;
|
color: #102039;
|
||||||
|
|
@ -141,10 +298,17 @@ h1 {
|
||||||
|
|
||||||
.status-card,
|
.status-card,
|
||||||
.boundaries,
|
.boundaries,
|
||||||
|
.profile-manager,
|
||||||
.error-banner {
|
.error-banner {
|
||||||
background: rgb(255 255 255 / 86%);
|
background: rgb(255 255 255 / 86%);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.profile-form,
|
||||||
|
.profile-list,
|
||||||
|
.profile-card {
|
||||||
|
background: rgb(245 249 255 / 90%);
|
||||||
|
}
|
||||||
|
|
||||||
.status-card strong {
|
.status-card strong {
|
||||||
color: #102039;
|
color: #102039;
|
||||||
}
|
}
|
||||||
|
|
@ -153,4 +317,28 @@ h1 {
|
||||||
.subtitle {
|
.subtitle {
|
||||||
color: #405775;
|
color: #405775;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
select {
|
||||||
|
color: #102039;
|
||||||
|
background: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-heading > p,
|
||||||
|
.form-note,
|
||||||
|
.empty-state,
|
||||||
|
.profile-card p {
|
||||||
|
color: #405775;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.section-heading,
|
||||||
|
.profile-layout {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-shell {
|
||||||
|
padding: 2rem 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1 +1,8 @@
|
||||||
import "@testing-library/jest-dom/vitest";
|
import "@testing-library/jest-dom/vitest";
|
||||||
|
|
||||||
|
import { cleanup } from "@testing-library/react";
|
||||||
|
import { afterEach } from "vitest";
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,13 @@
|
||||||
export interface BootstrapStatus {
|
import { z } from "zod";
|
||||||
appVersion: string;
|
|
||||||
platform: string;
|
export const bootstrapStatusSchema = z
|
||||||
rustCore: "ready" | "pending";
|
.object({
|
||||||
protocolVersion: string;
|
appVersion: z.string().min(1),
|
||||||
}
|
platform: z.string().min(1),
|
||||||
|
rustCore: z.enum(["ready", "pending"]),
|
||||||
|
protocolVersion: z.string().min(1),
|
||||||
|
databaseSchemaVersion: z.number().int().positive(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
export type BootstrapStatus = z.infer<typeof bootstrapStatusSchema>;
|
||||||
|
|
|
||||||
54
src/types/profile.ts
普通文件
54
src/types/profile.ts
普通文件
|
|
@ -0,0 +1,54 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const profileRoleSchema = z.enum(["companion", "operations", "general"]);
|
||||||
|
|
||||||
|
export const authenticationTypeSchema = z.enum(["device-token", "api-key"]);
|
||||||
|
|
||||||
|
const optionalIdentifier = z.string().min(1).optional();
|
||||||
|
|
||||||
|
export const connectionProfileSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.uuid(),
|
||||||
|
displayName: z.string().min(1).max(80),
|
||||||
|
role: profileRoleSchema,
|
||||||
|
baseUrl: z.url(),
|
||||||
|
eventStreamUrl: z.url().optional(),
|
||||||
|
authenticationType: authenticationTypeSchema,
|
||||||
|
credentialReference: optionalIdentifier,
|
||||||
|
allowInsecureHttp: z.boolean(),
|
||||||
|
pinnedCertificateFingerprint: z
|
||||||
|
.string()
|
||||||
|
.regex(/^[A-F0-9]{64}$/)
|
||||||
|
.optional(),
|
||||||
|
autoConnectSlot: z.enum(["companion", "operations"]).optional(),
|
||||||
|
autoConnect: z.boolean(),
|
||||||
|
serverInstanceId: optionalIdentifier,
|
||||||
|
serverVersion: optionalIdentifier,
|
||||||
|
protocolVersion: optionalIdentifier,
|
||||||
|
localToolPolicyId: optionalIdentifier,
|
||||||
|
lastConnectedAt: optionalIdentifier,
|
||||||
|
createdAt: z.string().min(1),
|
||||||
|
updatedAt: z.string().min(1),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
export const connectionProfileListSchema = z.array(connectionProfileSchema);
|
||||||
|
|
||||||
|
export type ProfileRole = z.infer<typeof profileRoleSchema>;
|
||||||
|
export type AuthenticationType = z.infer<typeof authenticationTypeSchema>;
|
||||||
|
export type ConnectionProfile = z.infer<typeof connectionProfileSchema>;
|
||||||
|
|
||||||
|
export interface ConnectionProfileInput {
|
||||||
|
displayName: string;
|
||||||
|
role: ProfileRole;
|
||||||
|
baseUrl: string;
|
||||||
|
eventStreamUrl?: string;
|
||||||
|
authenticationType: AuthenticationType;
|
||||||
|
allowInsecureHttp: boolean;
|
||||||
|
pinnedCertificateFingerprint?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateConnectionProfileRequest {
|
||||||
|
id: string;
|
||||||
|
profile: ConnectionProfileInput;
|
||||||
|
}
|
||||||
|
|
@ -12,5 +12,13 @@ test("renders the bootstrap shell and safe browser fallback", async ({
|
||||||
await expect(
|
await expect(
|
||||||
page.getByText("IPC unavailable:", { exact: false }),
|
page.getByText("IPC unavailable:", { exact: false }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
await expect(page.getByRole("button")).toBeEnabled();
|
await expect(
|
||||||
|
page.getByRole("heading", { name: "连接 Profile" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByText("Profile storage unavailable:", { exact: false }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByRole("button", { name: "重新检查 IPC" }),
|
||||||
|
).toBeEnabled();
|
||||||
});
|
});
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用