Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05abfdfc4e | ||
|
|
a5860a70f0 | ||
|
|
d82f2d45e5
|
||
|
|
64ddbebde3
|
||
|
|
f7bbe53f96
|
||
|
|
0f2f2be5d4 | ||
|
|
f781690b5f
|
||
|
|
ee557ab532
|
||
|
|
6d4843465a
|
||
|
|
23adc8ef6d
|
||
|
|
c205dd0589
|
||
|
|
4349dddd43
|
||
|
|
b204f48a0e
|
||
|
|
62d7178eab
|
||
|
|
48fd03983f
|
||
|
|
4a4e887134
|
||
|
|
694d98388e
|
||
|
|
81657aa058
|
||
|
|
37950a05ff
|
||
|
|
d7f816c7c8 | ||
|
|
d2dcebc6dd
|
||
|
|
304693cfa0
|
||
|
|
db35bd70af
|
||
|
|
66415bbd61
|
||
|
|
6157c53d55
|
||
|
|
b4cbf68cce
|
||
|
|
3fc7f0edf2
|
||
|
|
1f89545e30
|
||
|
|
e2f001baf7 | ||
|
|
c65a5aa021 | ||
|
|
4d9e70e599 | ||
|
|
ca82bae016 | ||
|
|
c424a400f6 | ||
|
|
c972606014 | ||
|
|
b80842a77c | ||
|
|
b4bc97eb97 | ||
|
|
b9cedcc160 | ||
|
|
c98dd4ded9 | ||
|
|
6df370ec68 | ||
|
|
a587db3774 | ||
|
|
906170f4eb | ||
|
|
dfac11c964 | ||
|
|
a592a64058 | ||
|
|
a941710b29 | ||
|
|
bf10498fc0 | ||
|
|
612f191ce7 | ||
|
|
e084a6d636 | ||
|
|
25e6064d38 | ||
|
|
0ac6e067ee | ||
|
|
873f1e8fea | ||
|
|
43f94f1b65 | ||
|
|
bfc1b8c219 | ||
|
|
4c1be876f7 | ||
|
|
fa2bc278ce | ||
|
|
1bd91115d8 | ||
|
|
d9af1c5fcb | ||
|
|
dec3efaf68 | ||
|
|
1732f9371c | ||
|
|
ee90b5b746 | ||
|
|
200645e623 | ||
|
|
52aad7d7ff | ||
|
|
279aa3a24c | ||
|
|
de3ed23687 | ||
|
|
68e62f3f22 | ||
|
|
5126561937 | ||
|
|
c386021b81 | ||
|
|
594499d604 | ||
|
|
bc132b82e6 | ||
|
|
f1f974768b | ||
|
|
17d5a5cc19 | ||
|
|
60774a59c6 | ||
|
|
9332722997 | ||
|
|
3c20113651 | ||
|
|
fc985d259a | ||
|
|
a371cd1e48 | ||
|
|
3713c8189a | ||
|
|
ad91973a3f | ||
|
|
ef83c88083 |
No files matched your search
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"vpk": {
|
||||
"version": "1.2.161",
|
||||
"commands": [
|
||||
"vpk"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,10 @@ behavior that violates
|
||||
[GitHub's Acceptable Use Policies](https://docs.github.com/site-policy/acceptable-use-policies)
|
||||
are not tolerated in this project's spaces (issues, pull requests, discussions, and comments).
|
||||
|
||||
Please read the full text linked above. To report unacceptable behavior, contact the maintainer
|
||||
via [GitHub private vulnerability reporting](https://github.com/poli0981/CommandForge/security/advisories/new)
|
||||
or by opening a minimal issue asking for a private contact channel (do not include sensitive
|
||||
details in a public issue).
|
||||
Please read the full text linked above.
|
||||
|
||||
## Reporting
|
||||
|
||||
To report unacceptable behavior, email **[code@poli0981.dev](mailto:code@poli0981.dev)**. Reports
|
||||
are handled privately; don't put sensitive details in a public issue. You can also use GitHub's
|
||||
**Report content** option on the comment or issue concerned.
|
||||
+51
-10
@@ -6,33 +6,73 @@ opening an issue or pull request.
|
||||
|
||||
## Quick start
|
||||
|
||||
Requires Windows 10 22H2 / 11 and the .NET 10 SDK.
|
||||
|
||||
```bash
|
||||
dotnet restore
|
||||
dotnet build -c Release # must be 0 warnings (warnings are errors)
|
||||
dotnet test # all tests must pass
|
||||
dotnet format # match the code style
|
||||
dotnet build -c Release # must be 0 warnings (warnings are errors)
|
||||
dotnet test # all tests must pass
|
||||
dotnet format --verify-no-changes # match the code style (run `dotnet format` to fix)
|
||||
```
|
||||
|
||||
See [BUILD.md](../BUILD.md) for publish/packaging.
|
||||
See [BUILD.md](../BUILD.md) for packaging and CI.
|
||||
|
||||
## Reporting issues
|
||||
|
||||
- Use the issue templates (Bug report / Feature request).
|
||||
- **Get straight to the point**: what you expected, what happened, exact steps, your Windows
|
||||
version/build and the app version (Settings → About).
|
||||
version/build and the app version (**More → About** in the app).
|
||||
- For **security vulnerabilities, do NOT open a public issue** — see [SECURITY.md](SECURITY.md).
|
||||
- Questions and ideas: [Discussions](https://github.com/poli0981/CommandForge/discussions), or
|
||||
email [code@poli0981.dev](mailto:code@poli0981.dev).
|
||||
|
||||
## Pull requests
|
||||
|
||||
- Keep PRs **focused and small**; one logical change per PR.
|
||||
- Match existing style; run `dotnet format` and keep the build at **0 warnings**.
|
||||
- Match existing style; run `dotnet format` and keep the build at **0 warnings** (analyzers,
|
||||
including SonarAnalyzer, run as part of the build).
|
||||
- **Don't delete or disable tests** to make CI pass; add tests for new behavior.
|
||||
- **Adding a command?** Add it to the catalog JSON (`Infrastructure/Catalog/commands.json`) per
|
||||
the schema, add the EN/VI resource strings, and keep `requiresAdmin`/`dangerLevel` accurate.
|
||||
Never add a code path that runs arbitrary commands or self-elevates outside the vetted catalog.
|
||||
- **Sign your commits** (GPG, SSH or S/MIME) — `main` only accepts verified signatures. Commit
|
||||
messages follow [Conventional Commits](https://www.conventionalcommits.org/)
|
||||
(`fix(catalog): …`, `feat(ui): …`).
|
||||
- PRs need the required checks to pass: `build`, `package`, CodeQL (`Analyze (csharp)`,
|
||||
`Analyze (actions)`) and `dependency-review`.
|
||||
- **Dependencies:** package versions live in each `.csproj` (GitHub's dependency graph doesn't read
|
||||
`Directory.Packages.props`). Discuss a new package before adding it; runtime dependencies must be
|
||||
GPLv3-compatible (dependency review enforces a license allow-list).
|
||||
- **UI text** goes in the `.resx` files, never hardcoded, and every key needs a value in all five
|
||||
languages: `Strings.resx` (English), `Strings.vi.resx`, `Strings.ja.resx`, `Strings.zh-Hans.resx`
|
||||
and `Strings.es.resx`. A test fails when a key the UI uses is missing from any of them.
|
||||
Machine-translated text is fine if you say so; native-speaker fixes are very welcome.
|
||||
- **Disclose AI assistance.** AI-assisted contributions are welcome — just say so in the PR
|
||||
description.
|
||||
|
||||
### Adding a command
|
||||
|
||||
Commands live only in the embedded catalog,
|
||||
`src/CommandForge.Infrastructure/Catalog/commands.json`. Never add a code path that runs arbitrary
|
||||
commands or elevates outside the vetted catalog.
|
||||
|
||||
- Give it a unique `id`, a `categoryId` from `categories.json`, and `titleKey`/`descriptionKey`
|
||||
strings in all five languages.
|
||||
- Keep `requiresAdmin` and `dangerLevel` accurate:
|
||||
- **Safe** — no risk of losing data: read-only queries, opening a tool or settings page, or a
|
||||
small preference change that is undone the same way it was made.
|
||||
- **Caution** — changes system state (services, registry, caches, boot-time checks);
|
||||
recoverable, but undoing it may take effort.
|
||||
- **Dangerous** — may lose data, remove a rollback option or leave Windows unstable.
|
||||
|
||||
Caution and Dangerous commands need `"confirmBeforeRun": true`.
|
||||
- `executable` is a plain program name (it is resolved to a trusted absolute path). PowerShell
|
||||
commands must pass `-NoProfile -NonInteractive`.
|
||||
- Use the `{SystemDrive}`, `{SystemRoot}` and `{UserProfile}` placeholders instead of hard-coded
|
||||
paths or `%VARIABLES%`.
|
||||
- Use `minOsBuild` / `maxOsBuild` for commands that only exist on some Windows builds, and
|
||||
`revertCommandId` when another catalog command undoes this one.
|
||||
- The `icon` name must be mapped in `src/CommandForge.Wpf/Converters/IconMap.cs`.
|
||||
|
||||
The catalog tests check these rules, and the app's loader rejects invalid records.
|
||||
|
||||
## AI-assisted contributions
|
||||
|
||||
AI tools are welcome for writing and reviewing changes **when disclosed**. What is *not*
|
||||
@@ -63,7 +103,8 @@ ban — no exceptions:
|
||||
## Conduct
|
||||
|
||||
By participating you agree to the [Code of Conduct](CODE_OF_CONDUCT.md). Be respectful; do not
|
||||
use the project or its spaces to attack, insult, or harass others.
|
||||
use the project or its spaces to attack, insult, or harass others. Report problems to
|
||||
[code@poli0981.dev](mailto:code@poli0981.dev).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ body:
|
||||
id: app-version
|
||||
attributes:
|
||||
label: CommandForge version
|
||||
description: Settings → About (e.g. 1.0.0)
|
||||
description: More (⋯) → About, or Settings → About (e.g. 2.0.0)
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
|
||||
@@ -15,7 +15,9 @@ Do NOT delete tests or use --no-verify to bypass hooks.
|
||||
|
||||
- [ ] `dotnet build -c Release` passes with **0 warnings**
|
||||
- [ ] `dotnet test` passes (and I added/updated tests for new behavior)
|
||||
- [ ] `dotnet format` applied; no unrelated reformatting
|
||||
- [ ] `dotnet format --verify-no-changes` passes; no unrelated reformatting
|
||||
- [ ] No tests deleted/disabled; hooks not bypassed (`--no-verify` not used)
|
||||
- [ ] If I added a command: it's a vetted catalog entry with correct `requiresAdmin`/`dangerLevel`, EN+VI strings, and no arbitrary-execution path
|
||||
- [ ] My commits are signed (`main` requires verified signatures)
|
||||
- [ ] New or changed UI text is in all five `Strings*.resx` files (EN, VI, JA, zh-Hans, ES) — no hardcoded strings
|
||||
- [ ] If I added a command: it's a vetted catalog entry with correct `requiresAdmin`/`dangerLevel`, strings in all five languages, and no arbitrary-execution path
|
||||
- [ ] **AI disclosure:** I have disclosed any AI assistance used (delete if none)
|
||||
+81
-25
@@ -1,48 +1,104 @@
|
||||
# Security Policy
|
||||
|
||||
CommandForge runs system-level commands, some elevated, so security is a top priority.
|
||||
CommandForge runs system-level commands, some as administrator, so security is a top priority.
|
||||
|
||||
## Supported versions
|
||||
|
||||
| Version | Supported |
|
||||
|---|---|
|
||||
| 2.0.x (latest) | ✅ |
|
||||
| < 2.0 | ❌ — please update |
|
||||
|
||||
Only the **latest release** receives security fixes. Please update before reporting.
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
**Do not open a public issue for security vulnerabilities.**
|
||||
**Do not open a public issue for security vulnerabilities.** Report privately in either of these ways:
|
||||
|
||||
Use **[GitHub private vulnerability reporting](https://github.com/poli0981/CommandForge/security/advisories/new)**
|
||||
(Security → Advisories → Report a vulnerability). Include:
|
||||
- **[GitHub private vulnerability reporting](https://github.com/poli0981/CommandForge/security/advisories/new)**
|
||||
(Security → Advisories → Report a vulnerability) — preferred, or
|
||||
- **email: [security@poli0981.dev](mailto:security@poli0981.dev)**.
|
||||
|
||||
- affected version (Settings → About),
|
||||
Please include:
|
||||
|
||||
- the affected version (More → About in the app),
|
||||
- steps to reproduce,
|
||||
- impact.
|
||||
- the impact you observed or expect.
|
||||
|
||||
We aim to acknowledge reports within a reasonable time and will credit reporters who wish to be
|
||||
named. Please give us a reasonable window to fix before any public disclosure.
|
||||
named. Please give us a reasonable window to fix the issue before any public disclosure.
|
||||
|
||||
## Security model (summary)
|
||||
## Security model
|
||||
|
||||
- **Vetted, read-only catalog.** Every runnable command is in an embedded, maintainer-reviewed
|
||||
catalog. The app never loads arbitrary commands from files/users/network and self-elevates.
|
||||
- **Least privilege.** The UI runs `asInvoker` (non-elevated). Only a separate `Elevator` helper
|
||||
runs as Administrator, and only when needed (one UAC prompt per session). The Elevator accepts
|
||||
only a `commandId` validated against its own embedded catalog — never an arbitrary command
|
||||
string over the pipe.
|
||||
- **Transparency.** The exact command line is shown before it runs.
|
||||
- **No telemetry.** The only network call is the GitHub update check.
|
||||
CommandForge guards the line between your normal (non-elevated) session and administrator rights:
|
||||
no file, setting, network response or other program running as you should be able to decide what
|
||||
runs elevated.
|
||||
|
||||
## Code signing & distribution integrity
|
||||
- **Vetted, read-only catalog.** Every command that can run as administrator is in a catalog that
|
||||
is built into the app and reviewed by the maintainer. The app never loads catalog commands from
|
||||
files, users or the network. When the catalog loads, contradictory or unsafe records are rejected
|
||||
(for example, unknown placeholders, or a Caution/Dangerous command without a confirmation).
|
||||
- **Least privilege.** The UI runs as the invoking user (`asInvoker`). Admin commands go to a
|
||||
separate helper, `CommandForge.Elevator`, which starts with one UAC prompt per session; you can
|
||||
end the session at any time. The helper accepts only a **command ID**, which it looks up in its
|
||||
own copy of the catalog — never a command line.
|
||||
- **Authenticated channel.** The named pipe has a random name and an access list for your account
|
||||
only, and each end verifies the other: the app accepts only the helper process it launched, and
|
||||
the helper serves only `CommandForge.Wpf.exe` from its own folder. The helper connects with
|
||||
Identification-level impersonation and writes no files; its diagnostics travel back to the app's
|
||||
log through the pipe.
|
||||
- **Trusted paths and environment.** Catalog programs resolve to absolute paths in `System32` or
|
||||
the Windows folder, never through a search of the per-user app folder. Elevated commands get an
|
||||
environment rebuilt from trusted sources (the system directory, known folders, HKLM), so per-user
|
||||
variables such as `PSModulePath`, `COR_PROFILER`, `SystemRoot` or `windir` can't redirect what an
|
||||
elevated command loads or deletes. The `{SystemDrive}`, `{SystemRoot}` and `{UserProfile}`
|
||||
placeholders in the catalog are filled from the same trusted values, and PowerShell always runs
|
||||
with `-NoProfile -NonInteractive`. The helper ignores `DOTNET_STARTUP_HOOKS`.
|
||||
- **Your own commands stay unprivileged.** Commands you add under *My commands* are stored apart
|
||||
from the catalog and always run without administrator rights.
|
||||
- **Transparency and confirmation.** The exact command line is shown before it runs. Caution
|
||||
commands ask first; Dangerous commands require typing the command's name or ID, and that check
|
||||
can't be turned off. A System Restore Point can be created first.
|
||||
- **Containment.** Commands whose output is captured run in a kill-on-close job object, so closing
|
||||
or crashing the app doesn't leave them running.
|
||||
- **No telemetry.** The only network connection the app makes is the GitHub update check (see
|
||||
[PRIVACY.md](../PRIVACY.md)).
|
||||
|
||||
Releases are **not code-signed yet**, so SmartScreen may warn "unknown publisher" and some AV
|
||||
engines may show false positives (common for admin tools). Mitigations:
|
||||
### Known limitations
|
||||
|
||||
- We **do not obfuscate** (obfuscation is a leading cause of AV false positives).
|
||||
- Every release publishes **SHA-256 checksums** (`checksums.txt`) and a **VirusTotal** link in the
|
||||
release notes.
|
||||
- The source is public (GPLv3) and CI runs **CodeQL** on every change.
|
||||
- **Per-user installation.** Velopack installs the app under `%LocalAppData%\CommandForge`, a
|
||||
folder your account can write to. Malware already running as you could replace the app's files —
|
||||
including the elevated helper — and wait for you to approve the next UAC prompt. This applies to
|
||||
every per-user app (UAC does not separate programs running as the same user), and since releases
|
||||
aren't Authenticode-signed yet, the UAC prompt can't show a verified publisher either. Keep
|
||||
untrusted software off your account, and approve the prompt only right after you started an
|
||||
admin command and it names `CommandForge.Elevator`.
|
||||
- **winget** is an App Execution Alias in `%LocalAppData%\Microsoft\WindowsApps`, another per-user
|
||||
folder. The catalog's winget commands start it from there, including the ones that run as
|
||||
administrator, so the same caveat applies.
|
||||
- **Commands do what they say.** Commands you choose to run can change system settings, use the
|
||||
network (winget, DNS tests…) or delete data by design; read the preview and see
|
||||
[DISCLAIMER.md](../DISCLAIMER.md).
|
||||
|
||||
Code signing (Azure Trusted Signing, or SignPath Foundation for OSS) is planned for a future
|
||||
release.
|
||||
## Distribution integrity
|
||||
|
||||
Releases are **not Authenticode-signed yet**, so SmartScreen may warn about an unknown publisher
|
||||
and some antivirus engines may show false positives (common for admin tools). Instead:
|
||||
|
||||
- Every release is built by GitHub Actions from a tagged commit and carries **build-provenance
|
||||
attestations** for the installer and packages. Verify a download with
|
||||
`gh attestation verify <file> --repo poli0981/CommandForge`.
|
||||
- **SHA-256 checksums** (`checksums.txt`), an **SPDX SBOM** (`sbom.spdx.json`) and **VirusTotal**
|
||||
scan links come with every release.
|
||||
- The code is **not obfuscated** (obfuscation is a leading cause of false positives), and the
|
||||
source is public under the GPLv3.
|
||||
- CI runs **CodeQL** (C# and GitHub Actions), **dependency review**, **OpenSSF Scorecard**,
|
||||
**SonarCloud** and **Snyk**; every restore audits direct and transitive NuGet packages;
|
||||
Dependabot keeps dependencies and the SHA-pinned actions current; `main` only accepts pull
|
||||
requests that pass the required checks.
|
||||
|
||||
Code signing (Azure Trusted Signing, or SignPath Foundation for open source) is planned for a
|
||||
future release.
|
||||
|
||||
## Malicious contributions
|
||||
|
||||
|
||||
@@ -4,14 +4,47 @@ updates:
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 5
|
||||
commit-message:
|
||||
prefix: "deps"
|
||||
labels: ["dependencies", "nuget"]
|
||||
cooldown:
|
||||
default-days: 3
|
||||
semver-major-days: 14
|
||||
groups:
|
||||
microsoft-extensions:
|
||||
patterns: ["Microsoft.Extensions.*"]
|
||||
serilog:
|
||||
patterns: ["Serilog*"]
|
||||
# The Velopack library and the vpk CLI (.config/dotnet-tools.json) must move together.
|
||||
velopack:
|
||||
patterns: ["Velopack", "vpk"]
|
||||
testing:
|
||||
patterns: ["xunit*", "Microsoft.NET.Test.Sdk", "coverlet.*"]
|
||||
build-tooling:
|
||||
patterns: ["SonarAnalyzer.CSharp", "Microsoft.Windows.CsWin32"]
|
||||
|
||||
- package-ecosystem: dotnet-sdk
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
commit-message:
|
||||
prefix: "build"
|
||||
labels: ["dependencies", "dotnet-sdk"]
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 5
|
||||
commit-message:
|
||||
prefix: "ci"
|
||||
labels: ["dependencies", "github-actions"]
|
||||
cooldown:
|
||||
default-days: 3
|
||||
groups:
|
||||
actions:
|
||||
patterns: ["*"]
|
||||
@@ -1,9 +1,10 @@
|
||||
name: Announce Release
|
||||
|
||||
# Posts a release announcement to Discord (reuses the shared workflow in poli0981/.github).
|
||||
# Requires repo/org secret DISCORD_RELEASES_WEBHOOK (or DISCORD_REPO_WEBHOOK); optional
|
||||
# DISCORD_PING_ROLE_ID. No-op effect if those secrets are unset (the job will error — set them
|
||||
# or disable this workflow).
|
||||
# Tag releases are announced by release.yml itself (a release published with GITHUB_TOKEN does
|
||||
# not fire the `release` event); this workflow covers releases published by hand and re-runs.
|
||||
# Requires repo secret DISCORD_RELEASES_WEBHOOK (or DISCORD_REPO_WEBHOOK); optional
|
||||
# DISCORD_PING_ROLE_ID.
|
||||
|
||||
on:
|
||||
release:
|
||||
@@ -11,10 +12,13 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Release tag to announce (e.g. v0.3.0)
|
||||
description: Release tag to announce (e.g. v2.0.0)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
announce:
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
|
||||
@@ -10,18 +10,37 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
DOTNET_NOLOGO: true
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: true
|
||||
NUGET_PACKAGES: ${{ github.workspace }}/.nuget/packages
|
||||
|
||||
jobs:
|
||||
build:
|
||||
# WPF (net10.0-windows) only builds on Windows.
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-dotnet@v5
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
persist-credentials: false
|
||||
|
||||
- name: Restore
|
||||
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
|
||||
with:
|
||||
global-json-file: global.json
|
||||
|
||||
- name: Cache NuGet packages
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ${{ env.NUGET_PACKAGES }}
|
||||
key: nuget-${{ runner.os }}-${{ hashFiles('global.json', 'Directory.Packages.props', '**/*.csproj') }}
|
||||
restore-keys: nuget-${{ runner.os }}-
|
||||
|
||||
- name: Restore (NuGet audit fails on moderate+ advisories)
|
||||
run: dotnet restore CommandForge.slnx
|
||||
|
||||
- name: Verify formatting
|
||||
@@ -31,4 +50,48 @@ jobs:
|
||||
run: dotnet build CommandForge.slnx -c Release --no-restore
|
||||
|
||||
- name: Test
|
||||
run: dotnet test CommandForge.slnx -c Release --no-build
|
||||
run: >-
|
||||
dotnet test CommandForge.slnx -c Release --no-build
|
||||
--logger "trx;LogFileName=test-results.trx"
|
||||
--collect "XPlat Code Coverage"
|
||||
--results-directory TestResults
|
||||
|
||||
- name: Upload test results
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: test-results
|
||||
path: TestResults
|
||||
retention-days: 14
|
||||
|
||||
package:
|
||||
# Publishes and packs exactly like release.yml, so a packaging regression (e.g. the Elevator
|
||||
# missing from the publish folder) fails the PR instead of the tagged release.
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
|
||||
with:
|
||||
global-json-file: global.json
|
||||
|
||||
- name: Cache NuGet packages
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ${{ env.NUGET_PACKAGES }}
|
||||
key: nuget-package-${{ runner.os }}-${{ hashFiles('global.json', 'Directory.Packages.props', '**/*.csproj', '.config/dotnet-tools.json') }}
|
||||
restore-keys: nuget-package-${{ runner.os }}-
|
||||
|
||||
- name: Publish + pack (Velopack smoke test)
|
||||
shell: pwsh
|
||||
run: ./scripts/pack.ps1 -Version 0.0.1
|
||||
|
||||
- name: Upload installer preview
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: installer-preview
|
||||
path: Releases/*-Setup.exe
|
||||
retention-days: 7
|
||||
@@ -1,8 +1,8 @@
|
||||
name: CodeQL
|
||||
|
||||
# Project-specific CodeQL (not the shared reusable codeql-csharp.yml): this is a WPF
|
||||
# (net10.0-windows) app that only builds on Windows and uses a .slnx solution, whereas the
|
||||
# reusable workflow runs on ubuntu and looks for a .sln.
|
||||
# Project-specific CodeQL (not the shared reusable workflow): the C# code is a WPF
|
||||
# (net10.0-windows) app that only builds on Windows from a .slnx solution. The workflows
|
||||
# themselves are analysed too (`actions` language).
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -10,36 +10,58 @@ on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: '37 14 * * 1' # Mondays 14:37 UTC
|
||||
- cron: '37 14 * * 1' # Mondays 14:37 UTC
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze (csharp)
|
||||
runs-on: windows-latest
|
||||
name: Analyze (${{ matrix.language }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- language: csharp
|
||||
os: windows-latest
|
||||
build-mode: manual
|
||||
- language: actions
|
||||
os: ubuntu-latest
|
||||
build-mode: none
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-dotnet@v5
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
persist-credentials: false
|
||||
|
||||
- if: matrix.language == 'csharp'
|
||||
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
|
||||
with:
|
||||
global-json-file: global.json
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4
|
||||
uses: github/codeql-action/init@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0
|
||||
with:
|
||||
languages: csharp
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
queries: security-extended
|
||||
|
||||
- name: Build
|
||||
run: dotnet build CommandForge.slnx -c Release
|
||||
- if: matrix.build-mode == 'manual'
|
||||
name: Build
|
||||
# Roslyn analyzers add nothing to CodeQL's extraction and slow the traced build down.
|
||||
run: dotnet build CommandForge.slnx -c Release -p:RunAnalyzers=false
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4
|
||||
uses: github/codeql-action/analyze@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0
|
||||
with:
|
||||
category: "/language:csharp"
|
||||
category: "/language:${{ matrix.language }}"
|
||||
@@ -0,0 +1,32 @@
|
||||
name: Dependency Review
|
||||
|
||||
# Blocks pull requests that add dependencies with known vulnerabilities (moderate or worse) or
|
||||
# with licenses that are not compatible with GPLv3.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
dependency-review:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write # summary comment on failure
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
|
||||
with:
|
||||
fail-on-severity: moderate
|
||||
comment-summary-in-pr: on-failure
|
||||
allow-licenses: >-
|
||||
MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause, ISC, 0BSD, Zlib, BSL-1.0,
|
||||
Unlicense, CC0-1.0, MPL-2.0, OFL-1.1, LGPL-2.1-or-later, LGPL-3.0-only,
|
||||
LGPL-3.0-or-later, GPL-3.0-only, GPL-3.0-or-later
|
||||
@@ -1,14 +1,26 @@
|
||||
name: Notify CI Failure
|
||||
|
||||
# Posts a Discord alert when the Build workflow fails on main (reuses the shared workflow in
|
||||
# poli0981/.github). Requires repo/org secret DISCORD_CI_WEBHOOK.
|
||||
# poli0981/.github). Requires repo secret DISCORD_CI_WEBHOOK.
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["Build"]
|
||||
types: [completed]
|
||||
|
||||
# The reusable workflow requests actions: read; without granting it here every run was a
|
||||
# startup_failure (the repository default token is read-only for contents only).
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
# Build only runs on `push` for main, so this limits alerts to main without trusting
|
||||
# forgeable values (branch names, actor logins) — and skips pull-request runs (including
|
||||
# Dependabot's), which have no access to the webhook secret anyway.
|
||||
if: >-
|
||||
github.event.workflow_run.conclusion == 'failure' &&
|
||||
github.event.workflow_run.event == 'push'
|
||||
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
|
||||
secrets: inherit
|
||||
@@ -1,8 +1,8 @@
|
||||
name: Release
|
||||
|
||||
# Triggered by pushing a SemVer tag (vX.Y.Z). Builds a self-contained, Velopack-packaged
|
||||
# release and publishes it to GitHub Releases with SHA-256 checksums and (optionally) a
|
||||
# VirusTotal scan. No code signing yet (see SECURITY.md).
|
||||
# release and publishes it to GitHub Releases with build-provenance attestations, SHA-256
|
||||
# checksums, an SPDX SBOM and (optionally) a VirusTotal scan. No code signing yet (see SECURITY.md).
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -10,88 +10,142 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Version without the leading v (e.g. 0.3.0)'
|
||||
description: 'Version without the leading v (e.g. 2.0.0)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
DOTNET_NOLOGO: true
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: true
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 45
|
||||
permissions:
|
||||
contents: write # create the release and upload assets
|
||||
id-token: write # OIDC for build-provenance attestations
|
||||
attestations: write
|
||||
outputs:
|
||||
tag: ${{ steps.ver.outputs.tag }}
|
||||
env:
|
||||
REPO_URL: https://github.com/poli0981/CommandForge
|
||||
REPO_URL: https://github.com/${{ github.repository }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VT_API_KEY: ${{ secrets.VT_API_KEY }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-dotnet@v5
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
|
||||
with:
|
||||
global-json-file: global.json
|
||||
|
||||
- name: Resolve version and tag
|
||||
id: ver
|
||||
shell: pwsh
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
INPUT_VERSION: ${{ github.event.inputs.version }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
run: |
|
||||
if ('${{ github.event_name }}' -eq 'workflow_dispatch') {
|
||||
$version = '${{ github.event.inputs.version }}'
|
||||
if ($env:EVENT_NAME -eq 'workflow_dispatch') {
|
||||
$version = $env:INPUT_VERSION
|
||||
$tag = "v$version"
|
||||
} else {
|
||||
$tag = '${{ github.ref_name }}'
|
||||
$tag = $env:REF_NAME
|
||||
$version = $tag -replace '^v', ''
|
||||
}
|
||||
if ($version -notmatch '^\d+\.\d+\.\d+$') { throw "Version '$version' is not X.Y.Z" }
|
||||
"version=$version" >> $env:GITHUB_OUTPUT
|
||||
"tag=$tag" >> $env:GITHUB_OUTPUT
|
||||
Write-Host "Releasing $version (tag $tag)"
|
||||
|
||||
- name: Install Velopack CLI (vpk)
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet tool install -g vpk
|
||||
"$env:USERPROFILE\.dotnet\tools" >> $env:GITHUB_PATH
|
||||
- name: Restore pinned tools (vpk)
|
||||
run: dotnet tool restore
|
||||
|
||||
- name: Download previous release (delta base)
|
||||
continue-on-error: true # first release has nothing to download
|
||||
run: vpk download github --repoUrl $env:REPO_URL --token ${{ secrets.GITHUB_TOKEN }}
|
||||
continue-on-error: true # the very first release has nothing to download
|
||||
shell: pwsh
|
||||
run: dotnet vpk download github --repoUrl $env:REPO_URL --token $env:GH_TOKEN
|
||||
|
||||
- name: Publish + pack (Velopack)
|
||||
run: ./scripts/pack.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||
shell: pwsh
|
||||
env:
|
||||
VERSION: ${{ steps.ver.outputs.version }}
|
||||
run: ./scripts/pack.ps1 -Version $env:VERSION
|
||||
|
||||
- name: Publish GitHub Release (Velopack)
|
||||
run: >
|
||||
vpk upload github
|
||||
- name: Attest build provenance
|
||||
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
|
||||
with:
|
||||
subject-path: |
|
||||
Releases/*-Setup.exe
|
||||
Releases/*.nupkg
|
||||
|
||||
# Upload as a DRAFT first: publishing is what makes installed copies auto-update, so the
|
||||
# release only goes live once every asset (SBOM, checksums, scan links) is attached.
|
||||
- name: Create draft GitHub Release (Velopack)
|
||||
shell: pwsh
|
||||
env:
|
||||
VERSION: ${{ steps.ver.outputs.version }}
|
||||
TAG: ${{ steps.ver.outputs.tag }}
|
||||
run: >-
|
||||
dotnet vpk upload github
|
||||
--repoUrl $env:REPO_URL
|
||||
--token ${{ secrets.GITHUB_TOKEN }}
|
||||
--publish
|
||||
--releaseName "CommandForge ${{ steps.ver.outputs.version }}"
|
||||
--tag ${{ steps.ver.outputs.tag }}
|
||||
shell: pwsh
|
||||
--token $env:GH_TOKEN
|
||||
--releaseName "CommandForge $env:VERSION"
|
||||
--tag $env:TAG
|
||||
|
||||
- name: SHA-256 checksums
|
||||
- name: SBOM + SHA-256 checksums
|
||||
shell: pwsh
|
||||
env:
|
||||
TAG: ${{ steps.ver.outputs.tag }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
run: |
|
||||
$rel = Join-Path (Get-Location) 'Releases'
|
||||
$sbom = Join-Path $rel 'sbom.spdx.json'
|
||||
gh api "repos/$env:REPOSITORY/dependency-graph/sbom" --jq '.sbom' | Out-File $sbom -Encoding utf8NoBOM
|
||||
$checksums = Join-Path $rel 'checksums.txt'
|
||||
# NOTE: filter with Where-Object, not Get-ChildItem -Exclude — the latter returns nothing
|
||||
# without a trailing wildcard/-Recurse, which produced an empty checksums.txt (HTTP 400).
|
||||
# Filter with Where-Object, not Get-ChildItem -Exclude (which returns nothing without a
|
||||
# trailing wildcard/-Recurse and once produced an empty checksums.txt).
|
||||
Get-ChildItem -Path $rel -File |
|
||||
Where-Object { $_.Name -ne 'checksums.txt' } |
|
||||
Get-FileHash -Algorithm SHA256 |
|
||||
ForEach-Object { '{0} {1}' -f $_.Hash.ToLower(), (Split-Path $_.Path -Leaf) } |
|
||||
Out-File $checksums -Encoding ascii
|
||||
gh release upload ${{ steps.ver.outputs.tag }} $checksums --clobber
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
gh release upload $env:TAG $sbom $checksums --clobber
|
||||
|
||||
- name: Publish the release
|
||||
shell: pwsh
|
||||
env:
|
||||
TAG: ${{ steps.ver.outputs.tag }}
|
||||
run: gh release edit $env:TAG --draft=false --latest
|
||||
|
||||
# The release-by-tag API used to append scan links can't see drafts, so this runs after publishing.
|
||||
- name: VirusTotal scan (optional)
|
||||
if: env.VT_API_KEY != ''
|
||||
uses: crazy-max/ghaction-virustotal@v5
|
||||
uses: crazy-max/ghaction-virustotal@936d8c5c00afe97d3d9a1af26d017cfdf26800a2 # v5.0.0
|
||||
with:
|
||||
vt_api_key: ${{ env.VT_API_KEY }}
|
||||
update_release_body: true
|
||||
files: |
|
||||
Releases/*-Setup.exe
|
||||
Releases/*-full.nupkg
|
||||
|
||||
announce:
|
||||
# A release published with GITHUB_TOKEN does not fire the `release` event, so the standalone
|
||||
# announce workflow never ran for tag releases — call the shared announcer directly instead.
|
||||
needs: release
|
||||
permissions:
|
||||
contents: read
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
with:
|
||||
tag_override: ${{ needs.release.outputs.tag }}
|
||||
secrets: inherit
|
||||
@@ -0,0 +1,45 @@
|
||||
name: Scorecard
|
||||
|
||||
# OpenSSF Scorecard supply-chain checks; results land in Security → Code scanning.
|
||||
|
||||
on:
|
||||
branch_protection_rule:
|
||||
schedule:
|
||||
- cron: '25 6 * * 1' # Mondays 06:25 UTC
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
name: Scorecard analysis
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write # upload SARIF
|
||||
id-token: write # publish results to the OpenSSF API / badge
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
publish_results: true
|
||||
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: scorecard-sarif
|
||||
path: results.sarif
|
||||
retention-days: 5
|
||||
|
||||
- uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -0,0 +1,6 @@
|
||||
# SonarCloud Automatic Analysis configuration.
|
||||
sonar.sources=src,helper,scripts,.github
|
||||
sonar.tests=tests
|
||||
sonar.exclusions=**/bin/**,**/obj/**
|
||||
# The catalog JSON and the per-language .resx files repeat structure by design.
|
||||
sonar.cpd.exclusions=**/Catalog/*.json,**/*.resx
|
||||
@@ -3,12 +3,20 @@
|
||||
## Requirements
|
||||
|
||||
- Windows 10 (22H2) or Windows 11
|
||||
- **.NET 10 SDK** (`dotnet --version` → `10.0.x`)
|
||||
- For packaging: the **Velopack CLI** — `dotnet tool install -g vpk`
|
||||
- **.NET 10 SDK** — the feature band is pinned in `global.json` (`dotnet --version` → `10.0.4xx`)
|
||||
- Admin rights are only needed to **test** elevated commands, not to build.
|
||||
|
||||
The solution file is **`CommandForge.slnx`** (the XML solution format).
|
||||
|
||||
| Project | Role |
|
||||
|---|---|
|
||||
| `src/CommandForge.Domain` | Entities; no dependencies |
|
||||
| `src/CommandForge.Application` | Use cases and ports; depends only on Domain |
|
||||
| `src/CommandForge.Infrastructure` | Processes, registry, catalog, storage, Velopack, logging |
|
||||
| `src/CommandForge.Wpf` | The WPF app (WPF-UI); namespace `CommandForge.Desktop` |
|
||||
| `helper/CommandForge.Elevator` | The elevated helper that runs admin commands over a named pipe |
|
||||
| `tests/CommandForge.Tests` | xUnit v3 tests |
|
||||
|
||||
## Build, run, test
|
||||
|
||||
```bash
|
||||
@@ -18,42 +26,80 @@ dotnet run --project src/CommandForge.Wpf
|
||||
dotnet test CommandForge.slnx
|
||||
```
|
||||
|
||||
## Code style
|
||||
The tests use xUnit v3 in VSTest mode (`xunit.v3.mtp-off`), so `dotnet test` and the coverlet
|
||||
collector work as usual.
|
||||
|
||||
## Code style and analysis
|
||||
|
||||
```bash
|
||||
dotnet format CommandForge.slnx # apply formatting
|
||||
dotnet format CommandForge.slnx --verify-no-changes # CI gate
|
||||
```
|
||||
|
||||
The build enforces analyzers as errors (`TreatWarningsAsErrors`, `EnforceCodeStyleInBuild`),
|
||||
including unused-using/unused-member rules.
|
||||
The build treats warnings as errors and enforces the .NET analyzers, code style
|
||||
(`EnforceCodeStyleInBuild`) and **SonarAnalyzer.CSharp** (the same rules SonarCloud applies),
|
||||
including unused-using and unused-member rules.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Package versions live in **each `.csproj`**; SonarAnalyzer is referenced once from
|
||||
`Directory.Build.props`. Central Package Management is deliberately not used: GitHub's dependency
|
||||
graph (Dependabot alerts, dependency review, the release SBOM) doesn't read
|
||||
`Directory.Packages.props`.
|
||||
- Every restore runs a **NuGet audit** of direct and transitive packages; moderate or higher
|
||||
advisories fail the build.
|
||||
- Dependabot groups updates (Velopack and the `vpk` tool move together) with a cooldown.
|
||||
|
||||
## Publish (self-contained) + package
|
||||
|
||||
The Velopack CLI is pinned as a local tool in `.config/dotnet-tools.json`, at the same version as
|
||||
the Velopack library:
|
||||
|
||||
```bash
|
||||
# One-step helper (publish + vpk pack):
|
||||
pwsh ./scripts/pack.ps1 -Version 0.3.0
|
||||
dotnet tool restore
|
||||
pwsh ./scripts/pack.ps1 -Version 2.0.0 # publish + vpk pack
|
||||
pwsh ./scripts/pack.ps1 -Version 2.0.0 -SkipPack # publish only
|
||||
```
|
||||
|
||||
`pack.ps1` runs a self-contained `win-x64` publish (stamping the assembly version so the in-app
|
||||
version matches the release) and then `vpk pack`. It writes these artifacts to `Releases/`:
|
||||
`pack.ps1` (parameters: `-Version`, `-Runtime` = `win-x64`, `-Configuration` = `Release`,
|
||||
`-SkipPack`):
|
||||
|
||||
- runs a self-contained **ReadyToRun** publish, stamping the version so the in-app version matches
|
||||
the release;
|
||||
- checks that `CommandForge.Elevator` is in the publish folder (the
|
||||
`PublishElevatorOnPublish` target in `src/CommandForge.Wpf/CommandForge.Wpf.csproj` publishes it
|
||||
alongside the app);
|
||||
- runs `vpk pack` with `--runtime`, so the installer and updater helpers are native x64, and stops
|
||||
on any non-zero exit code.
|
||||
|
||||
It writes these artifacts to `Releases/`:
|
||||
|
||||
- `CommandForge-win-Setup.exe` — the installer
|
||||
- `CommandForge-<version>-full.nupkg` — full package
|
||||
- `CommandForge-<version>-delta.nupkg` — delta package (only when a previous full is present)
|
||||
- `CommandForge-<version>-delta.nupkg` — delta package (only when a previous full package is
|
||||
present; see [UPDATES.md](UPDATES.md))
|
||||
- `releases.win.json` / `RELEASES` — the update manifest read by the app
|
||||
|
||||
The `CommandForge.Elevator` helper is published into the same folder automatically (see the
|
||||
`PublishElevatorOnPublish` target in `src/CommandForge.Wpf/CommandForge.Wpf.csproj`).
|
||||
|
||||
> No code signing yet — see [SECURITY.md](.github/SECURITY.md). Don't add a signing step until
|
||||
> Azure Trusted Signing (or SignPath Foundation for OSS) is set up.
|
||||
> No Authenticode signing yet — see [SECURITY.md](.github/SECURITY.md). Don't add a signing step
|
||||
> until Azure Trusted Signing (or SignPath Foundation for OSS) is set up.
|
||||
|
||||
## CI
|
||||
|
||||
- **`build.yml`** — restore + `dotnet format --verify-no-changes` + Release build + tests on every
|
||||
PR/push to `main` (Windows).
|
||||
- **`codeql.yml`** — CodeQL C# analysis (Windows, builds `CommandForge.slnx`).
|
||||
- **`release.yml`** — see [RELEASING.md](RELEASING.md).
|
||||
All workflows pin actions to full commit SHAs and use least-privilege permissions.
|
||||
|
||||
| Workflow | What it does |
|
||||
|---|---|
|
||||
| `build.yml` | `build`: restore, `dotnet format --verify-no-changes`, Release build, tests (results and coverage uploaded). `package`: publish and `vpk pack` exactly like a release. |
|
||||
| `codeql.yml` | CodeQL for C# (Windows, manual build) and for the workflows themselves (`actions`). |
|
||||
| `dependency-review.yml` | Fails a PR that adds a dependency with a moderate+ vulnerability or a license outside the GPLv3-compatible allow-list. |
|
||||
| `scorecard.yml` | OpenSSF Scorecard, reported to code scanning. |
|
||||
| `release.yml` | Tag-triggered release — see [RELEASING.md](RELEASING.md). |
|
||||
| `notify-ci-failure.yml` | Posts a Discord alert when the Build workflow fails on `main` (needs the `DISCORD_CI_WEBHOOK` secret). |
|
||||
|
||||
SonarCloud (Automatic Analysis, scoped by `.sonarcloud.properties`) and Snyk also check every PR.
|
||||
|
||||
`main` is protected by a repository ruleset: changes land through pull requests; `build`,
|
||||
`package`, `Analyze (csharp)`, `Analyze (actions)` and `dependency-review` must pass; and a PR
|
||||
can't introduce CodeQL errors or high-severity security alerts.
|
||||
|
||||
See [UPDATES.md](UPDATES.md) for how auto-update works.
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to **CommandForge** are documented here.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.0.0] — 2026-10-21
|
||||
|
||||
A redesign in the Fluent style of Windows 11, plus a broad safety, reliability and security
|
||||
overhaul. Settings, favorites, history, recipes and your own commands carry over unchanged.
|
||||
|
||||
### Added
|
||||
- **Fluent UI (WPF-UI 4.3).** A Mica window with its own title bar, a navigation pane (Home,
|
||||
Favorites, History, Recipes, My commands and the catalog with its 12 categories and counts; Log
|
||||
viewer, Debug panel and Settings at the bottom), in-window dialogs, snackbar notifications and
|
||||
the Windows accent color. Light, dark or system theme; High Contrast always wins.
|
||||
- **Resizable window** (minimum 960×600, default 1200×780) that remembers its size, position and
|
||||
maximized state, and never reopens off-screen.
|
||||
- **Title bar:** a search box for the whole catalog (`Ctrl+K`), an admin-session indicator with
|
||||
**End admin session**, and a **More** menu (Command Palette, Check for updates, Create System
|
||||
Restore Point, export logs, open the config and log folders, keyboard shortcuts, user guide,
|
||||
report a bug, terms, About).
|
||||
- **Catalog:** filter chips for Safe / Caution / Dangerous and Admin only, the estimated duration,
|
||||
the command line with paths filled in, and a splitter between the details and the console.
|
||||
- **Console:** one shared console for the catalog, recipes and your own commands — virtualized,
|
||||
capped at 10,000 lines (with an "N earlier lines" note), **Copy all output**, **Save output to a
|
||||
file**, a "Waiting for administrator permission…" status, and **Restart now** (asks first,
|
||||
never while a command runs).
|
||||
- A finished run shows a notification and flashes the taskbar button when the console isn't
|
||||
visible; the taskbar button shows progress while a command runs.
|
||||
- The Legal Gate lets you choose the app language before reading the terms.
|
||||
- **20 new commands** (catalog grew from 241 to 261): restore point list, System Restore, Automatic
|
||||
Maintenance, clock resync, DNS cache, listening ports, Wi-Fi interface details, third-party
|
||||
scheduled tasks, Run keys, stopped automatic services, Windows Search restart, Store and optional
|
||||
updates, UAC status, Core isolation, environment variables, WSL status, TRIM status, crash dumps
|
||||
and battery charge.
|
||||
- A **user guide** ([USAGE.md](USAGE.md)), linked from the More menu and About. About also lists
|
||||
contact addresses for security reports and code questions.
|
||||
- **Release integrity:** build-provenance attestations (`gh attestation verify`), an SPDX SBOM and
|
||||
SHA-256 checksums are attached to every release.
|
||||
|
||||
### Changed
|
||||
- **One set of safety rules.** Dangerous commands always ask with typing; Caution commands ask
|
||||
unless you turn that off; a restore point is offered only for risky admin commands (or commands
|
||||
flagged for one), so per-user tweaks no longer trigger a UAC prompt for it.
|
||||
- **Type-to-confirm** accepts the command name regardless of case and Unicode form, or the command
|
||||
ID, so Vietnamese input methods and Japanese/Chinese IMEs can confirm. Cancel is the default.
|
||||
- **Recipes** no longer run Dangerous steps after a single Yes/No: an overview prompt is followed
|
||||
by each risky step's own confirmation, with one restore point before the chain.
|
||||
- **Search** returns relevant matches only (descriptions and tags must contain your words), ranks
|
||||
titles better, highlights the right letters and ignores accents ("don dep" finds "Dọn dẹp").
|
||||
- **Catalog safety and accuracy:**
|
||||
- Automatic Disk Cleanup uses its own allow-list of safe handlers, so Downloads, the Recycle
|
||||
Bin and Windows.old are never touched and your own `/sageset:1` choices are kept.
|
||||
- Removing Windows.old and clearing the event logs are now Dangerous.
|
||||
- Drive repair uses `Repair-Volume -OfflineScanAndFix`; drive letters and profile paths come
|
||||
from your actual system drive and profile.
|
||||
- PowerShell commands run with `-NoProfile -NonInteractive` and stop at the first error instead
|
||||
of always printing success; cleanups report what they removed and what was in use.
|
||||
- winget never prompts; activation status no longer needs VBScript; the Windows 11 Widgets
|
||||
button opens Settings, because Windows now blocks that change from scripts.
|
||||
- Switching the language changes only the app's text; number and date formats keep following
|
||||
your regional settings.
|
||||
- **Logs:** 14 daily files of at most 10 MB each (they grew without limit before). Every run is
|
||||
logged as a one-line summary (ID, exit code, duration), never with its output.
|
||||
- Faster startup: ReadyToRun publish and no Generic Host (about 20 fewer packages).
|
||||
- Font size now scales every text and control live.
|
||||
|
||||
### Removed
|
||||
- MaterialDesignThemes, Microsoft.Extensions.Hosting and Serilog.Extensions.Hosting.
|
||||
|
||||
### Fixed
|
||||
- **Garbled output** from `sfc`, `wsl` and other native tools on non-English Windows: output is
|
||||
decoded as UTF-16, UTF-8 or the OEM code page, whichever it is.
|
||||
- The console could stay "running" forever when a run failed or was cancelled while the admin
|
||||
helper was starting.
|
||||
- A failed startup left an invisible process holding the single-instance lock, so every later
|
||||
launch silently did nothing. The app now shows an error and exits.
|
||||
- Settings, history, recipes, profiles and your commands are saved atomically. A damaged file is
|
||||
kept as a backup instead of silently resetting everything (including the accepted terms).
|
||||
- **Updates:** closing the update dialog with X cancels the download; the app no longer restarts
|
||||
mid-command to apply an update; timeouts and other errors are reported instead of leaving the
|
||||
dialog on "Checking".
|
||||
- **Restore points:** "Windows already made one in the last 24 hours" is reported as skipped, not
|
||||
as created; any other failure asks before running the command anyway.
|
||||
- **Keyboard:** AltGr no longer triggers shortcuts (typing "@" on a German keyboard closed the
|
||||
app); `Ctrl+B` toggles the navigation pane as advertised.
|
||||
- History's Run again and Undo are disabled while a command runs; runs that never started are not
|
||||
recorded.
|
||||
- My commands: a quoted `cmd` is recognized and `/c` is no longer added twice.
|
||||
- Exporting logs or settings to a locked path, or opening a link with no browser set up, shows a
|
||||
message instead of the crash dialog. Imported settings files are validated.
|
||||
- Crash support codes stay the same across runs.
|
||||
- The Log Viewer refreshes once per burst of log events instead of once per event.
|
||||
|
||||
### Security
|
||||
- Catalog programs resolve to absolute paths in System32/Windows, so a program planted in the
|
||||
app's per-user folder can't run elevated; Launch commands pin their working directory.
|
||||
- Elevated commands get an environment rebuilt from trusted sources: per-user variables such as
|
||||
`PSModulePath`, `COR_PROFILER`, `SystemRoot` and `windir` can no longer redirect what an elevated
|
||||
command loads or deletes. The elevated helper ignores `DOTNET_STARTUP_HOOKS`.
|
||||
- The app and the elevated helper verify each other's process on the named pipe; the helper
|
||||
connects with Identification-level impersonation and no longer writes files.
|
||||
- Captured commands run in a kill-on-close job object.
|
||||
- The catalog loader registers a command only after it passes validation; contradictory or unsafe
|
||||
records are rejected.
|
||||
- **CI and supply chain:** actions pinned to commit SHAs with least-privilege permissions, CodeQL
|
||||
for C# and GitHub Actions, dependency review, OpenSSF Scorecard, a NuGet audit of transitive
|
||||
packages, SonarAnalyzer rules enforced at build time, and a protected `main` branch with
|
||||
required checks.
|
||||
|
||||
## [1.5.1] — 2026-07-09
|
||||
|
||||
### Fixed
|
||||
- **Single instance:** launching the app while it is already running no longer opens a second
|
||||
window. Later launches bring the existing window to the foreground (restoring it if minimized)
|
||||
and then exit.
|
||||
|
||||
## [1.5.0] — 2026-07-08
|
||||
|
||||
### Added
|
||||
- **40 new commands** (catalog grew from 201 to 241), focused on rarely-used and Windows-version-specific
|
||||
features, gated by OS build so Windows 10-only commands are hidden on Windows 11 and vice-versa:
|
||||
- **Windows 11-only tweaks & pages:** hide the Widgets and Copilot taskbar buttons; enable taskbar
|
||||
"End task"; "Never combine + labels" taskbar; "More pins" Start layout; and open Dynamic Lighting,
|
||||
Presence sensing and (24H2) Energy Saver settings.
|
||||
- **Windows 10-only tweaks:** turn off News and Interests; hide the Meet Now, People and Cortana
|
||||
buttons; and turn off all Start menu live tiles.
|
||||
- **Diagnostics & system info:** current-user rights & groups, Start menu app IDs, Boot Configuration
|
||||
(BCD), devices reporting problems, all event-log channels and Entra/AD device-join state.
|
||||
- **Security, storage, power, network & developer:** local Administrators members, trusted root
|
||||
certificates, all firewall rules and Recall feature status (24H2); SMART reliability counters,
|
||||
volume dirty bit and sector-size info; active wake timers and reduced-size hibernation; Wi-Fi radio
|
||||
capabilities, global TCP settings and a Wi-Fi history report; and Dev Drive status, Sudo for Windows
|
||||
status, the Hyper-V VM list and the boot hypervisor launch type.
|
||||
|
||||
### Fixed
|
||||
- **TPM Status** and **Defender Exclusions** now run with administrator elevation, so they return
|
||||
results instead of appearing blank (both underlying queries require an elevated session).
|
||||
|
||||
## [1.4.0] — 2026-06-29
|
||||
|
||||
### Added
|
||||
- **60 new commands and a new "Services & Startup" category** (catalog grew from 141 to 201):
|
||||
- **Services & Startup** (new 12th category): restart the Print Spooler, Windows Audio, Windows
|
||||
Update and BITS services; list running and automatic services; and open the Startup apps settings
|
||||
and the Startup folder.
|
||||
- **System info & storage:** battery health, network-adapter speed, disk health and SMART status,
|
||||
page-file usage, local user accounts, time zone and Windows install date; plus a drive-usage
|
||||
summary, largest temp files, partition list, fragmentation analysis, Disk Cleanup configuration
|
||||
and a DiskPart disk/volume listing.
|
||||
- **Network & diagnostics:** a public DNS lookup test, active TCP connections, firewall profiles,
|
||||
shared folders, the hosts file and Network Connections; plus recent boot/shutdown and
|
||||
unexpected-shutdown events, recent system errors, Print Management and Certificate Manager.
|
||||
- **Cleanup, power & maintenance:** clear the icon cache, recent items and event logs; the Power
|
||||
Saver plan and hibernate-now; and an online disk scan and a read-only system-file verification.
|
||||
- **Security, updates & tweaks:** Defender threat history and exclusions, BitLocker volume details,
|
||||
reset firewall to defaults, remove dynamic signatures and open Windows Security; update history,
|
||||
Windows Update settings, App Installer self-update, package export, third-party drivers and
|
||||
troubleshooters; and hide/show the Windows 11 taskbar search plus transparency, Snap-assist and
|
||||
Telnet-client toggles.
|
||||
|
||||
## [1.3.0] — 2026-06-26
|
||||
|
||||
### Added
|
||||
- **25 new commands and a new "Storage" category** (catalog grew from 116 to 141): optimize /
|
||||
defragment C:, Disk Management, list volumes & free space, and open Storage settings; TPM status,
|
||||
Secure Boot state and a computer & OS summary; network adapters, DNS servers and an internet
|
||||
connectivity test; startup programs, Driver Verifier, Performance Monitor and a system health
|
||||
report; clear crash dumps, Windows Error Reporting data and the DNS + ARP caches; lid-close and
|
||||
monitor-timeout power toggles; and NumLock-at-startup and verbose sign-in toggles.
|
||||
- **Two new UI languages — Simplified Chinese (简体中文) and Spanish (Español)** — joining English,
|
||||
Vietnamese and Japanese. Selectable in Settings and the View menu and switching live without a
|
||||
restart.
|
||||
|
||||
### Changed
|
||||
- **Fixed main window size.** The main window is now a fixed 1100×720 and can no longer be resized
|
||||
or maximized; the F11 full-screen shortcut has been removed.
|
||||
|
||||
## [1.2.0] — 2026-06-21
|
||||
|
||||
### Added
|
||||
- **38 new commands** across all ten categories (catalog grew from 78 to 116): installed
|
||||
updates / drivers / BIOS / programs / displays; active connections, ARP cache, routing table,
|
||||
Wi-Fi profiles and WinHTTP proxy; dark/light mode and Windows 11 taskbar-alignment and
|
||||
clock-seconds tweaks; thumbnail / font / Prefetch cleanup; the Balanced power plan, power
|
||||
requests and a Fast Startup toggle; Task Manager, Device Manager, Services and Group Policy
|
||||
result; winget source list and Microsoft Store reset; Defender status and full scan; firewall
|
||||
on/off; WSL shutdown, Windows Sandbox off and a long-paths toggle.
|
||||
- **Japanese (日本語) language.** A full Japanese translation joins English and Vietnamese,
|
||||
selectable in Settings and the View menu and switching live without a restart.
|
||||
|
||||
### Changed
|
||||
- **Version-aware command list.** Commands that only apply to a specific Windows version (such as
|
||||
the Windows 11 taskbar and clock tweaks) are now hidden automatically when they do not apply to
|
||||
your build of Windows.
|
||||
|
||||
## [1.1.1] — 2026-06-19
|
||||
|
||||
### Fixed
|
||||
- **User commands hanging on `cmd`.** A user-defined command using `cmd` (e.g.
|
||||
`ping google.com`) could stay "running" forever without responding. The process runner now
|
||||
redirects and immediately closes the child's standard input, so an interactive `cmd` receives
|
||||
EOF and exits instead of blocking. User commands that use `cmd` also get `/c` prepended
|
||||
automatically (`cmd` + `ping google.com` runs as `cmd /c ping google.com`), and the run
|
||||
confirmation shows the exact command line. PowerShell and other executables are unchanged.
|
||||
- **Recipes — duplicate steps.** A command already in a recipe can no longer be added again, so a
|
||||
recipe never runs the same command multiple times.
|
||||
- **Sidebar.** Hid the vertical scrollbar on the command-groups list (still scrollable by wheel).
|
||||
|
||||
## [1.1.0] — 2026-06-19
|
||||
|
||||
### Added
|
||||
- **Package & assembly metadata.** Product, author, company, copyright and repository information
|
||||
are embedded in the assemblies (shown in About and file properties) and in the Velopack
|
||||
installer.
|
||||
- **Execution history.** A new History screen lists finished runs (newest first) with time, status
|
||||
and duration, plus **Run again** and **Clear history**. Stored locally; no telemetry.
|
||||
- **Import / export & profiles.** Export your appearance, behavior and favorites to a `.json` file
|
||||
and import them on another machine. Save the current configuration as a named **profile**
|
||||
(e.g. "Gaming PC", "Office") and switch between them.
|
||||
- **Recipes (command chains).** Build a named sequence of vetted catalog commands and run them with
|
||||
a single aggregated confirmation, **one UAC prompt** for an all-admin chain, and **stop-on-error**
|
||||
(and stop-on-reboot-required) for safety.
|
||||
- **User-defined commands ("My commands").** Add your own commands. They are kept entirely separate
|
||||
from the vetted catalog and **always run without administrator rights**.
|
||||
- **Registry before/after & undo.** For applicable tweaks, the affected registry values are read
|
||||
before and after the run and a diff is shown in the console (read-only). History entries for
|
||||
reversible commands offer **Undo**, which runs the command's vetted revert command — no arbitrary
|
||||
registry writes.
|
||||
- **Home maintenance suggestions** (e.g. low disk space → Disk Cleanup; long uptime → restart) and
|
||||
**local natural-language search** (everyday phrases such as "clean disk" suggest a catalog
|
||||
keyword). Both are 100% local — no cloud, no LLM.
|
||||
|
||||
## [1.0.0] — 2026-06-18
|
||||
|
||||
Initial public release.
|
||||
|
||||
### Added
|
||||
- **Command catalog.** An embedded, vetted, read-only catalog of Windows commands organized by
|
||||
category, with fuzzy search and a Command Palette (Ctrl+K) and an exact command-line preview.
|
||||
- **Execution engine.** Real-time console output streamed off the UI thread, cancellation, and
|
||||
restart-required detection (exit code `3010`).
|
||||
- **Admin / UAC.** Elevated commands run through a separate `CommandForge.Elevator` broker over a
|
||||
named pipe (one UAC prompt per session); the main UI stays non-elevated.
|
||||
- **Safety.** Confirmation dialogs for Caution/Dangerous commands (type-to-confirm for Dangerous,
|
||||
which cannot be disabled), optional System Restore Point, and revert for reversible tweaks.
|
||||
- **Self-update** via Velopack (per-user, delta updates) from GitHub Releases.
|
||||
- **Localization & theming.** Full English/Vietnamese UI, light/dark/system themes, and font
|
||||
scaling.
|
||||
- **Home dashboard** with recent commands, favorites and a read-only system-status widget.
|
||||
- **Diagnostics.** Settings screen, Log Viewer (filter/export), Debug panel, a global crash handler
|
||||
and a "Report a bug" flow.
|
||||
- **Accessibility** (automation names, keyboard navigation, AA contrast) and a first-run Legal Gate
|
||||
(EULA / GPLv3 / Disclaimer / Privacy).
|
||||
- **CI/CD.** Build, test and CodeQL on every change; tag-triggered releases publish SHA-256
|
||||
checksums (and an optional VirusTotal scan). No telemetry — the only network use is checking
|
||||
GitHub for updates.
|
||||
|
||||
[Unreleased]: https://github.com/poli0981/CommandForge/compare/v2.0.0...HEAD
|
||||
[2.0.0]: https://github.com/poli0981/CommandForge/compare/v1.5.1...v2.0.0
|
||||
[1.5.1]: https://github.com/poli0981/CommandForge/compare/v1.5.0...v1.5.1
|
||||
[1.5.0]: https://github.com/poli0981/CommandForge/compare/v1.4.0...v1.5.0
|
||||
[1.4.0]: https://github.com/poli0981/CommandForge/compare/v1.3.0...v1.4.0
|
||||
[1.3.0]: https://github.com/poli0981/CommandForge/compare/v1.2.0...v1.3.0
|
||||
[1.2.0]: https://github.com/poli0981/CommandForge/compare/v1.1.1...v1.2.0
|
||||
[1.1.1]: https://github.com/poli0981/CommandForge/compare/v1.1.0...v1.1.1
|
||||
[1.1.0]: https://github.com/poli0981/CommandForge/compare/v1.0.0...v1.1.0
|
||||
[1.0.0]: https://github.com/poli0981/CommandForge/releases/tag/v1.0.0
|
||||
@@ -21,7 +21,7 @@
|
||||
3. **Khởi động lại:** Phát hiện cần reboot bằng **exit code `3010`** (`ERROR_SUCCESS_REBOOT_REQUIRED`), không chỉ parse text.
|
||||
4. **Ranh giới kiến trúc:** `Domain` không phụ thuộc gì. `Application` chỉ phụ thuộc `Domain`. `Infrastructure`/`Wpf` hiện thực các interface của `Application`. **Không bao giờ** để `Domain`/`Application` tham chiếu WPF hay Win32.
|
||||
5. **Không obfuscate.** Mã GPLv3 vốn công khai; obfuscate vừa vô nghĩa vừa gây false-positive antivirus.
|
||||
6. **Hiện chưa ký số** (sẽ thêm Azure Trusted Signing sau — xem `docs/Build.md`). Đừng thêm bước ký vào build/CI lúc này.
|
||||
6. **Hiện chưa ký số Authenticode** (sẽ thêm Azure Trusted Signing/SignPath sau — xem `docs/Build.md`). Đừng thêm bước ký Authenticode vào build/CI lúc này. Attestation build-provenance (Sigstore, `actions/attest-build-provenance`), SBOM và checksums trong `release.yml` là được phép và phải giữ.
|
||||
7. **Không telemetry.** Mạng duy nhất được phép: gọi GitHub để kiểm tra cập nhật. Bất kỳ thu thập dữ liệu nào khác đều bị cấm (vi phạm `docs/Privacy.md`).
|
||||
8. **Xác nhận trước lệnh nguy hiểm.** Lệnh `Caution`/`Dangerous` phải có hộp thoại xác nhận; không cho phép tắt xác nhận với nhóm `Dangerous`.
|
||||
|
||||
@@ -29,11 +29,12 @@
|
||||
|
||||
## 3. Tech stack (tóm tắt — chi tiết ở `docs/tech.md`)
|
||||
|
||||
- **.NET 10 (LTS), C# 14** · **WPF** + **Material Design In XAML**
|
||||
- **CommunityToolkit.Mvvm** (MVVM) · **Microsoft.Extensions.DependencyInjection/Hosting** (DI)
|
||||
- **.NET 10 (LTS), C# 14** · **WPF** + **WPF-UI 4.3** (Fluent, lepoco) — đã thay Material Design từ v2.0.0
|
||||
- **CommunityToolkit.Mvvm** (MVVM) · **Microsoft.Extensions.DependencyInjection** (`ServiceCollection` + `ValidateOnBuild`; **không** dùng Generic Host)
|
||||
- **CsWin32** (P/Invoke) · **Serilog** (logging) · `System.Threading.Channels`
|
||||
- **Velopack** (`vpk`) cho cài đặt + cập nhật qua GitHub Releases
|
||||
- i18n: `.resx` (EN/VI)
|
||||
- **Velopack** (`vpk` pin làm local tool trong `.config/dotnet-tools.json`) cho cài đặt + cập nhật qua GitHub Releases
|
||||
- Test: **xUnit v3** (`xunit.v3.mtp-off`, chạy qua VSTest) · **SonarAnalyzer.CSharp** chạy trong build
|
||||
- i18n: `.resx` 5 ngôn ngữ (EN/VI/JA/zh-Hans/ES)
|
||||
|
||||
---
|
||||
|
||||
@@ -44,7 +45,7 @@ src/
|
||||
CommandForge.Domain/ # entities thuần
|
||||
CommandForge.Application/ # use-cases + interfaces (ports)
|
||||
CommandForge.Infrastructure/ # Process, registry, Velopack, GitHub, Serilog
|
||||
CommandForge.Wpf/ # View + ViewModel + DI bootstrap + .resx
|
||||
CommandForge.Wpf/ # View + ViewModel + DI bootstrap + .resx (namespace: CommandForge.Desktop)
|
||||
helper/
|
||||
CommandForge.Elevator/ # tiến trình phụ chạy lệnh Admin (named pipe)
|
||||
tests/
|
||||
@@ -60,16 +61,22 @@ dotnet restore
|
||||
dotnet build -c Debug
|
||||
dotnet run --project src/CommandForge.Wpf
|
||||
dotnet test
|
||||
# Phát hành + đóng gói:
|
||||
dotnet publish src/CommandForge.Wpf -c Release -r win-x64 --self-contained
|
||||
vpk pack --packId CommandForge --packVersion <ver> --packDir <publishDir>
|
||||
dotnet format CommandForge.slnx --verify-no-changes
|
||||
# Phát hành + đóng gói (publish ReadyToRun + vpk pack → Releases/):
|
||||
dotnet tool restore
|
||||
pwsh ./scripts/pack.ps1 -Version <ver>
|
||||
```
|
||||
|
||||
Phát hành thật: tag ký GPG `vX.Y.Z` trên `main` → `release.yml` (xem `RELEASING.md`).
|
||||
|
||||
---
|
||||
|
||||
## 6. Quy ước code (chi tiết ở `docs/codestyle.md`)
|
||||
|
||||
- Code, định danh, comment kỹ thuật: **tiếng Anh**. Chuỗi hiển thị cho người dùng: **`.resx` (EN/VI)** — không hardcode chuỗi UI.
|
||||
- Code, định danh, comment kỹ thuật: **tiếng Anh**. Chuỗi hiển thị cho người dùng: **`.resx` (EN/VI/JA/zh-Hans/ES)** — không hardcode chuỗi UI; mỗi key phải có ở cả 5 file (test `ResxKeyTests` quét UI để kiểm tra).
|
||||
- Namespace tầng giao diện là `CommandForge.Desktop` (project/assembly/exe vẫn tên `CommandForge.Wpf`): namespace `CommandForge.Wpf` che namespace gốc `Wpf` của WPF-UI trong code XAML sinh ra.
|
||||
- WPF-UI: mỗi trang (UserControl trong NavigationView) phải đặt `Foreground="{DynamicResource TextFillColorPrimaryBrush}"` ở gốc (Frame không truyền màu chữ xuống); lớp con của `ContentDialog` phải gọi `SetResourceReference(StyleProperty, typeof(ContentDialog))` — `XamlConventionsTests` kiểm tra cả hai. Cỡ chữ dùng `DynamicResource AppFontSize*`.
|
||||
- Version package đặt trong **từng `.csproj`** (không dùng Central Package Management — dependency graph của GitHub không đọc `Directory.Packages.props`).
|
||||
- Nullable reference types **bật**; `TreatWarningsAsErrors` **bật**; analyzers **bật**.
|
||||
- `async/await` xuyên suốt cho I/O; không `async void` (trừ event handler); luôn truyền `CancellationToken`.
|
||||
- MVVM bằng source-generator của CommunityToolkit (`[ObservableProperty]`, `[RelayCommand]`).
|
||||
@@ -80,7 +87,7 @@ vpk pack --packId CommandForge --packVersion <ver> --packDir <publishDir>
|
||||
|
||||
## 7. Bất biến quan trọng khi đụng tới các vùng nhạy cảm
|
||||
|
||||
- **Thêm lệnh mới:** chỉ thêm vào catalog JSON (`Infrastructure/Catalog/commands.json`) theo schema ở `docs/CatalogCommand.md`; thêm key chuỗi vào `.resx`; viết test validate catalog. **Catalog sẽ được bổ sung/cập nhật liên tục theo thời gian** — giữ schema ổn định, dễ mở rộng.
|
||||
- **Thêm lệnh mới:** chỉ thêm vào catalog JSON (`Infrastructure/Catalog/commands.json`) theo schema ở `docs/CatalogCommand.md`; thêm key chuỗi vào cả 5 file `.resx`; icon phải có trong `Converters/IconMap.cs`; PowerShell luôn `-NoProfile -NonInteractive`; dùng token `{SystemDrive}`/`{SystemRoot}`/`{UserProfile}` thay vì đường dẫn cứng; viết test validate catalog. **Catalog sẽ được bổ sung/cập nhật liên tục theo thời gian** — giữ schema ổn định, dễ mở rộng.
|
||||
- **Sửa luồng nâng quyền:** đọc kỹ `docs/Security.md` trước.
|
||||
- **Sửa luồng cập nhật:** xử lý đủ `404 / 403 / 429 / 5xx / offline` (KHÔNG có mã `419`).
|
||||
|
||||
@@ -93,7 +100,7 @@ vpk pack --packId CommandForge --packVersion <ver> --packDir <publishDir>
|
||||
| `docs/tech.md` | Tech stack, third-party (font, update…), phiên bản |
|
||||
| `docs/architectures.md` | Kiến trúc chi tiết, ports/adapters, elevation broker, threading |
|
||||
| `docs/codestyle.md` | Chuẩn code C#/XAML, `.editorconfig`, analyzers |
|
||||
| `docs/UI.md` | Đặc tả giao diện từng thành phần |
|
||||
| `docs/UI.md` | Đặc tả giao diện từng thành phần (Fluent / WPF-UI) |
|
||||
| `docs/CatalogCommand.md` | Toàn bộ lệnh + nhóm lệnh + schema |
|
||||
| `docs/roadmap.md` | Lộ trình theo phase, milestone, version |
|
||||
| `docs/note.md` | Ghi chú, quyết định, "gotcha", nhắc nhở |
|
||||
@@ -101,7 +108,11 @@ vpk pack --packId CommandForge --packVersion <ver> --packDir <publishDir>
|
||||
| `docs/Security.md` | Mô hình bảo mật, threat model, disclosure |
|
||||
| `docs/Build.md` | Build, test, publish, release, CI |
|
||||
| `docs/Testing.md` | Chiến lược kiểm thử |
|
||||
| `docs/Changelog.md` | Nhật ký thay đổi |
|
||||
| `LICENSE.md` / `Privacy.md` / `EULA.md` / `Disclaimer.md` | Pháp lý |
|
||||
| `docs/Changelog.md` | Chỉ trỏ về `CHANGELOG.md` (gốc repo) |
|
||||
| `docs/LICENSE.md` / `Privacy.md` / `EULA.md` / `Disclaimer.md` | Bản pháp lý nội bộ (bản công khai ở gốc repo là chuẩn) |
|
||||
|
||||
> ⚠️ Bộ tài liệu này nằm trong `.gitignore` (tài liệu nội bộ). Nếu sau này cần publish các file pháp lý (để Legal Gate trỏ link tới GitHub), tạo bản công khai riêng — xem `docs/note.md`.
|
||||
> ⚠️ Thư mục `docs/` nằm trong `.gitignore` (tài liệu nội bộ, chỉ có trên máy).
|
||||
|
||||
**Tài liệu công khai (ở gốc repo, được commit):** `README.md`, `USAGE.md` (hướng dẫn người dùng — link "User guide" trong app), `CHANGELOG.md`, `BUILD.md`, `RELEASING.md`, `UPDATES.md`, `PRIVACY.md`, `EULA.md`, `DISCLAIMER.md`, `THIRD-PARTY-NOTICES.md`, `MAINTAINERS.md`, `LICENSE`, và trong `.github/`: `SECURITY.md`, `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md`. Legal Gate trỏ tới EULA/PRIVACY/DISCLAIMER/LICENSE công khai.
|
||||
|
||||
**Email liên hệ (@poli0981.dev):** `security@` (lỗ hổng, cùng GitHub private vulnerability reporting) · `privacy@` · `legal@` · `copyright@` / `dmca@` / `takedown@` (bản quyền, DMCA, yêu cầu gỡ bỏ khác) · `code@` (mã nguồn, đóng góp, báo cáo Code of Conduct) · `collab@` · `press@` · `sponsor@`. Không dùng `games@` cho dự án này.
|
||||
+24
-1
@@ -1,6 +1,6 @@
|
||||
# Disclaimer — CommandForge
|
||||
|
||||
> Last updated: 2026-06-18. This is not legal advice.
|
||||
> Last updated: 2026-10-21. This is not legal advice.
|
||||
|
||||
## ⚠️ Use at your own risk
|
||||
|
||||
@@ -52,3 +52,26 @@ please report translation problems via an issue.
|
||||
Command descriptions and documentation are provided in good faith but **may be incomplete or
|
||||
out of date** for some Windows versions. Command behavior can differ between Windows 10 and 11
|
||||
and across OS updates.
|
||||
|
||||
## Copyright and takedown requests
|
||||
|
||||
CommandForge's code and documentation are © poli0981 and contributors, licensed under the GPLv3.
|
||||
Third-party components keep their own licenses (see
|
||||
[THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md)). If you believe something in this project
|
||||
infringes your rights, please contact us first so it can be corrected quickly:
|
||||
|
||||
- **Copyright questions** (attribution, licensing, permission requests):
|
||||
[copyright@poli0981.dev](mailto:copyright@poli0981.dev)
|
||||
- **DMCA notices:** [dmca@poli0981.dev](mailto:dmca@poli0981.dev). Include the details required by
|
||||
17 U.S.C. § 512(c)(3): the work, the material you believe infringes it and its location (URL),
|
||||
your contact details, a good-faith statement, a statement that the notice is accurate and that
|
||||
you are authorized to act, and your signature.
|
||||
- **Other takedown requests** (trademark, impersonation, unlawful content):
|
||||
[takedown@poli0981.dev](mailto:takedown@poli0981.dev)
|
||||
|
||||
Because the project is hosted on GitHub, you can also use GitHub's
|
||||
[DMCA Takedown Policy](https://docs.github.com/site-policy/content-removal-policies/dmca-takedown-policy).
|
||||
|
||||
## Contact
|
||||
|
||||
Other legal questions: [legal@poli0981.dev](mailto:legal@poli0981.dev).
|
||||
@@ -21,6 +21,49 @@
|
||||
don't force XML docs on every public member. -->
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>$(NoWarn);CS1591</NoWarn>
|
||||
|
||||
<!-- Supply-chain audit: restore checks direct AND transitive packages against the GitHub
|
||||
Advisory Database. Moderate+ advisories (NU1902-NU1904) fail the build through
|
||||
TreatWarningsAsErrors; low-severity ones (NU1901) stay warnings. -->
|
||||
<NuGetAudit>true</NuGetAudit>
|
||||
<NuGetAuditMode>all</NuGetAuditMode>
|
||||
<NuGetAuditLevel>low</NuGetAuditLevel>
|
||||
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901</WarningsNotAsErrors>
|
||||
|
||||
<!-- Normalized source paths in PDBs for CI builds (reproducible artifacts). -->
|
||||
<ContinuousIntegrationBuild Condition="'$(GITHUB_ACTIONS)' == 'true'">true</ContinuousIntegrationBuild>
|
||||
</PropertyGroup>
|
||||
|
||||
<!--
|
||||
Package / assembly metadata, inherited by every project. Surfaced in Settings -> About
|
||||
and the Report-Bug template (via Assembly.GetName().Version), in the file properties, and
|
||||
in the Velopack installer (scripts/pack.ps1 passes Authors via the packAuthors flag).
|
||||
|
||||
Version here is only the dev-build default; scripts/pack.ps1 overrides it at publish time
|
||||
with the Version/FileVersion/InformationalVersion properties off the git tag. AssemblyVersion is
|
||||
intentionally NOT pinned, so it follows Version and the in-app "App version" stays accurate
|
||||
(binding-redirect churn is a non-issue for a self-contained app, not a shared library).
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<Product>CommandForge</Product>
|
||||
<Authors>poli0981</Authors>
|
||||
<Company>poli0981</Company>
|
||||
<Copyright>Copyright © 2026 poli0981</Copyright>
|
||||
<Description>Run complex Windows system commands through a visual, categorized interface.</Description>
|
||||
<RepositoryUrl>https://github.com/poli0981/CommandForge</RepositoryUrl>
|
||||
<PackageProjectUrl>https://github.com/poli0981/CommandForge</PackageProjectUrl>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<Version>2.0.0</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Same rules SonarCloud applies, enforced at build time (warnings are errors). Package versions
|
||||
live in each .csproj: GitHub's dependency graph (Dependabot alerts, dependency review, the
|
||||
release SBOM) reads .csproj files but not Directory.Packages.props. -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.35.0.4138">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,6 +1,6 @@
|
||||
# Terms of Use (EULA) — CommandForge
|
||||
|
||||
> Not legal advice. Last updated: 2026-06-18 · Version 1.1
|
||||
> Not legal advice. Last updated: 2026-10-21 · Version 1.1
|
||||
>
|
||||
> ⚠️ **Important:** CommandForge is licensed under the **GNU GPL v3** (see [LICENSE](LICENSE)).
|
||||
> **The GPLv3 governs your rights to the software.** This document does **not** restrict any
|
||||
@@ -58,3 +58,9 @@ trademark owner mentioned. All trademarks belong to their respective owners. See
|
||||
|
||||
By installing and using the software, you acknowledge that you have read, understood, and agree to
|
||||
this document and to the terms of the GPLv3.
|
||||
|
||||
## 8. Contact
|
||||
|
||||
Questions about these terms or licensing: **[legal@poli0981.dev](mailto:legal@poli0981.dev)**.
|
||||
For copyright, DMCA and other takedown notices, see
|
||||
[DISCLAIMER.md](DISCLAIMER.md#copyright-and-takedown-requests).
|
||||
@@ -4,5 +4,8 @@ CommandForge is currently maintained by:
|
||||
|
||||
- [@poli0981](https://github.com/poli0981) — author & maintainer
|
||||
|
||||
Contact: [code@poli0981.dev](mailto:code@poli0981.dev) for the code and contributions; see the
|
||||
[README](README.md#contact) for the other addresses (security, privacy, legal…).
|
||||
|
||||
Want to help maintain the project? Start by contributing (see
|
||||
[CONTRIBUTING.md](.github/CONTRIBUTING.md)); active, trusted contributors may be invited.
|
||||
+38
-21
@@ -1,41 +1,57 @@
|
||||
# Privacy Policy — CommandForge
|
||||
|
||||
> This is a plain-language summary, not legal advice. Last updated: 2026-06-18.
|
||||
> This is a plain-language summary, not legal advice. Last updated: 2026-10-21.
|
||||
|
||||
## Summary
|
||||
|
||||
**CommandForge does not collect, store on any server, or transmit any of your personal data.**
|
||||
The app runs entirely **locally** on your machine. The **only** network connection it makes is
|
||||
to GitHub, to check for and download software updates.
|
||||
The app runs entirely **locally** on your machine. The **only** network connection the app itself
|
||||
makes is to GitHub, to check for and download software updates.
|
||||
|
||||
## Data processed locally (never leaves your machine)
|
||||
## Data stored on your PC (never leaves your machine)
|
||||
|
||||
| Data | Location | Purpose |
|
||||
|---|---|---|
|
||||
| Settings (theme, language, font size, favorites, window placement, accepted-terms version) | `%AppData%\CommandForge\config.json` | Remember your preferences |
|
||||
| Application logs | `%AppData%\CommandForge\logs\` | Local troubleshooting |
|
||||
| Reports you generate (e.g. exported logs) | A folder you choose | Only when you ask for them |
|
||||
| Settings: theme, language, font size, safety and behavior options, log level, favorites, recent commands, window size and position, accepted-terms version | `%AppData%\CommandForge\config.json` | Remember your preferences |
|
||||
| Execution history: command ID, time, exit code, result, duration | `%AppData%\CommandForge\history.json` | The History page, Run again and Undo |
|
||||
| Recipes you create | `%AppData%\CommandForge\recipes.json` | Your saved command chains |
|
||||
| Commands you add under *My commands* | `%AppData%\CommandForge\user-commands.json` | Your own commands |
|
||||
| Saved settings profiles | `%AppData%\CommandForge\profiles.json` | Switching between profiles |
|
||||
| Application logs (at most 14 daily files of up to 10 MB each) | `%AppData%\CommandForge\logs\` | Local troubleshooting |
|
||||
| Backups of damaged files (`*.corrupt-<timestamp>.json`) | `%AppData%\CommandForge\` | So a damaged file is never silently lost |
|
||||
| Files you export: settings, logs (`.zip`), console output | A location you choose | Only when you ask for them |
|
||||
| The program itself | `%LocalAppData%\CommandForge\` | Installed app files (Velopack) |
|
||||
|
||||
This data stays on your device and is never sent to us or any third party.
|
||||
This data stays on your device and is never sent to us or to any third party. The history stores
|
||||
command IDs and results, not command output.
|
||||
|
||||
**Logs** record app events, errors, and a one-line summary of each command you run (its ID, exit
|
||||
code and duration). They don't contain the commands' output, but they may contain machine-specific
|
||||
details such as file paths, your user name or device names.
|
||||
|
||||
## Network connections
|
||||
|
||||
- **Update check:** the app contacts **GitHub** (releases API + asset download) to see whether a
|
||||
newer version exists and to fetch it. This is subject to
|
||||
[GitHub's Privacy Statement](https://docs.github.com/site-policy). We receive no identifying
|
||||
data from it.
|
||||
- The app makes **no other network connections**.
|
||||
- **Update check:** the app contacts **GitHub** (the releases API and asset downloads) when it
|
||||
starts, if *Check for updates on startup* is on (the default), and whenever you choose **Check
|
||||
for updates** (`F5`). As with any download, GitHub sees your IP address and the request; see
|
||||
[GitHub's Privacy Statement](https://docs.github.com/site-policy/privacy-policies/github-general-privacy-statement).
|
||||
We receive no data from it.
|
||||
- **Links you open** — GitHub, the user guide, the license, *Report a bug* — open in your browser.
|
||||
- The app makes **no other network connections**. Some **commands you choose to run** use the
|
||||
network by their nature (for example winget, DNS and connectivity tests, Windows Update); that
|
||||
traffic goes between Windows and those services, not to us.
|
||||
|
||||
## No telemetry / analytics
|
||||
|
||||
CommandForge contains **no** telemetry, analytics, advertising, or behavioral tracking of any kind.
|
||||
CommandForge contains **no** telemetry, analytics, advertising, crash uploading, or behavioral
|
||||
tracking of any kind.
|
||||
|
||||
## Commands you run
|
||||
## Bug reports
|
||||
|
||||
When you run a command, its output is shown in the app and may be written to the **local** log
|
||||
for troubleshooting. This output is never sent anywhere. If you export logs to file a bug report,
|
||||
**review the contents yourself before sharing** — logs may include machine-specific details
|
||||
(paths, device names) you may not wish to publish.
|
||||
*Report a bug* opens a pre-filled GitHub issue form in your browser with the app version, your
|
||||
Windows version and, after a crash, the error details. **Nothing is sent until you submit the form
|
||||
yourself**, and you can edit it first. If you attach exported logs, **review them before sharing**
|
||||
— they may include paths, user names or device names you may not wish to publish.
|
||||
|
||||
## Children
|
||||
|
||||
@@ -49,6 +65,7 @@ to review the terms again on startup.
|
||||
|
||||
## Contact
|
||||
|
||||
- Privacy questions: **[privacy@poli0981.dev](mailto:privacy@poli0981.dev)**
|
||||
- Security issues: see [SECURITY.md](.github/SECURITY.md) (security@poli0981.dev or private
|
||||
vulnerability reporting).
|
||||
- Repository: https://github.com/poli0981/CommandForge
|
||||
- Questions: open an issue, or use private vulnerability reporting for security matters
|
||||
(see [SECURITY.md](.github/SECURITY.md)).
|
||||
@@ -6,61 +6,90 @@
|
||||
CommandForge is an open-source Windows desktop app that wraps common system commands
|
||||
(winget, DISM, SFC, God Mode, registry tweaks, network reset, power plans, diagnostics…)
|
||||
in a visual, categorized interface. Every command is shown to you **before** it runs, with a
|
||||
clear danger level, optional confirmation, and an optional System Restore Point.
|
||||
clear danger level, a confirmation for anything risky, and an optional System Restore Point.
|
||||
|
||||
- **Windows 10 (22H2) and Windows 11**, x64.
|
||||
- **Open source, GPLv3.**
|
||||
- **Offline-first. No telemetry.** The only network call is to GitHub to check for updates.
|
||||
- **Offline-first. No telemetry.** The only network connection the app makes is to GitHub, to
|
||||
check for updates.
|
||||
- Installed and auto-updated with [Velopack](https://velopack.io/) (per-user, no UAC for updates).
|
||||
|
||||
> **Status:** pre‑1.0. Built by a solo developer with AI assistance (see
|
||||
> [Disclaimer](DISCLAIMER.md) and the AI disclosure below).
|
||||
> Built by a solo developer with AI assistance — see the [Disclaimer](DISCLAIMER.md) and the
|
||||
> AI disclosure below.
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **Categorized command catalog** — browse by group (System & Maintenance, Updates & Packages,
|
||||
Tweaks & Shortcuts, Network, Cleanup, Power, System Info, Diagnostics, Security & Privacy,
|
||||
Developer) with fuzzy search and a Command Palette (`Ctrl+K`).
|
||||
- **Safe by design** — the command catalog is a vetted, read-only embedded resource. The app
|
||||
never loads arbitrary commands and self-elevates. Admin commands run through a separate
|
||||
elevation broker (one UAC prompt per session).
|
||||
- **See before you run** — the exact command line is previewed; `Caution`/`Dangerous` commands
|
||||
require confirmation (type-to-confirm for `Dangerous`), with an optional Restore Point.
|
||||
- **Real-time console** — stream output, cancel long-running commands, detect reboot-required
|
||||
(`exit 3010`).
|
||||
- **Home dashboard** — recent commands, pinned favorites, and a read-only system-status widget
|
||||
(Windows build, RAM, system drive, uptime).
|
||||
- **Polish** — light/dark/system theme, font scaling, live English/Vietnamese switching, a Log
|
||||
Viewer, a Debug panel, and a global crash handler with a "Report a bug" flow.
|
||||
- **261 vetted commands in 12 categories** — System & Maintenance, Updates & Packages, Tweaks &
|
||||
Shortcuts, Network, Cleanup, Power, System Info, Diagnostics, Security & Privacy, Developer,
|
||||
Storage, and Services & Startup. Commands that don't apply to your Windows build are hidden.
|
||||
- **Fluent design** — a Windows 11-style window (Mica, navigation pane, in-window dialogs) that
|
||||
follows your light/dark theme, accent color and High Contrast. It is resizable and remembers its
|
||||
size and position.
|
||||
- **Find anything fast** — accent-insensitive search (`Ctrl+F`), filters by danger level and admin
|
||||
rights, favorites, and a Command Palette over the whole catalog (`Ctrl+K`).
|
||||
- **Safe by design** — the catalog is a read-only part of the app, reviewed by the maintainer;
|
||||
nothing outside it ever runs as administrator. Admin commands run in a separate elevated helper
|
||||
(one UAC prompt per session, which you can end at any time).
|
||||
- **See before you run** — the exact command line is previewed with paths filled in. `Caution`
|
||||
commands ask first; `Dangerous` ones require typing the command's name or ID, and that check
|
||||
can't be turned off. A System Restore Point can be created first.
|
||||
- **Live console** — output streams in real time and stays readable on non-English Windows
|
||||
(UTF-16, UTF-8 and OEM code pages are decoded); cancel, copy, or save it to a file.
|
||||
Restart-required is detected from the exit code (`3010`).
|
||||
- **History, undo and recipes** — run past commands again, undo reversible tweaks (with a registry
|
||||
before/after diff), and chain commands into recipes that confirm every risky step.
|
||||
- **My commands** — save your own commands. They are kept apart from the catalog and always run
|
||||
without admin rights.
|
||||
- **Five languages** — English, Tiếng Việt, 日本語, 简体中文 and Español, switchable without a
|
||||
restart.
|
||||
- **Diagnostics** — Log Viewer, Debug panel, local logs with retention, and a crash dialog with a
|
||||
"Report a bug" flow that never sends anything by itself.
|
||||
|
||||
New here? Read the **[user guide](USAGE.md)**.
|
||||
|
||||
---
|
||||
|
||||
## Install
|
||||
|
||||
1. Download the latest **`CommandForge-win-Setup.exe`** from the
|
||||
[Releases page](https://github.com/poli0981/CommandForge/releases).
|
||||
2. Run it. The app installs per-user and updates itself from future releases.
|
||||
1. Download **`CommandForge-win-Setup.exe`** from the
|
||||
[latest release](https://github.com/poli0981/CommandForge/releases/latest).
|
||||
2. Run it. The app installs per-user (no admin rights needed) and updates itself from future
|
||||
releases.
|
||||
|
||||
### "Unknown publisher" / SmartScreen
|
||||
Already on 1.x? The app offers 2.0 as a normal update; your settings, favorites, history, recipes
|
||||
and commands carry over.
|
||||
|
||||
CommandForge is **not code-signed yet** (see [SECURITY.md](.github/SECURITY.md)), so Windows
|
||||
SmartScreen may warn about an unknown publisher and some antivirus engines may show a false
|
||||
positive (common for system-administration tools). To proceed: **More info → Run anyway**.
|
||||
### "Unknown publisher" and verifying your download
|
||||
|
||||
To verify your download, compare its SHA-256 against the `checksums.txt` attached to the release,
|
||||
and review the VirusTotal link in the release notes:
|
||||
CommandForge is **not Authenticode-signed yet** (see [SECURITY.md](.github/SECURITY.md)), so
|
||||
SmartScreen may warn about an unknown publisher, and some antivirus engines may flag it (common
|
||||
for system-administration tools). To proceed: **More info → Run anyway**.
|
||||
|
||||
```powershell
|
||||
Get-FileHash .\CommandForge-win-Setup.exe -Algorithm SHA256
|
||||
```
|
||||
Every release is built by GitHub Actions from a tagged commit. You can check your download first:
|
||||
|
||||
- **Build provenance** — with the [GitHub CLI](https://cli.github.com/), confirm the file was built
|
||||
by this repository's release workflow:
|
||||
|
||||
```powershell
|
||||
gh attestation verify .\CommandForge-win-Setup.exe --repo poli0981/CommandForge
|
||||
```
|
||||
|
||||
- **SHA-256** — compare with `checksums.txt` on the release page (case doesn't matter):
|
||||
|
||||
```powershell
|
||||
(Get-FileHash .\CommandForge-win-Setup.exe -Algorithm SHA256).Hash
|
||||
```
|
||||
|
||||
- The release notes link a **VirusTotal** scan, and each release ships an SPDX **SBOM**
|
||||
(`sbom.spdx.json`).
|
||||
|
||||
---
|
||||
|
||||
## Build from source
|
||||
|
||||
Requires the **.NET 10 SDK** on Windows 10 22H2 / 11.
|
||||
Requires Windows 10 22H2 / 11 and the **.NET 10 SDK** (the exact band is pinned in `global.json`).
|
||||
|
||||
```bash
|
||||
dotnet restore
|
||||
@@ -69,8 +98,7 @@ dotnet run --project src/CommandForge.Wpf
|
||||
dotnet test
|
||||
```
|
||||
|
||||
See [BUILD.md](BUILD.md) for publish/packaging and [UPDATES.md](UPDATES.md) for how the
|
||||
Velopack update mechanism works.
|
||||
See [BUILD.md](BUILD.md) for packaging and CI, and [UPDATES.md](UPDATES.md) for how updates work.
|
||||
|
||||
---
|
||||
|
||||
@@ -78,15 +106,39 @@ Velopack update mechanism works.
|
||||
|
||||
| Topic | File |
|
||||
|---|---|
|
||||
| User guide | [USAGE.md](USAGE.md) |
|
||||
| Release history | [CHANGELOG.md](CHANGELOG.md) |
|
||||
| Build, test, publish, release | [BUILD.md](BUILD.md) · [RELEASING.md](RELEASING.md) |
|
||||
| Update mechanism (Velopack) | [UPDATES.md](UPDATES.md) |
|
||||
| Contributing & contribution rules | [CONTRIBUTING.md](.github/CONTRIBUTING.md) |
|
||||
| Contributing | [CONTRIBUTING.md](.github/CONTRIBUTING.md) |
|
||||
| Security policy & disclosure | [SECURITY.md](.github/SECURITY.md) |
|
||||
| Privacy policy | [PRIVACY.md](PRIVACY.md) |
|
||||
| Disclaimer | [DISCLAIMER.md](DISCLAIMER.md) |
|
||||
| Terms of use (EULA) | [EULA.md](EULA.md) |
|
||||
| Third-party notices | [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md) |
|
||||
| Code of Conduct | [CODE_OF_CONDUCT.md](.github/CODE_OF_CONDUCT.md) |
|
||||
| Maintainers | [MAINTAINERS.md](MAINTAINERS.md) |
|
||||
|
||||
---
|
||||
|
||||
## Contact
|
||||
|
||||
Bugs and feature requests go to [GitHub Issues](https://github.com/poli0981/CommandForge/issues),
|
||||
and questions to [Discussions](https://github.com/poli0981/CommandForge/discussions). For
|
||||
everything else:
|
||||
|
||||
| Topic | Address |
|
||||
|---|---|
|
||||
| Security vulnerabilities (private) | security@poli0981.dev, or [private vulnerability reporting](https://github.com/poli0981/CommandForge/security/advisories/new) |
|
||||
| Privacy | privacy@poli0981.dev |
|
||||
| Terms, licensing and other legal questions | legal@poli0981.dev |
|
||||
| Copyright questions and permissions | copyright@poli0981.dev |
|
||||
| DMCA notices | dmca@poli0981.dev |
|
||||
| Other takedown requests (trademark, impersonation, unlawful content) | takedown@poli0981.dev |
|
||||
| Code, contributions and Code of Conduct reports | code@poli0981.dev |
|
||||
| Collaboration | collab@poli0981.dev |
|
||||
| Press | press@poli0981.dev |
|
||||
| Sponsorship | sponsor@poli0981.dev |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+40
-23
@@ -5,35 +5,51 @@ SemVer tag.
|
||||
|
||||
## Steps
|
||||
|
||||
1. Update `docs/Changelog.md` (internal) and make sure `main` is green.
|
||||
2. Choose a SemVer version `X.Y.Z`.
|
||||
3. Tag and push:
|
||||
1. Make sure `main` is green and contains everything for the release.
|
||||
2. Choose a SemVer version `X.Y.Z`. In a pull request, move the `[Unreleased]` notes in
|
||||
[CHANGELOG.md](CHANGELOG.md) under `## [X.Y.Z] — <date>`, add the compare link at the bottom,
|
||||
and set `<Version>` in `Directory.Build.props` (the dev-build default; the release build stamps
|
||||
the tag's version anyway). Merge it.
|
||||
3. Tag the merge commit on `main` with a **signed, annotated** tag and push it:
|
||||
|
||||
```bash
|
||||
git tag v0.3.0
|
||||
git push origin v0.3.0
|
||||
git switch main && git pull
|
||||
git tag -s vX.Y.Z -m "CommandForge X.Y.Z"
|
||||
git push origin vX.Y.Z
|
||||
```
|
||||
|
||||
The `release tags` ruleset protects `v*` tags: once pushed, a release tag can't be moved or
|
||||
deleted (only a repository admin can bypass this).
|
||||
4. The **Release** workflow runs on `windows-latest` and:
|
||||
- resolves the version from the tag (`vX.Y.Z` → `X.Y.Z`),
|
||||
- installs `vpk`,
|
||||
- **downloads the previous release** (`vpk download github`) so a delta can be computed
|
||||
(skipped/ignored on the very first release),
|
||||
- publishes self-contained and packages with Velopack (`scripts/pack.ps1`, which stamps the
|
||||
assembly version),
|
||||
- **publishes the GitHub Release** with all `Releases/` assets (`vpk upload github --publish`),
|
||||
- generates **`checksums.txt`** (SHA-256) and attaches it,
|
||||
- if `VT_API_KEY` is set, submits `Setup.exe` + `*-full.nupkg` to **VirusTotal** and appends the
|
||||
scan links to the release notes.
|
||||
5. Edit the GitHub Release notes if needed (changelog highlights). The SHA-256 + VirusTotal info is
|
||||
- resolves the version from the tag (`vX.Y.Z` → `X.Y.Z`);
|
||||
- restores the pinned `vpk` tool and **downloads the previous release** so a delta package can
|
||||
be computed;
|
||||
- publishes and packages with Velopack (`scripts/pack.ps1`);
|
||||
- creates **build-provenance attestations** for `Setup.exe` and the `.nupkg` files;
|
||||
- uploads everything as a **draft** GitHub Release, attaches the **SPDX SBOM**
|
||||
(`sbom.spdx.json`) and **`checksums.txt`** (SHA-256), then **publishes** it as the latest
|
||||
release — installed copies only see the update once every asset is in place;
|
||||
- if `VT_API_KEY` is set, submits `Setup.exe` and the full package to **VirusTotal** and appends
|
||||
the scan links to the release notes;
|
||||
- calls the shared announcer (`poli0981/.github`) to post the release to Discord.
|
||||
5. Check the release page: the assets are all there, and the attestation verifies:
|
||||
|
||||
```bash
|
||||
gh release download vX.Y.Z --pattern "*-Setup.exe"
|
||||
gh attestation verify CommandForge-win-Setup.exe --repo poli0981/CommandForge
|
||||
```
|
||||
|
||||
Edit the release notes if needed (changelog highlights). The SHA-256 and VirusTotal details are
|
||||
already attached.
|
||||
|
||||
You can also run the workflow manually (**Actions → Release → Run workflow**) with a `version`
|
||||
input; it tags `vX.Y.Z` via the upload step.
|
||||
input; the upload step then creates the `vX.Y.Z` tag.
|
||||
|
||||
## Required repository secrets
|
||||
## Repository secrets
|
||||
|
||||
| Secret | Used for | Required |
|
||||
|---|---|---|
|
||||
| `GITHUB_TOKEN` | Create the release & upload assets | automatic |
|
||||
| `GITHUB_TOKEN` | Create the release, upload assets, read the SBOM | automatic |
|
||||
| `VT_API_KEY` | VirusTotal scan + links | optional (step skipped if unset) |
|
||||
| `DISCORD_RELEASES_WEBHOOK` (or `DISCORD_REPO_WEBHOOK`) | Release announcement to Discord | optional |
|
||||
| `DISCORD_PING_ROLE_ID` | Role ping on stable releases | optional |
|
||||
@@ -44,7 +60,8 @@ input; it tags `vX.Y.Z` via the upload step.
|
||||
|
||||
## Code signing
|
||||
|
||||
Not done yet. Releases ship unsigned; users may see a SmartScreen "unknown publisher" warning.
|
||||
Mitigations: SHA-256 + VirusTotal (above), no obfuscation, public source. When Azure Trusted
|
||||
Signing (or SignPath Foundation) is configured, add a signing step after `dotnet publish` and
|
||||
before `vpk pack`, and update [SECURITY.md](.github/SECURITY.md).
|
||||
Not done yet: releases ship without an Authenticode signature, so users may see a SmartScreen
|
||||
"unknown publisher" warning. Mitigations: build-provenance attestations, SHA-256 checksums, an
|
||||
SBOM, VirusTotal, no obfuscation, and public source. When Azure Trusted Signing (or SignPath
|
||||
Foundation) is configured, add a signing step between `dotnet publish` and `vpk pack` in
|
||||
`scripts/pack.ps1`, and update [SECURITY.md](.github/SECURITY.md).
|
||||
+25
-17
@@ -1,29 +1,37 @@
|
||||
# Third-Party Notices
|
||||
|
||||
CommandForge (licensed under GPLv3) bundles or depends on the third-party components below.
|
||||
Each remains under its own license; all are compatible with GPLv3. Versions reflect the current
|
||||
build — see the `.csproj` files for the authoritative versions.
|
||||
Each remains under its own license; every component shipped with the app is compatible with
|
||||
GPLv3. Versions reflect the current build — see the `.csproj` files for the authoritative
|
||||
versions.
|
||||
|
||||
## NuGet packages (runtime)
|
||||
## NuGet packages shipped with the app
|
||||
|
||||
| Component | Version | License | Project |
|
||||
|---|---|---|---|
|
||||
| MaterialDesignThemes (+ MaterialDesignColors) | 5.3.2 | MIT | https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit |
|
||||
| WPF-UI (+ WPF-UI.Abstractions) | 4.3.0 | MIT | https://github.com/lepoco/wpfui |
|
||||
| CommunityToolkit.Mvvm | 8.4.2 | MIT | https://github.com/CommunityToolkit/dotnet |
|
||||
| Microsoft.Extensions.Hosting | 10.0.9 | MIT | https://github.com/dotnet/runtime |
|
||||
| Microsoft.Extensions.DependencyInjection.Abstractions | 10.0.9 | MIT | https://github.com/dotnet/runtime |
|
||||
| Serilog | 4.3.1 | Apache-2.0 | https://github.com/serilog/serilog |
|
||||
| Serilog.Extensions.Hosting | 10.0.0 | Apache-2.0 | https://github.com/serilog/serilog-extensions-hosting |
|
||||
| Microsoft.Extensions.DependencyInjection (+ .Abstractions) | 10.0.13 | MIT | https://github.com/dotnet/runtime |
|
||||
| Serilog | 4.4.0 | Apache-2.0 | https://github.com/serilog/serilog |
|
||||
| Serilog.Sinks.File | 7.0.0 | Apache-2.0 | https://github.com/serilog/serilog-sinks-file |
|
||||
| Serilog.Sinks.Async | 2.1.0 | Apache-2.0 | https://github.com/serilog/serilog-sinks-async |
|
||||
| Velopack | 1.2.0 | MIT | https://github.com/velopack/velopack |
|
||||
| System.Text.Json | (bundled with .NET 10) | MIT | https://github.com/dotnet/runtime |
|
||||
| Velopack (library, installer and update helpers) | 1.2.161 | MIT | https://github.com/velopack/velopack |
|
||||
| System.Text.Json and the rest of the .NET libraries | (bundled with .NET 10) | MIT | https://github.com/dotnet/runtime |
|
||||
|
||||
## Build-time only (not redistributed)
|
||||
WPF-UI incorporates code from VirtualizingWrapPanel, dotnet/wpf and microsoft-ui-xaml (all MIT)
|
||||
and the Fluent System Icons (below); see the `ThirdPartyNotices.txt` in the WPF-UI package.
|
||||
|
||||
## Build and test tools (not redistributed)
|
||||
|
||||
| Component | Version | License | Project |
|
||||
|---|---|---|---|
|
||||
| Microsoft.Windows.CsWin32 | 0.3.296 | MIT | https://github.com/microsoft/CsWin32 |
|
||||
| Microsoft.Windows.CsWin32 | 0.3.366 | MIT | https://github.com/microsoft/CsWin32 |
|
||||
| SonarAnalyzer.CSharp | 10.35.0.4138 | SONAR Source-Available License v1.0 | https://github.com/SonarSource/sonar-dotnet |
|
||||
| vpk (Velopack CLI) | 1.2.161 | MIT | https://github.com/velopack/velopack |
|
||||
| xunit.v3 (`xunit.v3.mtp-off`) | 4.0.2 | Apache-2.0 | https://github.com/xunit/xunit |
|
||||
| xunit.runner.visualstudio | 4.0.1 | Apache-2.0 | https://github.com/xunit/visualstudio.xunit |
|
||||
| Microsoft.NET.Test.Sdk | 18.11.0 | MIT | https://github.com/microsoft/vstest |
|
||||
| coverlet.collector | 10.1.0 | MIT | https://github.com/coverlet-coverage/coverlet |
|
||||
|
||||
## Runtime & platform
|
||||
|
||||
@@ -31,11 +39,11 @@ build — see the `.csproj` files for the authoritative versions.
|
||||
|
||||
## Fonts & icons
|
||||
|
||||
- **Material Design Icons** (via MaterialDesignThemes `PackIcon`) — Apache-2.0 / SIL OFL 1.1 —
|
||||
https://github.com/Templarian/MaterialDesign
|
||||
- **Cascadia Code / Cascadia Mono** (console/monospace, referenced by name with fallbacks; not
|
||||
bundled) — SIL OFL 1.1 — https://github.com/microsoft/cascadia-code
|
||||
- **Segoe UI / Segoe UI Variable** — Windows system font (not bundled).
|
||||
- **Fluent System Icons** (bundled inside WPF-UI; used for every icon in the app) — MIT,
|
||||
© Microsoft Corporation — https://github.com/microsoft/fluentui-system-icons
|
||||
- **Cascadia Mono** (console and code text, referenced by name with Consolas / Courier New
|
||||
fallbacks; not bundled) — SIL OFL 1.1 — https://github.com/microsoft/cascadia-code
|
||||
- **Segoe UI Variable / Segoe UI** — Windows system fonts (not bundled).
|
||||
|
||||
## AI disclosure
|
||||
|
||||
|
||||
+37
-20
@@ -6,21 +6,37 @@ CommandForge installs and updates itself with [Velopack](https://velopack.io/).
|
||||
## For users
|
||||
|
||||
1. Download `CommandForge-win-Setup.exe` from the
|
||||
[latest release](https://github.com/poli0981/CommandForge/releases) and run it. It installs
|
||||
per-user under `%LocalAppData%\CommandForge`.
|
||||
2. After that, the app checks GitHub Releases for newer versions (on startup if enabled, or via
|
||||
**Help → Check for updates** / `F5`) and updates itself. When a newer version exists it downloads
|
||||
the update (a small **delta** when possible) and applies it on restart.
|
||||
[latest release](https://github.com/poli0981/CommandForge/releases/latest) and run it. It
|
||||
installs per-user under `%LocalAppData%\CommandForge`.
|
||||
2. After that, the app checks GitHub Releases for newer versions — on startup if **Settings →
|
||||
Updates → Check for updates on startup** is on (the default), or when you choose **More (⋯) →
|
||||
Check for updates** or press `F5`.
|
||||
3. When a newer version exists, choose **Download & restart**. The app downloads the update (a
|
||||
small **delta** when possible), then restarts into the new version.
|
||||
|
||||
The only network connection involved is to GitHub (see [PRIVACY.md](PRIVACY.md)). Update errors are
|
||||
mapped to clear messages: offline, not found (404), rate limited (403/429), and server error (5xx).
|
||||
Good to know:
|
||||
|
||||
- Closing the update dialog — including with its **X** button — cancels the download.
|
||||
- The app never restarts in the middle of a command: if one is running, finish or cancel it first.
|
||||
If you start a command while the update downloads, the restart waits; choose **Download &
|
||||
restart** again when the command is done.
|
||||
- Before applying an update, the app ends the admin session, because the elevated helper runs
|
||||
from the folder that Velopack replaces.
|
||||
- Errors are shown in plain words: offline or timed out, no release feed found (404), rate limited
|
||||
(403/429), and GitHub server error (5xx).
|
||||
|
||||
The only network connection involved is to GitHub (see [PRIVACY.md](PRIVACY.md)).
|
||||
|
||||
## How it works under the hood
|
||||
|
||||
- The app calls `VelopackApp.Build().Run()` at startup to handle install/update/uninstall hooks.
|
||||
- It checks for updates via `UpdateManager(new GithubSource("https://github.com/poli0981/CommandForge", null, prerelease: false))`.
|
||||
- Auto-update only works for an **installed** build (not a dev/portable run); the app detects this
|
||||
and hides update prompts otherwise.
|
||||
- `Program.Main` calls `VelopackApp.Build().Run()` before WPF starts, to handle the
|
||||
install/update/uninstall hooks.
|
||||
- The app checks for updates via
|
||||
`UpdateManager(new GithubSource("https://github.com/poli0981/CommandForge", null, prerelease: false))`.
|
||||
- Download and apply are separate steps, so the app can end the admin session and check for a
|
||||
running command just before it restarts.
|
||||
- Auto-update only works for an **installed** build (not a dev or portable run); the app detects
|
||||
this and says so instead of offering an update.
|
||||
|
||||
## Release artifacts and the delta mechanism
|
||||
|
||||
@@ -33,15 +49,16 @@ Each release (see [RELEASING.md](RELEASING.md)) uploads the contents of `Release
|
||||
| `CommandForge-<version>-delta.nupkg` | Delta from the previous version (small download) |
|
||||
| `releases.win.json` / `RELEASES` | Update manifest the client reads |
|
||||
| `checksums.txt` | SHA-256 of the assets (manual verification) |
|
||||
| `sbom.spdx.json` | SPDX software bill of materials |
|
||||
|
||||
**First release (e.g. `v0.3.0`):** there is no previous version, so only a **full** package +
|
||||
`Setup.exe` + manifest are produced and uploaded.
|
||||
The installer and packages also have build-provenance attestations (see the
|
||||
[README](README.md#unknown-publisher-and-verifying-your-download)).
|
||||
|
||||
**Subsequent releases (e.g. `v0.3.1`):** Velopack needs the **previous** `-full.nupkg` present
|
||||
while packing to compute the delta. The release workflow does this automatically by running
|
||||
`vpk download github` before `vpk pack`, so each release after the first produces **both** a
|
||||
`-full.nupkg` and a `-delta.nupkg`. Clients already on `0.3.0` download only the small
|
||||
`-delta.nupkg`; the full package remains the fallback.
|
||||
Velopack needs the **previous** `-full.nupkg` present while packing to compute a delta. The
|
||||
release workflow runs `vpk download github` before `vpk pack`, so every release after the first
|
||||
produces **both** a `-full.nupkg` and a `-delta.nupkg`. Clients on the previous version (for
|
||||
example 1.5.1 when 2.0.0 ships) download only the delta; the full package remains the fallback. The very first release had no previous version, so it shipped only a full package.
|
||||
|
||||
> If you ever build a release **locally**, run `vpk download github --repoUrl <repo>` first so the
|
||||
> prior full package is available for the delta — otherwise only a full package is produced.
|
||||
> If you ever build a release **locally**, run `dotnet vpk download github --repoUrl <repo>`
|
||||
> first so the prior full package is available for the delta — otherwise only a full package is
|
||||
> produced.
|
||||
@@ -0,0 +1,264 @@
|
||||
# CommandForge user guide
|
||||
|
||||
CommandForge runs Windows maintenance commands for you: pick a command, read what it will do, and
|
||||
run it. This guide covers version 2.0. For installing and verifying downloads, see the
|
||||
[README](README.md#install).
|
||||
|
||||
- [First start](#first-start)
|
||||
- [The window](#the-window)
|
||||
- [Finding a command](#finding-a-command)
|
||||
- [Running a command](#running-a-command)
|
||||
- [Home](#home)
|
||||
- [History and undo](#history-and-undo)
|
||||
- [Recipes](#recipes)
|
||||
- [My commands](#my-commands)
|
||||
- [Settings](#settings)
|
||||
- [Log viewer and Debug panel](#log-viewer-and-debug-panel)
|
||||
- [Keyboard shortcuts](#keyboard-shortcuts)
|
||||
- [Updates](#updates)
|
||||
- [Your data and uninstalling](#your-data-and-uninstalling)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
|
||||
## First start
|
||||
|
||||
The first time you open CommandForge, it asks you to accept its terms:
|
||||
|
||||
1. Pick your language in the list above the terms. English, Tiếng Việt, 日本語, 简体中文 and
|
||||
Español are available, and you can change it later in Settings.
|
||||
2. Read the summaries on the **EULA**, **GPLv3**, **Disclaimer** and **Privacy** tabs. **Read the
|
||||
full text on GitHub** opens the complete documents.
|
||||
3. Tick **I have read and agree to all of the terms**, then choose **Continue**.
|
||||
|
||||
You'll be asked again only if the terms change.
|
||||
|
||||
## The window
|
||||
|
||||
- **Title bar**
|
||||
- The search box, **Search all commands (Ctrl+K)**, opens the Command Palette.
|
||||
- **Admin session active** appears while administrator commands can run without a new UAC
|
||||
prompt. Open it to **End admin session**.
|
||||
- **More (⋯)** holds the Command Palette, **Check for updates**, **Create System Restore
|
||||
Point**, **Export logs (.zip)**, the config and log folders, **Portable info**, **Keyboard
|
||||
shortcuts**, **User guide**, **Report a bug**, **Terms & Privacy** and **About CommandForge**.
|
||||
- **Navigation pane** (left)
|
||||
- Home, Favorites, History, Recipes and My commands.
|
||||
- **Command catalog**, with its 12 categories and the number of commands in each.
|
||||
- Log viewer, Debug panel and Settings, at the bottom.
|
||||
- `Ctrl+B` shows or hides the pane.
|
||||
- The window can be resized (down to a minimum size) and maximized. It reopens where you left it.
|
||||
|
||||
## Finding a command
|
||||
|
||||
- **Browse**: open **Command catalog** or one of its categories. Commands that don't apply to your
|
||||
version of Windows are hidden.
|
||||
- **Search**: type in the search box above the list (`Ctrl+F`). Search ignores case and accents
|
||||
("don dep" finds "Dọn dẹp") and matches titles, descriptions and tags. For everyday phrases such
|
||||
as "clean disk", a **Did you mean:** suggestion offers the catalog's own word.
|
||||
- **Filter**: the chips above the list show only **Safe**, **Caution** or **Dangerous** commands,
|
||||
or **Admin only**. **Clear filters** resets them.
|
||||
- **Favorites**: select the star on a command to pin it. Pinned commands appear on the
|
||||
**Favorites** page and on Home.
|
||||
- **Command Palette** (`Ctrl+K`): search the whole catalog from anywhere. Use `↑`/`↓` to move and
|
||||
`Enter` to open the command.
|
||||
|
||||
## Running a command
|
||||
|
||||
Select a command to see its details:
|
||||
|
||||
- its description and danger level (**Safe**, **Caution** or **Dangerous**);
|
||||
- whether it **Requires admin** or **May require restart**;
|
||||
- the **Estimated time**;
|
||||
- **Command to run** — the exact command line, with paths filled in. **Copy** copies it.
|
||||
|
||||
Choose **Run** to start it. A command that can be undone also shows **Revert**.
|
||||
|
||||
### Danger levels and confirmations
|
||||
|
||||
| Level | Meaning | Before it runs |
|
||||
|---|---|---|
|
||||
| **Safe** | No risk of losing data: read-only queries, opening a tool or settings page, or a small preference change you can undo the same way. | Runs right away. |
|
||||
| **Caution** | Changes system state (services, registry, caches, boot-time checks). Recoverable, but undoing it may take effort. | Asks you to confirm, unless you turned that off in Settings. |
|
||||
| **Dangerous** | May lose data, remove a rollback option or leave Windows unstable. | You must type the command's name (or the ID shown) before **Run** appears. This can't be turned off. |
|
||||
|
||||
In every confirmation, **Cancel** is the default and `Esc` closes the dialog.
|
||||
|
||||
### System Restore Points
|
||||
|
||||
For risky administrator commands, the confirmation offers **Create a System Restore Point first
|
||||
(recommended)**.
|
||||
|
||||
- Windows allows only one restore point every 24 hours. If a recent one exists, CommandForge says
|
||||
it skipped creating a new one.
|
||||
- If creating it fails, you're asked whether to run the command without one. **No** is the
|
||||
default.
|
||||
|
||||
You can also create one at any time from **More → Create System Restore Point**.
|
||||
|
||||
### Administrator commands
|
||||
|
||||
The first administrator command of a session shows a Windows UAC prompt for
|
||||
**CommandForge.Elevator**, and the console shows **Waiting for administrator permission…**.
|
||||
|
||||
- If you approve, the elevated helper stays open, so later admin commands run without another
|
||||
prompt. **Admin session active** appears in the title bar.
|
||||
- **End admin session** closes the helper when you're done; the next admin command asks again.
|
||||
- If you decline the prompt, the command doesn't run.
|
||||
|
||||
The rest of CommandForge never runs as administrator.
|
||||
|
||||
### The console
|
||||
|
||||
Output appears live below the details. Drag the splitter to give it more room.
|
||||
|
||||
- **Cancel** stops the running command.
|
||||
- **Copy all output** and **Save output to a file** keep a copy of what it printed.
|
||||
- When the command ends, the console shows the result (**Success**, **Failed** or **Cancelled**),
|
||||
the exit code and how long it took.
|
||||
- Very long output keeps the newest 10,000 lines; a note tells you how many earlier lines aren't
|
||||
shown.
|
||||
- Registry tweaks list the affected values before and after the run.
|
||||
- While a command runs, the taskbar button shows progress. If you moved to another page when it
|
||||
finishes, a notification tells you the result; if CommandForge is in the background, its
|
||||
taskbar button also flashes.
|
||||
|
||||
### Restarting Windows
|
||||
|
||||
When a command reports that a restart is needed (exit code 3010, or a command that always needs
|
||||
one), the console shows **Restart now**. It asks before restarting and isn't available while a
|
||||
command is running.
|
||||
|
||||
## Home
|
||||
|
||||
Home shows:
|
||||
|
||||
- **System status**: Windows build, memory, system drive space and uptime.
|
||||
- **Maintenance suggestions**: for example, Disk Cleanup when the system drive is low on space, or
|
||||
a restart after a week of uptime. **Open** shows the suggested command.
|
||||
- Your **Recent commands** and **Favorites**.
|
||||
|
||||
## History and undo
|
||||
|
||||
**History** lists every command you ran, with the time, result and duration.
|
||||
|
||||
- **Run again** repeats a command, with the same confirmations as the first time.
|
||||
- **Undo** appears for commands that have a vetted revert command (for example, turning a tweak
|
||||
back off).
|
||||
- **Clear history** deletes the list after asking.
|
||||
|
||||
Run again and Undo are unavailable while another command is running.
|
||||
|
||||
## Recipes
|
||||
|
||||
A recipe runs several catalog commands in order.
|
||||
|
||||
1. Open **Recipes** and choose **New**, then give the recipe a name.
|
||||
2. Use **Add a command…** and **Add** to append steps. Reorder them with **Move up** and **Move
|
||||
down**, or use **Remove step**.
|
||||
3. Choose **Save**, then **Run recipe**.
|
||||
|
||||
When a recipe runs:
|
||||
|
||||
- You first see an overview of its steps and confirm (**No** is the default).
|
||||
- Each Caution or Dangerous step then asks exactly as it would on its own.
|
||||
- If any step is a risky administrator command, a restore point is offered once, before the
|
||||
first step.
|
||||
- Administrator steps share one admin session, so you get a single UAC prompt.
|
||||
- The recipe stops if a step fails, and pauses if a step needs a restart. **Cancel** stops it.
|
||||
- Steps that aren't available on this PC stay in the recipe but are skipped.
|
||||
|
||||
## My commands
|
||||
|
||||
Under **My commands** you can save your own command lines, such as a `ping` you run often.
|
||||
|
||||
- They are **not part of the vetted catalog** and always run **without administrator rights**.
|
||||
You alone are responsible for what they do.
|
||||
- Choose **New**, fill in **Name**, **Executable** (for example `cmd` or `powershell`) and
|
||||
**Arguments**, then choose **Save**.
|
||||
- **Run** shows the exact command line and asks before running it.
|
||||
- With `cmd`, `/c` is added for you, so `cmd` + `ping example.com` runs `cmd /c ping example.com`.
|
||||
|
||||
## Settings
|
||||
|
||||
| Section | Options |
|
||||
|---|---|
|
||||
| **Appearance** | Theme (System, Light, Dark), Language, Font size (Small, Medium, Large). |
|
||||
| **Behavior & Safety** | Collapse the navigation pane by default; show Admin/Restart badges in lists; confirm before Caution commands; confirm before Dangerous commands (always on); tick "create a restore point" by default for risky admin commands; auto-scroll the console; warn before closing while a command is running. |
|
||||
| **Updates** | Check for updates on startup, the current version, the last check and **Check now**. |
|
||||
| **Backup & profiles** | **Export…** / **Import…** your appearance, behavior and favorites as a `.json` file, and save named profiles (for example "Gaming PC" or "Office") that you can **Apply** or **Delete**. |
|
||||
| **Logs** | Log level, log size, **Open log folder**, **Export logs (.zip)**, **Delete old logs**. |
|
||||
| **Advanced** | Run mode (Installed or Portable / dev), the config folder, the Debug panel, and **Reset to defaults** (keeps your accepted terms and logs). |
|
||||
| **About** | Version, license and GitHub links. |
|
||||
|
||||
Theme, language and font size change immediately; no restart needed.
|
||||
|
||||
## Log viewer and Debug panel
|
||||
|
||||
- **Log viewer** (`Ctrl+L`) shows this session's log.
|
||||
- Filter by level or text, and turn auto-scroll on or off.
|
||||
- **Open log folder** or **Export logs (.zip)** to share them. Review an export before you share
|
||||
it.
|
||||
- **Clear** empties the list shown.
|
||||
- **Debug panel** has three tabs:
|
||||
- **Log**: the detailed log.
|
||||
- **Catalog**: command and category counts, plus any validation errors.
|
||||
- **System info**: details you can **Copy** into a bug report.
|
||||
|
||||
## Keyboard shortcuts
|
||||
|
||||
| Keys | Action |
|
||||
|---|---|
|
||||
| `Ctrl+K` | Open the Command Palette |
|
||||
| `Ctrl+F` | Search the current list |
|
||||
| `Ctrl+H` | Home |
|
||||
| `Ctrl+B` | Show or hide the navigation pane |
|
||||
| `Ctrl+,` | Settings |
|
||||
| `Ctrl+L` | Log viewer |
|
||||
| `F5` | Check for updates |
|
||||
| `Ctrl+Q` | Exit |
|
||||
| `↑` / `↓` | Move the selection (lists and palette) |
|
||||
| `Enter` | Open the selected command |
|
||||
| `Esc` | Close a dialog or cancel |
|
||||
|
||||
Shortcuts are paused while a dialog is open, and `AltGr` combinations never trigger them, so
|
||||
typing characters like `@` on international keyboards is safe. The list is also under **More →
|
||||
Keyboard shortcuts**.
|
||||
|
||||
## Updates
|
||||
|
||||
The app checks GitHub for new versions on startup (unless you turned that off) and when you press
|
||||
`F5`.
|
||||
|
||||
- When an update is available, choose **Download & restart**.
|
||||
- Closing the dialog cancels the download.
|
||||
- The app never restarts while a command is running.
|
||||
|
||||
See [UPDATES.md](UPDATES.md) for details.
|
||||
|
||||
## Your data and uninstalling
|
||||
|
||||
Everything stays on your PC:
|
||||
|
||||
- Settings, history, recipes, your commands and profiles are in `%AppData%\CommandForge`.
|
||||
- Logs are in `%AppData%\CommandForge\logs`.
|
||||
- The program itself is in `%LocalAppData%\CommandForge`.
|
||||
|
||||
**More → Portable info** shows the exact folders. Nothing is sent anywhere except the update check
|
||||
— see [PRIVACY.md](PRIVACY.md).
|
||||
|
||||
To uninstall, go to **Settings → Apps → Installed apps** in Windows (**Apps & features** on
|
||||
Windows 10), find **CommandForge** and choose **Uninstall**. To also remove your settings and history, delete `%AppData%\CommandForge`
|
||||
afterwards.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **SmartScreen or antivirus warnings**: releases aren't code-signed yet. See
|
||||
[verifying your download](README.md#unknown-publisher-and-verifying-your-download).
|
||||
- **Nothing happens when I open the app**: it runs as a single instance, so a second launch brings
|
||||
the existing window forward. If it still doesn't appear, check the logs in
|
||||
`%AppData%\CommandForge\logs`.
|
||||
- **An admin command didn't run**: it needs the UAC prompt to be approved. Run it again to get a
|
||||
new prompt. If admin commands keep failing, use **End admin session** and try again.
|
||||
- **Output looks garbled**: please report it with the command and your Windows display language.
|
||||
- **Something went wrong**: the error dialog has an **Error code** and **Copy details**.
|
||||
**Report a bug** (also in the More menu) opens a pre-filled GitHub issue. Nothing is sent until
|
||||
you submit it. Export the logs to attach them, but review them first.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "10.0.301",
|
||||
"version": "10.0.402",
|
||||
"rollForward": "latestFeature"
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,9 @@
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<RootNamespace>CommandForge.Elevator</RootNamespace>
|
||||
<!-- The Elevator runs as administrator but inherits the user's environment block: never honour
|
||||
DOTNET_STARTUP_HOOKS, which would load an arbitrary assembly into the elevated process. -->
|
||||
<StartupHookSupport>false</StartupHookSupport>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
//
|
||||
// Connects to the UI's named pipe and serves ONLY admin commands from its OWN embedded catalog
|
||||
// (golden rules #1/#2). It never builds a command line from pipe input — it accepts a commandId,
|
||||
// looks it up, validates requiresAdmin, and runs it.
|
||||
// looks it up, validates requiresAdmin, and runs it. It writes no files: diagnostics go back to
|
||||
// the UI over the pipe (a file in the user-writable profile could be redirected by a junction).
|
||||
|
||||
using System.IO.Pipes;
|
||||
using CommandForge.Infrastructure;
|
||||
using System.Security.Principal;
|
||||
using CommandForge.Infrastructure.Catalog;
|
||||
using CommandForge.Infrastructure.Elevation;
|
||||
using CommandForge.Infrastructure.Execution;
|
||||
@@ -15,29 +16,23 @@ if (args.Length < 1 || string.IsNullOrWhiteSpace(args[0]))
|
||||
return 2;
|
||||
}
|
||||
|
||||
var pipeName = args[0];
|
||||
AppPaths.EnsureCreated();
|
||||
var logPath = Path.Combine(AppPaths.LogsDirectory, "elevator.log");
|
||||
|
||||
void Log(string message) =>
|
||||
File.AppendAllText(logPath, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}");
|
||||
|
||||
try
|
||||
{
|
||||
Log($"Starting; connecting to pipe {pipeName}");
|
||||
|
||||
using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
|
||||
// Identification level: the (non-elevated) pipe server may learn who we are but cannot act as us.
|
||||
using var client = new NamedPipeClientStream(".", args[0], PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Identification);
|
||||
await client.ConnectAsync(30_000);
|
||||
Log("Connected to UI");
|
||||
|
||||
var server = new ElevationServer(new JsonCatalogProvider(), new ProcessCommandExecutor(new SystemProcessRunner()));
|
||||
await server.RunAsync(client, CancellationToken.None);
|
||||
if (!PeerVerifier.IsExpectedServer(client))
|
||||
{
|
||||
return 3; // someone else owns the pipe — serve nothing
|
||||
}
|
||||
|
||||
Log("Pipe closed; exiting");
|
||||
// Elevated children get a clean environment (see ChildEnvironment for why).
|
||||
var executor = new ProcessCommandExecutor(new SystemProcessRunner(ChildEnvironment.Apply));
|
||||
await new ElevationServer(new JsonCatalogProvider(), executor).RunAsync(client, CancellationToken.None);
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException or OperationCanceledException)
|
||||
{
|
||||
Log($"Failed: {ex}");
|
||||
return 1;
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
# Disclaimer — CommandForge
|
||||
|
||||
> **BẢN NHÁP — không phải tư vấn pháp lý.** Rà soát trước khi công bố.
|
||||
>
|
||||
> *Cập nhật lần cuối: [ĐIỀN NGÀY]*
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Sử dụng với rủi ro của riêng bạn
|
||||
|
||||
CommandForge là công cụ **thực thi các lệnh cấp hệ thống** trên Windows. Việc sử dụng có thể dẫn đến:
|
||||
|
||||
- Thay đổi cấu hình hệ thống (registry, dịch vụ, tính năng Windows…).
|
||||
- **Mất dữ liệu** hoặc hệ thống **không ổn định** nếu dùng sai hoặc trong điều kiện không phù hợp.
|
||||
- Cần khởi động lại máy để hoàn tất một số thao tác.
|
||||
|
||||
**Bạn tự chịu hoàn toàn trách nhiệm** với mọi lệnh bạn chọn chạy và mọi hậu quả.
|
||||
|
||||
---
|
||||
|
||||
## Khuyến nghị an toàn
|
||||
|
||||
- **Sao lưu** dữ liệu quan trọng trước khi dùng các lệnh có rủi ro.
|
||||
- **Tạo System Restore Point** trước các thao tác mức `Caution`/`Dangerous` (ứng dụng có hỗ trợ).
|
||||
- Đọc kỹ **mô tả & phần xem trước lệnh** trước khi chạy.
|
||||
- Không chạy lệnh bạn không hiểu rõ.
|
||||
|
||||
---
|
||||
|
||||
## Không bảo hành
|
||||
|
||||
Phần mềm được cung cấp **"NGUYÊN TRẠNG" (AS IS)**, không kèm bảo hành dưới bất kỳ hình thức nào. Tác giả và người đóng góp **không chịu trách nhiệm** cho bất kỳ thiệt hại nào phát sinh từ việc sử dụng phần mềm. Xem chi tiết ở `EULA.md` (mục 3, 4) và `LICENSE` (GPLv3 mục 15, 16).
|
||||
|
||||
---
|
||||
|
||||
## Không liên kết & nhãn hiệu
|
||||
|
||||
- CommandForge là dự án độc lập, **không** liên kết, tài trợ, hay được xác nhận bởi **Microsoft Corporation** hay bất kỳ bên nào.
|
||||
- "Windows", "Microsoft", "Hyper-V", và các tên liên quan là **nhãn hiệu của Microsoft Corporation**. Các nhãn hiệu khác thuộc về chủ sở hữu tương ứng. Việc nhắc tới chỉ nhằm mục đích mô tả/tương thích.
|
||||
- Các lệnh được gọi (DISM, SFC, winget, powercfg, netsh…) là **công cụ sẵn có của Windows**; CommandForge chỉ cung cấp giao diện thuận tiện để gọi chúng.
|
||||
|
||||
---
|
||||
|
||||
## Tính chính xác của thông tin
|
||||
|
||||
Mô tả lệnh và tài liệu được cung cấp với thiện chí nhưng **có thể không đầy đủ hoặc không cập nhật** cho mọi phiên bản Windows. Hành vi của lệnh có thể khác nhau giữa Windows 10 và 11 và theo bản cập nhật của hệ điều hành.
|
||||
@@ -1,57 +0,0 @@
|
||||
# End User License Agreement (EULA) — CommandForge
|
||||
|
||||
> **BẢN NHÁP — không phải tư vấn pháp lý.** Rà soát trước khi công bố.
|
||||
>
|
||||
> ⚠️ **Quan trọng:** CommandForge được cấp phép theo **GNU GPL v3** (xem `LICENSE`). **GPLv3 là giấy phép điều chỉnh quyền của bạn đối với phần mềm.** Tài liệu "EULA" này **không** hạn chế bất kỳ quyền nào mà GPLv3 trao cho bạn; nó chỉ là **xác nhận rủi ro và miễn trừ trách nhiệm khi sử dụng**. Nếu có mâu thuẫn, **GPLv3 ưu tiên**.
|
||||
>
|
||||
> *Cập nhật lần cuối: [ĐIỀN NGÀY] · Phiên bản: 1.0*
|
||||
|
||||
---
|
||||
|
||||
## 1. Giấy phép
|
||||
|
||||
Phần mềm này là mã nguồn mở theo **GNU General Public License v3.0**. Bạn được quyền sử dụng, sao chép, sửa đổi và phân phối theo các điều khoản của GPLv3. Toàn văn: `LICENSE` (hoặc https://www.gnu.org/licenses/gpl-3.0.html).
|
||||
|
||||
Tài liệu này **không thay thế** GPLv3 và **không thêm ràng buộc** trái với GPLv3.
|
||||
|
||||
---
|
||||
|
||||
## 2. Bản chất phần mềm & chấp nhận rủi ro
|
||||
|
||||
Bạn hiểu và đồng ý rằng:
|
||||
|
||||
1. CommandForge **thực thi các lệnh cấp hệ thống** (ví dụ DISM, SFC, winget, thay đổi registry, reset mạng…) trên máy của bạn.
|
||||
2. Các thao tác này **có thể gây thay đổi cấu hình hệ thống, mất dữ liệu, hoặc khiến hệ thống không ổn định** nếu dùng sai hoặc trong điều kiện không phù hợp.
|
||||
3. Bạn **tự chịu trách nhiệm** với mọi lệnh bạn chọn chạy và mọi hậu quả phát sinh.
|
||||
4. Bạn nên **sao lưu dữ liệu quan trọng** và cân nhắc **tạo điểm khôi phục (Restore Point)** trước khi chạy lệnh có rủi ro.
|
||||
|
||||
---
|
||||
|
||||
## 3. Miễn trừ bảo hành
|
||||
|
||||
Phần mềm được cung cấp **"NGUYÊN TRẠNG" (AS IS), KHÔNG KÈM BẢO HÀNH** dưới bất kỳ hình thức nào, rõ ràng hay ngụ ý, bao gồm nhưng không giới hạn ở khả năng thương mại, sự phù hợp cho mục đích cụ thể, và không vi phạm. (Phù hợp với **GPLv3 mục 15**.)
|
||||
|
||||
---
|
||||
|
||||
## 4. Giới hạn trách nhiệm
|
||||
|
||||
Trong phạm vi pháp luật cho phép, tác giả/người đóng góp **không chịu trách nhiệm** cho bất kỳ thiệt hại nào (mất dữ liệu, gián đoạn, hư hỏng hệ thống, thiệt hại trực tiếp/gián tiếp/ngẫu nhiên) phát sinh từ việc sử dụng hoặc không thể sử dụng phần mềm. (Phù hợp với **GPLv3 mục 16**.)
|
||||
|
||||
---
|
||||
|
||||
## 5. Quyền & cách dùng phù hợp
|
||||
|
||||
- Sử dụng phần mềm tuân thủ pháp luật áp dụng tại nơi bạn ở.
|
||||
- Phần mềm dành cho việc quản trị **máy tính của chính bạn** hoặc máy bạn được phép quản trị.
|
||||
|
||||
---
|
||||
|
||||
## 6. Không liên kết với bên thứ ba
|
||||
|
||||
CommandForge **không** liên kết, tài trợ, hay được xác nhận bởi Microsoft hoặc bất kỳ chủ sở hữu thương hiệu nào được nhắc tới. Mọi nhãn hiệu thuộc về chủ sở hữu tương ứng. Xem `Disclaimer.md`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Chấp nhận
|
||||
|
||||
Bằng việc cài đặt và sử dụng phần mềm, bạn xác nhận đã đọc, hiểu và đồng ý với tài liệu này cùng các điều khoản của GPLv3.
|
||||
@@ -1,56 +0,0 @@
|
||||
# LICENSE — CommandForge
|
||||
|
||||
> Đây là **chỉ dẫn** về giấy phép. Toàn văn GPLv3 nên đặt trong file `LICENSE` (hoặc `COPYING`) ở **gốc repo** — lấy bản chuẩn tại: https://www.gnu.org/licenses/gpl-3.0.txt (đừng tự gõ tay).
|
||||
|
||||
---
|
||||
|
||||
## Giấy phép dự án
|
||||
|
||||
**CommandForge** được cấp phép theo **GNU General Public License v3.0 (GPLv3)**.
|
||||
|
||||
- Bạn được tự do **sử dụng, nghiên cứu, sửa đổi và phân phối** phần mềm theo các điều khoản GPLv3.
|
||||
- Mọi bản phân phối (gồm bản đã sửa) phải **kèm mã nguồn tương ứng** và **giữ nguyên giấy phép GPLv3**.
|
||||
- Phần mềm cung cấp **không kèm bảo hành** (GPLv3 mục 15, 16).
|
||||
|
||||
---
|
||||
|
||||
## Cách áp dụng (header gợi ý cho file mã nguồn)
|
||||
|
||||
```
|
||||
CommandForge — giao diện trực quan chạy lệnh hệ thống Windows.
|
||||
Copyright (C) [NĂM] [TÊN/HANDLE]
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Giấy phép bên thứ ba (tương thích GPLv3)
|
||||
|
||||
| Thành phần | Giấy phép |
|
||||
|---|---|
|
||||
| .NET 10 runtime, CommunityToolkit.Mvvm, MaterialDesignThemes/Colors, CsWin32, Velopack, System.Text.Json, Microsoft.Extensions.* | MIT |
|
||||
| Serilog (+ sinks) | Apache-2.0 |
|
||||
| Cascadia Code/Mono (font) | SIL OFL 1.1 |
|
||||
| (tùy chọn) Inter / JetBrains Mono | SIL OFL 1.1 |
|
||||
|
||||
> MIT, Apache-2.0 và OFL đều **tương thích** với GPLv3. Khi thêm phụ thuộc mới, kiểm tra tương thích trước. Chi tiết phiên bản: `docs/tech.md`.
|
||||
|
||||
---
|
||||
|
||||
## Ghi nhận
|
||||
|
||||
- Font **Cascadia** © Microsoft (OFL).
|
||||
- Biểu tượng **Material Design Icons** (MIT/OFL).
|
||||
- Các thư viện mã nguồn mở liệt kê ở trên — cảm ơn cộng đồng.
|
||||
@@ -1,61 +0,0 @@
|
||||
# Privacy Policy — CommandForge
|
||||
|
||||
> **BẢN NHÁP.** Đây là bản nháp tham khảo, **không phải tư vấn pháp lý**. Hãy rà soát và (nếu cần) nhờ luật sư trước khi công bố. Khi publish, đặt bản công khai trong repo và cập nhật ngày tháng.
|
||||
>
|
||||
> *Cập nhật lần cuối: [ĐIỀN NGÀY] · Phiên bản: 1.0*
|
||||
|
||||
---
|
||||
|
||||
## 1. Tóm tắt (ngắn gọn)
|
||||
|
||||
**CommandForge không thu thập, không lưu trữ trên máy chủ, và không gửi đi bất kỳ dữ liệu cá nhân nào của bạn.** Ứng dụng hoạt động hoàn toàn cục bộ trên máy của bạn. Kết nối mạng **duy nhất** là tới GitHub để kiểm tra cập nhật phần mềm.
|
||||
|
||||
---
|
||||
|
||||
## 2. Dữ liệu được xử lý cục bộ (KHÔNG rời khỏi máy bạn)
|
||||
|
||||
| Loại | Nơi lưu | Mục đích |
|
||||
|---|---|---|
|
||||
| Cấu hình (theme, ngôn ngữ, favorites, trạng thái chấp nhận điều khoản) | `%AppData%\CommandForge\config.json` | Ghi nhớ tùy chọn của bạn |
|
||||
| Nhật ký (log) hoạt động ứng dụng | `%AppData%\CommandForge\logs\` | Gỡ lỗi cục bộ |
|
||||
| Báo cáo do bạn tạo (pin, năng lượng…) | Thư mục bạn chọn | Theo yêu cầu của bạn |
|
||||
|
||||
Các dữ liệu này **chỉ nằm trên máy bạn** và **không** được gửi cho chúng tôi hay bên thứ ba.
|
||||
|
||||
---
|
||||
|
||||
## 3. Kết nối mạng
|
||||
|
||||
- **Kiểm tra cập nhật:** Ứng dụng gọi **GitHub** (api/releases) để xem có phiên bản mới và tải bản cập nhật. Quá trình này tuân theo [Chính sách quyền riêng tư của GitHub](https://docs.github.com/site-policy). Chúng tôi không nhận được dữ liệu định danh từ việc này.
|
||||
- Ngoài ra, ứng dụng **không** thực hiện kết nối mạng nào khác.
|
||||
|
||||
---
|
||||
|
||||
## 4. Không có telemetry / phân tích
|
||||
|
||||
Ứng dụng **không** tích hợp bất kỳ công cụ telemetry, analytics, quảng cáo, hay theo dõi hành vi nào.
|
||||
|
||||
---
|
||||
|
||||
## 5. Lệnh hệ thống bạn chạy
|
||||
|
||||
Khi bạn chạy một lệnh, kết quả (output) được hiển thị trên giao diện và có thể ghi vào log **cục bộ** để gỡ lỗi. Output này **không** được gửi đi đâu. Khi bạn chủ động xuất/chia sẻ log để báo lỗi, hãy tự rà soát nội dung trước khi gửi.
|
||||
|
||||
---
|
||||
|
||||
## 6. Trẻ em
|
||||
|
||||
Ứng dụng không hướng tới trẻ em và không cố ý thu thập dữ liệu của trẻ em (vì không thu thập dữ liệu của ai).
|
||||
|
||||
---
|
||||
|
||||
## 7. Thay đổi chính sách
|
||||
|
||||
Chính sách có thể được cập nhật. Phiên bản mới sẽ kèm ngày cập nhật. Nếu thay đổi đáng kể, ứng dụng có thể yêu cầu bạn xem lại khi khởi động.
|
||||
|
||||
---
|
||||
|
||||
## 8. Liên hệ
|
||||
|
||||
- Repo: `https://github.com/[user]/[repo]`
|
||||
- Vấn đề/câu hỏi: mở issue, hoặc [ĐIỀN KÊNH LIÊN HỆ].
|
||||
+51
-18
@@ -4,16 +4,22 @@
|
||||
Publishes CommandForge self-contained and packages it with Velopack (vpk) for GitHub Releases.
|
||||
|
||||
.DESCRIPTION
|
||||
Phase 4 release helper (no CI — that is Phase 6). Produces, under Releases/:
|
||||
CommandForge-win-Setup.exe, RELEASES, *-full.nupkg, *-delta.nupkg
|
||||
Update is per-user (no UAC). The Elevator is copied into the publish dir by the
|
||||
CopyElevatorOnPublish MSBuild target, so vpk packages it automatically.
|
||||
Produces, under Releases/:
|
||||
CommandForge-win-Setup.exe, RELEASES, releases.win.json, *-full.nupkg, *-delta.nupkg
|
||||
Update is per-user (no UAC). The Elevator is published into the same folder by the
|
||||
PublishElevatorOnPublish MSBuild target, so vpk packages it automatically.
|
||||
|
||||
vpk is pinned as a local .NET tool (.config/dotnet-tools.json) and must match the Velopack
|
||||
library version in Directory.Packages.props.
|
||||
|
||||
.PARAMETER Version
|
||||
SemVer package version, e.g. 0.3.0 (no leading 'v'). Should match the git tag vX.Y.Z.
|
||||
SemVer package version, e.g. 2.0.0 (no leading 'v'). Should match the git tag vX.Y.Z.
|
||||
|
||||
.PARAMETER SkipPack
|
||||
Publish only (no vpk pack) — used by the CI packaging smoke test when vpk is not wanted.
|
||||
|
||||
.EXAMPLE
|
||||
./scripts/pack.ps1 -Version 0.3.0
|
||||
./scripts/pack.ps1 -Version 2.0.0
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
@@ -22,7 +28,9 @@ param(
|
||||
|
||||
[string] $Runtime = 'win-x64',
|
||||
|
||||
[string] $Configuration = 'Release'
|
||||
[string] $Configuration = 'Release',
|
||||
|
||||
[switch] $SkipPack
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -33,23 +41,48 @@ $wpfProject = Join-Path $repoRoot 'src/CommandForge.Wpf'
|
||||
|
||||
Write-Host "Publishing CommandForge $Version ($Runtime, $Configuration)..." -ForegroundColor Cyan
|
||||
# Stamp the assembly version so the in-app "App version" (Settings -> About, Report Bug) matches
|
||||
# the released package version; otherwise it stays at the 1.0.0 default regardless of the tag.
|
||||
# the released package version. ReadyToRun precompiles the app's own assemblies for faster startup
|
||||
# (the self-contained framework assemblies are already precompiled).
|
||||
dotnet publish $wpfProject `
|
||||
-c $Configuration -r $Runtime --self-contained true `
|
||||
-p:PublishSingleFile=false `
|
||||
-p:Version=$Version -p:InformationalVersion=$Version `
|
||||
-p:PublishReadyToRun=true `
|
||||
-p:Version=$Version -p:FileVersion=$Version -p:InformationalVersion=$Version `
|
||||
-o $publishDir
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed with exit code $LASTEXITCODE" }
|
||||
|
||||
# vpk is the Velopack CLI: dotnet tool install -g vpk
|
||||
if (-not (Get-Command vpk -ErrorAction SilentlyContinue)) {
|
||||
throw "vpk not found. Install it with: dotnet tool install -g vpk"
|
||||
# The elevated helper must ship next to the app (BrokerElevationService spawns it from there).
|
||||
foreach ($file in 'CommandForge.Wpf.exe', 'CommandForge.Elevator.exe', 'CommandForge.Elevator.dll') {
|
||||
if (-not (Test-Path (Join-Path $publishDir $file))) {
|
||||
throw "Publish output is missing $file"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Packing with Velopack..." -ForegroundColor Cyan
|
||||
vpk pack `
|
||||
--packId CommandForge `
|
||||
--packVersion $Version `
|
||||
--packDir $publishDir `
|
||||
--mainExe CommandForge.Wpf.exe
|
||||
if ($SkipPack) {
|
||||
Write-Host "Publish OK (pack skipped). Output: $publishDir" -ForegroundColor Green
|
||||
return
|
||||
}
|
||||
|
||||
Push-Location $repoRoot
|
||||
try {
|
||||
dotnet tool restore
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet tool restore failed with exit code $LASTEXITCODE" }
|
||||
|
||||
Write-Host "Packing with Velopack..." -ForegroundColor Cyan
|
||||
# --runtime selects native x64 Update.exe/Setup.exe helpers (vpk otherwise defaults to x86);
|
||||
# the update channel stays the default "win", so existing installs keep receiving updates.
|
||||
dotnet vpk pack `
|
||||
--runtime $Runtime `
|
||||
--packId CommandForge `
|
||||
--packTitle CommandForge `
|
||||
--packAuthors poli0981 `
|
||||
--packVersion $Version `
|
||||
--packDir $publishDir `
|
||||
--mainExe CommandForge.Wpf.exe
|
||||
if ($LASTEXITCODE -ne 0) { throw "vpk pack failed with exit code $LASTEXITCODE" }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
Write-Host "Done. Artifacts are in $(Join-Path $repoRoot 'Releases')." -ForegroundColor Green
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace CommandForge.Application;
|
||||
|
||||
/// <summary>
|
||||
/// Placeholders a catalog <c>argsTemplate</c> may use for machine-specific paths, e.g.
|
||||
/// <c>chkdsk {SystemDrive}</c>. The executor fills them from trusted OS sources — never from
|
||||
/// environment variables, which a standard user can redefine even for elevated processes.
|
||||
/// </summary>
|
||||
public static partial class ArgumentTokens
|
||||
{
|
||||
/// <summary>The Windows drive, e.g. <c>C:</c>.</summary>
|
||||
public const string SystemDrive = "{SystemDrive}";
|
||||
|
||||
/// <summary>The Windows directory, e.g. <c>C:\Windows</c>.</summary>
|
||||
public const string SystemRoot = "{SystemRoot}";
|
||||
|
||||
/// <summary>The current user's profile folder, e.g. <c>C:\Users\name</c>.</summary>
|
||||
public const string UserProfile = "{UserProfile}";
|
||||
|
||||
/// <summary>Every supported token.</summary>
|
||||
public static IReadOnlyList<string> All { get; } = [SystemDrive, SystemRoot, UserProfile];
|
||||
|
||||
/// <summary>Replaces each token present in <paramref name="values"/>; anything else is left as-is.</summary>
|
||||
public static string Expand(string template, IReadOnlyDictionary<string, string> values)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
|
||||
foreach (var (token, value) in values)
|
||||
{
|
||||
template = template.Replace(token, value, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
return template;
|
||||
}
|
||||
|
||||
/// <summary>Token-like sequences (<c>{Word}</c>) in <paramref name="template"/> that are not supported tokens.</summary>
|
||||
public static IReadOnlyList<string> FindUnknown(string template)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
return TokenPattern().Matches(template)
|
||||
.Select(m => m.Value)
|
||||
.Where(token => !All.Contains(token, StringComparer.Ordinal))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\{[A-Z][A-Za-z]+\}", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)]
|
||||
private static partial Regex TokenPattern();
|
||||
}
|
||||
@@ -4,16 +4,21 @@ namespace CommandForge.Application;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the exact command line shown to the user before running (transparency —
|
||||
/// see docs/Security.md §1). Display only; execution uses an argument array, not this string.
|
||||
/// see docs/Security.md §1). The executor passes the same argument string to the process.
|
||||
/// </summary>
|
||||
public static class CommandPreview
|
||||
{
|
||||
/// <summary>Returns <c>executable args</c>, or just the executable when there are no args.</summary>
|
||||
/// <summary>Returns <c>executable args</c> with path tokens left as placeholders.</summary>
|
||||
public static string Build(CommandDefinition command)
|
||||
=> Build(command, new Dictionary<string, string>());
|
||||
|
||||
/// <summary>Returns <c>executable args</c> with <see cref="ArgumentTokens"/> replaced by <paramref name="tokens"/>.</summary>
|
||||
public static string Build(CommandDefinition command, IReadOnlyDictionary<string, string> tokens)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(tokens);
|
||||
|
||||
var args = command.ArgsTemplate.Trim();
|
||||
var args = ArgumentTokens.Expand(command.ArgsTemplate, tokens).Trim();
|
||||
return args.Length == 0 ? command.Executable : $"{command.Executable} {args}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.History;
|
||||
|
||||
/// <summary>
|
||||
/// Pure helper for the execution-history list: newest first, capped at <see cref="MaxItems"/>.
|
||||
/// Unlike recent commands, history is NOT de-duplicated — each run is a distinct event.
|
||||
/// </summary>
|
||||
public static class ExecutionHistory
|
||||
{
|
||||
/// <summary>Maximum number of records retained (oldest are dropped beyond this).</summary>
|
||||
public const int MaxItems = 200;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a new list with <paramref name="record"/> prepended (newest first) and capped at
|
||||
/// <see cref="MaxItems"/>. The input list is not mutated.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ExecutionRecord> Add(IReadOnlyList<ExecutionRecord> current, ExecutionRecord record)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(current);
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
|
||||
var result = new List<ExecutionRecord>(Math.Min(current.Count + 1, MaxItems)) { record };
|
||||
foreach (var existing in current)
|
||||
{
|
||||
if (result.Count >= MaxItems)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
result.Add(existing);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,21 @@ namespace CommandForge.Application.Ports;
|
||||
/// </summary>
|
||||
public interface IElevationService
|
||||
{
|
||||
/// <summary>Whether elevation is currently available (broker reachable).</summary>
|
||||
public bool IsElevationAvailable { get; }
|
||||
/// <summary>Whether an elevated session (a connected Elevator) is currently open.</summary>
|
||||
public bool IsSessionActive { get; }
|
||||
|
||||
/// <summary>Raised, on any thread, when a session starts or ends; <see cref="IsSessionActive"/> has the new state.</summary>
|
||||
public event EventHandler? SessionChanged;
|
||||
|
||||
/// <summary>Runs <paramref name="command"/> elevated via the broker, streaming output lines.</summary>
|
||||
public Task<ExecutionResult> RunElevatedAsync(
|
||||
CommandDefinition command,
|
||||
ChannelWriter<OutputLine> output,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Ends the elevated session and waits (briefly) for the Elevator to exit — e.g. before an
|
||||
/// update replaces the files it is running from. The next admin command starts a new session.
|
||||
/// </summary>
|
||||
public Task EndSessionAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Persists a local history of finished command executions (newest first). All data stays on
|
||||
/// the machine (golden rule: no telemetry).
|
||||
/// </summary>
|
||||
public interface IExecutionHistoryService
|
||||
{
|
||||
/// <summary>The recorded executions, newest first.</summary>
|
||||
public IReadOnlyList<ExecutionRecord> GetRecent();
|
||||
|
||||
/// <summary>Appends a record (newest first), trims to the cap, and persists.</summary>
|
||||
public void Record(ExecutionRecord record);
|
||||
|
||||
/// <summary>Clears all history and persists.</summary>
|
||||
public void Clear();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using CommandForge.Application.Settings;
|
||||
|
||||
namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Stores named profiles — bundles of portable settings + favorites by context
|
||||
/// (e.g. "Gaming PC", "Office"). Persisted locally (golden rule: no telemetry).
|
||||
/// </summary>
|
||||
public interface IProfileService
|
||||
{
|
||||
/// <summary>Profile names, in stored order.</summary>
|
||||
public IReadOnlyList<string> GetNames();
|
||||
|
||||
/// <summary>The settings stored under <paramref name="name"/>, or null if none.</summary>
|
||||
public PortableSettings? Get(string name);
|
||||
|
||||
/// <summary>Creates or overwrites the profile <paramref name="name"/> and persists.</summary>
|
||||
public void Save(string name, PortableSettings settings);
|
||||
|
||||
/// <summary>Deletes the profile <paramref name="name"/> (no-op if absent) and persists.</summary>
|
||||
public void Delete(string name);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Stores user-defined recipes (named command chains) locally (golden rule: no telemetry).
|
||||
/// Recipes reference only vetted catalog command ids — never raw command lines.
|
||||
/// </summary>
|
||||
public interface IRecipeStore
|
||||
{
|
||||
/// <summary>All saved recipes, in stored order.</summary>
|
||||
public IReadOnlyList<Recipe> GetAll();
|
||||
|
||||
/// <summary>Creates or overwrites a recipe (matched by name, case-insensitive) and persists.</summary>
|
||||
public void Save(Recipe recipe);
|
||||
|
||||
/// <summary>Deletes the recipe <paramref name="name"/> (no-op if absent) and persists.</summary>
|
||||
public void Delete(string name);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Reads registry values for read-only before/after comparison. CommandForge never writes the
|
||||
/// registry through this service — changes happen only via vetted catalog commands.
|
||||
/// </summary>
|
||||
public interface IRegistryService
|
||||
{
|
||||
/// <summary>Reads the current value as a string, or null if the key/value does not exist.</summary>
|
||||
public string? Read(RegistryValueRef reference);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a System Restore Point before risky operations.
|
||||
/// </summary>
|
||||
public interface IRestorePointService
|
||||
{
|
||||
/// <summary>Creates a restore point with the given description. Returns whether it succeeded.</summary>
|
||||
public Task<bool> CreateRestorePointAsync(string description, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using CommandForge.Application.Settings;
|
||||
|
||||
namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Reads/writes portable settings to a user-chosen file (import/export between machines).
|
||||
/// </summary>
|
||||
public interface ISettingsFile
|
||||
{
|
||||
/// <summary>Writes <paramref name="settings"/> to <paramref name="path"/> as JSON.</summary>
|
||||
public void Write(string path, PortableSettings settings);
|
||||
|
||||
/// <summary>Reads portable settings from <paramref name="path"/>; null if missing or invalid.</summary>
|
||||
public PortableSettings? Read(string path);
|
||||
}
|
||||
@@ -17,7 +17,7 @@ public interface ISettingsService
|
||||
/// <summary>The UI color theme (default <see cref="AppTheme.System"/>).</summary>
|
||||
public AppTheme Theme { get; set; }
|
||||
|
||||
/// <summary>UI language: <c>""</c> = follow OS, otherwise a culture code such as <c>"en"</c> or <c>"vi"</c>.</summary>
|
||||
/// <summary>UI language: <c>""</c> = follow OS, otherwise a culture code such as <c>"en"</c>, <c>"vi"</c>, <c>"ja"</c>, <c>"zh-Hans"</c> or <c>"es"</c>.</summary>
|
||||
public string Language { get; set; }
|
||||
|
||||
/// <summary>The overall UI font size (default <see cref="FontScale.Medium"/>).</summary>
|
||||
@@ -51,10 +51,16 @@ public interface ISettingsService
|
||||
/// <summary>Recently-run command ids, most-recent first (default empty). Capped by the caller.</summary>
|
||||
public IReadOnlyList<string> RecentCommandIds { get; set; }
|
||||
|
||||
/// <summary>Last main-window width in device-independent pixels, or <see langword="null"/> if never saved.</summary>
|
||||
/// <summary>
|
||||
/// Retained for config back-compat only. The main window is now a fixed, non-resizable size, so this
|
||||
/// value is no longer read or written; it round-trips untouched for users upgrading from older versions.
|
||||
/// </summary>
|
||||
public double? WindowWidth { get; set; }
|
||||
|
||||
/// <summary>Last main-window height in device-independent pixels, or <see langword="null"/> if never saved.</summary>
|
||||
/// <summary>
|
||||
/// Retained for config back-compat only. The main window is now a fixed, non-resizable size, so this
|
||||
/// value is no longer read or written; it round-trips untouched for users upgrading from older versions.
|
||||
/// </summary>
|
||||
public double? WindowHeight { get; set; }
|
||||
|
||||
/// <summary>Last main-window left position, or <see langword="null"/> if never saved (centre on launch).</summary>
|
||||
@@ -63,7 +69,10 @@ public interface ISettingsService
|
||||
/// <summary>Last main-window top position, or <see langword="null"/> if never saved (centre on launch).</summary>
|
||||
public double? WindowTop { get; set; }
|
||||
|
||||
/// <summary>Whether the main window was maximized when last closed (default <see langword="false"/>).</summary>
|
||||
/// <summary>
|
||||
/// Retained for config back-compat only. The main window can no longer be maximized, so this value is
|
||||
/// no longer read or written; it round-trips untouched for users upgrading from older versions.
|
||||
/// </summary>
|
||||
public bool WindowMaximized { get; set; }
|
||||
|
||||
/// <summary>Persists the current settings to disk.</summary>
|
||||
|
||||
@@ -2,7 +2,7 @@ namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Checks GitHub Releases for application updates (via Velopack) and applies them.
|
||||
/// Per-user install ⇒ no UAC, so it never interacts with the elevation broker.
|
||||
/// Per-user install ⇒ no UAC; applying ends any elevated session first.
|
||||
/// </summary>
|
||||
public interface IUpdateService
|
||||
{
|
||||
@@ -13,9 +13,14 @@ public interface IUpdateService
|
||||
public Task<UpdateCheckResult> CheckForUpdatesAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Downloads (delta if available) and applies the pending update from the last successful check,
|
||||
/// then restarts. Reports progress 0-100 via <paramref name="progress"/>. Returns an
|
||||
/// <see cref="UpdateError"/> on failure; on success the process exits and this does not return.
|
||||
/// Downloads (delta if available) the update found by the last successful check, reporting
|
||||
/// progress 0-100. Returns <see cref="UpdateError.None"/> once it is ready to apply.
|
||||
/// </summary>
|
||||
public Task<UpdateError> DownloadAndApplyAsync(IProgress<int>? progress, CancellationToken cancellationToken = default);
|
||||
public Task<UpdateError> DownloadAsync(IProgress<int>? progress, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Ends the elevated session (the Elevator runs from the folder being replaced), applies the
|
||||
/// downloaded update and restarts. On success the process exits and this does not return.
|
||||
/// </summary>
|
||||
public Task<UpdateError> ApplyAndRestartAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Stores user-defined commands locally, fully separate from the vetted embedded catalog
|
||||
/// (golden rule #1). These commands always run without elevation.
|
||||
/// </summary>
|
||||
public interface IUserCommandStore
|
||||
{
|
||||
/// <summary>All user-defined commands, in stored order.</summary>
|
||||
public IReadOnlyList<UserCommand> GetAll();
|
||||
|
||||
/// <summary>Creates or overwrites a command (matched by id) and persists.</summary>
|
||||
public void Save(UserCommand command);
|
||||
|
||||
/// <summary>Deletes the command <paramref name="id"/> (no-op if absent) and persists.</summary>
|
||||
public void Delete(string id);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace CommandForge.Application;
|
||||
|
||||
/// <summary>Fixed product identity strings that are not localized (brand name).</summary>
|
||||
public static class ProductInfo
|
||||
{
|
||||
/// <summary>The product name, used where localized resources may be unavailable (e.g. startup failures).</summary>
|
||||
public const string Name = "CommandForge";
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace CommandForge.Application;
|
||||
|
||||
/// <summary>
|
||||
/// The project's canonical public links, in one place so the update source, About, Settings and
|
||||
/// the bug-report flow can never drift apart.
|
||||
/// </summary>
|
||||
#pragma warning disable S1075 // These are the product's fixed public URLs, not environment-specific paths.
|
||||
public static class ProductLinks
|
||||
{
|
||||
/// <summary>The GitHub repository (also the Velopack update source).</summary>
|
||||
public const string Repository = "https://github.com/poli0981/CommandForge";
|
||||
|
||||
/// <summary>New-issue form used by "Report a bug".</summary>
|
||||
public const string NewIssue = Repository + "/issues/new";
|
||||
|
||||
/// <summary>Releases page (downloads, checksums, release notes).</summary>
|
||||
public const string Releases = Repository + "/releases";
|
||||
|
||||
/// <summary>The end-user guide in the repository.</summary>
|
||||
public const string UserGuide = Repository + "/blob/main/USAGE.md";
|
||||
|
||||
/// <summary>Private vulnerability reporting.</summary>
|
||||
public const string SecurityAdvisory = Repository + "/security/advisories/new";
|
||||
|
||||
/// <summary>Private security reports by email (the alternative to <see cref="SecurityAdvisory"/>).</summary>
|
||||
public const string SecurityEmail = "security@poli0981.dev";
|
||||
|
||||
/// <summary>Questions about the code and contributions.</summary>
|
||||
public const string CodeEmail = "code@poli0981.dev";
|
||||
|
||||
/// <summary>Full text of the GNU GPL v3.</summary>
|
||||
public const string License = "https://www.gnu.org/licenses/gpl-3.0.html";
|
||||
}
|
||||
#pragma warning restore S1075
|
||||
@@ -0,0 +1,19 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.Recipes;
|
||||
|
||||
/// <summary>Pure decision logic for running a recipe sequentially.</summary>
|
||||
public static class RecipeFlow
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether the recipe must stop after a step that produced this result: a failure, a
|
||||
/// cancellation, or a reboot-required signal (remaining steps may depend on the restart, so
|
||||
/// the safe default is to stop and let the user reboot).
|
||||
/// </summary>
|
||||
public static bool ShouldStop(ExecutionResult result)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(result);
|
||||
|
||||
return result.Cancelled || !result.Success || result.RequiresRestart;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.Registry;
|
||||
|
||||
/// <summary>A single before→after change of a registry value.</summary>
|
||||
public sealed record RegistryChange(RegistryValueRef Reference, string? Before, string? After);
|
||||
|
||||
/// <summary>Pure helpers to snapshot and diff a set of registry values (read-only).</summary>
|
||||
public static class RegistrySnapshot
|
||||
{
|
||||
/// <summary>Reads the current value of each reference into a snapshot.</summary>
|
||||
public static IReadOnlyDictionary<RegistryValueRef, string?> Capture(
|
||||
IRegistryService registry,
|
||||
IReadOnlyList<RegistryValueRef> references)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(registry);
|
||||
ArgumentNullException.ThrowIfNull(references);
|
||||
|
||||
var snapshot = new Dictionary<RegistryValueRef, string?>();
|
||||
foreach (var reference in references)
|
||||
{
|
||||
snapshot[reference] = registry.Read(reference);
|
||||
}
|
||||
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/// <summary>Returns the references whose value changed between the two snapshots.</summary>
|
||||
public static IReadOnlyList<RegistryChange> Diff(
|
||||
IReadOnlyList<RegistryValueRef> references,
|
||||
IReadOnlyDictionary<RegistryValueRef, string?> before,
|
||||
IReadOnlyDictionary<RegistryValueRef, string?> after)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(references);
|
||||
ArgumentNullException.ThrowIfNull(before);
|
||||
ArgumentNullException.ThrowIfNull(after);
|
||||
|
||||
var changes = new List<RegistryChange>();
|
||||
foreach (var reference in references)
|
||||
{
|
||||
before.TryGetValue(reference, out var oldValue);
|
||||
after.TryGetValue(reference, out var newValue);
|
||||
if (!string.Equals(oldValue, newValue, StringComparison.Ordinal))
|
||||
{
|
||||
changes.Add(new RegistryChange(reference, oldValue, newValue));
|
||||
}
|
||||
}
|
||||
|
||||
return changes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Text;
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application;
|
||||
|
||||
/// <summary>
|
||||
/// The confirmation and restore-point rules, in one place so single runs, re-runs from History,
|
||||
/// reverts and recipes all apply them identically (golden rule #8).
|
||||
/// </summary>
|
||||
public static class RunSafety
|
||||
{
|
||||
/// <summary>The vetted catalog command that creates a System Restore Point.</summary>
|
||||
public const string RestorePointCommandId = "system.restorepoint";
|
||||
|
||||
/// <summary>
|
||||
/// Exit code of <see cref="RestorePointCommandId"/> when Windows created nothing because another
|
||||
/// restore point was made recently (it allows one per 24 hours) — not a failure.
|
||||
/// </summary>
|
||||
public const int RestorePointSkippedExitCode = 2;
|
||||
|
||||
/// <summary>Dangerous commands always ask; Caution ones ask unless the user turned that off.</summary>
|
||||
public static bool NeedsConfirmation(CommandDefinition command, bool confirmCaution)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
return command.DangerLevel == DangerLevel.Dangerous
|
||||
|| (command.DangerLevel == DangerLevel.Caution && confirmCaution);
|
||||
}
|
||||
|
||||
/// <summary>Dangerous commands require typing the title (or id) — never just a click.</summary>
|
||||
public static bool NeedsTypedConfirmation(CommandDefinition command)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
return command.DangerLevel == DangerLevel.Dangerous;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a restore point is offered before <paramref name="command"/>: for commands the
|
||||
/// catalog flags, and for risky admin commands. Never for per-user (non-admin) tweaks — creating
|
||||
/// a restore point needs administrator rights, so it would add a UAC prompt they don't need.
|
||||
/// </summary>
|
||||
public static bool OffersRestorePoint(CommandDefinition command)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
if (string.Equals(command.Id, RestorePointCommandId, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return command.CreatesRestorePoint
|
||||
|| (command.RequiresAdmin && command.DangerLevel >= DangerLevel.Caution);
|
||||
}
|
||||
|
||||
/// <summary>The initial state of the restore-point checkbox.</summary>
|
||||
public static bool DefaultCreateRestorePoint(CommandDefinition command, bool autoCreateRestorePoint)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
return OffersRestorePoint(command) && (command.CreatesRestorePoint || autoCreateRestorePoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="input"/> confirms a Dangerous command: the title as displayed, or the
|
||||
/// command id. Unicode-normalized (Vietnamese input methods may type decomposed accents) and
|
||||
/// case-insensitive, so what looks identical always matches.
|
||||
/// </summary>
|
||||
public static bool IsTypedConfirmationValid(string? input, string title, string commandId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(title);
|
||||
ArgumentNullException.ThrowIfNull(commandId);
|
||||
if (string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var typed = Normalize(input);
|
||||
return string.Equals(typed, Normalize(title), StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(typed, commandId.Trim(), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string Normalize(string value)
|
||||
=> value.Trim().Normalize(NormalizationForm.FormC);
|
||||
}
|
||||
@@ -4,8 +4,9 @@ namespace CommandForge.Application.Search;
|
||||
public readonly record struct FuzzyMatchResult(int Score, IReadOnlyList<int> MatchedIndices);
|
||||
|
||||
/// <summary>
|
||||
/// Lightweight case-insensitive subsequence fuzzy matcher. Rewards consecutive matches and
|
||||
/// matches at word boundaries so the most relevant results rank first. No external dependency.
|
||||
/// Lightweight accent- and case-insensitive subsequence matcher. Rewards consecutive matches and
|
||||
/// matches at word boundaries, and tries every starting point so "flush" lights up the word
|
||||
/// "flush" rather than the first "f" and "l" it meets. No external dependency.
|
||||
/// </summary>
|
||||
public static class FuzzyMatcher
|
||||
{
|
||||
@@ -14,7 +15,7 @@ public static class FuzzyMatcher
|
||||
private const int WordBoundaryBonus = 10;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a match for <paramref name="query"/> within <paramref name="text"/>, or
|
||||
/// Returns the best match for <paramref name="query"/> within <paramref name="text"/>, or
|
||||
/// <see langword="null"/> if not all query characters appear in order. An empty query
|
||||
/// matches everything with score 0.
|
||||
/// </summary>
|
||||
@@ -33,43 +34,61 @@ public static class FuzzyMatcher
|
||||
return null;
|
||||
}
|
||||
|
||||
var foldedText = TextFolding.Fold(text);
|
||||
var foldedQuery = TextFolding.Fold(query);
|
||||
|
||||
FuzzyMatchResult? best = null;
|
||||
for (var start = foldedText.IndexOf(foldedQuery[0]);
|
||||
start >= 0;
|
||||
start = foldedText.IndexOf(foldedQuery[0], start + 1))
|
||||
{
|
||||
if (MatchFrom(foldedText, foldedQuery, start) is { } candidate
|
||||
&& (best is null || candidate.Score > best.Value.Score))
|
||||
{
|
||||
best = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>The smallest score a title match of <paramref name="queryLength"/> characters needs to count.</summary>
|
||||
public static int MinimumUsefulScore(int queryLength)
|
||||
=> queryLength <= 1 ? BaseScore : queryLength * BaseScore + (queryLength - 1) * 4;
|
||||
|
||||
private static FuzzyMatchResult? MatchFrom(string text, string query, int start)
|
||||
{
|
||||
var indices = new List<int>(query.Length);
|
||||
var score = 0;
|
||||
var textIndex = 0;
|
||||
var textIndex = start;
|
||||
var lastMatch = -2;
|
||||
|
||||
foreach (var queryChar in query)
|
||||
foreach (var target in query)
|
||||
{
|
||||
var found = false;
|
||||
for (; textIndex < text.Length; textIndex++)
|
||||
while (textIndex < text.Length && text[textIndex] != target)
|
||||
{
|
||||
if (char.ToLowerInvariant(text[textIndex]) != char.ToLowerInvariant(queryChar))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
indices.Add(textIndex);
|
||||
score += BaseScore;
|
||||
if (textIndex == lastMatch + 1)
|
||||
{
|
||||
score += ConsecutiveBonus;
|
||||
}
|
||||
|
||||
if (textIndex == 0 || !char.IsLetterOrDigit(text[textIndex - 1]))
|
||||
{
|
||||
score += WordBoundaryBonus;
|
||||
}
|
||||
|
||||
lastMatch = textIndex;
|
||||
textIndex++;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!found)
|
||||
if (textIndex >= text.Length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
indices.Add(textIndex);
|
||||
score += BaseScore;
|
||||
if (textIndex == lastMatch + 1)
|
||||
{
|
||||
score += ConsecutiveBonus;
|
||||
}
|
||||
|
||||
if (textIndex == 0 || !char.IsLetterOrDigit(text[textIndex - 1]))
|
||||
{
|
||||
score += WordBoundaryBonus;
|
||||
}
|
||||
|
||||
lastMatch = textIndex;
|
||||
textIndex++;
|
||||
}
|
||||
|
||||
return new FuzzyMatchResult(score, indices);
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
namespace CommandForge.Application.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Local natural-language search: maps everyday EN/VI phrases to a catalog search keyword
|
||||
/// (e.g. "clean disk" / "dọn ổ đĩa" → "cleanup"). 100% LOCAL — no LLM, no network (golden rule #5).
|
||||
/// Phrases match whole words, ignoring case and accents ("pin" is battery, "typing" is not).
|
||||
/// </summary>
|
||||
public static class NaturalLanguageSearch
|
||||
{
|
||||
// Lower-cased phrase fragment -> canonical keyword fed back into the existing fuzzy search.
|
||||
private static readonly (string Phrase, string Keyword)[] Map =
|
||||
[
|
||||
("free space", "cleanup"),
|
||||
("disk space", "cleanup"),
|
||||
("clean", "cleanup"),
|
||||
("dọn", "cleanup"),
|
||||
("dung lượng", "cleanup"),
|
||||
("slow", "cleanup"),
|
||||
("chậm", "cleanup"),
|
||||
("internet", "network"),
|
||||
("wifi", "network"),
|
||||
("network", "network"),
|
||||
("mạng", "network"),
|
||||
("dns", "network"),
|
||||
("update", "update"),
|
||||
("cập nhật", "update"),
|
||||
("battery", "battery"),
|
||||
("pin", "battery"),
|
||||
("driver", "driver"),
|
||||
("trình điều khiển", "driver"),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Returns a suggested search keyword for a natural-language query, or null if nothing matches
|
||||
/// (or the query already equals the keyword, so we don't suggest what the user typed).
|
||||
/// </summary>
|
||||
public static string? Suggest(string? query)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(query))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var text = TextFolding.Fold(query.Trim());
|
||||
foreach (var (phrase, keyword) in Map)
|
||||
{
|
||||
if (ContainsWholeWords(text, TextFolding.Fold(phrase))
|
||||
&& !string.Equals(text, keyword, StringComparison.Ordinal))
|
||||
{
|
||||
return keyword;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool ContainsWholeWords(string text, string phrase)
|
||||
{
|
||||
for (var at = text.IndexOf(phrase, StringComparison.Ordinal); at >= 0; at = text.IndexOf(phrase, at + 1, StringComparison.Ordinal))
|
||||
{
|
||||
var end = at + phrase.Length;
|
||||
var startsWord = at == 0 || !char.IsLetterOrDigit(text[at - 1]);
|
||||
var endsWord = end == text.Length || !char.IsLetterOrDigit(text[end]);
|
||||
if (startsWord && endsWord)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,21 @@ namespace CommandForge.Application.Search;
|
||||
|
||||
/// <summary>
|
||||
/// A command paired with its resolved (localized) searchable text. The presentation layer
|
||||
/// resolves resource keys to text and supplies these, keeping search logic free of i18n.
|
||||
/// resolves resource keys to text and supplies these, keeping search logic free of i18n. The
|
||||
/// accent-/case-folded forms are computed once here, not on every keystroke.
|
||||
/// </summary>
|
||||
public sealed record SearchableCommand(
|
||||
CommandDefinition Command,
|
||||
string Title,
|
||||
string Description,
|
||||
IReadOnlyList<string> Tags);
|
||||
IReadOnlyList<string> Tags)
|
||||
{
|
||||
internal string FoldedTitle { get; } = TextFolding.Fold(Title);
|
||||
|
||||
internal string FoldedDescription { get; } = TextFolding.Fold(Description);
|
||||
|
||||
internal IReadOnlyList<string> FoldedTags { get; } = Tags.Select(TextFolding.Fold).ToList();
|
||||
}
|
||||
|
||||
/// <summary>Optional filters applied before fuzzy ranking.</summary>
|
||||
public sealed record CommandSearchFilter
|
||||
@@ -41,7 +49,8 @@ public sealed record CommandSearchFilter
|
||||
return false;
|
||||
}
|
||||
|
||||
if (RequiresRestart is { } restart && (command.Restart != RestartPolicy.No) != restart)
|
||||
// "Requires restart" means always; exit-code/regex policies only restart sometimes.
|
||||
if (RequiresRestart is { } restart && (command.Restart == RestartPolicy.Always) != restart)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -59,12 +68,20 @@ public sealed record CommandSearchFilter
|
||||
public sealed record CommandSearchHit(CommandDefinition Command, int Score, IReadOnlyList<int> TitleMatches);
|
||||
|
||||
/// <summary>
|
||||
/// Filters and fuzzy-ranks commands. With an empty query, returns filtered commands in input
|
||||
/// order; otherwise ranks by relevance (title matches weighted above description/tags).
|
||||
/// Filters and ranks commands. With an empty query, returns filtered commands in input order;
|
||||
/// otherwise ranks by relevance. Titles allow fuzzy abbreviations ("sfc", "flsh dns"); descriptions
|
||||
/// and tags need the query words as real substrings — matching them as loose subsequences made a
|
||||
/// short query like "dns" hit most of the catalog. Matching ignores case and accents.
|
||||
/// </summary>
|
||||
public static class SearchCommandsUseCase
|
||||
{
|
||||
private const int TitleWeight = 20;
|
||||
private const int ExactTitleScore = 300;
|
||||
private const int TitleSubstringScore = 200;
|
||||
private const int TitleWordsScore = 160;
|
||||
private const int TitleFuzzyBase = 100;
|
||||
private const int TagScore = 60;
|
||||
private const int DescriptionScore = 40;
|
||||
private const int WordStartBonus = 30;
|
||||
|
||||
public static IReadOnlyList<CommandSearchHit> Search(
|
||||
IEnumerable<SearchableCommand> commands,
|
||||
@@ -74,56 +91,145 @@ public static class SearchCommandsUseCase
|
||||
ArgumentNullException.ThrowIfNull(commands);
|
||||
|
||||
var trimmed = query?.Trim() ?? string.Empty;
|
||||
var hasQuery = trimmed.Length > 0;
|
||||
var hits = new List<CommandSearchHit>();
|
||||
|
||||
foreach (var item in commands)
|
||||
var filtered = filter is null ? commands : commands.Where(c => filter.Matches(c.Command));
|
||||
if (trimmed.Length == 0)
|
||||
{
|
||||
if (filter is not null && !filter.Matches(item.Command))
|
||||
return filtered.Select(c => new CommandSearchHit(c.Command, 0, [])).ToList();
|
||||
}
|
||||
|
||||
var foldedQuery = TextFolding.Fold(trimmed);
|
||||
var words = foldedQuery.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
var hits = new List<CommandSearchHit>();
|
||||
foreach (var item in filtered)
|
||||
{
|
||||
var (titleScore, titleIndices) = MatchTitle(item, trimmed, foldedQuery, words);
|
||||
var score = Math.Max(titleScore, Math.Max(MatchTags(item, words), MatchDescription(item, words)));
|
||||
if (score > 0)
|
||||
{
|
||||
continue;
|
||||
hits.Add(new CommandSearchHit(item.Command, score, titleIndices));
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasQuery)
|
||||
// OrderByDescending is stable: equal scores keep catalog order.
|
||||
return hits.OrderByDescending(h => h.Score).ToList();
|
||||
}
|
||||
|
||||
private static (int Score, IReadOnlyList<int> Indices) MatchTitle(SearchableCommand item, string query, string foldedQuery, string[] words)
|
||||
{
|
||||
var title = item.FoldedTitle;
|
||||
if (string.Equals(title, foldedQuery, StringComparison.Ordinal))
|
||||
{
|
||||
return (ExactTitleScore, Enumerable.Range(0, title.Length).ToList());
|
||||
}
|
||||
|
||||
var index = BestOccurrence(title, foldedQuery);
|
||||
if (index >= 0)
|
||||
{
|
||||
var score = TitleSubstringScore + (IsWordStart(title, index) ? WordStartBonus : 0) - Math.Min(index, 20);
|
||||
return (score, Enumerable.Range(index, foldedQuery.Length).ToList());
|
||||
}
|
||||
|
||||
if (words.Length > 1)
|
||||
{
|
||||
var indices = new List<int>();
|
||||
var score = TitleWordsScore;
|
||||
foreach (var word in words)
|
||||
{
|
||||
hits.Add(new CommandSearchHit(item.Command, 0, []));
|
||||
continue;
|
||||
}
|
||||
|
||||
var titleMatch = FuzzyMatcher.Match(item.Title, trimmed);
|
||||
var best = int.MinValue;
|
||||
|
||||
if (titleMatch is { } tm)
|
||||
{
|
||||
best = tm.Score + TitleWeight;
|
||||
}
|
||||
|
||||
if (FuzzyMatcher.Match(item.Description, trimmed) is { } dm)
|
||||
{
|
||||
best = Math.Max(best, dm.Score);
|
||||
}
|
||||
|
||||
foreach (var tag in item.Tags)
|
||||
{
|
||||
if (FuzzyMatcher.Match(tag, trimmed) is { } tagMatch)
|
||||
var at = BestOccurrence(title, word);
|
||||
if (at < 0)
|
||||
{
|
||||
best = Math.Max(best, tagMatch.Score);
|
||||
indices.Clear();
|
||||
break;
|
||||
}
|
||||
|
||||
score += IsWordStart(title, at) ? 10 : 0;
|
||||
indices.AddRange(Enumerable.Range(at, word.Length));
|
||||
}
|
||||
|
||||
if (indices.Count > 0)
|
||||
{
|
||||
return (score, indices.Distinct().Order().ToList());
|
||||
}
|
||||
}
|
||||
|
||||
if (FuzzyMatcher.Match(item.Title, query) is { } fuzzy
|
||||
&& fuzzy.Score >= FuzzyMatcher.MinimumUsefulScore(foldedQuery.Length))
|
||||
{
|
||||
return (TitleFuzzyBase + fuzzy.Score, fuzzy.MatchedIndices);
|
||||
}
|
||||
|
||||
return (0, []);
|
||||
}
|
||||
|
||||
/// <summary>Every query word must start (or exactly equal) some tag.</summary>
|
||||
private static int MatchTags(SearchableCommand item, string[] words)
|
||||
{
|
||||
var score = 0;
|
||||
foreach (var word in words)
|
||||
{
|
||||
var best = 0;
|
||||
foreach (var tag in item.FoldedTags)
|
||||
{
|
||||
if (string.Equals(tag, word, StringComparison.Ordinal))
|
||||
{
|
||||
best = Math.Max(best, TagScore + 10);
|
||||
}
|
||||
else if (tag.StartsWith(word, StringComparison.Ordinal))
|
||||
{
|
||||
best = Math.Max(best, TagScore);
|
||||
}
|
||||
}
|
||||
|
||||
if (best == int.MinValue)
|
||||
if (best == 0)
|
||||
{
|
||||
continue;
|
||||
return 0;
|
||||
}
|
||||
|
||||
hits.Add(new CommandSearchHit(item.Command, best, titleMatch?.MatchedIndices ?? []));
|
||||
score = Math.Max(score, best);
|
||||
}
|
||||
|
||||
if (hasQuery)
|
||||
{
|
||||
hits.Sort(static (a, b) => b.Score.CompareTo(a.Score));
|
||||
}
|
||||
|
||||
return hits;
|
||||
return score;
|
||||
}
|
||||
|
||||
/// <summary>Every query word must appear in the description as a real substring.</summary>
|
||||
private static int MatchDescription(SearchableCommand item, string[] words)
|
||||
{
|
||||
var description = item.FoldedDescription;
|
||||
var score = DescriptionScore;
|
||||
foreach (var word in words)
|
||||
{
|
||||
var at = BestOccurrence(description, word);
|
||||
if (at < 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
score += IsWordStart(description, at) ? 5 : 0;
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
/// <summary>The first occurrence of <paramref name="value"/> at a word start, else the first occurrence (-1 if none).</summary>
|
||||
private static int BestOccurrence(string text, string value)
|
||||
{
|
||||
var first = -1;
|
||||
for (var at = text.IndexOf(value, StringComparison.Ordinal); at >= 0; at = text.IndexOf(value, at + 1, StringComparison.Ordinal))
|
||||
{
|
||||
if (IsWordStart(text, at))
|
||||
{
|
||||
return at;
|
||||
}
|
||||
|
||||
if (first < 0)
|
||||
{
|
||||
first = at;
|
||||
}
|
||||
}
|
||||
|
||||
return first;
|
||||
}
|
||||
|
||||
private static bool IsWordStart(string text, int index) => index == 0 || !char.IsLetterOrDigit(text[index - 1]);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace CommandForge.Application.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Accent- and case-insensitive text for search: "Dọn dẹp" folds to "don dep", "Đặt" to "dat".
|
||||
/// Folding works one character at a time, so index i of the result is index i of the input —
|
||||
/// highlighting maps matches straight back onto the displayed text.
|
||||
/// </summary>
|
||||
public static class TextFolding
|
||||
{
|
||||
/// <summary>Folds <paramref name="text"/>, preserving its length.</summary>
|
||||
public static string Fold(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
return string.Create(text.Length, text, static (span, source) =>
|
||||
{
|
||||
for (var i = 0; i < source.Length; i++)
|
||||
{
|
||||
span[i] = FoldChar(source[i]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Folds a single character: lower-case, without diacritics.</summary>
|
||||
public static char FoldChar(char c)
|
||||
{
|
||||
if (c < 128)
|
||||
{
|
||||
return char.ToLowerInvariant(c);
|
||||
}
|
||||
|
||||
if (c is 'đ' or 'Đ')
|
||||
{
|
||||
return 'd';
|
||||
}
|
||||
|
||||
foreach (var part in c.ToString().Normalize(NormalizationForm.FormD))
|
||||
{
|
||||
if (CharUnicodeInfo.GetUnicodeCategory(part) != UnicodeCategory.NonSpacingMark)
|
||||
{
|
||||
return char.ToLowerInvariant(part);
|
||||
}
|
||||
}
|
||||
|
||||
return c; // a lone combining mark stays as it is
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using CommandForge.Application.Logging;
|
||||
|
||||
namespace CommandForge.Application.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// The machine-portable subset of settings — appearance, behavior/safety preferences and favorites —
|
||||
/// used for import/export and named profiles. Excludes machine-specific state (window placement,
|
||||
/// accepted terms version, recent commands, execution history). Properties are settable so the
|
||||
/// source-generated serializer keeps these defaults for keys a file omits (init-only properties
|
||||
/// would be reset to false/0 — e.g. silently turning off Caution confirmations).
|
||||
/// </summary>
|
||||
public sealed record PortableSettings
|
||||
{
|
||||
/// <summary>Schema version of the portable payload (for forward-compat).</summary>
|
||||
public int Version { get; set; } = 1;
|
||||
|
||||
public AppTheme Theme { get; set; } = AppTheme.System;
|
||||
|
||||
public string Language { get; set; } = "";
|
||||
|
||||
public FontScale FontSize { get; set; } = FontScale.Medium;
|
||||
|
||||
public bool CollapseSidebarByDefault { get; set; }
|
||||
|
||||
public bool ShowAdminRestartBadges { get; set; } = true;
|
||||
|
||||
public bool ConfirmCaution { get; set; } = true;
|
||||
|
||||
public bool AutoCreateRestorePoint { get; set; } = true;
|
||||
|
||||
public bool AutoScrollConsole { get; set; } = true;
|
||||
|
||||
public bool WarnOnCancel { get; set; } = true;
|
||||
|
||||
public bool AutoCheckForUpdates { get; set; } = true;
|
||||
|
||||
public LogLevel LogLevel { get; set; } = LogLevel.Information;
|
||||
|
||||
/// <summary>Pinned favorite command ids, in pin order.</summary>
|
||||
public IReadOnlyList<string> FavoriteCommandIds { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Repairs what an imported or hand-edited file may contain: null lists or language, enum
|
||||
/// values outside the defined range, blank or duplicate favorite ids.
|
||||
/// </summary>
|
||||
public PortableSettings Normalized() => this with
|
||||
{
|
||||
Language = Language ?? string.Empty,
|
||||
Theme = Enum.IsDefined(Theme) ? Theme : AppTheme.System,
|
||||
FontSize = Enum.IsDefined(FontSize) ? FontSize : FontScale.Medium,
|
||||
LogLevel = Enum.IsDefined(LogLevel) ? LogLevel : LogLevel.Information,
|
||||
FavoriteCommandIds = FavoriteCommandIds?.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct(StringComparer.Ordinal).ToList() ?? [],
|
||||
};
|
||||
}
|
||||
@@ -17,13 +17,7 @@ public static class RecentCommands
|
||||
ArgumentException.ThrowIfNullOrEmpty(commandId);
|
||||
|
||||
var result = new List<string>(current.Count + 1) { commandId };
|
||||
foreach (var id in current)
|
||||
{
|
||||
if (!string.Equals(id, commandId, StringComparison.Ordinal))
|
||||
{
|
||||
result.Add(id);
|
||||
}
|
||||
}
|
||||
result.AddRange(current.Where(id => !string.Equals(id, commandId, StringComparison.Ordinal)));
|
||||
|
||||
if (result.Count > MaxItems)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using CommandForge.Application.Ports;
|
||||
|
||||
namespace CommandForge.Application.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Pure mapping between the live <see cref="ISettingsService"/> and the portable subset
|
||||
/// (<see cref="PortableSettings"/>) used for import/export and profiles.
|
||||
/// </summary>
|
||||
public static class SettingsTransfer
|
||||
{
|
||||
/// <summary>Reads the current portable settings from the live settings service.</summary>
|
||||
public static PortableSettings Capture(ISettingsService settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
|
||||
return new PortableSettings
|
||||
{
|
||||
Theme = settings.Theme,
|
||||
Language = settings.Language,
|
||||
FontSize = settings.FontSize,
|
||||
CollapseSidebarByDefault = settings.CollapseSidebarByDefault,
|
||||
ShowAdminRestartBadges = settings.ShowAdminRestartBadges,
|
||||
ConfirmCaution = settings.ConfirmCaution,
|
||||
AutoCreateRestorePoint = settings.AutoCreateRestorePoint,
|
||||
AutoScrollConsole = settings.AutoScrollConsole,
|
||||
WarnOnCancel = settings.WarnOnCancel,
|
||||
AutoCheckForUpdates = settings.AutoCheckForUpdates,
|
||||
LogLevel = settings.LogLevel,
|
||||
FavoriteCommandIds = settings.FavoriteCommandIds,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the portable settings into the live settings service (does NOT call Save, and does
|
||||
/// not apply live UI effects — callers persist and re-apply). Used in non-UI contexts and tests.
|
||||
/// </summary>
|
||||
public static void Apply(PortableSettings portable, ISettingsService settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(portable);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
|
||||
portable = portable.Normalized();
|
||||
settings.Theme = portable.Theme;
|
||||
settings.Language = portable.Language;
|
||||
settings.FontSize = portable.FontSize;
|
||||
settings.CollapseSidebarByDefault = portable.CollapseSidebarByDefault;
|
||||
settings.ShowAdminRestartBadges = portable.ShowAdminRestartBadges;
|
||||
settings.ConfirmCaution = portable.ConfirmCaution;
|
||||
settings.AutoCreateRestorePoint = portable.AutoCreateRestorePoint;
|
||||
settings.AutoScrollConsole = portable.AutoScrollConsole;
|
||||
settings.WarnOnCancel = portable.WarnOnCancel;
|
||||
settings.AutoCheckForUpdates = portable.AutoCheckForUpdates;
|
||||
settings.LogLevel = portable.LogLevel;
|
||||
settings.FavoriteCommandIds = portable.FavoriteCommandIds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using CommandForge.Application.Ports;
|
||||
|
||||
namespace CommandForge.Application.SystemInfo;
|
||||
|
||||
/// <summary>A maintenance hint derived from system status: a reason and an optional catalog command to run.</summary>
|
||||
public sealed record MaintenanceSuggestion(string ReasonKey, string? CommandId);
|
||||
|
||||
/// <summary>
|
||||
/// Pure, local heuristics mapping a <see cref="SystemStatus"/> to maintenance suggestions for the
|
||||
/// Home dashboard. No network, no telemetry — just thresholds over the read-only status snapshot.
|
||||
/// </summary>
|
||||
public static class MaintenanceSuggestions
|
||||
{
|
||||
/// <summary>Free system-drive space below this fraction triggers a cleanup suggestion.</summary>
|
||||
public const double LowDiskFreeFraction = 0.10;
|
||||
|
||||
/// <summary>Uptime at or above this triggers a restart suggestion.</summary>
|
||||
public static readonly TimeSpan HighUptime = TimeSpan.FromDays(7);
|
||||
|
||||
/// <summary>Returns the maintenance suggestions that apply to the given status (possibly empty).</summary>
|
||||
public static IReadOnlyList<MaintenanceSuggestion> For(SystemStatus status)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(status);
|
||||
|
||||
var suggestions = new List<MaintenanceSuggestion>();
|
||||
|
||||
if (status.SystemDriveTotalBytes > 0
|
||||
&& (double)status.SystemDriveFreeBytes / status.SystemDriveTotalBytes < LowDiskFreeFraction)
|
||||
{
|
||||
suggestions.Add(new MaintenanceSuggestion("Maint_LowDisk", "cleanup.cleanmgr"));
|
||||
}
|
||||
|
||||
if (status.Uptime >= HighUptime)
|
||||
{
|
||||
suggestions.Add(new MaintenanceSuggestion("Maint_HighUptime", null));
|
||||
}
|
||||
|
||||
return suggestions;
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ public static class UpdateErrorMapper
|
||||
if (status is null)
|
||||
{
|
||||
// No status: a transport failure (no network/DNS), a socket error, or a timeout.
|
||||
return exception is HttpRequestException or SocketException or TaskCanceledException
|
||||
return exception is not null && IsTransportFailure(exception)
|
||||
? UpdateError.Offline
|
||||
: UpdateError.Unknown;
|
||||
}
|
||||
@@ -32,4 +32,48 @@ public static class UpdateErrorMapper
|
||||
_ => UpdateError.Unknown, // incl. 419
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps an exception from the update library, looking through wrapper and aggregate
|
||||
/// exceptions for the HTTP status or transport failure underneath.
|
||||
/// </summary>
|
||||
public static UpdateError Map(Exception exception)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(exception);
|
||||
|
||||
var all = Flatten(exception).ToList();
|
||||
var http = all.OfType<HttpRequestException>().FirstOrDefault(e => e.StatusCode is not null);
|
||||
if (http is not null)
|
||||
{
|
||||
return Map(http.StatusCode, http);
|
||||
}
|
||||
|
||||
return all.Exists(IsTransportFailure) ? UpdateError.Offline : UpdateError.Unknown;
|
||||
}
|
||||
|
||||
// HttpClient timeouts surface as TaskCanceledException (with an inner TimeoutException).
|
||||
private static bool IsTransportFailure(Exception exception)
|
||||
=> exception is HttpRequestException or SocketException or TimeoutException or TaskCanceledException;
|
||||
|
||||
private static IEnumerable<Exception> Flatten(Exception root)
|
||||
{
|
||||
var pending = new Stack<Exception>();
|
||||
pending.Push(root);
|
||||
while (pending.Count > 0)
|
||||
{
|
||||
var current = pending.Pop();
|
||||
yield return current;
|
||||
if (current is AggregateException aggregate)
|
||||
{
|
||||
foreach (var inner in aggregate.InnerExceptions)
|
||||
{
|
||||
pending.Push(inner);
|
||||
}
|
||||
}
|
||||
else if (current.InnerException is { } inner)
|
||||
{
|
||||
pending.Push(inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,11 @@ public sealed class CheckForUpdateUseCase
|
||||
public Task<UpdateCheckResult> ExecuteAsync(CancellationToken cancellationToken = default)
|
||||
=> _updates.CheckForUpdatesAsync(cancellationToken);
|
||||
|
||||
/// <summary>Downloads and applies the pending update, then restarts.</summary>
|
||||
public Task<UpdateError> DownloadAndApplyAsync(IProgress<int>? progress, CancellationToken cancellationToken = default)
|
||||
=> _updates.DownloadAndApplyAsync(progress, cancellationToken);
|
||||
/// <summary>Downloads the pending update.</summary>
|
||||
public Task<UpdateError> DownloadAsync(IProgress<int>? progress, CancellationToken cancellationToken = default)
|
||||
=> _updates.DownloadAsync(progress, cancellationToken);
|
||||
|
||||
/// <summary>Applies the downloaded update and restarts.</summary>
|
||||
public Task<UpdateError> ApplyAndRestartAsync(CancellationToken cancellationToken = default)
|
||||
=> _updates.ApplyAndRestartAsync(cancellationToken);
|
||||
}
|
||||
@@ -15,20 +15,37 @@ public sealed class RunCommandUseCase
|
||||
|
||||
public RunCommandUseCase(ICommandExecutor executor, IElevationService elevation)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(executor);
|
||||
ArgumentNullException.ThrowIfNull(elevation);
|
||||
_executor = executor;
|
||||
_elevation = elevation;
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="command"/>, streaming output, choosing executor by <c>RequiresAdmin</c>.</summary>
|
||||
public Task<ExecutionResult> RunAsync(
|
||||
/// <summary>
|
||||
/// Runs <paramref name="command"/>, streaming output, choosing the executor by <c>RequiresAdmin</c>.
|
||||
/// The output channel is always completed — even when the run throws — so a reader never waits forever.
|
||||
/// </summary>
|
||||
public async Task<ExecutionResult> RunAsync(
|
||||
CommandDefinition command,
|
||||
ChannelWriter<OutputLine> output,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
|
||||
return command.RequiresAdmin
|
||||
? _elevation.RunElevatedAsync(command, output, cancellationToken)
|
||||
: _executor.ExecuteAsync(command, output, cancellationToken);
|
||||
try
|
||||
{
|
||||
return command.RequiresAdmin
|
||||
? await _elevation.RunElevatedAsync(command, output, cancellationToken).ConfigureAwait(false)
|
||||
: await _executor.ExecuteAsync(command, output, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return new ExecutionResult { ExitCode = -1, Success = false, Duration = TimeSpan.Zero, Cancelled = true };
|
||||
}
|
||||
finally
|
||||
{
|
||||
output.TryComplete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.UserCommands;
|
||||
|
||||
/// <summary>
|
||||
/// Builds an executable <see cref="CommandDefinition"/> for a user-defined command.
|
||||
///
|
||||
/// SAFETY (golden rule #1): the produced definition ALWAYS has <see cref="CommandDefinition.RequiresAdmin"/>
|
||||
/// = false, so user commands run as the current (non-elevated) user and can never be routed to the
|
||||
/// elevation broker by <c>RunCommandUseCase</c>. The id is namespaced with <see cref="IdPrefix"/> so it
|
||||
/// can never collide with — or be mistaken for — a vetted catalog id; even if a bug routed it to the
|
||||
/// Elevator, the Elevator validates ids against its own embedded catalog and rejects anything else.
|
||||
/// </summary>
|
||||
public static class UserCommandFactory
|
||||
{
|
||||
/// <summary>Prefix marking an id as user-defined (never present in the vetted catalog).</summary>
|
||||
public const string IdPrefix = "user:";
|
||||
|
||||
/// <summary>Converts a user command to a non-elevated executable definition.</summary>
|
||||
public static CommandDefinition ToDefinition(UserCommand command)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
|
||||
return new CommandDefinition
|
||||
{
|
||||
Id = IdPrefix + command.Id,
|
||||
CategoryId = "user",
|
||||
// Not resource keys: the shell displays user commands by name. A name that happens to
|
||||
// equal a resource key (e.g. "AppTitle") must not be translated into that resource.
|
||||
TitleKey = IdPrefix + command.Id,
|
||||
DescriptionKey = IdPrefix + command.Id,
|
||||
Executable = command.Executable,
|
||||
ArgsTemplate = NormalizeArguments(command.Executable, command.Arguments),
|
||||
ExecutionMode = ExecutionMode.Capture,
|
||||
RequiresAdmin = false, // INVARIANT — a user command must never elevate.
|
||||
DangerLevel = DangerLevel.Caution,
|
||||
Restart = RestartPolicy.No,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes arguments so a one-shot command actually runs and then exits. <c>cmd.exe</c>
|
||||
/// without <c>/c</c> (or <c>/k</c>) opens an interactive shell that blocks forever waiting on
|
||||
/// stdin, so for cmd we prepend <c>/c</c>. Other executables (e.g. powershell) are left as-is.
|
||||
/// </summary>
|
||||
public static string NormalizeArguments(string executable, string? arguments)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(executable);
|
||||
|
||||
var args = arguments ?? string.Empty;
|
||||
if (IsCmd(executable) && !HasCmdRunSwitch(args))
|
||||
{
|
||||
return args.Length == 0 ? "/c" : "/c " + args;
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
private static bool IsCmd(string executable)
|
||||
=> string.Equals(Path.GetFileNameWithoutExtension(executable.Trim().Trim('"')), "cmd", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>True when a /c or /k switch appears among the leading switches (e.g. "/q /c dir").</summary>
|
||||
private static bool HasCmdRunSwitch(string arguments)
|
||||
{
|
||||
foreach (var token in arguments.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (!token.StartsWith('/'))
|
||||
{
|
||||
return false; // switches come first; the command text starts here
|
||||
}
|
||||
|
||||
if (StartsWithSwitch(token, "/c") || StartsWithSwitch(token, "/k"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool StartsWithSwitch(string text, string flag)
|
||||
=> text.StartsWith(flag, StringComparison.OrdinalIgnoreCase)
|
||||
&& (text.Length == flag.Length || char.IsWhiteSpace(text[flag.Length]));
|
||||
}
|
||||
@@ -53,6 +53,9 @@ public sealed record CommandDefinition
|
||||
/// <summary>Id of the command that reverts this one, if reversible.</summary>
|
||||
public string? RevertCommandId { get; init; }
|
||||
|
||||
/// <summary>Registry values this command may change, for read-only before/after comparison (optional).</summary>
|
||||
public IReadOnlyList<RegistryValueRef> AffectedRegistryValues { get; init; } = [];
|
||||
|
||||
/// <summary>Rough duration hint for the UI.</summary>
|
||||
public EstimatedDuration EstimatedDuration { get; init; } = EstimatedDuration.Short;
|
||||
|
||||
@@ -61,4 +64,23 @@ public sealed record CommandDefinition
|
||||
|
||||
/// <summary>Free-form search tags.</summary>
|
||||
public IReadOnlyList<string> Tags { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Inclusive lowest Windows build this command applies to (e.g. <c>22000</c> for Windows 11+).
|
||||
/// <see langword="null"/> means no lower bound.
|
||||
/// </summary>
|
||||
public int? MinOsBuild { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Inclusive highest Windows build this command applies to (e.g. <c>19045</c> for Windows 10 only).
|
||||
/// <see langword="null"/> means no upper bound.
|
||||
/// </summary>
|
||||
public int? MaxOsBuild { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether this command applies to the given OS build. Pure logic (no Win32) so the presentation
|
||||
/// layer can hide commands that do not apply to the current Windows version.
|
||||
/// </summary>
|
||||
public bool AppliesToOsBuild(int build)
|
||||
=> (MinOsBuild is null || build >= MinOsBuild) && (MaxOsBuild is null || build <= MaxOsBuild);
|
||||
}
|
||||
@@ -5,12 +5,21 @@ namespace CommandForge.Domain;
|
||||
/// </summary>
|
||||
public enum DangerLevel
|
||||
{
|
||||
/// <summary>Read-only / informational, no risk.</summary>
|
||||
/// <summary>
|
||||
/// No risk of losing data: read-only queries, opening a tool or settings page, or a small
|
||||
/// preference change that is undone the same way it was made.
|
||||
/// </summary>
|
||||
Safe,
|
||||
|
||||
/// <summary>Changes the system but is recoverable / low risk.</summary>
|
||||
/// <summary>
|
||||
/// Changes system state (services, registry, caches, boot-time checks); recoverable, but undoing
|
||||
/// it may take effort. Confirmed before running unless the user turned that off.
|
||||
/// </summary>
|
||||
Caution,
|
||||
|
||||
/// <summary>May cause data loss or instability; requires strict confirmation.</summary>
|
||||
/// <summary>
|
||||
/// May lose data, remove a rollback option or leave Windows unstable. Always needs a typed
|
||||
/// confirmation, which the user cannot turn off.
|
||||
/// </summary>
|
||||
Dangerous,
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
namespace CommandForge.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// The kind of executable a command runs through. Maps the <c>executable</c> field of the catalog.
|
||||
/// </summary>
|
||||
public enum ExecutableKind
|
||||
{
|
||||
/// <summary>cmd.exe</summary>
|
||||
Cmd,
|
||||
|
||||
/// <summary>powershell.exe / pwsh</summary>
|
||||
PowerShell,
|
||||
|
||||
/// <summary>winget</summary>
|
||||
Winget,
|
||||
|
||||
/// <summary>dism.exe</summary>
|
||||
Dism,
|
||||
|
||||
/// <summary>A direct path to an executable.</summary>
|
||||
Direct,
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace CommandForge.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// A record of one finished command execution, persisted for the execution-history view.
|
||||
/// </summary>
|
||||
public sealed record ExecutionRecord
|
||||
{
|
||||
/// <summary>The catalog id of the command that ran.</summary>
|
||||
public required string CommandId { get; init; }
|
||||
|
||||
/// <summary>When the run finished (clock instant, with offset).</summary>
|
||||
public required DateTimeOffset Timestamp { get; init; }
|
||||
|
||||
/// <summary>The process exit code.</summary>
|
||||
public required int ExitCode { get; init; }
|
||||
|
||||
/// <summary>Whether the run was considered successful (exit 0 or the reboot-required code).</summary>
|
||||
public required bool Success { get; init; }
|
||||
|
||||
/// <summary>Wall-clock duration in milliseconds.</summary>
|
||||
public required long DurationMs { get; init; }
|
||||
|
||||
/// <summary>Whether the run signalled that a restart is required (e.g. exit code 3010).</summary>
|
||||
public bool RequiresRestart { get; init; }
|
||||
}
|
||||
@@ -18,13 +18,11 @@ public sealed record ExecutionResult
|
||||
public required TimeSpan Duration { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether a system restart is required to finish (e.g. exit code 3010 or a regex match).
|
||||
/// Whether a system restart is required to finish (exit code 3010, a restart-always command, or
|
||||
/// an output-regex match).
|
||||
/// </summary>
|
||||
public bool RequiresRestart { get; init; }
|
||||
|
||||
/// <summary>Whether the run was cancelled by the user (process tree killed).</summary>
|
||||
public bool Cancelled { get; init; }
|
||||
|
||||
/// <summary>Captured stdout/stderr lines, in order.</summary>
|
||||
public IReadOnlyList<string> OutputLines { get; init; } = [];
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace CommandForge.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// A named, ordered sequence of catalog command ids run together as one "recipe" (macro),
|
||||
/// e.g. CheckHealth → ScanHealth → RestoreHealth → SFC.
|
||||
/// </summary>
|
||||
public sealed record Recipe
|
||||
{
|
||||
/// <summary>User-visible recipe name (also the identity — matched case-insensitively).</summary>
|
||||
public required string Name { get; init; }
|
||||
|
||||
/// <summary>The catalog command ids to run, in order.</summary>
|
||||
public required IReadOnlyList<string> CommandIds { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace CommandForge.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// Reference to a single registry value that a command may modify, used for read-only
|
||||
/// before/after comparison. Reading only — CommandForge never writes the registry directly.
|
||||
/// </summary>
|
||||
public sealed record RegistryValueRef
|
||||
{
|
||||
/// <summary>Full key path including the hive prefix, e.g. <c>HKCU\Software\…\Advanced</c>.</summary>
|
||||
public required string Path { get; init; }
|
||||
|
||||
/// <summary>Value name under the key (empty string means the key's default value).</summary>
|
||||
public required string Name { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace CommandForge.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// A user-defined command. These are NOT part of the vetted, embedded catalog and ALWAYS run
|
||||
/// without elevation (asInvoker) — see golden rule #1. Stored separately from the catalog.
|
||||
/// </summary>
|
||||
public sealed record UserCommand
|
||||
{
|
||||
/// <summary>Stable local id (generated when the command is created).</summary>
|
||||
public required string Id { get; init; }
|
||||
|
||||
/// <summary>User-visible name.</summary>
|
||||
public required string Name { get; init; }
|
||||
|
||||
/// <summary>Executable to run (e.g. <c>cmd</c>, <c>powershell</c>, or a full path).</summary>
|
||||
public required string Executable { get; init; }
|
||||
|
||||
/// <summary>Command-line arguments (optional).</summary>
|
||||
public string Arguments { get; init; } = "";
|
||||
}
|
||||
@@ -20,6 +20,18 @@ public static class AppPaths
|
||||
/// <summary><c>%AppData%\CommandForge\config.json</c>.</summary>
|
||||
public static string ConfigFilePath { get; } = Path.Combine(DataDirectory, "config.json");
|
||||
|
||||
/// <summary><c>%AppData%\CommandForge\history.json</c> — persisted execution history.</summary>
|
||||
public static string HistoryFilePath { get; } = Path.Combine(DataDirectory, "history.json");
|
||||
|
||||
/// <summary><c>%AppData%\CommandForge\profiles.json</c> — named settings/favorites profiles.</summary>
|
||||
public static string ProfilesFilePath { get; } = Path.Combine(DataDirectory, "profiles.json");
|
||||
|
||||
/// <summary><c>%AppData%\CommandForge\recipes.json</c> — user-defined recipes (command chains).</summary>
|
||||
public static string RecipesFilePath { get; } = Path.Combine(DataDirectory, "recipes.json");
|
||||
|
||||
/// <summary><c>%AppData%\CommandForge\user-commands.json</c> — user-defined (non-elevated) commands.</summary>
|
||||
public static string UserCommandsFilePath { get; } = Path.Combine(DataDirectory, "user-commands.json");
|
||||
|
||||
/// <summary>Ensures the data and logs directories exist.</summary>
|
||||
public static void EnsureCreated()
|
||||
{
|
||||
|
||||
@@ -32,4 +32,14 @@ internal sealed record CommandDto
|
||||
public EstimatedDuration EstimatedDuration { get; init; }
|
||||
public string? DocUrl { get; init; }
|
||||
public string[]? Tags { get; init; }
|
||||
public RegistryValueDto[]? AffectedRegistryValues { get; init; }
|
||||
public int? MinOsBuild { get; init; }
|
||||
public int? MaxOsBuild { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>JSON shape of a registry-value reference (for before/after comparison).</summary>
|
||||
internal sealed record RegistryValueDto
|
||||
{
|
||||
public string? Path { get; init; }
|
||||
public string? Name { get; init; }
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.Buffers;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using System.Text.RegularExpressions;
|
||||
using CommandForge.Application;
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Domain;
|
||||
|
||||
@@ -13,19 +15,36 @@ public sealed record CatalogLoadResult(
|
||||
IReadOnlyList<string> Errors);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the embedded <c>categories.json</c> / <c>commands.json</c>, validates them, and
|
||||
/// maps to Domain entities. Structural validation only — the cross-check that title/desc
|
||||
/// resource keys exist lives in the test project (it owns the .resx).
|
||||
/// Reads the embedded <c>categories.json</c> / <c>commands.json</c>, validates them, and maps to
|
||||
/// Domain entities. A record that fails validation is reported and left out — never loaded half
|
||||
/// right. The cross-check that title/desc resource keys exist lives in the test project (it owns
|
||||
/// the .resx).
|
||||
/// </summary>
|
||||
public static class CatalogLoader
|
||||
{
|
||||
private const string ResourcePrefix = "CommandForge.Infrastructure.Catalog.";
|
||||
|
||||
// A catalog executable is a bare program name ("dism", "services.msc"); the resolver pins it to
|
||||
// the system directories. Paths, quotes and spaces would sidestep that.
|
||||
private static readonly SearchValues<char> NotInProgramName = SearchValues.Create(" \t\"/\\");
|
||||
|
||||
/// <summary>Loads and validates the catalog embedded in this assembly.</summary>
|
||||
public static CatalogLoadResult LoadEmbedded()
|
||||
{
|
||||
var categories = Deserialize("categories.json", CatalogJsonContext.Default.CategoryDtoArray);
|
||||
var commands = Deserialize("commands.json", CatalogJsonContext.Default.CommandDtoArray);
|
||||
CategoryDto[] categories;
|
||||
CommandDto[] commands;
|
||||
try
|
||||
{
|
||||
categories = Deserialize("categories.json", CatalogJsonContext.Default.CategoryDtoArray);
|
||||
commands = Deserialize("commands.json", CatalogJsonContext.Default.CommandDtoArray);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
// Tests make this unreachable for a released build; still, an empty catalog plus an error
|
||||
// in the log and the Debug panel beats an app (or Elevator) that cannot start at all.
|
||||
return new CatalogLoadResult([], [], [$"The embedded catalog is not valid JSON: {ex.Message}"]);
|
||||
}
|
||||
|
||||
return Build(categories, commands);
|
||||
}
|
||||
|
||||
@@ -43,13 +62,45 @@ public static class CatalogLoader
|
||||
internal static CatalogLoadResult Build(CategoryDto[] categoryDtos, CommandDto[] commandDtos)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var categories = BuildCategories(categoryDtos, errors);
|
||||
var categoryIds = categories.Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
var commands = new List<CommandDefinition>();
|
||||
var seenIds = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var dto in commandDtos)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dto.Id)) { errors.Add("A command has an empty id."); continue; }
|
||||
if (!seenIds.Add(dto.Id)) { errors.Add($"Duplicate command id '{dto.Id}'."); continue; }
|
||||
|
||||
var problem = FindStructuralProblem(dto, categoryIds) ?? FindBehaviorProblem(dto);
|
||||
if (problem is not null) { errors.Add($"Command '{dto.Id}' {problem}"); continue; }
|
||||
|
||||
commands.Add(ToDefinition(dto));
|
||||
}
|
||||
|
||||
// Only commands that were actually loaded can be reverted to; a dangling id would offer an
|
||||
// Undo that cannot run.
|
||||
var loadedIds = commands.Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
|
||||
for (var i = 0; i < commands.Count; i++)
|
||||
{
|
||||
if (commands[i].RevertCommandId is { } revertId && !loadedIds.Contains(revertId))
|
||||
{
|
||||
errors.Add($"Command '{commands[i].Id}' has revertCommandId '{revertId}' that does not exist.");
|
||||
commands[i] = commands[i] with { RevertCommandId = null };
|
||||
}
|
||||
}
|
||||
|
||||
return new CatalogLoadResult(categories, commands, errors);
|
||||
}
|
||||
|
||||
private static List<CommandCategory> BuildCategories(CategoryDto[] categoryDtos, List<string> errors)
|
||||
{
|
||||
var categories = new List<CommandCategory>();
|
||||
var categoryIds = new HashSet<string>(StringComparer.Ordinal);
|
||||
var seenIds = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var dto in categoryDtos)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dto.Id)) { errors.Add("A category has an empty id."); continue; }
|
||||
if (!categoryIds.Add(dto.Id)) { errors.Add($"Duplicate category id '{dto.Id}'."); continue; }
|
||||
if (!seenIds.Add(dto.Id)) { errors.Add($"Duplicate category id '{dto.Id}'."); continue; }
|
||||
if (string.IsNullOrWhiteSpace(dto.TitleKey)) { errors.Add($"Category '{dto.Id}' is missing titleKey."); continue; }
|
||||
|
||||
categories.Add(new CommandCategory
|
||||
@@ -61,54 +112,71 @@ public static class CatalogLoader
|
||||
});
|
||||
}
|
||||
|
||||
var commands = new List<CommandDefinition>();
|
||||
var commandIds = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var dto in commandDtos)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dto.Id)) { errors.Add("A command has an empty id."); continue; }
|
||||
if (!commandIds.Add(dto.Id)) { errors.Add($"Duplicate command id '{dto.Id}'."); continue; }
|
||||
if (string.IsNullOrWhiteSpace(dto.CategoryId)) { errors.Add($"Command '{dto.Id}' is missing categoryId."); continue; }
|
||||
if (!categoryIds.Contains(dto.CategoryId)) { errors.Add($"Command '{dto.Id}' references unknown categoryId '{dto.CategoryId}'."); continue; }
|
||||
if (string.IsNullOrWhiteSpace(dto.TitleKey)) { errors.Add($"Command '{dto.Id}' is missing titleKey."); continue; }
|
||||
if (string.IsNullOrWhiteSpace(dto.DescriptionKey)) { errors.Add($"Command '{dto.Id}' is missing descriptionKey."); continue; }
|
||||
if (string.IsNullOrWhiteSpace(dto.Executable)) { errors.Add($"Command '{dto.Id}' is missing executable."); continue; }
|
||||
if (dto.Restart == RestartPolicy.FromOutputRegex && !IsValidRegex(dto.RestartRegex)) { errors.Add($"Command '{dto.Id}' has an invalid restartRegex."); continue; }
|
||||
|
||||
commands.Add(new CommandDefinition
|
||||
{
|
||||
Id = dto.Id,
|
||||
CategoryId = dto.CategoryId,
|
||||
TitleKey = dto.TitleKey,
|
||||
DescriptionKey = dto.DescriptionKey,
|
||||
Icon = dto.Icon,
|
||||
Executable = dto.Executable,
|
||||
ArgsTemplate = dto.ArgsTemplate ?? string.Empty,
|
||||
ExecutionMode = dto.ExecutionMode,
|
||||
RequiresAdmin = dto.RequiresAdmin,
|
||||
DangerLevel = dto.DangerLevel,
|
||||
ConfirmBeforeRun = dto.ConfirmBeforeRun,
|
||||
CreatesRestorePoint = dto.CreatesRestorePoint,
|
||||
Restart = dto.Restart,
|
||||
RestartRegex = dto.RestartRegex,
|
||||
RevertCommandId = dto.RevertCommandId,
|
||||
EstimatedDuration = dto.EstimatedDuration,
|
||||
DocUrl = dto.DocUrl,
|
||||
Tags = dto.Tags ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
foreach (var command in commands)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(command.RevertCommandId) && !commandIds.Contains(command.RevertCommandId))
|
||||
{
|
||||
errors.Add($"Command '{command.Id}' has revertCommandId '{command.RevertCommandId}' that does not exist.");
|
||||
}
|
||||
}
|
||||
|
||||
categories.Sort((a, b) => a.Order.CompareTo(b.Order));
|
||||
return new CatalogLoadResult(categories, commands, errors);
|
||||
return categories;
|
||||
}
|
||||
|
||||
/// <summary>A missing or dangling field, as the end of an error sentence; <see langword="null"/> when there is none.</summary>
|
||||
private static string? FindStructuralProblem(CommandDto dto, HashSet<string> categoryIds)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dto.CategoryId)) { return "is missing categoryId."; }
|
||||
if (!categoryIds.Contains(dto.CategoryId)) { return $"references unknown categoryId '{dto.CategoryId}'."; }
|
||||
if (string.IsNullOrWhiteSpace(dto.TitleKey)) { return "is missing titleKey."; }
|
||||
if (string.IsNullOrWhiteSpace(dto.DescriptionKey)) { return "is missing descriptionKey."; }
|
||||
if (string.IsNullOrWhiteSpace(dto.Executable)) { return "is missing executable."; }
|
||||
if (dto.Executable.AsSpan().IndexOfAny(NotInProgramName) >= 0) { return "has an executable that is not a plain program name (arguments belong in argsTemplate)."; }
|
||||
if (dto.MinOsBuild is <= 0) { return "has a non-positive minOsBuild."; }
|
||||
if (dto.MaxOsBuild is <= 0) { return "has a non-positive maxOsBuild."; }
|
||||
if (dto.MinOsBuild is { } minBuild && dto.MaxOsBuild is { } maxBuild && maxBuild < minBuild) { return $"has maxOsBuild ({maxBuild}) less than minOsBuild ({minBuild})."; }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Settings that contradict each other or the safety rules; <see langword="null"/> when there are none.</summary>
|
||||
private static string? FindBehaviorProblem(CommandDto dto)
|
||||
{
|
||||
var unknownTokens = ArgumentTokens.FindUnknown(dto.ArgsTemplate ?? string.Empty);
|
||||
if (unknownTokens.Count > 0) { return $"uses unknown argument token(s) {string.Join(", ", unknownTokens)}."; }
|
||||
if (dto.DangerLevel != DangerLevel.Safe && !dto.ConfirmBeforeRun) { return $"is {dto.DangerLevel} but does not set confirmBeforeRun."; }
|
||||
if (dto.ExecutionMode == ExecutionMode.Launch && dto.Restart is RestartPolicy.FromExitCode or RestartPolicy.FromOutputRegex)
|
||||
{
|
||||
return $"cannot use restart policy {dto.Restart} in Launch mode (its exit code and output are not captured).";
|
||||
}
|
||||
|
||||
if (dto.Restart == RestartPolicy.FromOutputRegex && !IsValidRegex(dto.RestartRegex)) { return "has an invalid restartRegex."; }
|
||||
if (dto.Restart != RestartPolicy.FromOutputRegex && !string.IsNullOrEmpty(dto.RestartRegex)) { return $"has a restartRegex but its restart policy is {dto.Restart}."; }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static CommandDefinition ToDefinition(CommandDto dto) => new()
|
||||
{
|
||||
Id = dto.Id!,
|
||||
CategoryId = dto.CategoryId!,
|
||||
TitleKey = dto.TitleKey!,
|
||||
DescriptionKey = dto.DescriptionKey!,
|
||||
Icon = dto.Icon,
|
||||
Executable = dto.Executable!,
|
||||
ArgsTemplate = dto.ArgsTemplate ?? string.Empty,
|
||||
ExecutionMode = dto.ExecutionMode,
|
||||
RequiresAdmin = dto.RequiresAdmin,
|
||||
DangerLevel = dto.DangerLevel,
|
||||
ConfirmBeforeRun = dto.ConfirmBeforeRun,
|
||||
CreatesRestorePoint = dto.CreatesRestorePoint,
|
||||
Restart = dto.Restart,
|
||||
RestartRegex = dto.RestartRegex,
|
||||
RevertCommandId = string.IsNullOrWhiteSpace(dto.RevertCommandId) ? null : dto.RevertCommandId,
|
||||
EstimatedDuration = dto.EstimatedDuration,
|
||||
DocUrl = dto.DocUrl,
|
||||
Tags = dto.Tags ?? [],
|
||||
AffectedRegistryValues = dto.AffectedRegistryValues is null
|
||||
? []
|
||||
: dto.AffectedRegistryValues
|
||||
.Where(r => !string.IsNullOrWhiteSpace(r.Path))
|
||||
.Select(r => new RegistryValueRef { Path = r.Path!, Name = r.Name ?? string.Empty })
|
||||
.ToList(),
|
||||
MinOsBuild = dto.MinOsBuild,
|
||||
MaxOsBuild = dto.MaxOsBuild,
|
||||
};
|
||||
|
||||
private static bool IsValidRegex(string? pattern)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(pattern))
|
||||
@@ -118,7 +186,7 @@ public static class CatalogLoader
|
||||
|
||||
try
|
||||
{
|
||||
_ = Regex.Match(string.Empty, pattern);
|
||||
_ = Regex.Match(string.Empty, pattern, RegexOptions.None, TimeSpan.FromSeconds(1));
|
||||
return true;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
|
||||
@@ -8,5 +8,7 @@
|
||||
{ "id": "system-info", "titleKey": "Cat_system-info", "icon": "Information", "order": 7 },
|
||||
{ "id": "diagnostics", "titleKey": "Cat_diagnostics", "icon": "Stethoscope", "order": 8 },
|
||||
{ "id": "security-privacy", "titleKey": "Cat_security-privacy", "icon": "ShieldLock", "order": 9 },
|
||||
{ "id": "developer", "titleKey": "Cat_developer", "icon": "CodeBraces", "order": 10 }
|
||||
{ "id": "developer", "titleKey": "Cat_developer", "icon": "CodeBraces", "order": 10 },
|
||||
{ "id": "storage", "titleKey": "Cat_storage", "icon": "Harddisk", "order": 11 },
|
||||
{ "id": "services-startup", "titleKey": "Cat_services-startup", "icon": "Cog", "order": 12 }
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -25,13 +25,14 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.298">
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.13" />
|
||||
<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.366">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Serilog" Version="4.3.1" />
|
||||
<PackageReference Include="Velopack" Version="1.2.0" />
|
||||
<PackageReference Include="Serilog" Version="4.4.0" />
|
||||
<!-- Keep in lockstep with the vpk tool version in .config/dotnet-tools.json. -->
|
||||
<PackageReference Include="Velopack" Version="1.2.161" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -36,6 +36,12 @@ public static class ServiceCollectionExtensions
|
||||
services.AddSingleton<ILogMaintenance, LogMaintenance>();
|
||||
services.AddSingleton<IClock, SystemClock>();
|
||||
services.AddSingleton<ISettingsService, JsonSettingsService>();
|
||||
services.AddSingleton<IExecutionHistoryService, History.JsonExecutionHistoryService>();
|
||||
services.AddSingleton<ISettingsFile, Portability.JsonSettingsFile>();
|
||||
services.AddSingleton<IProfileService, Portability.JsonProfileService>();
|
||||
services.AddSingleton<IRecipeStore, Recipes.JsonRecipeStore>();
|
||||
services.AddSingleton<IUserCommandStore, UserCommands.JsonUserCommandStore>();
|
||||
services.AddSingleton<IRegistryService, Registry.WindowsRegistryService>();
|
||||
services.AddSingleton<ISystemInfoService, WindowsSystemInfoService>();
|
||||
services.AddSingleton<ICatalogProvider, JsonCatalogProvider>();
|
||||
services.AddSingleton<IProcessRunner, SystemProcessRunner>();
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Pipes;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Domain;
|
||||
using Serilog;
|
||||
|
||||
namespace CommandForge.Infrastructure.Elevation;
|
||||
|
||||
@@ -16,34 +18,86 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
|
||||
{
|
||||
private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(60);
|
||||
|
||||
// How long a cancelled command may take to wind down before the whole session is dropped.
|
||||
private static readonly TimeSpan CancelGracePeriod = TimeSpan.FromSeconds(10);
|
||||
private static readonly TimeSpan ExitTimeout = TimeSpan.FromSeconds(5);
|
||||
|
||||
private readonly ILogger _log = Log.ForContext<BrokerElevationService>();
|
||||
private readonly SemaphoreSlim _connectLock = new(1, 1);
|
||||
private NamedPipeServerStream? _server;
|
||||
private PipeMessageChannel? _channel;
|
||||
private Process? _elevator;
|
||||
|
||||
public bool IsElevationAvailable => OperatingSystem.IsWindows();
|
||||
/// <inheritdoc />
|
||||
public bool IsSessionActive => _channel is not null && _server is { IsConnected: true };
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? SessionChanged;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ExecutionResult> RunElevatedAsync(
|
||||
CommandDefinition command,
|
||||
ChannelWriter<OutputLine> output,
|
||||
CancellationToken cancellationToken)
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
|
||||
try
|
||||
{
|
||||
return await RunCoreAsync(command, output, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
output.TryComplete();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EndSessionAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _connectLock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
var elevator = _elevator;
|
||||
_elevator = null;
|
||||
ResetConnection(); // closing the pipe makes the Elevator stop its command and exit
|
||||
|
||||
if (elevator is not null)
|
||||
{
|
||||
await WaitForExitAsync(elevator, cancellationToken);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_connectLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ExecutionResult> RunCoreAsync(CommandDefinition command, ChannelWriter<OutputLine> output, CancellationToken cancellationToken)
|
||||
{
|
||||
PipeMessageChannel channel;
|
||||
try
|
||||
{
|
||||
channel = await EnsureConnectedAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is Win32Exception or TimeoutException or IOException or InvalidOperationException)
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return CancelledResult(); // cancelled while waiting for UAC / the Elevator to connect
|
||||
}
|
||||
catch (Exception ex) when (ex is Win32Exception or TimeoutException or IOException or InvalidOperationException or UnauthorizedAccessException)
|
||||
{
|
||||
_log.Warning(ex, "Elevation unavailable for {CommandId}.", command.Id);
|
||||
return await FailAsync(output, $"Elevation unavailable: {ex.Message}");
|
||||
}
|
||||
|
||||
using var cancelRegistration = cancellationToken.Register(
|
||||
static state => _ = SendCancelAsync((PipeMessageChannel)state!),
|
||||
channel);
|
||||
// Reads end when the Elevator answers — or CancelGracePeriod after the user cancels, if it doesn't.
|
||||
using var readCancel = new CancellationTokenSource();
|
||||
using var cancelRegistration = cancellationToken.Register(() =>
|
||||
{
|
||||
_ = SendCancelAsync(channel);
|
||||
readCancel.CancelAfter(CancelGracePeriod);
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
@@ -54,32 +108,37 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
|
||||
|
||||
while (true)
|
||||
{
|
||||
var message = await channel.ReadAsync(ElevationJsonContext.Default.ElevationMessage, CancellationToken.None);
|
||||
var message = await channel.ReadAsync(ElevationJsonContext.Default.ElevationMessage, readCancel.Token);
|
||||
if (message is null)
|
||||
{
|
||||
ResetConnection();
|
||||
return await FailAsync(output, "The Elevator closed the connection unexpectedly.");
|
||||
}
|
||||
|
||||
if (message.Kind == ElevationMessageKind.Output)
|
||||
switch (message.Kind)
|
||||
{
|
||||
await output.WriteAsync(new OutputLine(message.Text ?? string.Empty, message.IsError), CancellationToken.None);
|
||||
continue;
|
||||
case ElevationMessageKind.Output:
|
||||
await output.WriteAsync(new OutputLine(message.Text ?? string.Empty, message.IsError), CancellationToken.None);
|
||||
break;
|
||||
case ElevationMessageKind.Log:
|
||||
LogFromElevator(message);
|
||||
break;
|
||||
default:
|
||||
return ToResult(message);
|
||||
}
|
||||
|
||||
output.TryComplete();
|
||||
return new ExecutionResult
|
||||
{
|
||||
ExitCode = message.ExitCode,
|
||||
Success = message.Success,
|
||||
Duration = TimeSpan.FromMilliseconds(message.DurationMs),
|
||||
RequiresRestart = message.RequiresRestart,
|
||||
Cancelled = message.Cancelled,
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (IOException ex)
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
// The Elevator did not acknowledge the cancel in time; dropping the pipe makes it kill
|
||||
// the command and exit, and the next admin command starts a fresh session.
|
||||
_log.Warning(ex, "Elevator did not stop {CommandId} within {Seconds}s of cancel; ending the elevated session.", command.Id, CancelGracePeriod.TotalSeconds);
|
||||
ResetConnection();
|
||||
return CancelledResult();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ObjectDisposedException or JsonException)
|
||||
{
|
||||
_log.Warning(ex, "Elevation pipe failed while running {CommandId}.", command.Id);
|
||||
ResetConnection();
|
||||
return await FailAsync(output, $"Elevation pipe error: {ex.Message}");
|
||||
}
|
||||
@@ -128,13 +187,21 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
|
||||
throw new TimeoutException("The Elevator did not connect in time.");
|
||||
}
|
||||
|
||||
// The ACL admits any process of this user; only the Elevator we just started may talk to us.
|
||||
if (!PeerVerifier.IsExpectedClient(server, _elevator.Id))
|
||||
{
|
||||
throw new InvalidOperationException("An unexpected process connected to the elevation pipe.");
|
||||
}
|
||||
|
||||
_server = server;
|
||||
_channel = new PipeMessageChannel(server);
|
||||
_log.Information("Elevated session started (Elevator process {ProcessId}).", _elevator.Id);
|
||||
SessionChanged?.Invoke(this, EventArgs.Empty);
|
||||
return _channel;
|
||||
}
|
||||
catch
|
||||
{
|
||||
server.Dispose();
|
||||
await server.DisposeAsync();
|
||||
_elevator?.Dispose();
|
||||
_elevator = null;
|
||||
throw;
|
||||
@@ -146,6 +213,50 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private void LogFromElevator(ElevationMessage message)
|
||||
{
|
||||
if (message.IsError)
|
||||
{
|
||||
_log.Warning("Elevator: {Message}", message.Text);
|
||||
}
|
||||
else
|
||||
{
|
||||
_log.Information("Elevator: {Message}", message.Text);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WaitForExitAsync(Process elevator, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await elevator.WaitForExitAsync(cancellationToken).WaitAsync(ExitTimeout, cancellationToken);
|
||||
}
|
||||
catch (TimeoutException ex)
|
||||
{
|
||||
_log.Warning(ex, "The Elevator did not exit within {Seconds}s.", ExitTimeout.TotalSeconds);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// No process handle (already gone) — nothing to wait for.
|
||||
}
|
||||
finally
|
||||
{
|
||||
elevator.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static ExecutionResult ToResult(ElevationMessage message) => new()
|
||||
{
|
||||
ExitCode = message.ExitCode,
|
||||
Success = message.Success,
|
||||
Duration = TimeSpan.FromMilliseconds(message.DurationMs),
|
||||
RequiresRestart = message.RequiresRestart,
|
||||
Cancelled = message.Cancelled,
|
||||
};
|
||||
|
||||
private static ExecutionResult CancelledResult()
|
||||
=> new() { ExitCode = -1, Success = false, Duration = TimeSpan.Zero, Cancelled = true };
|
||||
|
||||
private static async Task SendCancelAsync(PipeMessageChannel channel)
|
||||
{
|
||||
try
|
||||
@@ -174,6 +285,7 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
|
||||
|
||||
private void ResetConnection()
|
||||
{
|
||||
var hadSession = _server is not null;
|
||||
_channel?.Dispose();
|
||||
_channel = null;
|
||||
|
||||
@@ -183,6 +295,11 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
|
||||
|
||||
_elevator?.Dispose();
|
||||
_elevator = null;
|
||||
|
||||
if (hadSession)
|
||||
{
|
||||
SessionChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
namespace CommandForge.Infrastructure.Elevation;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the environment for processes the elevated Elevator starts. The Elevator inherits the
|
||||
/// user's environment block, and a standard user can define per-user variables (HKCU\Environment)
|
||||
/// that redirect what an elevated child loads or touches: <c>COR_PROFILER</c>/<c>CORECLR_*</c>
|
||||
/// inject a DLL into .NET processes such as PowerShell, <c>PSModulePath</c> makes PowerShell
|
||||
/// auto-load modules from the user's Documents folder, and <c>windir</c>/<c>SystemRoot</c> retarget
|
||||
/// the recursive deletes some cleanup commands perform. So the child gets an allow-list: a few
|
||||
/// harmless pass-through values plus system paths re-derived from trusted sources.
|
||||
/// </summary>
|
||||
internal static class ChildEnvironment
|
||||
{
|
||||
// Copied from the Elevator's own environment when present (identity / hardware / user folders).
|
||||
private static readonly string[] PassThrough =
|
||||
[
|
||||
"APPDATA", "COMPUTERNAME", "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "LOGONSERVER",
|
||||
"NUMBER_OF_PROCESSORS", "OS", "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER",
|
||||
"PROCESSOR_LEVEL", "PROCESSOR_REVISION", "SESSIONNAME", "TEMP", "TMP", "USERDNSDOMAIN",
|
||||
"USERDOMAIN", "USERDOMAIN_ROAMINGPROFILE", "USERNAME",
|
||||
];
|
||||
|
||||
private const string SessionEnvironmentKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
|
||||
|
||||
/// <summary>Replaces the contents of <paramref name="environment"/> with the sanitized set.</summary>
|
||||
public static void Apply(IDictionary<string, string?> environment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
|
||||
var kept = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var name in PassThrough)
|
||||
{
|
||||
var match = environment.FirstOrDefault(pair => string.Equals(pair.Key, name, StringComparison.OrdinalIgnoreCase));
|
||||
if (match.Key is not null && !string.IsNullOrEmpty(match.Value))
|
||||
{
|
||||
kept[name] = match.Value;
|
||||
}
|
||||
}
|
||||
|
||||
environment.Clear();
|
||||
foreach (var (name, value) in kept)
|
||||
{
|
||||
environment[name] = value;
|
||||
}
|
||||
|
||||
foreach (var (name, value) in TrustedValues())
|
||||
{
|
||||
environment[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>System variables with values from the kernel, known folders and HKLM.</summary>
|
||||
internal static IReadOnlyDictionary<string, string> TrustedValues()
|
||||
{
|
||||
var system32 = SystemPaths.System32;
|
||||
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["SystemRoot"] = SystemPaths.WindowsDirectory,
|
||||
["windir"] = SystemPaths.WindowsDirectory,
|
||||
["SystemDrive"] = SystemPaths.SystemDrive,
|
||||
["ComSpec"] = Path.Combine(system32, "cmd.exe"),
|
||||
["USERPROFILE"] = SystemPaths.UserProfile,
|
||||
["ProgramData"] = SystemPaths.ProgramData,
|
||||
["ALLUSERSPROFILE"] = SystemPaths.ProgramData,
|
||||
["PUBLIC"] = SystemPaths.Public,
|
||||
["ProgramFiles"] = SystemPaths.ProgramFiles,
|
||||
["ProgramW6432"] = SystemPaths.ProgramFiles,
|
||||
["ProgramFiles(x86)"] = SystemPaths.ProgramFilesX86,
|
||||
["CommonProgramFiles"] = SystemPaths.CommonProgramFiles,
|
||||
["CommonProgramW6432"] = SystemPaths.CommonProgramFiles,
|
||||
["CommonProgramFiles(x86)"] = SystemPaths.CommonProgramFilesX86,
|
||||
|
||||
// Only $PSHOME\Modules: Windows PowerShell 5.1 re-inserts the per-user module folder when
|
||||
// this variable is missing or equals the machine value; to a narrower one it only adds the
|
||||
// admin-only Program Files module folder (built from the trusted ProgramFiles value above).
|
||||
["PSModulePath"] = Path.Combine(system32, "WindowsPowerShell", "v1.0", "Modules"),
|
||||
|
||||
["Path"] = MachinePath(),
|
||||
["PATHEXT"] = SystemPaths.ReadMachineValue(SessionEnvironmentKey, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WSF;.WSH;.MSC",
|
||||
};
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
/// <summary>The machine PATH from HKLM (no per-user directories), expanded with trusted values only.</summary>
|
||||
private static string MachinePath()
|
||||
{
|
||||
var fallback = string.Join(';', SystemPaths.System32, SystemPaths.WindowsDirectory, Path.Combine(SystemPaths.System32, "Wbem"), Path.Combine(SystemPaths.System32, "WindowsPowerShell", "v1.0"));
|
||||
if (SystemPaths.ReadMachineRawValue(SessionEnvironmentKey, "Path") is not { } raw)
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
|
||||
var entries = raw
|
||||
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(SystemPaths.ExpandTrusted)
|
||||
.Where(entry => entry is not null && Path.IsPathFullyQualified(entry))
|
||||
.Cast<string>()
|
||||
.ToList();
|
||||
return entries.Count == 0 ? fallback : string.Join(';', entries);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,9 @@ internal enum ElevationMessageKind
|
||||
{
|
||||
Output,
|
||||
Result,
|
||||
|
||||
/// <summary>A diagnostic for the UI's log (the elevated side writes no files of its own).</summary>
|
||||
Log,
|
||||
}
|
||||
|
||||
/// <summary>A request from the UI. Only a <see cref="CommandId"/> is ever sent — never a command line.</summary>
|
||||
@@ -25,7 +28,7 @@ internal sealed record ElevationRequest
|
||||
public string? CommandId { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A streamed output line or the final result.</summary>
|
||||
/// <summary>A streamed output line, a log line, or the final result.</summary>
|
||||
internal sealed record ElevationMessage
|
||||
{
|
||||
public ElevationMessageKind Kind { get; init; }
|
||||
@@ -47,6 +50,9 @@ internal sealed record ElevationMessage
|
||||
public static ElevationMessage Output(string text, bool isError)
|
||||
=> new() { Kind = ElevationMessageKind.Output, Text = text, IsError = isError };
|
||||
|
||||
public static ElevationMessage LogLine(string text, bool isError)
|
||||
=> new() { Kind = ElevationMessageKind.Log, Text = text, IsError = isError };
|
||||
|
||||
public static ElevationMessage FromResult(ExecutionResult result)
|
||||
=> new()
|
||||
{
|
||||
|
||||
@@ -27,6 +27,12 @@ internal sealed class ElevationServer
|
||||
CancellationTokenSource? runCts = null;
|
||||
var runTask = Task.CompletedTask;
|
||||
|
||||
// The elevated side has no log file; surface catalog problems in the UI's log instead.
|
||||
foreach (var error in _catalog.ValidationErrors)
|
||||
{
|
||||
await channel.WriteAsync(ElevationMessage.LogLine($"Catalog: {error}", isError: true), ElevationJsonContext.Default.ElevationMessage, cancellationToken);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
@@ -40,7 +46,11 @@ internal sealed class ElevationServer
|
||||
switch (request.Kind)
|
||||
{
|
||||
case ElevationRequestKind.Run:
|
||||
runCts?.Cancel();
|
||||
if (runCts is not null)
|
||||
{
|
||||
await runCts.CancelAsync();
|
||||
}
|
||||
|
||||
await runTask;
|
||||
runCts?.Dispose();
|
||||
runCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
@@ -48,7 +58,11 @@ internal sealed class ElevationServer
|
||||
break;
|
||||
|
||||
case ElevationRequestKind.Cancel:
|
||||
runCts?.Cancel();
|
||||
if (runCts is not null)
|
||||
{
|
||||
await runCts.CancelAsync();
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -58,7 +72,11 @@ internal sealed class ElevationServer
|
||||
}
|
||||
finally
|
||||
{
|
||||
runCts?.Cancel();
|
||||
if (runCts is not null)
|
||||
{
|
||||
await runCts.CancelAsync();
|
||||
}
|
||||
|
||||
await runTask;
|
||||
runCts?.Dispose();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Pipes;
|
||||
using Windows.Win32;
|
||||
|
||||
namespace CommandForge.Infrastructure.Elevation;
|
||||
|
||||
/// <summary>
|
||||
/// Checks who is on the other end of the elevation pipe. The pipe's ACL admits any process of the
|
||||
/// same user, so both sides also confirm the peer's identity: the UI only talks to the Elevator it
|
||||
/// launched, and the Elevator only serves CommandForge.Wpf.exe from its own install folder.
|
||||
/// </summary>
|
||||
internal static class PeerVerifier
|
||||
{
|
||||
/// <summary>File name of the UI executable the Elevator expects as its pipe server.</summary>
|
||||
public const string UiExecutableName = "CommandForge.Wpf.exe";
|
||||
|
||||
/// <summary>UI side: true when the connected client is the process with <paramref name="expectedProcessId"/>.</summary>
|
||||
public static bool IsExpectedClient(NamedPipeServerStream pipe, int expectedProcessId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pipe);
|
||||
return PInvoke.GetNamedPipeClientProcessId(pipe.SafePipeHandle, out var clientId)
|
||||
&& clientId == (uint)expectedProcessId;
|
||||
}
|
||||
|
||||
/// <summary>Elevator side: true when the pipe server is the UI executable next to this process.</summary>
|
||||
public static bool IsExpectedServer(NamedPipeClientStream pipe)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pipe);
|
||||
return PInvoke.GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var serverId)
|
||||
&& IsImage(serverId, Path.Combine(AppContext.BaseDirectory, UiExecutableName));
|
||||
}
|
||||
|
||||
private static bool IsImage(uint processId, string expectedPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.GetProcessById((int)processId);
|
||||
var image = process.MainModule?.FileName;
|
||||
return image is not null
|
||||
&& string.Equals(Path.GetFullPath(image), Path.GetFullPath(expectedPath), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or Win32Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Text;
|
||||
using Windows.Win32;
|
||||
|
||||
namespace CommandForge.Infrastructure.Execution;
|
||||
|
||||
/// <summary>The code page native console tools use for redirected output.</summary>
|
||||
internal static class ConsoleEncodings
|
||||
{
|
||||
/// <summary>The OEM code page (437 on US English, 1258 on Vietnamese, 932 on Japanese, 936 on Simplified Chinese…).</summary>
|
||||
public static Encoding Oem { get; } = CreateOem();
|
||||
|
||||
private static Encoding CreateOem()
|
||||
{
|
||||
// .NET only ships UTF/ASCII/Latin-1 by default; the legacy code pages come from this provider.
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
try
|
||||
{
|
||||
return Encoding.GetEncoding((int)PInvoke.GetOEMCP());
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException)
|
||||
{
|
||||
return Encoding.Latin1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
namespace CommandForge.Infrastructure.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// Turns a catalog executable name ("dism", "powershell", "services.msc") into an absolute path in
|
||||
/// the Windows system directories. CreateProcess otherwise searches the application's own folder
|
||||
/// first — for a per-user install that folder is writable by the user, so a planted "reg.exe" next
|
||||
/// to the (elevated) Elevator would run with administrator rights.
|
||||
/// </summary>
|
||||
internal static class ExecutableResolver
|
||||
{
|
||||
private static readonly string[] ImplicitExtensions = [".exe", ".com", ".msc", ".cpl"];
|
||||
|
||||
/// <summary>Returns the absolute path for <paramref name="executable"/>, or the input unchanged when it can't be resolved.</summary>
|
||||
public static string Resolve(string executable)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executable) || Path.IsPathRooted(executable)
|
||||
|| executable.IndexOfAny([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]) >= 0)
|
||||
{
|
||||
return executable;
|
||||
}
|
||||
|
||||
if (IsName(executable, "powershell"))
|
||||
{
|
||||
return Path.Combine(SystemPaths.System32, "WindowsPowerShell", "v1.0", "powershell.exe");
|
||||
}
|
||||
|
||||
if (IsName(executable, "winget"))
|
||||
{
|
||||
// winget is an App Execution Alias in the user's WindowsApps folder, not a system binary.
|
||||
var alias = Path.Combine(SystemPaths.LocalAppData, "Microsoft", "WindowsApps", "winget.exe");
|
||||
return File.Exists(alias) ? alias : executable;
|
||||
}
|
||||
|
||||
var candidates = Path.HasExtension(executable)
|
||||
? [executable]
|
||||
: ImplicitExtensions.Select(extension => executable + extension).ToArray();
|
||||
|
||||
foreach (var directory in new[] { SystemPaths.System32, SystemPaths.WindowsDirectory })
|
||||
{
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
var path = Path.Combine(directory, candidate);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return executable;
|
||||
}
|
||||
|
||||
private static bool IsName(string executable, string name)
|
||||
=> string.Equals(executable, name, StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(executable, name + ".exe", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.Text;
|
||||
|
||||
namespace CommandForge.Infrastructure.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// Splits a child process's raw stdout/stderr bytes into text lines. Windows tools disagree on the
|
||||
/// encoding of redirected output: most write the console's OEM code page (localized text on
|
||||
/// Vietnamese/Japanese/Chinese Windows), newer tools write UTF-8, and sfc/wsl write UTF-16LE. So the
|
||||
/// stream is sniffed once for UTF-16LE, and otherwise every line is decoded as strict UTF-8 with an
|
||||
/// OEM-code-page fallback. Line breaks are \n, \r\n or a lone \r (progress updates).
|
||||
/// </summary>
|
||||
internal sealed class OutputDecoder
|
||||
{
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
|
||||
|
||||
private readonly Encoding _fallback;
|
||||
private readonly List<byte> _pending = [];
|
||||
private bool? _utf16;
|
||||
private bool _bomChecked;
|
||||
|
||||
public OutputDecoder(Encoding fallback)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(fallback);
|
||||
_fallback = fallback;
|
||||
}
|
||||
|
||||
/// <summary>Appends <paramref name="chunk"/> and adds every completed line to <paramref name="lines"/>.</summary>
|
||||
public void Push(ReadOnlySpan<byte> chunk, List<string> lines)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
foreach (var b in chunk)
|
||||
{
|
||||
_pending.Add(b);
|
||||
}
|
||||
|
||||
_utf16 ??= DetectUtf16(_pending);
|
||||
if (_utf16 is null)
|
||||
{
|
||||
return; // not enough bytes yet to tell UTF-16LE from a byte encoding
|
||||
}
|
||||
|
||||
if (_utf16 == true && !_bomChecked && _pending.Count >= 2)
|
||||
{
|
||||
if (_pending[0] == 0xFF && _pending[1] == 0xFE)
|
||||
{
|
||||
_pending.RemoveRange(0, 2);
|
||||
}
|
||||
|
||||
_bomChecked = true;
|
||||
}
|
||||
|
||||
ExtractLines(lines, endOfStream: false);
|
||||
}
|
||||
|
||||
/// <summary>Returns the trailing text after the last line break (call once at end of stream).</summary>
|
||||
public string? Flush()
|
||||
{
|
||||
_utf16 ??= false;
|
||||
var lines = new List<string>();
|
||||
ExtractLines(lines, endOfStream: true);
|
||||
return lines.Count == 0 ? null : string.Join(Environment.NewLine, lines);
|
||||
}
|
||||
|
||||
private void ExtractLines(List<string> lines, bool endOfStream)
|
||||
{
|
||||
var unit = _utf16 == true ? 2 : 1;
|
||||
var start = 0;
|
||||
var i = 0;
|
||||
while (i + unit <= _pending.Count)
|
||||
{
|
||||
var code = CodeAt(i, unit);
|
||||
if (code == '\n')
|
||||
{
|
||||
lines.Add(Decode(start, i));
|
||||
i += unit;
|
||||
start = i;
|
||||
}
|
||||
else if (code == '\r')
|
||||
{
|
||||
var next = i + unit;
|
||||
if (next + unit > _pending.Count && !endOfStream)
|
||||
{
|
||||
break; // can't tell yet whether a \n follows
|
||||
}
|
||||
|
||||
lines.Add(Decode(start, i));
|
||||
var nextCode = next + unit <= _pending.Count ? CodeAt(next, unit) : -1;
|
||||
i = nextCode == '\n' ? next + unit : next;
|
||||
start = i;
|
||||
}
|
||||
else
|
||||
{
|
||||
i += unit;
|
||||
}
|
||||
}
|
||||
|
||||
if (endOfStream && start < _pending.Count)
|
||||
{
|
||||
lines.Add(Decode(start, _pending.Count));
|
||||
start = _pending.Count;
|
||||
}
|
||||
|
||||
_pending.RemoveRange(0, start);
|
||||
}
|
||||
|
||||
/// <summary>The code unit at <paramref name="index"/>: one byte, or a little-endian UTF-16 unit.</summary>
|
||||
private int CodeAt(int index, int unit)
|
||||
=> unit == 2 ? _pending[index] | (_pending[index + 1] << 8) : _pending[index];
|
||||
|
||||
private string Decode(int start, int end)
|
||||
{
|
||||
if (end <= start)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var bytes = _pending.GetRange(start, end - start).ToArray();
|
||||
if (_utf16 == true)
|
||||
{
|
||||
return Encoding.Unicode.GetString(bytes);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return StrictUtf8.GetString(bytes);
|
||||
}
|
||||
catch (DecoderFallbackException)
|
||||
{
|
||||
return _fallback.GetString(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>UTF-16LE when a BOM is present or most odd bytes of plain-ASCII-range text are zero.</summary>
|
||||
private static bool? DetectUtf16(List<byte> data)
|
||||
{
|
||||
if (data.Count >= 2 && data[0] == 0xFF && data[1] == 0xFE)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data.Count < 4)
|
||||
{
|
||||
return null; // decide once there is enough to look at
|
||||
}
|
||||
|
||||
var sample = Math.Min(data.Count, 512) & ~1;
|
||||
var zeroOdd = 0;
|
||||
var zeroEven = 0;
|
||||
for (var i = 0; i < sample; i += 2)
|
||||
{
|
||||
if (data[i] == 0)
|
||||
{
|
||||
zeroEven++;
|
||||
}
|
||||
|
||||
if (data[i + 1] == 0)
|
||||
{
|
||||
zeroOdd++;
|
||||
}
|
||||
}
|
||||
|
||||
var pairs = sample / 2;
|
||||
return zeroOdd * 2 >= pairs && zeroEven * 4 < pairs;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Channels;
|
||||
using CommandForge.Application;
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Domain;
|
||||
|
||||
@@ -14,36 +16,54 @@ namespace CommandForge.Infrastructure.Execution;
|
||||
/// </summary>
|
||||
internal sealed class ProcessCommandExecutor : ICommandExecutor
|
||||
{
|
||||
private readonly IProcessRunner _runner;
|
||||
// Only the tail of the output is kept for regex restart detection.
|
||||
private const int MaxCapturedChars = 256 * 1024;
|
||||
|
||||
public ProcessCommandExecutor(IProcessRunner runner) => _runner = runner;
|
||||
// Catalog patterns are vetted, but output size is unbounded — cap the match time anyway.
|
||||
private static readonly TimeSpan RegexTimeout = TimeSpan.FromSeconds(2);
|
||||
|
||||
private readonly IProcessRunner _runner;
|
||||
private readonly IReadOnlyDictionary<string, string> _tokens;
|
||||
|
||||
public ProcessCommandExecutor(IProcessRunner runner)
|
||||
: this(runner, SystemPathTokens.Values)
|
||||
{
|
||||
}
|
||||
|
||||
internal ProcessCommandExecutor(IProcessRunner runner, IReadOnlyDictionary<string, string> tokens)
|
||||
{
|
||||
_runner = runner;
|
||||
_tokens = tokens;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ExecutionResult> ExecuteAsync(
|
||||
CommandDefinition command,
|
||||
ChannelWriter<OutputLine> output,
|
||||
CancellationToken cancellationToken)
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
var arguments = ArgumentTokens.Expand(command.ArgsTemplate, _tokens);
|
||||
|
||||
if (command.ExecutionMode == ExecutionMode.Launch)
|
||||
{
|
||||
return Launch(command, output, stopwatch);
|
||||
return Launch(command, arguments, output, stopwatch);
|
||||
}
|
||||
|
||||
var capturedLines = new List<string>();
|
||||
// Keep (a bounded tail of) the text only when a restart regex needs to inspect it.
|
||||
var captured = command.Restart == RestartPolicy.FromOutputRegex ? new StringBuilder() : null;
|
||||
|
||||
// Internal pipe: runner (background threads) -> here. We tee each line to the caller's
|
||||
// channel (for the UI) while capturing the full text for regex restart detection.
|
||||
// Internal pipe: runner (background threads) -> here. Each line is teed to the caller's
|
||||
// channel (for the UI) and, when needed, into the capture buffer.
|
||||
var inner = Channel.CreateUnbounded<OutputLine>(new UnboundedChannelOptions { SingleReader = true });
|
||||
var runTask = _runner.RunAsync(command.Executable, command.ArgsTemplate, inner.Writer, cancellationToken);
|
||||
var runTask = _runner.RunAsync(command.Executable, arguments, inner.Writer, cancellationToken);
|
||||
|
||||
await foreach (var line in inner.Reader.ReadAllAsync(CancellationToken.None))
|
||||
{
|
||||
capturedLines.Add(line.Text);
|
||||
Capture(captured, line.Text);
|
||||
await output.WriteAsync(line, CancellationToken.None);
|
||||
}
|
||||
|
||||
@@ -60,7 +80,6 @@ internal sealed class ProcessCommandExecutor : ICommandExecutor
|
||||
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
|
||||
{
|
||||
var error = $"Failed to start '{command.Executable}': {ex.Message}";
|
||||
capturedLines.Add(error);
|
||||
await output.WriteAsync(new OutputLine(error, IsError: true), CancellationToken.None);
|
||||
}
|
||||
finally
|
||||
@@ -69,27 +88,24 @@ internal sealed class ProcessCommandExecutor : ICommandExecutor
|
||||
}
|
||||
|
||||
stopwatch.Stop();
|
||||
var requiresRestart = !cancelled && DetectRestart(command, exitCode, string.Join('\n', capturedLines));
|
||||
|
||||
return new ExecutionResult
|
||||
{
|
||||
ExitCode = exitCode,
|
||||
Success = !cancelled && (exitCode == 0 || exitCode == ExecutionResult.RebootRequiredExitCode),
|
||||
Duration = stopwatch.Elapsed,
|
||||
RequiresRestart = requiresRestart,
|
||||
RequiresRestart = !cancelled && DetectRestart(command, exitCode, captured),
|
||||
Cancelled = cancelled,
|
||||
OutputLines = capturedLines,
|
||||
};
|
||||
}
|
||||
|
||||
private ExecutionResult Launch(CommandDefinition command, ChannelWriter<OutputLine> output, Stopwatch stopwatch)
|
||||
private ExecutionResult Launch(CommandDefinition command, string arguments, ChannelWriter<OutputLine> output, Stopwatch stopwatch)
|
||||
{
|
||||
string message;
|
||||
bool success;
|
||||
try
|
||||
{
|
||||
_runner.Launch(command.Executable, command.ArgsTemplate);
|
||||
message = $"Launched: {command.Executable} {command.ArgsTemplate}".Trim();
|
||||
_runner.Launch(command.Executable, arguments);
|
||||
message = $"Launched: {command.Executable} {arguments}".Trim();
|
||||
success = true;
|
||||
}
|
||||
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
|
||||
@@ -107,18 +123,41 @@ internal sealed class ProcessCommandExecutor : ICommandExecutor
|
||||
ExitCode = success ? 0 : -1,
|
||||
Success = success,
|
||||
Duration = stopwatch.Elapsed,
|
||||
RequiresRestart = false,
|
||||
// A launched tool runs on its own; only an unconditional policy can be honoured.
|
||||
RequiresRestart = success && command.Restart == RestartPolicy.Always,
|
||||
Cancelled = false,
|
||||
OutputLines = [message],
|
||||
};
|
||||
}
|
||||
|
||||
private static bool DetectRestart(CommandDefinition command, int exitCode, string output)
|
||||
=> command.Restart switch
|
||||
private static void Capture(StringBuilder? captured, string line)
|
||||
{
|
||||
if (captured is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
captured.Append(line).Append('\n');
|
||||
if (captured.Length > MaxCapturedChars)
|
||||
{
|
||||
captured.Remove(0, captured.Length - MaxCapturedChars);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool DetectRestart(CommandDefinition command, int exitCode, StringBuilder? captured)
|
||||
{
|
||||
// 3010 is Windows' own "succeeded, restart required" signal, whatever the catalog policy says.
|
||||
if (exitCode == ExecutionResult.RebootRequiredExitCode)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return command.Restart switch
|
||||
{
|
||||
RestartPolicy.Always => true,
|
||||
RestartPolicy.FromExitCode => exitCode == ExecutionResult.RebootRequiredExitCode,
|
||||
RestartPolicy.FromOutputRegex => command.RestartRegex is { } pattern && Regex.IsMatch(output, pattern),
|
||||
RestartPolicy.FromOutputRegex => command.RestartRegex is { } pattern
|
||||
&& captured is not null
|
||||
&& Regex.IsMatch(captured.ToString(), pattern, RegexOptions.None, RegexTimeout),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using Windows.Win32;
|
||||
using Windows.Win32.System.JobObjects;
|
||||
|
||||
namespace CommandForge.Infrastructure.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// A process-wide job object with "kill on close": every captured command process (and anything it
|
||||
/// starts) is placed in it, so when CommandForge — or the Elevator — exits or crashes, Windows ends
|
||||
/// those processes instead of leaving a half-finished DISM/winget run behind. GUI targets started in
|
||||
/// Launch mode are deliberately not added; they belong to the user.
|
||||
/// </summary>
|
||||
internal sealed class ProcessJob : IDisposable
|
||||
{
|
||||
private static readonly Lazy<ProcessJob> SharedInstance = new(() => new ProcessJob());
|
||||
|
||||
private readonly SafeFileHandle? _job;
|
||||
|
||||
private ProcessJob()
|
||||
{
|
||||
try
|
||||
{
|
||||
_job = PInvoke.CreateJobObject(lpJobAttributes: null, lpName: null);
|
||||
var limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
|
||||
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
var bytes = MemoryMarshal.AsBytes(new ReadOnlySpan<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>(in limits));
|
||||
if (_job.IsInvalid || !PInvoke.SetInformationJobObject(_job, JOBOBJECTINFOCLASS.JobObjectExtendedLimitInformation, bytes))
|
||||
{
|
||||
_job.Dispose();
|
||||
_job = null;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException)
|
||||
{
|
||||
_job = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The shared job for this process.</summary>
|
||||
public static ProcessJob Shared => SharedInstance.Value;
|
||||
|
||||
/// <summary>Adds <paramref name="process"/> to the job. Best effort: a failure only loses the clean-up guarantee.</summary>
|
||||
public bool TryAdd(Process process)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(process);
|
||||
if (_job is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return PInvoke.AssignProcessToJobObject(_job, process.SafeHandle);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
return false; // the process already exited
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => _job?.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using CommandForge.Application;
|
||||
|
||||
namespace CommandForge.Infrastructure.Execution;
|
||||
|
||||
/// <summary>Values for <see cref="ArgumentTokens"/>, taken from <see cref="SystemPaths"/> (trusted sources only).</summary>
|
||||
public static class SystemPathTokens
|
||||
{
|
||||
/// <summary>Token → value map used by the executor and by the command preview.</summary>
|
||||
public static IReadOnlyDictionary<string, string> Values { get; } = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
[ArgumentTokens.SystemDrive] = SystemPaths.SystemDrive,
|
||||
[ArgumentTokens.SystemRoot] = SystemPaths.WindowsDirectory,
|
||||
[ArgumentTokens.UserProfile] = SystemPaths.UserProfile,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Buffers;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Threading.Channels;
|
||||
using CommandForge.Domain;
|
||||
|
||||
@@ -8,6 +10,21 @@ namespace CommandForge.Infrastructure.Execution;
|
||||
/// <summary>Real <see cref="IProcessRunner"/> backed by <see cref="Process"/>.</summary>
|
||||
internal sealed class SystemProcessRunner : IProcessRunner
|
||||
{
|
||||
private static readonly TimeSpan DrainAfterKill = TimeSpan.FromSeconds(2);
|
||||
|
||||
private readonly Action<IDictionary<string, string?>>? _configureEnvironment;
|
||||
private readonly Encoding _fallbackEncoding;
|
||||
|
||||
/// <param name="configureEnvironment">
|
||||
/// Optional hook that rewrites a child's environment before it starts (the Elevator uses it to
|
||||
/// give elevated commands a clean, trusted environment).
|
||||
/// </param>
|
||||
public SystemProcessRunner(Action<IDictionary<string, string?>>? configureEnvironment = null)
|
||||
{
|
||||
_configureEnvironment = configureEnvironment;
|
||||
_fallbackEncoding = ConsoleEncodings.Oem;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> RunAsync(
|
||||
string fileName,
|
||||
@@ -21,39 +38,36 @@ internal sealed class SystemProcessRunner : IProcessRunner
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
FileName = ExecutableResolver.Resolve(fileName),
|
||||
Arguments = arguments,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
// Redirect stdin so we can close it immediately: a process that reads input (e.g. an
|
||||
// interactive "cmd" with no /c) gets EOF and exits instead of hanging forever.
|
||||
RedirectStandardInput = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
// Pin the working directory to System32 so the CreateProcess search order can't
|
||||
// resolve a bare executable name (e.g. "dism") from an attacker-controlled CWD —
|
||||
// important because this runner also executes elevated commands via the broker.
|
||||
WorkingDirectory = Environment.SystemDirectory,
|
||||
// Pin the working directory to System32 so nothing is resolved from an
|
||||
// attacker-controlled current directory — this runner also serves elevated commands.
|
||||
WorkingDirectory = SystemPaths.System32,
|
||||
},
|
||||
};
|
||||
|
||||
process.OutputDataReceived += (_, e) =>
|
||||
{
|
||||
if (e.Data is not null)
|
||||
{
|
||||
output.TryWrite(new OutputLine(e.Data, IsError: false));
|
||||
}
|
||||
};
|
||||
process.ErrorDataReceived += (_, e) =>
|
||||
{
|
||||
if (e.Data is not null)
|
||||
{
|
||||
output.TryWrite(new OutputLine(e.Data, IsError: true));
|
||||
}
|
||||
};
|
||||
_configureEnvironment?.Invoke(process.StartInfo.Environment);
|
||||
|
||||
try
|
||||
{
|
||||
process.Start();
|
||||
process.BeginOutputReadLine();
|
||||
process.BeginErrorReadLine();
|
||||
ProcessJob.Shared.TryAdd(process);
|
||||
|
||||
// Signal EOF on the child's stdin right away — nothing here ever feeds it input, and
|
||||
// leaving it open lets an interactive process block indefinitely.
|
||||
process.StandardInput.Close();
|
||||
|
||||
// Read the raw bytes: OutputDecoder handles OEM code pages and UTF-16 output, which a
|
||||
// StreamReader with a single fixed encoding would garble.
|
||||
var pumps = Task.WhenAll(
|
||||
PumpAsync(process.StandardOutput.BaseStream, isError: false, output),
|
||||
PumpAsync(process.StandardError.BaseStream, isError: true, output));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -62,11 +76,11 @@ internal sealed class SystemProcessRunner : IProcessRunner
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
TryKillTree(process);
|
||||
await Task.WhenAny(pumps, Task.Delay(DrainAfterKill, CancellationToken.None));
|
||||
throw;
|
||||
}
|
||||
|
||||
// Ensure the async stdout/stderr handlers have flushed before returning.
|
||||
process.WaitForExit();
|
||||
await pumps;
|
||||
return process.ExitCode;
|
||||
}
|
||||
finally
|
||||
@@ -80,12 +94,47 @@ internal sealed class SystemProcessRunner : IProcessRunner
|
||||
{
|
||||
using var process = Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
FileName = ExecutableResolver.Resolve(fileName),
|
||||
Arguments = arguments,
|
||||
UseShellExecute = true,
|
||||
WorkingDirectory = SystemPaths.System32,
|
||||
});
|
||||
}
|
||||
|
||||
private async Task PumpAsync(Stream stream, bool isError, ChannelWriter<OutputLine> output)
|
||||
{
|
||||
var decoder = new OutputDecoder(_fallbackEncoding);
|
||||
var lines = new List<string>();
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(8192);
|
||||
try
|
||||
{
|
||||
int read;
|
||||
while ((read = await stream.ReadAsync(buffer.AsMemory(0, buffer.Length), CancellationToken.None).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
decoder.Push(buffer.AsSpan(0, read), lines);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
output.TryWrite(new OutputLine(line, isError));
|
||||
}
|
||||
|
||||
lines.Clear();
|
||||
}
|
||||
|
||||
if (decoder.Flush() is { } last)
|
||||
{
|
||||
output.TryWrite(new OutputLine(last, isError));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
|
||||
{
|
||||
// The pipe broke because the process was killed — nothing more to read.
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryKillTree(Process process)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Infrastructure.History;
|
||||
|
||||
/// <summary>
|
||||
/// Persisted shape of <c>history.json</c>: a schema <see cref="Version"/> (for forward-compat)
|
||||
/// plus the records, newest first.
|
||||
/// </summary>
|
||||
internal sealed record HistoryFile
|
||||
{
|
||||
/// <summary>Schema version of the file.</summary>
|
||||
public int Version { get; init; } = 1;
|
||||
|
||||
/// <summary>Recorded executions, newest first.</summary>
|
||||
public IReadOnlyList<ExecutionRecord> Records { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// System.Text.Json source-generation context for <c>history.json</c> (camelCase, indented).
|
||||
/// </summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
UseStringEnumConverter = true,
|
||||
WriteIndented = true)]
|
||||
[JsonSerializable(typeof(HistoryFile))]
|
||||
internal sealed partial class ExecutionHistoryJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,59 @@
|
||||
using CommandForge.Application.History;
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Domain;
|
||||
using CommandForge.Infrastructure.Persistence;
|
||||
|
||||
namespace CommandForge.Infrastructure.History;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IExecutionHistoryService"/> backed by a local <c>history.json</c>. All data stays
|
||||
/// on the machine (see Privacy policy / golden rule "no telemetry").
|
||||
/// </summary>
|
||||
public sealed class JsonExecutionHistoryService : IExecutionHistoryService
|
||||
{
|
||||
private readonly string _path;
|
||||
private readonly Lock _gate = new();
|
||||
private IReadOnlyList<ExecutionRecord> _records;
|
||||
|
||||
/// <summary>Creates a service backed by the default <see cref="AppPaths.HistoryFilePath"/>.</summary>
|
||||
public JsonExecutionHistoryService()
|
||||
: this(AppPaths.HistoryFilePath)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates a service backed by an explicit path (used in tests).</summary>
|
||||
public JsonExecutionHistoryService(string path)
|
||||
{
|
||||
_path = path;
|
||||
_records = Load(path);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ExecutionRecord> GetRecent() => _records;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Record(ExecutionRecord record)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_records = ExecutionHistory.Add(_records, record);
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_records = [];
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
private void Save()
|
||||
=> JsonFile.TryWrite(_path, new HistoryFile { Records = _records }, ExecutionHistoryJsonContext.Default.HistoryFile);
|
||||
|
||||
private static IReadOnlyList<ExecutionRecord> Load(string path)
|
||||
=> JsonFile.Read(path, ExecutionHistoryJsonContext.Default.HistoryFile)?.Records?.Where(r => r is not null).ToList() ?? [];
|
||||
}
|
||||
@@ -1,25 +1,20 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using CommandForge.Application.Logging;
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Application.Settings;
|
||||
using CommandForge.Infrastructure.Persistence;
|
||||
|
||||
namespace CommandForge.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ISettingsService"/> backed by a local <c>config.json</c>. All data stays on
|
||||
/// the machine (see Privacy policy / golden rule "no telemetry").
|
||||
/// the machine (see Privacy policy / golden rule "no telemetry"). Saving is atomic and never
|
||||
/// throws; a corrupt file is kept aside and replaced by defaults.
|
||||
/// </summary>
|
||||
public sealed class JsonSettingsService : ISettingsService
|
||||
{
|
||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Converters = { new JsonStringEnumConverter() }, // human-readable enum values in config.json
|
||||
};
|
||||
|
||||
private readonly string _configPath;
|
||||
private SettingsModel _model;
|
||||
private readonly Lock _gate = new();
|
||||
private SettingsFileModel _model;
|
||||
|
||||
/// <summary>Creates a service backed by the default <see cref="AppPaths.ConfigFilePath"/>.</summary>
|
||||
public JsonSettingsService()
|
||||
@@ -31,213 +26,156 @@ public sealed class JsonSettingsService : ISettingsService
|
||||
public JsonSettingsService(string configPath)
|
||||
{
|
||||
_configPath = configPath;
|
||||
_model = Load(configPath);
|
||||
_model = (JsonFile.Read(configPath, SettingsJsonContext.Default.SettingsFileModel) ?? new SettingsFileModel()).Normalized();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? AcceptedTermsVersion
|
||||
{
|
||||
get => _model.AcceptedTermsVersion;
|
||||
set => _model = _model with { AcceptedTermsVersion = value };
|
||||
set => Update(m => m with { AcceptedTermsVersion = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool AutoCheckForUpdates
|
||||
{
|
||||
get => _model.AutoCheckForUpdates;
|
||||
set => _model = _model with { AutoCheckForUpdates = value };
|
||||
set => Update(m => m with { AutoCheckForUpdates = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public AppTheme Theme
|
||||
{
|
||||
get => _model.Theme;
|
||||
set => _model = _model with { Theme = value };
|
||||
set => Update(m => m with { Theme = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Language
|
||||
{
|
||||
get => _model.Language;
|
||||
set => _model = _model with { Language = value };
|
||||
set => Update(m => m with { Language = value ?? string.Empty });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public FontScale FontSize
|
||||
{
|
||||
get => _model.FontSize;
|
||||
set => _model = _model with { FontSize = value };
|
||||
set => Update(m => m with { FontSize = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CollapseSidebarByDefault
|
||||
{
|
||||
get => _model.CollapseSidebarByDefault;
|
||||
set => _model = _model with { CollapseSidebarByDefault = value };
|
||||
set => Update(m => m with { CollapseSidebarByDefault = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool ShowAdminRestartBadges
|
||||
{
|
||||
get => _model.ShowAdminRestartBadges;
|
||||
set => _model = _model with { ShowAdminRestartBadges = value };
|
||||
set => Update(m => m with { ShowAdminRestartBadges = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool ConfirmCaution
|
||||
{
|
||||
get => _model.ConfirmCaution;
|
||||
set => _model = _model with { ConfirmCaution = value };
|
||||
set => Update(m => m with { ConfirmCaution = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool AutoCreateRestorePoint
|
||||
{
|
||||
get => _model.AutoCreateRestorePoint;
|
||||
set => _model = _model with { AutoCreateRestorePoint = value };
|
||||
set => Update(m => m with { AutoCreateRestorePoint = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool AutoScrollConsole
|
||||
{
|
||||
get => _model.AutoScrollConsole;
|
||||
set => _model = _model with { AutoScrollConsole = value };
|
||||
set => Update(m => m with { AutoScrollConsole = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool WarnOnCancel
|
||||
{
|
||||
get => _model.WarnOnCancel;
|
||||
set => _model = _model with { WarnOnCancel = value };
|
||||
set => Update(m => m with { WarnOnCancel = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public LogLevel LogLevel
|
||||
{
|
||||
get => _model.LogLevel;
|
||||
set => _model = _model with { LogLevel = value };
|
||||
set => Update(m => m with { LogLevel = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<string> FavoriteCommandIds
|
||||
{
|
||||
get => _model.FavoriteCommandIds;
|
||||
set => _model = _model with { FavoriteCommandIds = value };
|
||||
set => Update(m => m with { FavoriteCommandIds = value ?? [] });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<string> RecentCommandIds
|
||||
{
|
||||
get => _model.RecentCommandIds;
|
||||
set => _model = _model with { RecentCommandIds = value };
|
||||
set => Update(m => m with { RecentCommandIds = value ?? [] });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public double? WindowWidth
|
||||
{
|
||||
get => _model.WindowWidth;
|
||||
set => _model = _model with { WindowWidth = value };
|
||||
set => Update(m => m with { WindowWidth = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public double? WindowHeight
|
||||
{
|
||||
get => _model.WindowHeight;
|
||||
set => _model = _model with { WindowHeight = value };
|
||||
set => Update(m => m with { WindowHeight = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public double? WindowLeft
|
||||
{
|
||||
get => _model.WindowLeft;
|
||||
set => _model = _model with { WindowLeft = value };
|
||||
set => Update(m => m with { WindowLeft = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public double? WindowTop
|
||||
{
|
||||
get => _model.WindowTop;
|
||||
set => _model = _model with { WindowTop = value };
|
||||
set => Update(m => m with { WindowTop = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool WindowMaximized
|
||||
{
|
||||
get => _model.WindowMaximized;
|
||||
set => _model = _model with { WindowMaximized = value };
|
||||
set => Update(m => m with { WindowMaximized = value });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Save()
|
||||
{
|
||||
var directory = Path.GetDirectoryName(_configPath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
lock (_gate)
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
var json = JsonSerializer.Serialize(_model, SerializerOptions);
|
||||
File.WriteAllText(_configPath, json);
|
||||
}
|
||||
|
||||
private static SettingsModel Load(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return new SettingsModel();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(path);
|
||||
return JsonSerializer.Deserialize<SettingsModel>(json, SerializerOptions) ?? new SettingsModel();
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Corrupt config: fall back to defaults rather than crashing on startup.
|
||||
return new SettingsModel();
|
||||
JsonFile.TryWrite(_configPath, _model, SettingsJsonContext.Default.SettingsFileModel);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record SettingsModel
|
||||
private void Update(Func<SettingsFileModel, SettingsFileModel> change)
|
||||
{
|
||||
public string? AcceptedTermsVersion { get; init; }
|
||||
|
||||
// Default true so existing or freshly-created configs opt in to startup update checks.
|
||||
public bool AutoCheckForUpdates { get; init; } = true;
|
||||
|
||||
public AppTheme Theme { get; init; } = AppTheme.System;
|
||||
|
||||
public string Language { get; init; } = ""; // follow OS
|
||||
|
||||
public FontScale FontSize { get; init; } = FontScale.Medium;
|
||||
|
||||
public bool CollapseSidebarByDefault { get; init; }
|
||||
|
||||
public bool ShowAdminRestartBadges { get; init; } = true;
|
||||
|
||||
public bool ConfirmCaution { get; init; } = true;
|
||||
|
||||
public bool AutoCreateRestorePoint { get; init; } = true;
|
||||
|
||||
public bool AutoScrollConsole { get; init; } = true;
|
||||
|
||||
public bool WarnOnCancel { get; init; } = true;
|
||||
|
||||
public LogLevel LogLevel { get; init; } = LogLevel.Information;
|
||||
|
||||
public IReadOnlyList<string> FavoriteCommandIds { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<string> RecentCommandIds { get; init; } = [];
|
||||
|
||||
public double? WindowWidth { get; init; }
|
||||
|
||||
public double? WindowHeight { get; init; }
|
||||
|
||||
public double? WindowLeft { get; init; }
|
||||
|
||||
public double? WindowTop { get; init; }
|
||||
|
||||
public bool WindowMaximized { get; init; }
|
||||
lock (_gate)
|
||||
{
|
||||
_model = change(_model);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,31 @@ namespace CommandForge.Infrastructure.Logging;
|
||||
/// and the DI container. <see cref="EntriesChanged"/> may fire off the UI thread —
|
||||
/// consumers must marshal to the UI thread before touching UI state.
|
||||
/// </summary>
|
||||
public sealed class InMemoryLogStore : ILogEventSink, ILogReader
|
||||
/// <remarks>
|
||||
/// A burst of log events raises <see cref="EntriesChanged"/> once, shortly after the burst starts,
|
||||
/// so the Log Viewer re-reads the buffer a few times a second instead of once per event.
|
||||
/// </remarks>
|
||||
public sealed class InMemoryLogStore : ILogEventSink, ILogReader, IDisposable
|
||||
{
|
||||
private const int Capacity = 1000;
|
||||
private static readonly TimeSpan DefaultNotifyDelay = TimeSpan.FromMilliseconds(150);
|
||||
|
||||
private readonly ConcurrentQueue<LogEntry> _entries = new();
|
||||
private readonly Timer _notifyTimer;
|
||||
private readonly TimeSpan _notifyDelay;
|
||||
private int _notifyPending;
|
||||
private volatile bool _disposed;
|
||||
|
||||
public InMemoryLogStore()
|
||||
: this(DefaultNotifyDelay)
|
||||
{
|
||||
}
|
||||
|
||||
internal InMemoryLogStore(TimeSpan notifyDelay)
|
||||
{
|
||||
_notifyDelay = notifyDelay;
|
||||
_notifyTimer = new Timer(_ => RaiseEntriesChanged(), null, Timeout.Infinite, Timeout.Infinite);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? EntriesChanged;
|
||||
@@ -27,11 +48,13 @@ public sealed class InMemoryLogStore : ILogEventSink, ILogReader
|
||||
|
||||
_entries.Enqueue(new LogEntry(logEvent.Timestamp, MapLevel(logEvent.Level), logEvent.RenderMessage()));
|
||||
|
||||
while (_entries.Count > Capacity && _entries.TryDequeue(out _))
|
||||
{
|
||||
}
|
||||
TrimTo(Capacity);
|
||||
|
||||
EntriesChanged?.Invoke(this, EventArgs.Empty);
|
||||
// The first event of a burst arms the timer; the rest ride along with that notification.
|
||||
if (!_disposed && Interlocked.Exchange(ref _notifyPending, 1) == 0)
|
||||
{
|
||||
_notifyTimer.Change(_notifyDelay, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -40,13 +63,34 @@ public sealed class InMemoryLogStore : ILogEventSink, ILogReader
|
||||
/// <inheritdoc />
|
||||
public void Clear()
|
||||
{
|
||||
while (_entries.TryDequeue(out _))
|
||||
{
|
||||
}
|
||||
TrimTo(0);
|
||||
|
||||
EntriesChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
_notifyTimer.Dispose();
|
||||
}
|
||||
|
||||
private void RaiseEntriesChanged()
|
||||
{
|
||||
// Reset before notifying: an event that lands while handlers read the buffer arms a new round.
|
||||
Volatile.Write(ref _notifyPending, 0);
|
||||
EntriesChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
private void TrimTo(int capacity)
|
||||
{
|
||||
var removed = true;
|
||||
while (removed && _entries.Count > capacity)
|
||||
{
|
||||
removed = _entries.TryDequeue(out _);
|
||||
}
|
||||
}
|
||||
|
||||
private static LogLevel MapLevel(LogEventLevel level) => level switch
|
||||
{
|
||||
LogEventLevel.Verbose => LogLevel.Verbose,
|
||||
|
||||
@@ -57,7 +57,7 @@ public sealed class LogMaintenance : ILogMaintenance
|
||||
{
|
||||
await using var source = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
var entry = archive.CreateEntry(Path.GetFileName(file), CompressionLevel.Optimal);
|
||||
await using var entryStream = entry.Open();
|
||||
await using var entryStream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
await source.CopyToAsync(entryStream, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (IOException)
|
||||
|
||||
@@ -4,3 +4,15 @@
|
||||
GetCurrentProcessId
|
||||
// Read-only physical-memory query for the Home dashboard (ISystemInfoService).
|
||||
GlobalMemoryStatusEx
|
||||
// Lets the primary instance take the foreground when a second launch asks it to (SingleInstanceGuard).
|
||||
AllowSetForegroundWindow
|
||||
// Console OEM code page: the encoding native tools use for redirected output (OutputDecoder).
|
||||
GetOEMCP
|
||||
// Kill-on-close job object so spawned command processes never outlive the app (ProcessJob).
|
||||
CreateJobObject
|
||||
SetInformationJobObject
|
||||
AssignProcessToJobObject
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
||||
// Elevation broker peer checks: who is on the other end of the pipe.
|
||||
GetNamedPipeClientProcessId
|
||||
GetNamedPipeServerProcessId
|
||||
@@ -0,0 +1,131 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using Serilog;
|
||||
|
||||
namespace CommandForge.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Crash-safe JSON persistence shared by every local store (settings, history, recipes, profiles,
|
||||
/// user commands). Writes go to a temporary file that atomically replaces the original, so a power
|
||||
/// loss mid-write can't leave half a file; unreadable or corrupt files never crash startup, and a
|
||||
/// corrupt file is kept aside for recovery instead of being silently overwritten.
|
||||
/// </summary>
|
||||
internal static class JsonFile
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads <paramref name="path"/>: null when it doesn't exist, can't be read (locked, denied)
|
||||
/// or isn't valid JSON. With <paramref name="keepCorruptCopy"/> an invalid file is first renamed
|
||||
/// to <c>name.corrupt-yyyyMMddHHmmss.json</c> so the next save can't overwrite the user's data.
|
||||
/// </summary>
|
||||
public static T? Read<T>(string path, JsonTypeInfo<T> typeInfo, bool keepCorruptCopy = true)
|
||||
where T : class
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||
ArgumentNullException.ThrowIfNull(typeInfo);
|
||||
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
string json;
|
||||
try
|
||||
{
|
||||
json = File.ReadAllText(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning(ex, "Could not read {Path}; using defaults for this session.", path);
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(json, typeInfo);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
if (!keepCorruptCopy)
|
||||
{
|
||||
Log.Information(ex, "{Path} is not valid JSON.", path);
|
||||
return null;
|
||||
}
|
||||
|
||||
var backup = KeepCorruptCopy(path);
|
||||
Log.Warning(ex, "{Path} is not valid JSON; kept it as {Backup} and started from defaults.", path, backup);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes atomically; returns false (and logs) instead of throwing when the disk refuses.</summary>
|
||||
public static bool TryWrite<T>(string path, T value, JsonTypeInfo<T> typeInfo)
|
||||
{
|
||||
try
|
||||
{
|
||||
Write(path, value, typeInfo);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning(ex, "Could not save {Path}; the change is kept in memory only.", path);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes atomically (temporary file in the same folder, then replace); throws on I/O errors.</summary>
|
||||
public static void Write<T>(string path, T value, JsonTypeInfo<T> typeInfo)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||
ArgumentNullException.ThrowIfNull(typeInfo);
|
||||
|
||||
var fullPath = Path.GetFullPath(path);
|
||||
var directory = Path.GetDirectoryName(fullPath) ?? throw new IOException($"'{path}' has no parent directory.");
|
||||
Directory.CreateDirectory(directory);
|
||||
|
||||
var bytes = JsonSerializer.SerializeToUtf8Bytes(value, typeInfo);
|
||||
var temp = Path.Combine(directory, $".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp");
|
||||
try
|
||||
{
|
||||
using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 4096, FileOptions.WriteThrough))
|
||||
{
|
||||
stream.Write(bytes);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
File.Move(temp, fullPath, overwrite: true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
TryDelete(temp);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? KeepCorruptCopy(string path)
|
||||
{
|
||||
var backup = Path.Combine(
|
||||
Path.GetDirectoryName(Path.GetFullPath(path)) ?? string.Empty,
|
||||
$"{Path.GetFileNameWithoutExtension(path)}.corrupt-{DateTime.Now:yyyyMMddHHmmss}{Path.GetExtension(path)}");
|
||||
try
|
||||
{
|
||||
File.Move(path, backup, overwrite: true);
|
||||
return backup;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A stray .tmp file is harmless: its name is unique and nothing ever loads it.
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user