diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..d406888b --- /dev/null +++ b/.clang-format @@ -0,0 +1,43 @@ +# docs/12_BUILD.md: clang-format (LLVM base, 4-space, 120 col), enforced in CI +# via `clang-format --dry-run -Werror` over src/native. +--- +Language: Cpp +BasedOnStyle: LLVM + +IndentWidth: 4 +TabWidth: 4 +UseTab: Never +ColumnLimit: 120 + +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakTemplateDeclarations: Yes +BreakBeforeBraces: Attach +BreakConstructorInitializers: BeforeColon +Cpp11BracedListStyle: true +FixNamespaceComments: true +NamespaceIndentation: None +PointerAlignment: Left +SortIncludes: CaseInsensitive +SpaceAfterCStyleCast: false +SpacesBeforeTrailingComments: 4 +Standard: c++20 + +# Keep the hot-path record and header structs readable as tables: their field +# comments carry the byte offsets that 07_IPC.md declares normative. +AlignConsecutiveDeclarations: Consecutive +AlignTrailingComments: true + +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^' + Priority: 1 + - Regex: '^<(d3d|dxgi|vulkan|GL)' + Priority: 2 + - Regex: '^<' + Priority: 3 + - Regex: '^"' + Priority: 4 diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..4a953e63 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,74 @@ +root = true + +[*] +charset = utf-8 +end_of_line = crlf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{json,yml,yaml,xml,csproj,props,targets,sln}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false # two trailing spaces is a markdown line break + +[*.{c,cpp,h,hpp}] +indent_size = 4 # clang-format is authoritative here; see .clang-format + +[*.cs] +# --- C# style (docs/12_BUILD.md: dotnet format must be clean) --- +csharp_style_namespace_declarations = file_scoped:error +csharp_using_directive_placement = outside_namespace:warning +csharp_prefer_braces = true:warning +csharp_style_var_for_built_in_types = false:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_expression_bodied_methods = when_on_single_line:suggestion + +dotnet_sort_system_directives_first = true +dotnet_separate_import_directive_groups = false +dotnet_style_readonly_field = true:warning +dotnet_style_require_accessibility_modifiers = for_non_interface_members:warning +dotnet_style_qualification_for_field = false:warning +dotnet_style_qualification_for_property = false:warning + +# Naming +dotnet_naming_rule.private_fields_underscore.severity = warning +dotnet_naming_rule.private_fields_underscore.symbols = private_fields +dotnet_naming_rule.private_fields_underscore.style = underscore_camel +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private +dotnet_naming_style.underscore_camel.capitalization = camel_case +dotnet_naming_style.underscore_camel.required_prefix = _ + +# --- Analyzer severities --- +# CA1416 (platform compatibility) must stay an error: it is what enforces the +# Windows 10 22H2 floor from NFR-8 against SupportedOSPlatformVersion. +dotnet_diagnostic.CA1416.severity = error + +# Async hygiene (CLAUDE.md coding conventions). +dotnet_diagnostic.CA2007.severity = warning # ConfigureAwait +dotnet_diagnostic.VSTHRD200.severity = none # 'Async' suffix — enforced by review + +# All user-visible strings come from .resx (docs/09_I18N.md). MA0011 flags +# IFormatProvider omissions, which is the adjacent bug; keep it loud. +dotnet_diagnostic.MA0011.severity = warning + +# Documentation comments on public members: too noisy for internal projects, +# and GenerateDocumentationFile is on for the shipping ones. +dotnet_diagnostic.CS1591.severity = suggestion + +[src/FrameLedger.App/**.cs] +# WPF codegen constraints, not style choices. The generated App.g.cs and +# *.g.cs partials declare these types public, so making them internal is a +# compile error; and the WPF idiom docs/16_WPFUI_SYNTAX.md is written against +# (x:Class="FrameLedger.App.App") necessarily puts a type named App inside a +# namespace named FrameLedger.App. Scoped to this project only. +dotnet_diagnostic.CA1515.severity = none # types could be internal +dotnet_diagnostic.CA1724.severity = none # type name conflicts with namespace +dotnet_diagnostic.MA0049.severity = none # type name matches containing namespace + +[tests/**/*.cs] +dotnet_diagnostic.CA1707.severity = none # underscores in test method names +dotnet_diagnostic.CA2007.severity = none diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..4a510bc0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,28 @@ +# FrameLedger is a Windows-only project and .editorconfig mandates CRLF. +# Without this file, line endings depend on each contributor's core.autocrlf +# setting, and `dotnet format --verify-no-changes` (a build.ps1 check gate) +# fails for reasons that do not appear in a diff. + +* text=auto eol=crlf + +# Shell scripts must keep LF or they will not run under bash / CI containers. +*.sh text eol=lf +*.bash text eol=lf + +# Binary — never normalize, never diff as text. +*.png binary +*.jpg binary +*.ico binary +*.dll binary +*.exe binary +*.lib binary +*.pdb binary +*.db binary +*.zip binary +*.ttf binary +*.otf binary + +# Linguist: keep generated and vendored material out of language statistics. +docs/** linguist-documentation +legal/** linguist-documentation +src/native/third_party/** linguist-vendored diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..7e17d42f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,93 @@ +# Referenced by docs/10_LOGGING_AND_BUG_REPORTS.md — the in-app "Report a bug" +# flow deep-links here with app version and OS prefilled. +name: Bug report +description: Something in FrameLedger is broken +labels: [bug] +body: + - type: markdown + attributes: + value: | + **If you found a game with anti-cheat that FrameLedger failed to detect, + please use the "Safety gap" template instead.** That is treated with the + same priority as a security report. + + The app can build a diagnostic bundle for you: **Help → Report a bug**. + It is created locally, shows you every file it contains before you do + anything, and is never uploaded automatically — you attach it yourself. + + - type: textarea + id: what-happened + attributes: + label: What happened? + description: What did you expect, and what happened instead? + validations: + required: true + + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: | + 1. Add game X + 2. Enable hooking + 3. Launch from FrameLedger + 4. ... + validations: + required: true + + - type: input + id: app-version + attributes: + label: FrameLedger version + description: Help → About, or prefilled if you came from the app + validations: + required: true + + - type: input + id: os + attributes: + label: Windows version + placeholder: 'Windows 11 26100.2314' + validations: + required: true + + - type: dropdown + id: tier + attributes: + label: Capture tier + description: Shown on the session and on the Dashboard live card + options: + - 'Tier 1 (hooked)' + - 'Tier 2 (ETW / no injection)' + - 'Tier 3 (duration + sensors only)' + - "Don't know" + validations: + required: true + + - type: input + id: gpu + attributes: + label: GPU and driver version + placeholder: 'RTX 4070, 566.36' + + - type: input + id: game + attributes: + label: Game and graphics API + placeholder: 'Cyberpunk 2077, D3D12, DLSS Quality + FG' + + - type: textarea + id: bundle + attributes: + label: Diagnostic bundle + description: | + Drag the zip from Help → Report a bug into this box. Injection bugs are + very hard to diagnose without the overlay log and hook fault details. + + - type: checkboxes + id: confirm + attributes: + label: Before submitting + options: + - label: I reviewed the bundle contents before attaching it + - label: This is not a report about anti-cheat detection (that uses the Safety gap template) diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 00000000..10a98fd7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,39 @@ +name: Feature request +description: Suggest something FrameLedger should do +labels: [enhancement] +body: + - type: markdown + attributes: + value: | + Before opening: `docs/15_ROADMAP.md` lists what is planned, and + `docs/02_SPEC.md` §Out of scope lists what is permanently excluded. + + **Permanently out of scope, regardless of how it is framed:** any + evasion technique, reading or writing game memory, kernel drivers, + hardware control (overclocking, fan curves, power limits), and + online/competitive titles. These are architectural constraints from + `docs/19_SAFETY_AND_ANTICHEAT.md`, not a backlog. + + - type: textarea + id: problem + attributes: + label: What problem would this solve? + description: The situation you are in, not the solution you have in mind. + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: What would you like it to do? + validations: + required: true + + - type: checkboxes + id: scope + attributes: + label: Scope check + options: + - label: This does not require evasion, game memory access, a kernel driver, or hardware control + required: true + - label: I checked docs/15_ROADMAP.md diff --git a/.github/ISSUE_TEMPLATE/safety_gap.yml b/.github/ISSUE_TEMPLATE/safety_gap.yml new file mode 100644 index 00000000..bb94a664 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/safety_gap.yml @@ -0,0 +1,66 @@ +# README: "If you find a game with anti-cheat that FrameLedger fails to detect, +# please open an issue — that is a safety bug and is treated with the same +# priority as a security report." +# +# It deserves its own template rather than being buried in the bug form: a +# missed blocklist entry can cost someone their account, and blocklist entries +# ship as data so a fix does not need a release. +name: Safety gap — undetected anti-cheat +description: FrameLedger failed to detect anti-cheat in a game +labels: [safety, priority-high] +body: + - type: markdown + attributes: + value: | + Thank you for reporting this. Blocklist entries ship as data + (`rules/detection-rules.json`) and can be updated without a new release, + so this can usually be fixed quickly for everyone. + + **Please do not include instructions for defeating any anti-cheat + system.** We need to know what to refuse, not how to evade it. + + - type: input + id: game + attributes: + label: Game + placeholder: 'Name, and the store it came from' + validations: + required: true + + - type: input + id: anticheat + attributes: + label: Which anti-cheat or anti-tamper + placeholder: 'e.g. Easy Anti-Cheat, BattlEye, Denuvo Anti-Cheat' + validations: + required: true + + - type: textarea + id: evidence + attributes: + label: How do you know it is present? + description: | + Module names, a directory next to the executable, a service, or a + driver. Filenames are the most useful thing you can give us. + validations: + required: true + + - type: dropdown + id: what-happened + attributes: + label: What did FrameLedger do? + options: + - 'Allowed hooking to be enabled (the toggle was not disabled)' + - 'Injected successfully' + - 'Injected, then something went wrong' + - 'Other' + validations: + required: true + + - type: textarea + id: consequences + attributes: + label: Did anything happen to your account? + description: | + Only if you are comfortable sharing. It helps us judge severity, and it + is genuinely useful to other users. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..ef2429c1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,27 @@ +# Central package management makes NuGet PRs single-file diffs +# (docs/12_BUILD.md, docs/13_CI_CD.md). +version: 2 +updates: + - package-ecosystem: nuget + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + minor-and-patch: + update-types: [minor, patch] + ignore: + # WPF-UI is pinned exactly and bumped deliberately: the 4.x line has + # NuGet-deprecated releases with critical bugs, and every bump needs the + # release notes read (docs/16_WPFUI_SYNTAX.md §Version hygiene). + - dependency-name: WPF-UI* + # FluentAssertions 8.x moved from Apache-2.0 to Xceed's Community + # Licence. An automated major bump here would be a licensing regression + # in a GPL-3.0 project (see Directory.Packages.props). + - dependency-name: FluentAssertions + update-types: [version-update:semver-major] + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..f21296b7 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,41 @@ + + +## What and why + + + +## Definition of done + +- [ ] Builds warning-free (C# **and** C++); tests green +- [ ] `dotnet format` and `clang-format` clean (`./build.ps1 check`) +- [ ] Any deviation from a doc updates that doc **in this PR** +- [ ] New user-visible strings exist in `en`, `vi` and `ja` + +## Capture-layer changes only + +Skip this section if the PR does not touch the Overlay, the injector, the +Vulkan layer, or the guard. Otherwise every box must be ticked — these are the +review questions from `docs/19_SAFETY_AND_ANTICHEAT.md` §Review checklist. + +- [ ] No hook reads anything beyond the arguments of the API it hooks (CLAUDE.md rule 4) +- [ ] Nothing here makes FrameLedger harder for anti-cheat to identify (rule 3) +- [ ] No new path can reach `Injector.Attach` without a passing guard result (rule 2) +- [ ] Every new hook is listed in `docs/17_HOOK_ENGINE.md` §Hook inventory with a stated purpose +- [ ] No hook body allocates, locks, logs, or throws (rule 5) +- [ ] There is a Tier-2 degradation path if the hook is unavailable +- [ ] Measured hook overhead is stated below (`docs/14_TESTING.md` §Hook overhead) + +**Measured overhead:** + +## Safety-string changes only + +- [ ] `Safety_*` resx keys have human-reviewed `ja` (never machine-drafted — `docs/09_I18N.md`) +- [ ] Wording was not softened in any locale + +## Notes for the reviewer + + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..4309d5b4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,74 @@ +# FrameLedger CI (docs/13_CI_CD.md). +# +# Repo-local rather than a caller stub, by necessity: the poli0981/.github +# reusable `desktop-csharp` template runs dotnet restore/build/test directly and +# exposes no input for a native pre-step, MSVC setup, or the Vulkan SDK. +# FrameLedger's build is mixed-toolchain and native-first, and docs/12_BUILD.md +# commits to CI running *the identical script* as local — a promise a +# pure-managed template cannot keep. +# +# So this workflow does exactly one thing of substance: ./build.ps1 check. +# Anything CI checks that local does not is a way for the two to disagree. + +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +# Permissions do not inherit into reusable workflows, and defaults are broader +# than this job needs either way (docs/13_CI_CD.md). +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + check: + runs-on: windows-latest + timeout-minutes: 40 + + steps: + - uses: actions/checkout@v4 + + - name: Set up .NET + uses: actions/setup-dotnet@v4 + with: + # Version comes from global.json. Pinning it twice is a way for the + # two pins to drift. + global-json-file: global.json + + - name: Set up MSVC (x64) + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Cache NuGet + uses: actions/cache@v4 + with: + path: ~/.nuget/packages + key: nuget-${{ runner.os }}-${{ hashFiles('**/Directory.Packages.props', 'global.json') }} + restore-keys: nuget-${{ runner.os }}- + + # TODO: cache the Vulkan SDK once FrameLedger.VkLayer has real content. + # It is a large download and the layer target currently intercepts + # nothing (blocked on docs/20_OPEN_QUESTIONS.md §S2). + + - name: Quality gate + shell: pwsh + run: ./build.ps1 check + env: + CI: 'true' + + - name: Upload coverage + if: always() + uses: actions/upload-artifact@v4 + with: + name: coverage + path: '**/TestResults/**/coverage.cobertura.xml' + if-no-files-found: warn + retention-days: 14 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000..d989159a --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,71 @@ +# CodeQL for C# AND C++ (docs/13_CI_CD.md). +# +# The native layer is where memory-safety bugs would live — a lock-free ring +# written from inside a host process we do not own. Scanning only the managed +# side would defeat the purpose. +# +# Repo-local for now. The ops repo has codeql-mixed.yml, but C++ needs manual +# build mode driven by the CMake preset, and that input surface has not been +# verified. Switch to a caller stub once it has. + +name: CodeQL + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: '27 4 * * 1' + +permissions: + contents: read + security-events: write + +jobs: + analyze: + runs-on: windows-latest + timeout-minutes: 60 + + strategy: + fail-fast: false + matrix: + include: + - language: csharp + build-mode: none + - language: cpp + build-mode: manual + + steps: + - uses: actions/checkout@v4 + + - name: Set up .NET + if: matrix.language == 'csharp' + uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: Set up MSVC (x64) + if: matrix.language == 'cpp' + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + + - name: Build native + if: matrix.language == 'cpp' + shell: pwsh + run: | + cmake --preset x64-release + cmake --build --preset x64-release + working-directory: src/native + + - name: Analyze + uses: github/codeql-action/analyze@v3 + with: + category: /language:${{ matrix.language }} diff --git a/.github/workflows/rules-publish.yml b/.github/workflows/rules-publish.yml new file mode 100644 index 00000000..49308888 --- /dev/null +++ b/.github/workflows/rules-publish.yml @@ -0,0 +1,52 @@ +# Gate changes to the detection + anti-cheat rules (docs/13_CI_CD.md). +# +# The raw file on `main` IS the distribution endpoint (docs/05_DETECTION.md), +# so there is nothing to publish — this workflow only gates correctness. That +# also means a bad merge ships to every user on their next rules check, which +# is why the anticheat block gets extra scrutiny here. + +name: Rules + +on: + push: + branches: [main] + paths: ['rules/detection-rules.json'] + pull_request: + paths: ['rules/detection-rules.json'] + +permissions: + contents: read + +jobs: + validate: + runs-on: windows-latest + timeout-minutes: 10 + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - name: Validate schema and anticheat block + shell: pwsh + run: ./tools/rules-validate.ps1 + + # Removing a blocklist entry is a safety change and requires the same + # review as a security fix. This surfaces removals so a reviewer has to + # look at them rather than scrolling past a large diff. + - name: Report anticheat removals + if: github.event_name == 'pull_request' + shell: pwsh + run: | + $base = git show "origin/${{ github.base_ref }}:rules/detection-rules.json" 2>$null + if (-not $base) { Write-Host 'No base version to compare.'; exit 0 } + $old = ($base | ConvertFrom-Json).anticheat + $new = (Get-Content rules/detection-rules.json -Raw | ConvertFrom-Json).anticheat + $oldFams = @($old.modules + $old.drivers | ForEach-Object { $_.family }) + $newFams = @($new.modules + $new.drivers | ForEach-Object { $_.family }) + $removed = $oldFams | Where-Object { $_ -notin $newFams } + if ($removed) { + Write-Host "::warning::Anti-cheat families removed: $($removed -join ', '). This is a SAFETY change — the PR body must justify each removal." + } else { + Write-Host 'No anti-cheat families removed.' + } diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..31816b27 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,39 @@ +# Changelog + +All notable changes to FrameLedger are documented here. + +Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +Versioning: [Semantic Versioning](https://semver.org/spec/v2.0.0.html) — `MAJOR` +bumps for a database schema or IPC protocol break (`docs/11_UPDATER.md`). + +`release.yml` reads the section for the tag being released and uses it as the +GitHub release body, so a missing section means an empty release note. + +## [Unreleased] + +### Added +- Design documents (`CLAUDE.md`, `docs/01`–`20`, `legal/`) and the repository + skeleton: solution, project stubs, CMake presets, `build.ps1` quality gate, + CI workflows, issue and PR templates, seed detection rules. +- `docs/20_OPEN_QUESTIONS.md` — audit findings that need an empirical answer + from the P0 spike or a design decision, grouped by what they block. +- `tools/license-check.ps1` and `tools/rules-validate.ps1`, both proven to fail + on a planted violation rather than only to pass on a clean tree. + +### Fixed +- Shared-memory layout was arithmetically impossible: the header was 88 bytes + while the control block was mapped to `0x0040`. In code `unhookRequested` + would have aliased `faultCount`, firing the safety stop on any hook fault. +- Frame-generation detection relied on `GetFrameStatistics().PresentCount` + exceeding the application's own present count, which cannot happen. Replaced + with FG feature evaluations counted at the source. +- `dispatchRaysCount` was `uint16` and saturated on every ray-traced title at + 1080p or above. +- README, Disclaimer and EULA promised the no-injection capture mode is "always + available" when it requires an elevated agent. + +### Changed +- Direct3D 9 is not a Tier-1 API in v1: the Overlay is x64-only and those + titles are almost entirely 32-bit. They are captured at Tier 2. + +[Unreleased]: https://github.com/poli0981/frameledger/commits/main diff --git a/CLAUDE.md b/CLAUDE.md index 8b1a7590..9db6cf56 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,7 +24,7 @@ A C++ DLL (`FrameLedger.Overlay.dll`) is injected into games the user explicitly | Concern | Choice | |---|---| -| Managed runtime | .NET 10 (LTS, pinned via `global.json`), C# 14, TFM `net10.0-windows10.0.19041.0` with `SupportedOSPlatformVersion=10.0.19045.0` (Win10 22H2 floor, NFR-8), x64 only — `docs/12_BUILD.md` | +| Managed runtime | .NET 10 (LTS, pinned via `global.json`), C# 14, TFM `net10.0-windows10.0.22621.0` with `SupportedOSPlatformVersion=10.0.19045.0` (Win10 22H2 floor, NFR-8), x64 only — `docs/12_BUILD.md` | | Native | **C++20, MSVC v143+, `/MT` static CRT, `/GS`, `/guard:cf`, no RTTI, no C++ exceptions in hook paths** | | Hooking | **MinHook** (BSD-2-Clause) for inline hooks; direct vtable-entry swap for COM interfaces | | Vulkan | **Implicit Vulkan layer** (`VK_LAYER_frameledger_overlay`), not hooking — `17_HOOK_ENGINE` §Vulkan | @@ -45,11 +45,13 @@ A C++ DLL (`FrameLedger.Overlay.dll`) is injected into games the user explicitly ## Solution layout ``` -FrameLedger.sln +FrameLedger.slnx # XML solution format (SDK default since .NET 10) +global.json # pins the SDK band — see 12_BUILD +build.ps1 # the quality gate; CI runs this identical script src/ native/ FrameLedger.Overlay/ # C++20 DLL injected into the game (hooks + ring writer + optional overlay) - FrameLedger.Injector/ # C++20 static lib + tiny exe: launch/attach injection, AC guard probe + FrameLedger.Injector/ # C++20 static lib: launch/attach injection, AC guard probe FrameLedger.VkLayer/ # C++20 Vulkan implicit layer DLL + manifest JSON FrameLedger.Shm/ # header-only: ring buffer + record layout, shared by native & C# (mirrored) FrameLedger.Domain/ # entities, metric calculators — zero dependencies @@ -61,8 +63,12 @@ src/ tests/ FrameLedger.Domain.Tests/ FrameLedger.Application.Tests/ FrameLedger.Infrastructure.Tests/ native/FrameLedger.Overlay.Tests/ # Catch2: ring buffer, record encode, fault policy -tools/ # fixture recorder, rules validator, shm inspector, hook harness -docs/ legal/ +tools/ # rules-validate, license-check, resx-audit (PowerShell) + # native tooling lives under src/native/tools: + # fl-layout-dump -> struct offsets for the C# mirror test + # hook-harness -> dummy D3D11/12/Vulkan/OpenGL app (P0) +rules/detection-rules.json # engine/platform/capability + anticheat blocklist +docs/ legal/ legal/licenses/ ``` Dependency direction unchanged: `App/Agent → Application → Domain`; `Infrastructure` implements `Application` ports; Domain references nothing. **The native layer is reachable only through `Infrastructure`** — no P/Invoke anywhere else. diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 00000000..14620e70 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,83 @@ + + + + + net10.0-windows10.0.22621.0 + 10.0.19045.0 + + + x64 + x64 + + latest + enable + enable + false + + true + latest-all + true + true + + true + true + true + + + en;vi;ja + + true + + + + + false + false + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 00000000..6bf5daed --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,98 @@ + + + + + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FrameLedger.slnx b/FrameLedger.slnx new file mode 100644 index 00000000..0fce6a2b --- /dev/null +++ b/FrameLedger.slnx @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 00000000..efe4ee1a --- /dev/null +++ b/build.ps1 @@ -0,0 +1,174 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + FrameLedger local quality gate. CI runs this identical script, so local and + CI can never disagree (docs/12_BUILD.md §Local quality gate). + +.DESCRIPTION + ./build.ps1 check the full nine-gate pre-push check + ./build.ps1 native native build only + ./build.ps1 managed managed build + tests only + ./build.ps1 format apply formatting instead of verifying it + + Gates that are not yet implemented SKIP LOUDLY. A gate that silently passes + because its tool does not exist is worse than no gate: it reads as "checked" + in CI output when nothing was checked. +#> +[CmdletBinding()] +param( + [Parameter(Position = 0)] + [ValidateSet('check', 'native', 'managed', 'format')] + [string]$Task = 'check', + + [ValidateSet('Debug', 'Release')] + [string]$Configuration = 'Release', + + # Native build needs MSVC. Skip it when only touching managed code. + [switch]$SkipNative +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$repo = $PSScriptRoot +$solution = Join-Path $repo 'FrameLedger.slnx' +$nativeDir = Join-Path $repo 'src/native' + +$script:Skipped = @() + +function Write-Step([string]$Name) { + Write-Host '' + Write-Host "=== $Name " -NoNewline -ForegroundColor Cyan + Write-Host ('=' * [Math]::Max(0, 60 - $Name.Length)) -ForegroundColor Cyan +} + +function Skip-Gate([string]$Name, [string]$Why) { + $script:Skipped += "$Name — $Why" + Write-Host "SKIPPED: $Name ($Why)" -ForegroundColor Yellow +} + +function Invoke-Checked([string]$What, [scriptblock]$Body) { + & $Body + if ($LASTEXITCODE -ne 0) { throw "$What failed (exit $LASTEXITCODE)" } +} + +# --- 1-3. Native ------------------------------------------------------------ +function Invoke-Native { + Write-Step 'Native build (C++ /W4 /WX)' + if ($SkipNative) { Skip-Gate 'native build' '-SkipNative'; return } + if (-not (Get-Command cmake -ErrorAction SilentlyContinue)) { + Skip-Gate 'native build' 'cmake not on PATH'; return + } + if (-not (Get-Command cl -ErrorAction SilentlyContinue)) { + # Do not fall back to another compiler: the Overlay's whole point is + # the MSVC build profile (/MT, /GS, /guard:cf, /Qspectre). + Skip-Gate 'native build' 'cl.exe not on PATH — run from a Developer prompt or use ilammy/msvc-dev-cmd' + return + } + + $preset = if ($Configuration -eq 'Debug') { 'x64-debug' } else { 'x64-release' } + Push-Location $nativeDir + try { + Invoke-Checked 'cmake configure' { cmake --preset $preset } + Invoke-Checked 'cmake build' { cmake --build --preset $preset } + + Write-Step 'Native tests' + Invoke-Checked 'ctest' { ctest --preset $preset } + } + finally { Pop-Location } + + Write-Step 'clang-format' + if (-not (Get-Command clang-format -ErrorAction SilentlyContinue)) { + Skip-Gate 'clang-format' 'clang-format not on PATH'; return + } + $sources = Get-ChildItem $nativeDir -Recurse -Include *.cpp, *.h | + Where-Object { $_.FullName -notmatch 'third_party|[\\/]build[\\/]' } + if ($sources) { + Invoke-Checked 'clang-format' { clang-format --dry-run -Werror @($sources.FullName) } + } +} + +# --- 4-6. Managed ----------------------------------------------------------- +function Invoke-Managed([bool]$FixFormat) { + Write-Step 'Managed restore + build (warnings as errors)' + Invoke-Checked 'dotnet build' { dotnet build $solution -c $Configuration } + + Write-Step 'dotnet format' + if ($FixFormat) { + Invoke-Checked 'dotnet format' { dotnet format $solution } + } + else { + Invoke-Checked 'dotnet format --verify-no-changes' { dotnet format $solution --verify-no-changes } + } + + Write-Step 'Tests' + Invoke-Checked 'dotnet test' { + dotnet test $solution -c $Configuration --no-build --collect:"XPlat Code Coverage" + } +} + +# --- 7-9. Project-specific gates ------------------------------------------- +function Invoke-ProjectGates { + # A malformed or empty anticheat blocklist is a SAFETY bug, not a lint + # failure (docs/13_CI_CD.md). + Write-Step 'rules-validate' + $rulesTool = Join-Path $repo 'tools/rules-validate.ps1' + if (Test-Path $rulesTool) { + Invoke-Checked 'rules-validate' { & $rulesTool } + } + else { + Skip-Gate 'rules-validate' 'tools/rules-validate.ps1 not implemented yet' + } + + Write-Step 'license-check' + $licenseTool = Join-Path $repo 'tools/license-check.ps1' + if (Test-Path $licenseTool) { + Invoke-Checked 'license-check' { & $licenseTool } + } + else { + Skip-Gate 'license-check' 'tools/license-check.ps1 not implemented yet' + } + + Write-Step 'resx-audit' + $resxTool = Join-Path $repo 'tools/resx-audit' + if (Test-Path $resxTool) { + Invoke-Checked 'resx-audit' { & $resxTool } + } + else { + Skip-Gate 'resx-audit' 'tools/resx-audit not implemented yet (no .resx files exist)' + } + + Write-Step 'placeholder guard' + # {{RELEASE_DATE}} is substituted at release time and is the only token + # allowed to survive. Anything else in a document FR-11 displays for + # acceptance is a defect (docs/12_BUILD.md §Release-time token substitution). + $targets = @(Join-Path $repo 'README.md') + (Get-ChildItem (Join-Path $repo 'legal') -Filter *.md).FullName + $stray = Select-String -Path $targets -Pattern '\{\{(?!RELEASE_DATE\}\})' -AllMatches + if ($stray) { + $stray | ForEach-Object { Write-Host " $($_.Path):$($_.LineNumber): $($_.Line.Trim())" -ForegroundColor Red } + throw 'Unsubstituted placeholder tokens found in shipped documents' + } + Write-Host 'OK — only {{RELEASE_DATE}} remains' -ForegroundColor Green +} + +# --- Entry point ------------------------------------------------------------ +$sw = [Diagnostics.Stopwatch]::StartNew() +switch ($Task) { + 'native' { Invoke-Native } + 'managed' { Invoke-Managed $false } + 'format' { Invoke-Managed $true } + 'check' { + Invoke-Native # native first: the managed build copies its output + Invoke-Managed $false + Invoke-ProjectGates + } +} + +Write-Host '' +if ($script:Skipped.Count -gt 0) { + Write-Host "PASSED WITH $($script:Skipped.Count) SKIPPED GATE(S) in $([int]$sw.Elapsed.TotalSeconds)s" -ForegroundColor Yellow + $script:Skipped | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow } + Write-Host 'These gates did not run. Do not read this as a clean check.' -ForegroundColor Yellow +} +else { + Write-Host "ALL GATES PASSED in $([int]$sw.Elapsed.TotalSeconds)s" -ForegroundColor Green +} diff --git a/docs/12_BUILD.md b/docs/12_BUILD.md index f3a53cbc..db9c4f0f 100644 --- a/docs/12_BUILD.md +++ b/docs/12_BUILD.md @@ -40,7 +40,7 @@ Compiler/linker flags (enforced in CMake, not per-target ad hoc): `/std:c++20 /M - **`global.json` pins the SDK band** (`10.0.x`, `rollForward: latestFeature`). Without it `dotnet build` picks the newest installed SDK — on a machine with a .NET 11 preview installed that silently changes analyzer behaviour under `TreatWarningsAsErrors`, and makes local and CI disagree for reasons nobody can see in a diff. - `Directory.Build.props`: - - **`TargetFramework` = `net10.0-windows10.0.19041.0`** and **`SupportedOSPlatformVersion` = `10.0.19045.0`**. These are two different knobs and must not be conflated. The TFM platform version selects the Windows API projections available; the supported version is the floor CA1416 enforces. NFR-8 requires Windows 10 **22H2**, which is build **19045** — leaving it to default to the TFM's 19041 would silently accept installs three releases below the stated floor. A bare `net10.0-windows` is wrong for a different reason: it resolves to `net10.0-windows7.0`, and CA1416 would then error on Mica, `MiniDumpWriteDump` and `QueryVideoMemoryInfo` — every Windows-10-era API this app is built on. + - **`TargetFramework` = `net10.0-windows10.0.22621.0`** and **`SupportedOSPlatformVersion` = `10.0.19045.0`**. These are two different knobs and must not be conflated: the TFM platform version selects which Windows API projections are available to compile against, while the supported version is the floor CA1416 enforces. NFR-8 requires Windows 10 **22H2** = build **19045**; letting the supported version default to the TFM's would silently accept installs below the stated floor. Two constraints pin the target to 22621 rather than something closer to the floor: the SDK rejects `SupportedOSPlatformVersion` above `TargetPlatformVersion` (NETSDK1135), and 19045 is not a targeting-pack version in any case — the packs are cut at 19041, 20348, 22000, 22621, 26100. The Windows 11 SDK ≥ 10.0.22621 is already a prerequisite above, so this costs nothing. A bare `net10.0-windows` is wrong for a different reason: it resolves to `net10.0-windows7.0`, and CA1416 would then error on Mica, `MiniDumpWriteDump` and `QueryVideoMemoryInfo` — every Windows-10-era API this app is built on. - `Platforms`/`PlatformTarget` = `x64` and `RuntimeIdentifier` = `win-x64`. "x64 only" is asserted in CLAUDE.md and NFR-8 but was previously enforced nowhere except an ad-hoc `-r win-x64` on the publish command. - Nullable enable, ImplicitUsings enable, `TreatWarningsAsErrors=true`, `AnalysisLevel=latest-all`, deterministic, `ContinuousIntegrationBuild` on CI. - `Directory.Packages.props`: central package management, all versions pinned (including `WPF-UI` = 4.3.0 exactly — `16_WPFUI_SYNTAX` §Version hygiene). @@ -96,8 +96,21 @@ document the app displays for acceptance (FR-11) is a defect, not a template. 4. `dotnet restore` + build (warnings as errors) 5. `dotnet format --verify-no-changes` 6. `dotnet test` (incl. the struct-mirror check) -7. `tools/rules-validate` (schema + `anticheat` block sanity — a malformed blocklist is a safety bug) -8. `tools/license-check` — asserts every vendored third-party has a licence copy in `legal/licenses/`, and that no Intel IGCL / AMD ADLX material has appeared in the tree +7. `tools/rules-validate.ps1` (schema + `anticheat` block sanity — a malformed or empty blocklist is a safety bug) +8. `tools/license-check.ps1` — asserts every vendored third-party has a licence copy in `legal/licenses/`, and that no Intel IGCL / AMD ADLX material has appeared in the tree 9. `tools/resx-audit` +10. Placeholder guard — fails if any `{{` token other than `{{RELEASE_DATE}}` survives in `README.md` or `legal/*.md` CI runs the identical script (`13_CI_CD`), so local and CI can never disagree. + +**Gates skip loudly.** A gate whose tool is not installed (no `cl.exe`) or not +yet written prints `SKIPPED`, is listed again in the summary, and the run ends +with `PASSED WITH N SKIPPED GATE(S)` rather than a clean `ALL GATES PASSED`. +A gate that silently passes because it did nothing is worse than no gate: it +reads as "checked" in CI output when nothing was checked. + +**Gates are proven red-green, not just green.** `license-check` and +`rules-validate` were each verified to fail on a planted violation — an IGCL +header dropped into the tree, and an emptied `anticheat.modules` list — before +being wired in. A safety gate that has only ever been observed passing has not +been tested. diff --git a/global.json b/global.json new file mode 100644 index 00000000..0dd82482 --- /dev/null +++ b/global.json @@ -0,0 +1,8 @@ +{ + "$comment": "Pins the SDK band. Without this, dotnet picks the newest installed SDK — on a machine with a .NET 11 preview present that silently changes analyzer behaviour under TreatWarningsAsErrors and makes local and CI disagree for reasons invisible in a diff. See docs/12_BUILD.md.", + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + } +} diff --git a/legal/licenses/README.md b/legal/licenses/README.md new file mode 100644 index 00000000..cf895bd1 --- /dev/null +++ b/legal/licenses/README.md @@ -0,0 +1,30 @@ +# Third-party licence texts + +Full licence texts for everything FrameLedger bundles or links. Populated at P4 +by a licence-gathering script; `tools/license-check.ps1` fails the build if a +vendored component is present here without its licence copy. + +Required before the first release +(`legal/THIRD_PARTY_NOTICES.md` §Attribution requirements checklist): + +| File | Component | +|---|---| +| `minhook-BSD-2-Clause.txt` | MinHook — vendored and built from source | +| `nvapi-MIT.txt` | NVIDIA NVAPI SDK — headers + import library vendored | +| `wpfui-MIT.txt` | WPF UI (lepoco) — MIT requires the notice to ship | +| `presentmon-MIT.txt` | Intel PresentMon — ships beside the bundled binary | +| `librehardwaremonitor-MPL-2.0.txt` | LibreHardwareMonitorLib, consumed unmodified | +| `apache-2.0.txt` | Serilog, Dapper, the analyzers, Vulkan headers | +| `mit.txt` | Shared text for the MIT-licensed NuGet packages | + +Two of these are release-blocking questions, not paperwork +(`docs/20_OPEN_QUESTIONS.md` §M3, §M4): + +- **NVAPI** — confirm the exact vendored artifact is MIT, *including* + `nvapi64.lib`. The import library may not be covered by the same grant as the + headers. If it is not, Reflex / PC latency has no alternative source. +- **LibreHardwareMonitor** — confirm no depended-upon file carries MPL-2.0 + **Exhibit B** ("Incompatible With Secondary Licenses"), which would remove the + GPL-compatibility route and leave no sensor layer for any vendor. + +Answer both before writing NVAPI or LHM code, not after. diff --git a/rules/detection-rules.json b/rules/detection-rules.json new file mode 100644 index 00000000..2966e39a --- /dev/null +++ b/rules/detection-rules.json @@ -0,0 +1,137 @@ +{ + "$comment": [ + "Rules are DATA, not code (docs/05_DETECTION.md). This file ships with the", + "app and is updatable from the repository independently of releases.", + "", + "The `anticheat` block is what feeds the hard gate in", + "docs/19_SAFETY_AND_ANTICHEAT.md. Updates to it are treated as security", + "updates: applied on the next check regardless of the user's auto-update", + "preference for other rules. Removing an entry is a safety change and needs", + "the same review as a security fix (docs/13_CI_CD.md §rules-publish).", + "", + "SEED, NOT COMPLETE. docs/20_OPEN_QUESTIONS.md §S5 records that the schema", + "cannot yet express everything docs/19_SAFETY §Blocklist seed describes —", + "service names, directory presence and the unknown-but-suspicious heuristic", + "are represented below but the validator does not yet enforce their shape." + ], + "schemaVersion": 2, + "rulesVersion": "2026.08.1", + + "engines": [ + { + "id": "unity", + "name": "Unity", + "signals": { "any": [ + { "type": "sibling_glob", "value": "UnityPlayer.dll" }, + { "type": "dir_exists", "value": "${ExeName}_Data" } + ] }, + "version": { "type": "pe_file_version", "from": "UnityPlayer.dll" } + }, + { + "id": "unreal", + "name": "Unreal Engine", + "signals": { "any": [ + { "type": "sibling_glob", "value": "*-Win64-Shipping.exe" }, + { "type": "sibling_glob", "value": "*/Content/Paks/*.pak" } + ] }, + "version": { "type": "pe_product_version_regex", "value": "\\+\\+UE(4|5)\\+Release-(\\d+\\.\\d+)" } + }, + { + "id": "godot", + "name": "Godot", + "signals": { "any": [ + { "type": "sibling_glob", "value": "*.pck" }, + { "type": "strings_contains", "value": "Godot Engine v" } + ] }, + "version": { "type": "strings_regex", "value": "Godot Engine v(\\d+\\.\\d+[\\.\\d]*)" } + }, + { + "id": "gamemaker", + "name": "GameMaker", + "signals": { "all": [ { "type": "sibling_glob", "value": "data.win" } ] }, + "version": null + }, + { + "id": "renpy", + "name": "Ren'Py", + "signals": { "any": [ + { "type": "dir_exists", "value": "renpy" }, + { "type": "sibling_glob", "value": "*.rpa" } + ] }, + "version": null + } + ], + + "platforms": [ + { + "id": "steam", + "name": "Steam", + "signals": { "any": [ + { "type": "sibling_glob", "value": "steam_api64.dll" }, + { "type": "sibling_glob", "value": "steam_api.dll" }, + { "type": "path_contains", "value": "steamapps\\common" } + ] } + }, + { + "id": "gog", + "name": "GOG", + "signals": { "any": [ + { "type": "sibling_glob", "value": "goggame-*.info" }, + { "type": "sibling_glob", "value": "Galaxy64.dll" } + ] } + }, + { + "id": "epic", + "name": "Epic Games", + "signals": { "any": [ + { "type": "sibling_glob", "value": "EOSSDK-Win64-Shipping.dll" } + ] } + }, + { + "id": "itch", + "name": "itch.io", + "signals": { "any": [ + { "type": "sibling_glob", "value": ".itch/receipt.json.gz" } + ] } + } + ], + + "capabilities": [ + { "id": "dlss", "name": "DLSS", "signals": [ "nvngx_dlss.dll" ] }, + { "id": "dlss_g", "name": "DLSS Frame Gen", "signals": [ "nvngx_dlssg.dll", "sl.dlss_g.dll" ] }, + { "id": "dlss_rr", "name": "Ray Reconstruction","signals": [ "nvngx_dlssd.dll" ] }, + { "id": "streamline", "name": "Streamline", "signals": [ "sl.interposer.dll", "sl.reflex.dll" ] }, + { "id": "fsr", "name": "FSR", "signals": [ "ffx_fsr2_*.dll", "ffx_frameinterpolation_*.dll", "amd_fidelityfx_*.dll", "ffx_api*.dll" ] }, + { "id": "xess", "name": "XeSS", "signals": [ "libxess.dll" ] }, + { "id": "xefg", "name": "XeSS Frame Gen", "signals": [ "libxess_fg.dll" ] } + ], + + "anticheat": { + "$comment": "MUST be non-empty. An empty block is a fail-closed test fixture, never a ship state.", + "modules": [ + { "family": "Easy Anti-Cheat", "match": "prefix", "values": [ "EasyAntiCheat", "EasyAntiCheat_EOS" ] }, + { "family": "BattlEye", "match": "prefix", "values": [ "BEClient", "BEService" ] }, + { "family": "Denuvo Anti-Cheat","match": "prefix", "values": [ "denuvo" ] }, + { "family": "nProtect GameGuard","match": "prefix", "values": [ "GameGuard", "npgg", "GameMon" ] }, + { "family": "Xigncode3", "match": "prefix", "values": [ "xhunter" ] }, + { "family": "PunkBuster", "match": "prefix", "values": [ "PnkBstr", "pbcl", "pbsv" ] }, + { "family": "FACEIT", "match": "prefix", "values": [ "faceit" ] }, + { "family": "ESEA", "match": "prefix", "values": [ "esea" ] } + ], + "drivers": [ + { "family": "Riot Vanguard", "match": "exact", "values": [ "vgk.sys" ], "scope": "machine" }, + { "family": "mihoyo protect", "match": "prefix", "values": [ "mhyprot" ], "scope": "machine" } + ], + "directories": [ + { "family": "Easy Anti-Cheat", "values": [ "EasyAntiCheat" ] }, + { "family": "BattlEye", "values": [ "BattlEye" ] } + ], + "services": [ + { "family": "Easy Anti-Cheat", "values": [ "EasyAntiCheat", "EasyAntiCheat_EOS" ] }, + { "family": "Riot Vanguard", "values": [ "vgc" ] } + ], + "suspiciousNameFragments": [ "anticheat", "antitamper", "gameguard" ], + "blockedExecutables": [], + "blockedStoreIds": [] + } +} diff --git a/src/FrameLedger.Agent/FrameLedger.Agent.csproj b/src/FrameLedger.Agent/FrameLedger.Agent.csproj new file mode 100644 index 00000000..311d2ac4 --- /dev/null +++ b/src/FrameLedger.Agent/FrameLedger.Agent.csproj @@ -0,0 +1,31 @@ + + + + + + Exe + win-x64 + FrameLedger.Agent + FrameLedger.Agent + + + + + + + + + + + + + + + + + diff --git a/src/FrameLedger.Agent/Program.cs b/src/FrameLedger.Agent/Program.cs new file mode 100644 index 00000000..c49d8fcd --- /dev/null +++ b/src/FrameLedger.Agent/Program.cs @@ -0,0 +1,25 @@ +// FrameLedger.Agent — capture orchestrator. +// +// Scaffold only. The real entry point builds a Generic Host containing the +// process watcher, the anti-cheat guard, the injector control, the shm drain, +// the telemetry poller and the session recorder (docs/04_CAPTURE.md). +// +// Ordering constraint from CLAUDE.md rule 2 and docs/15_ROADMAP.md: the guard +// and its full test suite ship BEFORE the first real injection, not after. +// Nothing here may open a process with CREATE_THREAD | VM_WRITE until the +// safety-guard tests in docs/14_TESTING.md are green. +// +// CLI flags this must eventually accept (docs/12_BUILD.md §Debugging): +// --serve --console --diag --install-task --uninstall-task +// --register-vklayer --unregister-vklayer + +namespace FrameLedger.Agent; + +internal static class Program +{ + private static int Main(string[] args) + { + ArgumentNullException.ThrowIfNull(args); + return 0; + } +} diff --git a/src/FrameLedger.App/App.xaml b/src/FrameLedger.App/App.xaml new file mode 100644 index 00000000..6b8fe3b1 --- /dev/null +++ b/src/FrameLedger.App/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/src/FrameLedger.App/App.xaml.cs b/src/FrameLedger.App/App.xaml.cs new file mode 100644 index 00000000..4aecf947 --- /dev/null +++ b/src/FrameLedger.App/App.xaml.cs @@ -0,0 +1,23 @@ +using System.Windows; + +namespace FrameLedger.App; + +/// +/// Application entry point. +/// +/// +/// Scaffold only. The real bootstrap owns everything through a .NET Generic +/// Host and must follow docs/16_WPFUI_SYNTAX.md exactly: +/// +/// merged dictionaries in order ThemesDictionary → +/// ControlsDictionary → our styles — wrong order silently yields +/// default-looking controls; +/// SystemThemeWatcher.Watch from the window's Loaded +/// handler, never the constructor (it needs an HWND); +/// navigation only via INavigationService, with every page +/// registered in DI. +/// +/// +public partial class App : Application +{ +} diff --git a/src/FrameLedger.App/AssemblyInfo.cs b/src/FrameLedger.App/AssemblyInfo.cs new file mode 100644 index 00000000..b0ec8275 --- /dev/null +++ b/src/FrameLedger.App/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/src/FrameLedger.App/FrameLedger.App.csproj b/src/FrameLedger.App/FrameLedger.App.csproj new file mode 100644 index 00000000..e0eb2186 --- /dev/null +++ b/src/FrameLedger.App/FrameLedger.App.csproj @@ -0,0 +1,39 @@ + + + + + + WinExe + true + win-x64 + FrameLedger + FrameLedger.App + app.manifest + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/FrameLedger.App/MainWindow.xaml b/src/FrameLedger.App/MainWindow.xaml new file mode 100644 index 00000000..adc24ac6 --- /dev/null +++ b/src/FrameLedger.App/MainWindow.xaml @@ -0,0 +1,12 @@ + + + + + diff --git a/src/FrameLedger.App/MainWindow.xaml.cs b/src/FrameLedger.App/MainWindow.xaml.cs new file mode 100644 index 00000000..6dbc0301 --- /dev/null +++ b/src/FrameLedger.App/MainWindow.xaml.cs @@ -0,0 +1,21 @@ +using System.Windows; + +namespace FrameLedger.App; + +/// +/// Shell window. +/// +/// +/// Scaffold only. The real shell is a ui:FluentWindow with a custom +/// ui:TitleBar, a classic Menu row **outside** the title bar's +/// drag region, and a left ui:NavigationView +/// (docs/08_UI.md, docs/16_WPFUI_SYNTAX.md §Main window skeleton). +/// +public partial class MainWindow : Window +{ + /// Initializes the shell window. + public MainWindow() + { + InitializeComponent(); + } +} diff --git a/src/FrameLedger.App/app.manifest b/src/FrameLedger.App/app.manifest new file mode 100644 index 00000000..d86bf660 --- /dev/null +++ b/src/FrameLedger.App/app.manifest @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + PerMonitorV2 + true/pm + true + + + + diff --git a/src/FrameLedger.Application/FrameLedger.Application.csproj b/src/FrameLedger.Application/FrameLedger.Application.csproj new file mode 100644 index 00000000..651a4168 --- /dev/null +++ b/src/FrameLedger.Application/FrameLedger.Application.csproj @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/src/FrameLedger.Domain/FrameLedger.Domain.csproj b/src/FrameLedger.Domain/FrameLedger.Domain.csproj new file mode 100644 index 00000000..c8374184 --- /dev/null +++ b/src/FrameLedger.Domain/FrameLedger.Domain.csproj @@ -0,0 +1,14 @@ + + + + + diff --git a/src/FrameLedger.Infrastructure/FrameLedger.Infrastructure.csproj b/src/FrameLedger.Infrastructure/FrameLedger.Infrastructure.csproj new file mode 100644 index 00000000..31b382a8 --- /dev/null +++ b/src/FrameLedger.Infrastructure/FrameLedger.Infrastructure.csproj @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/src/FrameLedger.Shared/FrameLedger.Shared.csproj b/src/FrameLedger.Shared/FrameLedger.Shared.csproj new file mode 100644 index 00000000..03cf2909 --- /dev/null +++ b/src/FrameLedger.Shared/FrameLedger.Shared.csproj @@ -0,0 +1,16 @@ + + + + + diff --git a/src/native/CMakeLists.txt b/src/native/CMakeLists.txt new file mode 100644 index 00000000..ddf7ddbb --- /dev/null +++ b/src/native/CMakeLists.txt @@ -0,0 +1,69 @@ +# FrameLedger native layer (docs/12_BUILD.md, docs/17_HOOK_ENGINE.md). +# +# Scaffold. Targets are declared with their build profiles so the flags are +# established before any hook code exists — the flags are the part that is +# hard to retrofit, and two of them are open questions (see below). + +cmake_minimum_required(VERSION 3.28) +project(FrameLedgerNative LANGUAGES CXX) + +if(NOT WIN32) + message(FATAL_ERROR "FrameLedger's native layer is Windows-only.") +endif() + +if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) + # An x64 DLL cannot be injected into a 32-bit process. This is why D3D9 is + # not a Tier-1 API in v1 (docs/20_OPEN_QUESTIONS.md §Scope). If a 32-bit + # Overlay is ever added, it gets its own preset, not a relaxed check here. + message(FATAL_ERROR "x64 only. Configure with the x64-debug or x64-release preset.") +endif() + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Static CRT everywhere: never drag a VC runtime dependency into a host process +# we do not control (docs/17_HOOK_ENGINE.md §Build profile). +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + +add_library(fl_native_flags INTERFACE) +target_compile_options(fl_native_flags INTERFACE + /W4 /WX + /GS /guard:cf /Qspectre + /GR- # no RTTI + /permissive- + $<$:/O2> +) +target_link_options(fl_native_flags INTERFACE + /DYNAMICBASE /NXCOMPAT /HIGHENTROPYVA +) + +# --------------------------------------------------------------------------- +# Two flags on the Overlay are unresolved and MUST be settled in P0 before hook +# code is written. Both are recorded in docs/20_OPEN_QUESTIONS.md: +# +# H1 /guard:cf — an indirect call to a MinHook trampoline is not a +# registered CFG call target, so in a CFG-enabled host it can +# __fastfail, i.e. take the game down. Directly contradicts NFR-3. +# +# H3 -D_HAS_EXCEPTIONS=0 — not a configuration Microsoft's STL supports, +# and is load-bearing here because the ring writer is built on +# std::atomic_ref. +# +# They are deliberately NOT applied to the Overlay target yet. Applying them +# now would mean discovering the problem as a crash in a real game rather than +# as a decision. Add them once P0 answers the questions. +# --------------------------------------------------------------------------- + +add_subdirectory(FrameLedger.Shm) +add_subdirectory(FrameLedger.Overlay) +add_subdirectory(FrameLedger.Injector) +add_subdirectory(FrameLedger.VkLayer) + +if(FL_BUILD_TESTS) + add_subdirectory(tests) +endif() + +if(FL_BUILD_TOOLS) + add_subdirectory(tools) +endif() diff --git a/src/native/CMakePresets.json b/src/native/CMakePresets.json new file mode 100644 index 00000000..e99ab186 --- /dev/null +++ b/src/native/CMakePresets.json @@ -0,0 +1,41 @@ +{ + "version": 6, + "cmakeMinimumRequired": { "major": 3, "minor": 28, "patch": 0 }, + "configurePresets": [ + { + "name": "x64-base", + "hidden": true, + "generator": "Ninja", + "binaryDir": "${sourceDir}/../../build/native/${presetName}", + "architecture": { "value": "x64", "strategy": "external" }, + "cacheVariables": { + "CMAKE_CXX_COMPILER": "cl.exe", + "FL_BUILD_TESTS": "ON", + "FL_BUILD_TOOLS": "ON" + } + }, + { + "name": "x64-debug", + "inherits": "x64-base", + "displayName": "x64 Debug", + "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } + }, + { + "name": "x64-release", + "inherits": "x64-base", + "displayName": "x64 Release", + "cacheVariables": { "CMAKE_BUILD_TYPE": "RelWithDebInfo" } + } + ], + "buildPresets": [ + { "name": "x64-debug", "configurePreset": "x64-debug" }, + { "name": "x64-release", "configurePreset": "x64-release" } + ], + "testPresets": [ + { + "name": "x64-release", + "configurePreset": "x64-release", + "output": { "outputOnFailure": true } + } + ] +} diff --git a/src/native/FrameLedger.Injector/CMakeLists.txt b/src/native/FrameLedger.Injector/CMakeLists.txt new file mode 100644 index 00000000..8e31c318 --- /dev/null +++ b/src/native/FrameLedger.Injector/CMakeLists.txt @@ -0,0 +1,12 @@ +# Launch/attach injection and the anti-cheat guard probe. +# +# The guard is a hard gate: no code path here may open a process with +# CREATE_THREAD|VM_WRITE without a passing AntiCheatGuard result +# (CLAUDE.md rule 2, docs/19_SAFETY_AND_ANTICHEAT.md). +add_library(FrameLedger.Injector STATIC src/injector.cpp) +target_link_libraries(FrameLedger.Injector PUBLIC FrameLedger.Shm fl_native_flags) + +# NOTE: docs/20_OPEN_QUESTIONS.md §S9 asks whether the thin CLI should ship to +# users at all. A standalone LoadLibraryW injector outside the managed guard is +# both a bypass and a bad look for a project whose position is "we refuse where +# we are not welcome". No executable target until that is decided. diff --git a/src/native/FrameLedger.Injector/src/injector.cpp b/src/native/FrameLedger.Injector/src/injector.cpp new file mode 100644 index 00000000..105d0caa --- /dev/null +++ b/src/native/FrameLedger.Injector/src/injector.cpp @@ -0,0 +1,27 @@ +// FrameLedger.Injector — launch/attach injection and the anti-cheat guard probe. +// +// Scaffold. Nothing in this file may open a process with +// CREATE_THREAD | VM_OPERATION | VM_WRITE until the guard and its full test +// suite exist (CLAUDE.md rule 2; docs/14_TESTING.md §Safety-guard tests; +// docs/15_ROADMAP.md "it ships before the first real injection, not after"). +// +// Injection uses documented LoadLibraryW. No manual mapping, no PE header +// erasure, no PEB unlinking, no thread hiding — ever. A performance tool must +// be visible to anti-cheat, not hidden from it (docs/19_SAFETY §What we will +// never build). +// +// Open safety question blocking this target: docs/20_OPEN_QUESTIONS.md §S1 — +// the guard's module scan is a no-op against a CREATE_SUSPENDED process, +// because a suspended process has loaded no modules yet, and launch mode is +// the preferred path. + +#include + +namespace fl::injector { + +// Placeholder so the target links. Real API arrives in P1, behind the guard. +unsigned int LayoutVersion() noexcept { + return FL_SHM_LAYOUT_VERSION; +} + +} // namespace fl::injector diff --git a/src/native/FrameLedger.Overlay/CMakeLists.txt b/src/native/FrameLedger.Overlay/CMakeLists.txt new file mode 100644 index 00000000..14ac3aaf --- /dev/null +++ b/src/native/FrameLedger.Overlay/CMakeLists.txt @@ -0,0 +1,9 @@ +# The injected DLL. Install hooks, write 64-byte records into the ring, stay +# invisible in the frame budget, never take the game down (docs/17_HOOK_ENGINE.md). +add_library(FrameLedger.Overlay SHARED src/dllmain.cpp) +target_link_libraries(FrameLedger.Overlay PRIVATE FrameLedger.Shm fl_native_flags) +set_target_properties(FrameLedger.Overlay PROPERTIES OUTPUT_NAME "FrameLedger.Overlay") + +# VERSIONINFO is mandatory and CI fails the build without it: being plainly +# identifiable to anti-cheat is a requirement, not a nicety (docs/19_SAFETY). +# TODO(P1): add version.rc once the target has real content. diff --git a/src/native/FrameLedger.Overlay/src/dllmain.cpp b/src/native/FrameLedger.Overlay/src/dllmain.cpp new file mode 100644 index 00000000..408b24af --- /dev/null +++ b/src/native/FrameLedger.Overlay/src/dllmain.cpp @@ -0,0 +1,30 @@ +// FrameLedger.Overlay — the injected DLL. +// +// Scaffold. docs/17_HOOK_ENGINE.md is the specification; the constraints that +// shape every line written here: +// +// - DllMain(DLL_PROCESS_ATTACH) does ONLY DisableThreadLibraryCalls and +// CreateThread -> InitThread. Loader-lock rules. All real work (dummy +// device creation, MinHook init, hook installation, shm creation) happens +// on the init thread. +// - Every hook body is SEH-guarded, allocation-free, lock-free, and logs +// nothing. Three faults => self-disable and go dormant. +// - Never __try around the call to the original function — only around our +// own code, so we never mask a game bug as ours or vice versa. +// - Read nothing but the arguments of APIs we hooked (CLAUDE.md rule 4). +// +// Two build-profile questions block real hook code and are recorded in +// docs/20_OPEN_QUESTIONS.md: /guard:cf vs MinHook trampolines (H1), and +// -D_HAS_EXCEPTIONS=0 vs (H3). + +#include + +// Exports keep their real names. Being identifiable to anti-cheat is a +// requirement, not an accident (docs/19_SAFETY_AND_ANTICHEAT.md). +extern "C" { + +__declspec(dllexport) unsigned int FlGetLayoutVersion() { + return FL_SHM_LAYOUT_VERSION; +} + +} // extern "C" diff --git a/src/native/FrameLedger.Shm/CMakeLists.txt b/src/native/FrameLedger.Shm/CMakeLists.txt new file mode 100644 index 00000000..f9d4d9a4 --- /dev/null +++ b/src/native/FrameLedger.Shm/CMakeLists.txt @@ -0,0 +1,5 @@ +# Header-only: the shared-memory contract between the Overlay (inside the game) +# and the Agent (outside it). Exactly one definition, no link dependency. +add_library(FrameLedger.Shm INTERFACE) +target_include_directories(FrameLedger.Shm INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) +target_compile_features(FrameLedger.Shm INTERFACE cxx_std_20) diff --git a/src/native/FrameLedger.Shm/include/fl_shm.h b/src/native/FrameLedger.Shm/include/fl_shm.h new file mode 100644 index 00000000..2eda8153 --- /dev/null +++ b/src/native/FrameLedger.Shm/include/fl_shm.h @@ -0,0 +1,246 @@ +// FrameLedger shared-memory layout. +// +// NORMATIVE. This header and docs/07_IPC.md must agree; the static_asserts +// below are what enforce it. Mirrored in C# by FrameLedger.Shared, and a test +// in FrameLedger.Infrastructure.Tests compares both sides against the offsets +// emitted by tools/fl-layout-dump (CLAUDE.md §Struct mirroring). +// +// Header-only by design: the Overlay writes these structs from inside a game +// process and the Agent reads them from outside, so there must be exactly one +// definition and no link-time dependency between the two. +// +// Layout (docs/07_IPC.md §A + B): +// +// [0x0000] FlShmHandshake 64 B write-once by the Overlay at init +// [0x0040] FlWriterState 64 B Overlay-written (writeIndex every present) +// [0x0080] FlControlBlock 64 B Agent-written +// [0x00C0] FlFrameRecord[capacity] +// +// The three header regions are separate cache lines on purpose. The Overlay +// writes region 2 every frame while the Agent writes region 3 every second; +// sharing a line would put a cross-process cache-line bounce on the hot path. +// +// A previous revision of the design declared a single 88-byte header while +// mapping the control block to 0x0040. In code, unhookRequested would have +// aliased faultCount — the safety stop would fire on any hook fault, and the +// Agent's heartbeat would clobber the fault counter. Hence the asserts. + +#ifndef FRAMELEDGER_FL_SHM_H +#define FRAMELEDGER_FL_SHM_H + +#include +#include + +// Bump whenever ANY struct below changes. The Agent refuses to attach on +// mismatch and tells the user to restart the game — the DLL lives inside a +// running process, so the two sides cannot be assumed to update in lockstep. +#define FL_SHM_LAYOUT_VERSION 2u + +#define FL_SHM_HANDSHAKE_OFFSET 0x00u +#define FL_SHM_WRITER_OFFSET 0x40u +#define FL_SHM_CONTROL_OFFSET 0x80u +#define FL_SHM_RING_OFFSET 0xC0u + +#define FL_SHM_DEFAULT_CAPACITY 8192u // 8192 * 64 B = 512 KiB, ~16 s at 500 fps + +namespace fl { + +// status values published in FlWriterState::status +enum FlStatus : uint32_t { + FL_STATUS_INIT = 0, + FL_STATUS_READY = 1, + FL_STATUS_SELF_DISABLED = 2, // 3 hook faults; see 17_HOOK_ENGINE §Fault policy + FL_STATUS_UNHOOKED = 3, +}; + +// bits in FlWriterState::apiMask and FlFrameRecord::api +enum FlApi : uint8_t { + FL_API_UNKNOWN = 0, + FL_API_D3D11 = 1, + FL_API_D3D12 = 2, + FL_API_VULKAN = 3, + FL_API_OPENGL = 4, + // No D3D9: those titles are almost entirely 32-bit and the Overlay is + // x64-only, so they are Tier 2 in v1 (docs/20_OPEN_QUESTIONS.md §Scope). +}; + +enum FlUpscaler : uint8_t { + FL_UPSCALER_NONE = 0, + FL_UPSCALER_DLSS = 1, + FL_UPSCALER_DLSS_RR = 2, + FL_UPSCALER_FSR2 = 3, + FL_UPSCALER_FSR3 = 4, + FL_UPSCALER_FSR4 = 5, + FL_UPSCALER_XESS = 6, + FL_UPSCALER_NIS = 7, + FL_UPSCALER_UNKNOWN = 0xFF, +}; + +enum FlFgMode : uint8_t { + FL_FG_NONE = 0, + FL_FG_DLSS_G = 1, + FL_FG_FSR_FG = 2, + FL_FG_XEFG = 3, + FL_FG_UNKNOWN = 0xFF, + // No AFMF: driver-side frame generation happens after present and is + // invisible to an in-process hook (docs/03_METRICS.md §Frame Generation). +}; + +// bits in FlFrameRecord::rtFlags +enum FlRtFlags : uint8_t { + FL_RT_AS_BUILD = 1u << 0, // catches inline RayQuery, which DispatchRays misses + FL_RT_DISPATCH_RAYS = 1u << 1, + FL_RT_PSO_ALIVE = 1u << 2, +}; + +// --------------------------------------------------------------------------- +// Region 1 — write-once at init by the Overlay. +// --------------------------------------------------------------------------- +struct alignas(64) FlShmHandshake { + uint32_t layoutVersion; // @0 must equal FL_SHM_LAYOUT_VERSION on both sides + uint32_t recordSize; // @4 64; belt-and-braces against struct drift + uint32_t capacity; // @8 power of two + uint32_t pid; // @12 + char buildId[32]; // @16 native DLL build id + uint64_t qpcEpoch; // @48 session time base, shared with sensor samples + uint64_t adapterLuid; // @56 which GPU the swapchain is on +}; + +// --------------------------------------------------------------------------- +// Region 2 — Overlay-written. writeIndex is touched every present. +// +// Fields shared across the process boundary are plain integers accessed +// through std::atomic_ref, NOT std::atomic members: std::atomic has no +// guaranteed layout, cannot be memcpy'd, and cannot be mirrored by a C# +// [StructLayout(LayoutKind.Sequential)] struct. Every offset below satisfies +// atomic_ref's alignment requirement (4 for uint32_t, 8 for uint64_t). +// --------------------------------------------------------------------------- +struct alignas(64) FlWriterState { + uint64_t writeIndex; // @0 monotonic; release-store + uint32_t status; // @8 FlStatus + uint32_t apiMask; // @12 which graphics APIs got hooked + uint32_t faultCount; // @16 17_HOOK_ENGINE §Fault policy + uint32_t vramBudgetMb; // @20 IDXGIAdapter3 Budget, refreshed at 1 Hz + uint32_t reserved[10]; // @24..63 must be zero; room for additive fields + + // NOTE: there is deliberately no droppedRecords here. The writer has no + // reader index and cannot know whether the slot it overwrites was ever + // consumed — the field was unimplementable as originally specified. The + // Agent computes drops from its own read index (docs/07_IPC.md). +}; + +// --------------------------------------------------------------------------- +// Region 3 — Agent-written. +// --------------------------------------------------------------------------- +struct alignas(64) FlControlBlock { + uint32_t pauseRequested; // @0 + uint32_t unhookRequested; // @4 set when the guard fires mid-session + uint32_t overlayEnabled; // @8 in-game overlay draw toggle (v1.1) + uint32_t agentHeartbeat; // @12 Agent bumps every second + uint32_t reserved[12]; // @16..63 must be zero +}; + +// --------------------------------------------------------------------------- +// Region 4 — the ring. 64 bytes exactly, no implicit padding. +// --------------------------------------------------------------------------- +struct alignas(64) FlFrameRecord { + uint64_t qpc; // @0 present entry timestamp + uint32_t frameIndex; // @8 + uint32_t presentFlags; // @12 + uint16_t syncInterval; // @16 + uint16_t renderW; // @18 0 = unknown + uint16_t renderH; // @20 + uint16_t outputW; // @22 + uint16_t outputH; // @24 + uint8_t api; // @26 FlApi + uint8_t upscaler; // @27 FlUpscaler + uint8_t upscalerQuality; // @28 vendor enum, 0xFF unknown + uint8_t fgMode; // @29 FlFgMode + uint8_t rtFlags; // @30 FlRtFlags + uint8_t hdr; // @31 + + // Volume, not a call count, and 32-bit for a reason: one 3840x2160 + // primary-ray dispatch is 8,294,400 rays — 126x a uint16's range. A + // narrower counter saturates on every RT title at 1080p or above, which + // is exactly the regime the path-tracing heuristic reads. + uint32_t dispatchRaysVolume; // @32 sum of W*H*D this frame + + uint16_t psoCreatedThisFrame; // @36 compile COUNT, not a flag + uint8_t maxTraceRecursionDepth; // @38 from the live RT PSO config + uint8_t _pad0; // @39 explicit: keeps the next field 8-aligned + + uint64_t vramUsedBytes; // @40 + uint32_t reflexLatencyUs; // @48 0 = unavailable + uint32_t fgEvaluations; // @52 FG feature evaluations this frame + + // Seqlock counter. Monotonic per slot and NEVER reset, so a full lap of + // the ring always changes it — otherwise a reader stalled exactly one lap + // would validate a different frame as unchanged. The payload write must + // cover [0,56) and [60,64) and must never touch this field. + uint32_t seq; // @56 + uint32_t _pad1; // @60 explicit +}; + +// --------------------------------------------------------------------------- +// Layout contract. If one of these fires, the C# mirror and every offset in +// docs/07_IPC.md are wrong too — fix all three together. +// --------------------------------------------------------------------------- +static_assert(sizeof(FlShmHandshake) == 64, "FlShmHandshake must be one cache line"); +static_assert(sizeof(FlWriterState) == 64, "FlWriterState must be one cache line"); +static_assert(sizeof(FlControlBlock) == 64, "FlControlBlock must be one cache line"); +static_assert(sizeof(FlFrameRecord) == 64, "FlFrameRecord must be exactly 64 bytes"); + +static_assert(offsetof(FlShmHandshake, layoutVersion) == 0); +static_assert(offsetof(FlShmHandshake, recordSize) == 4); +static_assert(offsetof(FlShmHandshake, capacity) == 8); +static_assert(offsetof(FlShmHandshake, pid) == 12); +static_assert(offsetof(FlShmHandshake, buildId) == 16); +static_assert(offsetof(FlShmHandshake, qpcEpoch) == 48); +static_assert(offsetof(FlShmHandshake, adapterLuid) == 56); + +static_assert(offsetof(FlWriterState, writeIndex) == 0); +static_assert(offsetof(FlWriterState, status) == 8); +static_assert(offsetof(FlWriterState, apiMask) == 12); +static_assert(offsetof(FlWriterState, faultCount) == 16); +static_assert(offsetof(FlWriterState, vramBudgetMb) == 20); + +static_assert(offsetof(FlControlBlock, pauseRequested) == 0); +static_assert(offsetof(FlControlBlock, unhookRequested) == 4); +static_assert(offsetof(FlControlBlock, overlayEnabled) == 8); +static_assert(offsetof(FlControlBlock, agentHeartbeat) == 12); + +static_assert(offsetof(FlFrameRecord, qpc) == 0); +static_assert(offsetof(FlFrameRecord, frameIndex) == 8); +static_assert(offsetof(FlFrameRecord, presentFlags) == 12); +static_assert(offsetof(FlFrameRecord, syncInterval) == 16); +static_assert(offsetof(FlFrameRecord, renderW) == 18); +static_assert(offsetof(FlFrameRecord, renderH) == 20); +static_assert(offsetof(FlFrameRecord, outputW) == 22); +static_assert(offsetof(FlFrameRecord, outputH) == 24); +static_assert(offsetof(FlFrameRecord, api) == 26); +static_assert(offsetof(FlFrameRecord, upscaler) == 27); +static_assert(offsetof(FlFrameRecord, upscalerQuality) == 28); +static_assert(offsetof(FlFrameRecord, fgMode) == 29); +static_assert(offsetof(FlFrameRecord, rtFlags) == 30); +static_assert(offsetof(FlFrameRecord, hdr) == 31); +static_assert(offsetof(FlFrameRecord, dispatchRaysVolume) == 32); +static_assert(offsetof(FlFrameRecord, psoCreatedThisFrame) == 36); +static_assert(offsetof(FlFrameRecord, maxTraceRecursionDepth) == 38); +static_assert(offsetof(FlFrameRecord, vramUsedBytes) == 40); +static_assert(offsetof(FlFrameRecord, reflexLatencyUs) == 48); +static_assert(offsetof(FlFrameRecord, fgEvaluations) == 52); +static_assert(offsetof(FlFrameRecord, seq) == 56); + +// The regions must not overlap, and the ring must stay 64-aligned. +static_assert(FL_SHM_HANDSHAKE_OFFSET + sizeof(FlShmHandshake) <= FL_SHM_WRITER_OFFSET); +static_assert(FL_SHM_WRITER_OFFSET + sizeof(FlWriterState) <= FL_SHM_CONTROL_OFFSET); +static_assert(FL_SHM_CONTROL_OFFSET + sizeof(FlControlBlock) <= FL_SHM_RING_OFFSET); +static_assert(FL_SHM_RING_OFFSET % 64 == 0); + +constexpr size_t FlShmSizeForCapacity(uint32_t capacity) noexcept { + return FL_SHM_RING_OFFSET + static_cast(capacity) * sizeof(FlFrameRecord); +} + +} // namespace fl + +#endif // FRAMELEDGER_FL_SHM_H diff --git a/src/native/FrameLedger.VkLayer/CMakeLists.txt b/src/native/FrameLedger.VkLayer/CMakeLists.txt new file mode 100644 index 00000000..8e32aebb --- /dev/null +++ b/src/native/FrameLedger.VkLayer/CMakeLists.txt @@ -0,0 +1,9 @@ +# Vulkan implicit layer. Vulkan titles use this INSTEAD of injection — it is the +# mechanism Khronos supports and far more robust than hooking dispatch tables. +# +# A layer is machine-wide by nature. docs/20_OPEN_QUESTIONS.md §S2 is unresolved +# and blocks this target: the layer currently has no anti-cheat guard and no +# mid-session unhook path, and it loads before anything of ours runs. +add_library(FrameLedger.VkLayer SHARED src/layer.cpp) +target_link_libraries(FrameLedger.VkLayer PRIVATE FrameLedger.Shm fl_native_flags) +set_target_properties(FrameLedger.VkLayer PROPERTIES OUTPUT_NAME "FrameLedger.VkLayer") diff --git a/src/native/FrameLedger.VkLayer/src/layer.cpp b/src/native/FrameLedger.VkLayer/src/layer.cpp new file mode 100644 index 00000000..6afa5b6b --- /dev/null +++ b/src/native/FrameLedger.VkLayer/src/layer.cpp @@ -0,0 +1,30 @@ +// FrameLedger.VkLayer — Vulkan implicit layer. +// +// Scaffold. Vulkan titles use a layer INSTEAD of injection: it is the +// mechanism Khronos supports, and it is how OBS and RTSS do it. +// +// BLOCKED on docs/20_OPEN_QUESTIONS.md §S2 before any interception is added. +// An implicit layer is machine-wide and loads before anything of ours runs, so +// today this path has: +// - no anti-cheat guard (the guard is defined as pre-injection only, and +// there is no injection here), and +// - no mid-session unhook, though docs/19_SAFETY calls that "the single most +// important runtime behavior in the whole capture layer". +// +// The proposed fix is enable_environment in the manifest, so the loader does +// not map us unless the Agent sets the variable when launching an opted-in +// game — which makes Vulkan Tier 1 launch-mode-only — plus an in-layer module +// scan that goes passthrough on any blocklist hit. +// +// Until then this target builds but intercepts nothing. That is the correct +// failure mode: passthrough. + +#include + +namespace fl::vklayer { + +unsigned int LayoutVersion() noexcept { + return FL_SHM_LAYOUT_VERSION; +} + +} // namespace fl::vklayer diff --git a/src/native/tests/CMakeLists.txt b/src/native/tests/CMakeLists.txt new file mode 100644 index 00000000..f756beaa --- /dev/null +++ b/src/native/tests/CMakeLists.txt @@ -0,0 +1,13 @@ +# Native unit tests (docs/14_TESTING.md §Native unit tests): ring buffer SPSC +# correctness under a hammering writer, seqlock torn-read detection, the +# one-full-lap case, wrap semantics, and the fault policy. +# +# The record and header layout contract needs no test framework — it is enforced +# by static_assert in fl_shm.h, so simply compiling this target proves it. +include(CTest) + +add_executable(fl_shm_layout_test layout_test.cpp) +target_link_libraries(fl_shm_layout_test PRIVATE FrameLedger.Shm fl_native_flags) +add_test(NAME fl_shm_layout COMMAND fl_shm_layout_test) + +# TODO(P1): Catch2 via FetchContent for the ring-buffer and fault-policy suites. diff --git a/src/native/tests/layout_test.cpp b/src/native/tests/layout_test.cpp new file mode 100644 index 00000000..4c6fb4cf --- /dev/null +++ b/src/native/tests/layout_test.cpp @@ -0,0 +1,16 @@ +// Compiling this file IS the layout test: every size and offset assertion +// lives in fl_shm.h as a static_assert, so a drift makes the build fail rather +// than making a test fail. Running it re-checks the derived size arithmetic. +#include + +#include + +int main() { + if (fl::FlShmSizeForCapacity(FL_SHM_DEFAULT_CAPACITY) != + FL_SHM_RING_OFFSET + static_cast(FL_SHM_DEFAULT_CAPACITY) * 64u) { + std::puts("shm size arithmetic mismatch"); + return 1; + } + std::puts("layout ok"); + return 0; +} diff --git a/src/native/tools/CMakeLists.txt b/src/native/tools/CMakeLists.txt new file mode 100644 index 00000000..e0c73601 --- /dev/null +++ b/src/native/tools/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(fl-layout-dump) diff --git a/src/native/tools/fl-layout-dump/CMakeLists.txt b/src/native/tools/fl-layout-dump/CMakeLists.txt new file mode 100644 index 00000000..25d34396 --- /dev/null +++ b/src/native/tools/fl-layout-dump/CMakeLists.txt @@ -0,0 +1,6 @@ +# Emits the native struct offsets as JSON. FrameLedger.Infrastructure.Tests +# reads this and asserts the C# [StructLayout] mirrors match field for field. +# Struct drift between the two layers is the most dangerous silent bug in this +# architecture (CLAUDE.md §Struct mirroring) — this is what catches it. +add_executable(fl-layout-dump main.cpp) +target_link_libraries(fl-layout-dump PRIVATE FrameLedger.Shm fl_native_flags) diff --git a/src/native/tools/fl-layout-dump/main.cpp b/src/native/tools/fl-layout-dump/main.cpp new file mode 100644 index 00000000..9ec40070 --- /dev/null +++ b/src/native/tools/fl-layout-dump/main.cpp @@ -0,0 +1,88 @@ +// Emits the native shared-memory struct layout as JSON. +// +// FrameLedger.Infrastructure.Tests consumes this and asserts that the C# +// [StructLayout(LayoutKind.Sequential)] mirrors in FrameLedger.Shared match +// field for field. CLAUDE.md §Struct mirroring requires a test that checks +// sizeof AND every field offset on both sides; this is the native half. +// +// Struct drift between C++ and C# is the most dangerous silent bug in this +// architecture: nothing crashes, the Agent just reads garbage into fields that +// look plausible. + +#include + +#include +#include + +using namespace fl; + +namespace { + +void Field(const char* name, size_t offset, size_t size, bool last = false) { + std::printf(" { \"name\": \"%s\", \"offset\": %zu, \"size\": %zu }%s\n", name, offset, size, + last ? "" : ","); +} + +} // namespace + +int main() { + std::printf("{\n"); + std::printf(" \"layoutVersion\": %u,\n", FL_SHM_LAYOUT_VERSION); + std::printf(" \"regions\": { \"handshake\": %u, \"writer\": %u, \"control\": %u, \"ring\": %u },\n", + FL_SHM_HANDSHAKE_OFFSET, FL_SHM_WRITER_OFFSET, FL_SHM_CONTROL_OFFSET, FL_SHM_RING_OFFSET); + std::printf(" \"structs\": {\n"); + + std::printf(" \"FlShmHandshake\": { \"size\": %zu, \"fields\": [\n", sizeof(FlShmHandshake)); + Field("layoutVersion", offsetof(FlShmHandshake, layoutVersion), sizeof(uint32_t)); + Field("recordSize", offsetof(FlShmHandshake, recordSize), sizeof(uint32_t)); + Field("capacity", offsetof(FlShmHandshake, capacity), sizeof(uint32_t)); + Field("pid", offsetof(FlShmHandshake, pid), sizeof(uint32_t)); + Field("buildId", offsetof(FlShmHandshake, buildId), 32); + Field("qpcEpoch", offsetof(FlShmHandshake, qpcEpoch), sizeof(uint64_t)); + Field("adapterLuid", offsetof(FlShmHandshake, adapterLuid), sizeof(uint64_t), true); + std::printf(" ] },\n"); + + std::printf(" \"FlWriterState\": { \"size\": %zu, \"fields\": [\n", sizeof(FlWriterState)); + Field("writeIndex", offsetof(FlWriterState, writeIndex), sizeof(uint64_t)); + Field("status", offsetof(FlWriterState, status), sizeof(uint32_t)); + Field("apiMask", offsetof(FlWriterState, apiMask), sizeof(uint32_t)); + Field("faultCount", offsetof(FlWriterState, faultCount), sizeof(uint32_t)); + Field("vramBudgetMb", offsetof(FlWriterState, vramBudgetMb), sizeof(uint32_t), true); + std::printf(" ] },\n"); + + std::printf(" \"FlControlBlock\": { \"size\": %zu, \"fields\": [\n", sizeof(FlControlBlock)); + Field("pauseRequested", offsetof(FlControlBlock, pauseRequested), sizeof(uint32_t)); + Field("unhookRequested", offsetof(FlControlBlock, unhookRequested), sizeof(uint32_t)); + Field("overlayEnabled", offsetof(FlControlBlock, overlayEnabled), sizeof(uint32_t)); + Field("agentHeartbeat", offsetof(FlControlBlock, agentHeartbeat), sizeof(uint32_t), true); + std::printf(" ] },\n"); + + std::printf(" \"FlFrameRecord\": { \"size\": %zu, \"fields\": [\n", sizeof(FlFrameRecord)); + Field("qpc", offsetof(FlFrameRecord, qpc), sizeof(uint64_t)); + Field("frameIndex", offsetof(FlFrameRecord, frameIndex), sizeof(uint32_t)); + Field("presentFlags", offsetof(FlFrameRecord, presentFlags), sizeof(uint32_t)); + Field("syncInterval", offsetof(FlFrameRecord, syncInterval), sizeof(uint16_t)); + Field("renderW", offsetof(FlFrameRecord, renderW), sizeof(uint16_t)); + Field("renderH", offsetof(FlFrameRecord, renderH), sizeof(uint16_t)); + Field("outputW", offsetof(FlFrameRecord, outputW), sizeof(uint16_t)); + Field("outputH", offsetof(FlFrameRecord, outputH), sizeof(uint16_t)); + Field("api", offsetof(FlFrameRecord, api), sizeof(uint8_t)); + Field("upscaler", offsetof(FlFrameRecord, upscaler), sizeof(uint8_t)); + Field("upscalerQuality", offsetof(FlFrameRecord, upscalerQuality), sizeof(uint8_t)); + Field("fgMode", offsetof(FlFrameRecord, fgMode), sizeof(uint8_t)); + Field("rtFlags", offsetof(FlFrameRecord, rtFlags), sizeof(uint8_t)); + Field("hdr", offsetof(FlFrameRecord, hdr), sizeof(uint8_t)); + Field("dispatchRaysVolume", offsetof(FlFrameRecord, dispatchRaysVolume), sizeof(uint32_t)); + Field("psoCreatedThisFrame", offsetof(FlFrameRecord, psoCreatedThisFrame), sizeof(uint16_t)); + Field("maxTraceRecursionDepth", offsetof(FlFrameRecord, maxTraceRecursionDepth), sizeof(uint8_t)); + Field("_pad0", offsetof(FlFrameRecord, _pad0), sizeof(uint8_t)); + Field("vramUsedBytes", offsetof(FlFrameRecord, vramUsedBytes), sizeof(uint64_t)); + Field("reflexLatencyUs", offsetof(FlFrameRecord, reflexLatencyUs), sizeof(uint32_t)); + Field("fgEvaluations", offsetof(FlFrameRecord, fgEvaluations), sizeof(uint32_t)); + Field("seq", offsetof(FlFrameRecord, seq), sizeof(uint32_t)); + Field("_pad1", offsetof(FlFrameRecord, _pad1), sizeof(uint32_t), true); + std::printf(" ] }\n"); + + std::printf(" }\n}\n"); + return 0; +} diff --git a/tests/FrameLedger.Application.Tests/FrameLedger.Application.Tests.csproj b/tests/FrameLedger.Application.Tests/FrameLedger.Application.Tests.csproj new file mode 100644 index 00000000..9bf0deb3 --- /dev/null +++ b/tests/FrameLedger.Application.Tests/FrameLedger.Application.Tests.csproj @@ -0,0 +1,25 @@ + + + + false + FrameLedger.Application.Tests + + + + + + + + + + + + + + + + + + + + diff --git a/tests/FrameLedger.Application.Tests/HarnessSmokeTests.cs b/tests/FrameLedger.Application.Tests/HarnessSmokeTests.cs new file mode 100644 index 00000000..b1386b7f --- /dev/null +++ b/tests/FrameLedger.Application.Tests/HarnessSmokeTests.cs @@ -0,0 +1,16 @@ +namespace FrameLedger.Application.Tests; + +/// +/// Proves the xUnit v3 harness discovers and runs tests in this project. +/// +/// +/// Scaffolding. Delete this once real tests exist here — but not before: +/// an empty test project reports "No test is available", which makes the +/// dotnet test gate in build.ps1 pass without having verified anything. +/// docs/14_TESTING.md says the golden metric tests are written FIRST. +/// +public sealed class HarnessSmokeTests +{ + [Fact] + public void HarnessDiscoversAndRunsTests() => Assert.True(true); +} diff --git a/tests/FrameLedger.Domain.Tests/FrameLedger.Domain.Tests.csproj b/tests/FrameLedger.Domain.Tests/FrameLedger.Domain.Tests.csproj new file mode 100644 index 00000000..e38c7420 --- /dev/null +++ b/tests/FrameLedger.Domain.Tests/FrameLedger.Domain.Tests.csproj @@ -0,0 +1,25 @@ + + + + false + FrameLedger.Domain.Tests + + + + + + + + + + + + + + + + + + + + diff --git a/tests/FrameLedger.Domain.Tests/HarnessSmokeTests.cs b/tests/FrameLedger.Domain.Tests/HarnessSmokeTests.cs new file mode 100644 index 00000000..010823e1 --- /dev/null +++ b/tests/FrameLedger.Domain.Tests/HarnessSmokeTests.cs @@ -0,0 +1,16 @@ +namespace FrameLedger.Domain.Tests; + +/// +/// Proves the xUnit v3 harness discovers and runs tests in this project. +/// +/// +/// Scaffolding. Delete this once real tests exist here — but not before: +/// an empty test project reports "No test is available", which makes the +/// dotnet test gate in build.ps1 pass without having verified anything. +/// docs/14_TESTING.md says the golden metric tests are written FIRST. +/// +public sealed class HarnessSmokeTests +{ + [Fact] + public void HarnessDiscoversAndRunsTests() => Assert.True(true); +} diff --git a/tests/FrameLedger.Infrastructure.Tests/FrameLedger.Infrastructure.Tests.csproj b/tests/FrameLedger.Infrastructure.Tests/FrameLedger.Infrastructure.Tests.csproj new file mode 100644 index 00000000..83ec7fc0 --- /dev/null +++ b/tests/FrameLedger.Infrastructure.Tests/FrameLedger.Infrastructure.Tests.csproj @@ -0,0 +1,25 @@ + + + + false + FrameLedger.Infrastructure.Tests + + + + + + + + + + + + + + + + + + + + diff --git a/tests/FrameLedger.Infrastructure.Tests/HarnessSmokeTests.cs b/tests/FrameLedger.Infrastructure.Tests/HarnessSmokeTests.cs new file mode 100644 index 00000000..5ba0b44f --- /dev/null +++ b/tests/FrameLedger.Infrastructure.Tests/HarnessSmokeTests.cs @@ -0,0 +1,16 @@ +namespace FrameLedger.Infrastructure.Tests; + +/// +/// Proves the xUnit v3 harness discovers and runs tests in this project. +/// +/// +/// Scaffolding. Delete this once real tests exist here — but not before: +/// an empty test project reports "No test is available", which makes the +/// dotnet test gate in build.ps1 pass without having verified anything. +/// docs/14_TESTING.md says the golden metric tests are written FIRST. +/// +public sealed class HarnessSmokeTests +{ + [Fact] + public void HarnessDiscoversAndRunsTests() => Assert.True(true); +} diff --git a/tools/license-check.ps1 b/tools/license-check.ps1 new file mode 100644 index 00000000..5f9e329e --- /dev/null +++ b/tools/license-check.ps1 @@ -0,0 +1,107 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + Licence guard. Fails the build on a licensing regression. + +.DESCRIPTION + Two checks, both from docs/18_GPU_VENDOR_APIS.md and + legal/THIRD_PARTY_NOTICES.md: + + 1. No Intel IGCL or AMD ADLX material anywhere in the tree. + + These are rejected on licence grounds, not preference. IGCL ships under + the Intel Software License Agreement, which permits use "solely for use + on Intel platforms", imposes broad indemnification, and adds its own + termination trigger — each a further restriction on downstream + recipients that GPL-3.0 §10 forbids and §7 does not permit. + + Re-declaring the API by hand is explicitly NOT an approved workaround: + struct layouts must match byte for byte, so an "independent" + implementation is indistinguishable from a copy. + + Licensing regressions are silent and hard to unwind later. That is why + this runs at PR time rather than at release. + + 2. Every vendored third-party component has a licence copy in + legal/licenses/. + + Exit 0 clean, 1 on any violation. +#> +[CmdletBinding()] +param([string]$RepoRoot = (Split-Path $PSScriptRoot -Parent)) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$violations = [System.Collections.Generic.List[string]]::new() + +# --- 1. Rejected vendor SDKs ------------------------------------------------ +# Distinctive identifiers, not bare product names: "adlx" alone would match +# prose in the very docs that explain why we do not use it. +$forbidden = @( + @{ Pattern = 'ctl_api\.h|ctlApiInit|CTL_RESULT_SUCCESS|igcl_api'; Name = 'Intel IGCL' } + @{ Pattern = 'IADLXHelper|ADLXHelper\.h|adlx\.h|ADLX_RESULT'; Name = 'AMD ADLX' } + @{ Pattern = 'adl_sdk\.h|ADL2_Main_Control_Create'; Name = 'AMD ADL' } +) + +$scanRoots = @('src', 'tools', 'tests') | + ForEach-Object { Join-Path $RepoRoot $_ } | + Where-Object { Test-Path $_ } + +if ($scanRoots) { + $files = Get-ChildItem -Path $scanRoots -Recurse -File -ErrorAction SilentlyContinue | + Where-Object { + $_.Extension -in '.c', '.cpp', '.h', '.hpp', '.cs', '.txt', '.json', '.props', '.targets' -and + $_.FullName -notmatch '[\\/](bin|obj|build|TestResults)[\\/]' + } + + foreach ($rule in $forbidden) { + $hits = $files | Select-String -Pattern $rule.Pattern -List -ErrorAction SilentlyContinue + foreach ($hit in $hits) { + $rel = [IO.Path]::GetRelativePath($RepoRoot, $hit.Path) + $violations.Add("$($rule.Name) material found: ${rel}:$($hit.LineNumber)") + } + } +} + +# --- 2. Vendored components have licence copies ----------------------------- +# Keyed by the directory that would exist if the component were vendored, so a +# missing licence is only reported once the component is actually present. +$vendored = @( + @{ Path = 'src/native/third_party/minhook'; Licence = 'minhook-BSD-2-Clause.txt'; Name = 'MinHook' } + @{ Path = 'src/native/third_party/nvapi'; Licence = 'nvapi-MIT.txt'; Name = 'NVIDIA NVAPI SDK' } +) + +$licenceDir = Join-Path $RepoRoot 'legal/licenses' +foreach ($v in $vendored) { + if (Test-Path (Join-Path $RepoRoot $v.Path)) { + $copy = Join-Path $licenceDir $v.Licence + if (-not (Test-Path $copy)) { + $violations.Add("$($v.Name) is vendored at $($v.Path) but legal/licenses/$($v.Licence) is missing") + } + } +} + +# NVAPI's SPDX headers must survive vendoring — the MIT grant travels with them. +$nvapiDir = Join-Path $RepoRoot 'src/native/third_party/nvapi' +if (Test-Path $nvapiDir) { + $headers = Get-ChildItem $nvapiDir -Recurse -Filter *.h -ErrorAction SilentlyContinue + $stripped = $headers | Where-Object { + -not (Select-String -Path $_.FullName -Pattern 'SPDX-License-Identifier:\s*MIT' -Quiet) + } + foreach ($h in $stripped) { + $violations.Add("NVAPI header lost its SPDX-License-Identifier: MIT block: $($h.Name)") + } +} + +# --- Report ----------------------------------------------------------------- +if ($violations.Count -gt 0) { + Write-Host 'LICENCE CHECK FAILED' -ForegroundColor Red + $violations | ForEach-Object { Write-Host " - $_" -ForegroundColor Red } + Write-Host '' + Write-Host 'See docs/18_GPU_VENDOR_APIS.md §Vendor SDKs we deliberately do not use.' -ForegroundColor Red + exit 1 +} + +Write-Host 'licence check OK — no rejected vendor SDK material, vendored licences present' -ForegroundColor Green +exit 0 diff --git a/tools/rules-validate.ps1 b/tools/rules-validate.ps1 new file mode 100644 index 00000000..5c0315ce --- /dev/null +++ b/tools/rules-validate.ps1 @@ -0,0 +1,136 @@ +#Requires -Version 7.0 +<# +.SYNOPSIS + Validates rules/detection-rules.json, with extra scrutiny on the anticheat + block that feeds the hard gate. + +.DESCRIPTION + A malformed or empty blocklist is a SAFETY bug, not a lint failure + (docs/13_CI_CD.md §rules-publish.yml). This runs in build.ps1 check and in + CI on every change to the rules file. + + Fail-closed is the guiding rule everywhere: if this script cannot prove the + blocklist is well-formed and non-empty, it fails. + + NOTE: this is structural validation, not a full JSON Schema. Writing the + schema to validator grade is docs/20_OPEN_QUESTIONS.md §S5, and until that + lands some signal shapes described in docs/19_SAFETY are accepted without + being checked in depth. +#> +[CmdletBinding()] +param( + [string]$Path = (Join-Path (Split-Path $PSScriptRoot -Parent) 'rules/detection-rules.json') +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$errors = [System.Collections.Generic.List[string]]::new() + +if (-not (Test-Path $Path)) { + Write-Host "RULES VALIDATION FAILED: $Path does not exist" -ForegroundColor Red + exit 1 +} + +try { + $rules = Get-Content $Path -Raw | ConvertFrom-Json +} +catch { + Write-Host "RULES VALIDATION FAILED: not valid JSON — $($_.Exception.Message)" -ForegroundColor Red + exit 1 +} + +function Test-Member($Object, [string]$Name) { + return $null -ne $Object -and $Object.PSObject.Properties.Name -contains $Name +} + +# --- Top level -------------------------------------------------------------- +foreach ($key in 'schemaVersion', 'rulesVersion', 'engines', 'platforms', 'capabilities', 'anticheat') { + if (-not (Test-Member $rules $key)) { $errors.Add("missing top-level key: $key") } +} + +if ((Test-Member $rules 'schemaVersion') -and $rules.schemaVersion -ne 2) { + $errors.Add("schemaVersion must be 2, got $($rules.schemaVersion)") +} + +if ((Test-Member $rules 'rulesVersion') -and $rules.rulesVersion -notmatch '^\d{4}\.\d{2}\.\d+$') { + $errors.Add("rulesVersion must look like YYYY.MM.N, got '$($rules.rulesVersion)'") +} + +# --- Identifier uniqueness -------------------------------------------------- +foreach ($section in 'engines', 'platforms', 'capabilities') { + if (-not (Test-Member $rules $section)) { continue } + $ids = @($rules.$section | ForEach-Object { $_.id }) + $dupes = $ids | Group-Object | Where-Object Count -gt 1 + foreach ($d in $dupes) { $errors.Add("duplicate id '$($d.Name)' in $section") } + foreach ($id in $ids) { + if ([string]::IsNullOrWhiteSpace($id)) { $errors.Add("empty id in $section") } + } +} + +# --- The anticheat block: fail closed --------------------------------------- +if (Test-Member $rules 'anticheat') { + $ac = $rules.anticheat + + foreach ($key in 'modules', 'drivers', 'blockedExecutables', 'blockedStoreIds') { + if (-not (Test-Member $ac $key)) { $errors.Add("anticheat.$key is missing") } + } + + # Non-empty is a ship requirement. blockedExecutables/blockedStoreIds may + # legitimately be empty (they are per-title opt-outs); modules and drivers + # may not — an empty module list means the guard matches nothing. + foreach ($key in 'modules', 'drivers') { + if ((Test-Member $ac $key) -and @($ac.$key).Count -eq 0) { + $errors.Add("anticheat.$key is EMPTY — the guard would match nothing. This is a fail-closed fixture, not a ship state.") + } + } + + $validMatch = @('exact', 'prefix') + foreach ($group in @('modules', 'drivers')) { + if (-not (Test-Member $ac $group)) { continue } + foreach ($entry in $ac.$group) { + $label = if (Test-Member $entry 'family') { $entry.family } else { '' } + foreach ($k in 'family', 'match', 'values') { + if (-not (Test-Member $entry $k)) { $errors.Add("anticheat.$group entry '$label' missing '$k'") } + } + if ((Test-Member $entry 'match') -and $entry.match -notin $validMatch) { + $errors.Add("anticheat.$group entry '$label' has match '$($entry.match)', expected one of: $($validMatch -join ', ')") + } + if ((Test-Member $entry 'values')) { + if (@($entry.values).Count -eq 0) { + $errors.Add("anticheat.$group entry '$label' has no values") + } + foreach ($v in $entry.values) { + if ([string]::IsNullOrWhiteSpace($v)) { + $errors.Add("anticheat.$group entry '$label' has a blank value — would match everything") + } + } + } + } + } + + # Known families that must never silently disappear. Removing one is a + # safety change requiring the same review as a security fix. + $required = @('Easy Anti-Cheat', 'BattlEye', 'Riot Vanguard') + $present = @() + foreach ($group in 'modules', 'drivers') { + if (Test-Member $ac $group) { $present += @($ac.$group | ForEach-Object { $_.family }) } + } + foreach ($fam in $required) { + if ($fam -notin $present) { + $errors.Add("anticheat blocklist no longer covers '$fam' — removing a family requires an explicit justification in the PR body") + } + } +} + +# --- Report ----------------------------------------------------------------- +if ($errors.Count -gt 0) { + Write-Host 'RULES VALIDATION FAILED' -ForegroundColor Red + $errors | ForEach-Object { Write-Host " - $_" -ForegroundColor Red } + exit 1 +} + +$moduleCount = @($rules.anticheat.modules).Count +$driverCount = @($rules.anticheat.drivers).Count +Write-Host "rules OK — schema v$($rules.schemaVersion), rules $($rules.rulesVersion), $moduleCount anticheat module families, $driverCount driver families" -ForegroundColor Green +exit 0