diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c57d5a7e..a8de6a7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,8 +1,11 @@ name: CI on: - push: - pull_request: + workflow_call: + workflow_dispatch: + +permissions: + contents: read jobs: test: diff --git a/.github/workflows/linux-image.yml b/.github/workflows/linux-image.yml new file mode 100644 index 00000000..403fe9f0 --- /dev/null +++ b/.github/workflows/linux-image.yml @@ -0,0 +1,154 @@ +name: Linux development image + +on: + workflow_call: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: linux-image-${{ github.ref }} + cancel-in-progress: true + +jobs: + live-image: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Build an unsigned development image in isolated Arch Linux + run: | + set -euo pipefail + mkdir -p dist/linux + builder_image=$(python3 -c 'import json; print(json.load(open("packaging/linux/release.json"))["builder_image"])') + docker pull "$builder_image" + docker image inspect "$builder_image" > dist/linux/builder-image.json + docker run --rm --privileged \ + -v "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE:ro" \ + -v "$GITHUB_WORKSPACE/dist/linux:/artifacts" \ + -w "$GITHUB_WORKSPACE" \ + -e PHIOS_SOURCE_COMMIT="$(git rev-parse HEAD)" \ + -e PHIOS_OUTPUT_DIR=/artifacts -e PHIOS_CI_SMOKE=1 \ + "$builder_image" bash packaging/linux/build-linux.sh 2>&1 | tee dist/linux/build.log + - name: Qualify the exact ISO in a disposable UEFI VM + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y qemu-system-x86 ovmf python3-pil + if [[ -e /dev/kvm ]]; then + sudo chgrp "$(id -gn)" /dev/kvm + sudo chmod g+rw /dev/kvm + fi + python3 packaging/linux/tests/qemu_boot.py \ + --iso dist/linux/phios-linux-0.1.0-alpha.1-x86_64.iso \ + --source "$(cat dist/linux/source-commit.txt)" \ + --output "$RUNNER_TEMP/phios-boot" + - name: Install only to a disposable virtual disk and qualify no-ISO recovery + run: | + python3 packaging/linux/tests/qemu_install.py \ + --recovery \ + --signed-update \ + --iso dist/linux/phios-linux-0.1.0-alpha.1-x86_64.iso \ + --source "$(cat dist/linux/source-commit.txt)" \ + --output "$RUNNER_TEMP/phios-installed" + - name: Convert display evidence even when qualification fails + if: always() + run: | + /usr/bin/python3 -I - <<'PY' + from pathlib import Path + import os + files = [p for name in ["phios-boot","phios-installed"] for p in Path(os.environ['RUNNER_TEMP'], name).glob('*.ppm')] + if files: + from PIL import Image + for path in files: + Image.open(path).save(path.with_suffix('.png')) + else: + print('No VM display captures exist; retain the earlier failure logs.') + PY + - name: Emit bounded qualification metadata for review + if: always() + run: | + /usr/bin/python3 -I - <<'PY' + import hashlib, json, os, re + from pathlib import Path + source = os.environ['GITHUB_SHA'] + assert re.fullmatch('[0-9a-f]{40}', source) + roots = [('PhiOS/PhiOS/dist/linux', Path('dist/linux'))] + roots += [('_temp/' + name, Path(os.environ['RUNNER_TEMP'], name)) for name in ["phios-boot","phios-installed"]] + payload = {'schema_version': 'phios.ci-review-metadata.v1', 'source_commit': source, + 'run_attempt': int(os.environ['GITHUB_RUN_ATTEMPT']), 'files': {}, 'reports': {}, 'inventory_counts': {}, + 'producer_metadata_only': True, 'review_archive_independently_verified': False, 'release_ready': False} + counts = {'native-packages.json': 'native', 'python-packages.json': 'python', + 'javascript-packages.json': 'installed_npm', 'javascript-bundled-packages.json': 'bundled_frontend_origins'} + for prefix, root in roots: + if not root.exists(): + continue + for path in sorted(root.iterdir()): + if path.suffix not in {'.json', '.txt', '.log', '.png'} and path.name != 'SHA256SUMS': + continue + if path.is_symlink() or not path.is_file() or path.stat().st_size > 64 * 1024 * 1024: + raise ValueError('unexpected or oversized review evidence file') + with path.open('rb') as stream: + digest = hashlib.file_digest(stream, 'sha256').hexdigest() + payload['files'][prefix + '/' + path.name] = {'sha256': digest, 'size': path.stat().st_size} + if path.suffix != '.json': + continue + if path.stat().st_size > 4 * 1024 * 1024: + raise ValueError('review JSON exceeds its bound') + data = json.loads(path.read_text()) + if path.name in {'provenance.json', 'boot-evidence.json', 'preview-evidence.json', 'installed-evidence.json'}: + if data.get('source_commit') != source: + raise ValueError('review source identity differs from this CI source') + payload['reports'][prefix + '/' + path.name] = {k: v for k, v in data.items() if k not in {'command', 'commands', 'artifacts'}} + elif path.name in counts: + if not isinstance(data, list): + raise ValueError('review inventory is not a list') + payload['inventory_counts'][counts[path.name]] = len(data) + elif path.name == 'sbom.cdx.json': + payload['inventory_counts']['cyclonedx_components'] = len(data['components']) + elif path.name == 'third-party-notices.json': + payload['inventory_counts']['supplier_notice_files'] = len(data['files']) + elif path.name == 'source-review.json': + payload['first_party_source_archive'] = data['first_party_source_archive'] + payload['source_delivery_reviewed'] = data['third_party_source_compliance_reviewed'] + wire = json.dumps(payload, sort_keys=True, separators=(',', ':')) + if len(wire.encode()) > 60000: + raise ValueError('compact review metadata exceeds its bound') + print('PHIOS_REVIEW_METADATA:' + wire) + PY + - name: Preserve candidate and qualification evidence + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: phios-linux-development-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: | + dist/linux/ + ${{ runner.temp }}/phios-boot/*.log + ${{ runner.temp }}/phios-boot/*.json + ${{ runner.temp }}/phios-boot/*.png + ${{ runner.temp }}/phios-installed/*.log + ${{ runner.temp }}/phios-installed/*.json + ${{ runner.temp }}/phios-installed/*.png + if-no-files-found: warn + retention-days: 7 + - name: Preserve reviewable logs and screenshot separately + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: phios-linux-evidence-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: | + dist/linux/*.json + dist/linux/*.txt + dist/linux/*.log + dist/linux/SHA256SUMS + ${{ runner.temp }}/phios-boot/*.log + ${{ runner.temp }}/phios-boot/*.json + ${{ runner.temp }}/phios-boot/*.png + ${{ runner.temp }}/phios-installed/*.log + ${{ runner.temp }}/phios-installed/*.json + ${{ runner.temp }}/phios-installed/*.png + if-no-files-found: warn + retention-days: 7 diff --git a/.github/workflows/os-release-candidate.yml b/.github/workflows/os-release-candidate.yml new file mode 100644 index 00000000..cf6237e6 --- /dev/null +++ b/.github/workflows/os-release-candidate.yml @@ -0,0 +1,156 @@ +name: Fixture-free OS candidate (unpublished) + +on: + workflow_call: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: os-release-candidate-${{ github.ref }} + cancel-in-progress: true + +jobs: + fixture-free-candidate: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Build the exact source with production profile and no QA fixtures + run: | + set -euo pipefail + mkdir -p dist/fixture-free + builder_image=$(python3 -c 'import json; print(json.load(open("packaging/linux/release.json"))["builder_image"])') + docker pull "$builder_image" + docker image inspect "$builder_image" > dist/fixture-free/builder-image.json + docker run --rm --privileged \ + -v "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE:ro" \ + -v "$GITHUB_WORKSPACE/dist/fixture-free:/artifacts" \ + -w "$GITHUB_WORKSPACE" \ + -e PHIOS_SOURCE_COMMIT="$(git rev-parse HEAD)" \ + -e PHIOS_OUTPUT_DIR=/artifacts -e PHIOS_CI_SMOKE=0 \ + "$builder_image" bash packaging/linux/build-linux.sh 2>&1 | tee dist/fixture-free/build.log + - name: Validate SBOM and qualify this unmodified ISO through normal PAM + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y qemu-system-x86 ovmf python3-pil python3-venv + if [[ -e /dev/kvm ]]; then + sudo chgrp "$(id -gn)" /dev/kvm + sudo chmod g+rw /dev/kvm + fi + python3 -m venv "$RUNNER_TEMP/phios-sbom-validator" + "$RUNNER_TEMP/phios-sbom-validator/bin/python" -m pip install jsonschema==4.26.0 + "$RUNNER_TEMP/phios-sbom-validator/bin/python" packaging/linux/validate_sbom.py dist/fixture-free/sbom.cdx.json + python3 packaging/linux/tests/qemu_preview.py \ + --iso dist/fixture-free/phios-linux-0.1.0-alpha.1-x86_64.iso \ + --source "$(cat dist/fixture-free/source-commit.txt)" \ + --output "$RUNNER_TEMP/phios-preview" + - name: Install and recover the exact normal ISO through production commands + run: | + python3 packaging/linux/tests/qemu_install.py \ + --fixture-free --recovery \ + --iso dist/fixture-free/phios-linux-0.1.0-alpha.1-x86_64.iso \ + --source "$(cat dist/fixture-free/source-commit.txt)" \ + --output "$RUNNER_TEMP/phios-normal-installed" + - name: Preserve display evidence even on failure + if: always() + run: | + /usr/bin/python3 -I - <<'PY' + from pathlib import Path + import os + files = [p for name in ["phios-preview","phios-normal-installed"] for p in Path(os.environ['RUNNER_TEMP'], name).glob('*.ppm')] + if files: + from PIL import Image + for path in files: + Image.open(path).save(path.with_suffix('.png')) + else: + print('No VM display captures exist; retain the earlier failure logs.') + PY + - name: Emit bounded qualification metadata for review + if: always() + run: | + /usr/bin/python3 -I - <<'PY' + import hashlib, json, os, re + from pathlib import Path + source = os.environ['GITHUB_SHA'] + assert re.fullmatch('[0-9a-f]{40}', source) + roots = [('PhiOS/PhiOS/dist/fixture-free', Path('dist/fixture-free'))] + roots += [('_temp/' + name, Path(os.environ['RUNNER_TEMP'], name)) for name in ["phios-preview","phios-normal-installed"]] + payload = {'schema_version': 'phios.ci-review-metadata.v1', 'source_commit': source, + 'run_attempt': int(os.environ['GITHUB_RUN_ATTEMPT']), 'files': {}, 'reports': {}, 'inventory_counts': {}, + 'producer_metadata_only': True, 'review_archive_independently_verified': False, 'release_ready': False} + counts = {'native-packages.json': 'native', 'python-packages.json': 'python', + 'javascript-packages.json': 'installed_npm', 'javascript-bundled-packages.json': 'bundled_frontend_origins'} + for prefix, root in roots: + if not root.exists(): + continue + for path in sorted(root.iterdir()): + if path.suffix not in {'.json', '.txt', '.log', '.png'} and path.name != 'SHA256SUMS': + continue + if path.is_symlink() or not path.is_file() or path.stat().st_size > 64 * 1024 * 1024: + raise ValueError('unexpected or oversized review evidence file') + with path.open('rb') as stream: + digest = hashlib.file_digest(stream, 'sha256').hexdigest() + payload['files'][prefix + '/' + path.name] = {'sha256': digest, 'size': path.stat().st_size} + if path.suffix != '.json': + continue + if path.stat().st_size > 4 * 1024 * 1024: + raise ValueError('review JSON exceeds its bound') + data = json.loads(path.read_text()) + if path.name in {'provenance.json', 'boot-evidence.json', 'preview-evidence.json', 'installed-evidence.json'}: + if data.get('source_commit') != source: + raise ValueError('review source identity differs from this CI source') + payload['reports'][prefix + '/' + path.name] = {k: v for k, v in data.items() if k not in {'command', 'commands', 'artifacts'}} + elif path.name in counts: + if not isinstance(data, list): + raise ValueError('review inventory is not a list') + payload['inventory_counts'][counts[path.name]] = len(data) + elif path.name == 'sbom.cdx.json': + payload['inventory_counts']['cyclonedx_components'] = len(data['components']) + elif path.name == 'third-party-notices.json': + payload['inventory_counts']['supplier_notice_files'] = len(data['files']) + elif path.name == 'source-review.json': + payload['first_party_source_archive'] = data['first_party_source_archive'] + payload['source_delivery_reviewed'] = data['third_party_source_compliance_reviewed'] + wire = json.dumps(payload, sort_keys=True, separators=(',', ':')) + if len(wire.encode()) > 60000: + raise ValueError('compact review metadata exceeds its bound') + print('PHIOS_REVIEW_METADATA:' + wire) + PY + - name: Preserve unpublished candidate and exact provenance + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: phios-fixture-free-candidate-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: | + dist/fixture-free/ + ${{ runner.temp }}/phios-preview/*.log + ${{ runner.temp }}/phios-preview/*.json + ${{ runner.temp }}/phios-preview/*.png + ${{ runner.temp }}/phios-normal-installed/*.log + ${{ runner.temp }}/phios-normal-installed/*.json + ${{ runner.temp }}/phios-normal-installed/*.png + if-no-files-found: warn + retention-days: 7 + - name: Preserve compact review evidence + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: phios-fixture-free-evidence-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: | + dist/fixture-free/*.json + dist/fixture-free/*.txt + dist/fixture-free/*.log + dist/fixture-free/SHA256SUMS + ${{ runner.temp }}/phios-preview/*.log + ${{ runner.temp }}/phios-preview/*.json + ${{ runner.temp }}/phios-preview/*.png + ${{ runner.temp }}/phios-normal-installed/*.log + ${{ runner.temp }}/phios-normal-installed/*.json + ${{ runner.temp }}/phios-normal-installed/*.png + if-no-files-found: warn + retention-days: 7 diff --git a/.github/workflows/phishell.yml b/.github/workflows/phishell.yml index 7e54668f..007299ea 100644 --- a/.github/workflows/phishell.yml +++ b/.github/workflows/phishell.yml @@ -1,18 +1,7 @@ name: PhiShell on: - pull_request: - paths: - - "phishell/**" - - "docs/PHISHELL_*.md" - - ".github/workflows/phishell.yml" - push: - branches: - - main - paths: - - "phishell/**" - - "docs/PHISHELL_*.md" - - ".github/workflows/phishell.yml" + workflow_call: workflow_dispatch: permissions: @@ -31,7 +20,7 @@ jobs: node-version: "22" package-manager-cache: false - name: Install PhiShell dependencies - run: npm install --no-audit --no-fund + run: npm ci --no-audit --no-fund - name: Test PhiShell contracts run: npm test - name: Exercise read-only Linux host probe diff --git a/.github/workflows/release-qualification.yml b/.github/workflows/release-qualification.yml new file mode 100644 index 00000000..241067ba --- /dev/null +++ b/.github/workflows/release-qualification.yml @@ -0,0 +1,65 @@ +name: PhiOS qualification + +on: + pull_request: + push: + branches: [main] + tags: ['phios-linux-v*'] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: phios-qualification-${{ github.ref }} + cancel-in-progress: true + +jobs: + changes: + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + image: ${{ steps.scope.outputs.image }} + ui: ${{ steps.scope.outputs.ui }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + fetch-depth: 0 + persist-credentials: false + - id: scope + name: Determine required qualification from the complete local diff + run: python3 scripts/os_ci_gate.py plan + + python-tests: + needs: changes + uses: ./.github/workflows/ci.yml + + phishell: + needs: changes + if: ${{ needs.changes.outputs.ui == 'true' }} + uses: ./.github/workflows/phishell.yml + + normal-image: + needs: changes + if: ${{ needs.changes.outputs.image == 'true' }} + uses: ./.github/workflows/os-release-candidate.yml + + qa-image: + needs: changes + if: ${{ needs.changes.outputs.image == 'true' }} + uses: ./.github/workflows/linux-image.yml + + release-gate: + name: release-gate + if: ${{ always() }} + needs: [changes, python-tests, phishell, normal-image, qa-image] + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Require actual success for every requested job + env: + PHIOS_CI_NEEDS: ${{ toJSON(needs) }} + run: python3 scripts/os_ci_gate.py check diff --git a/README.md b/README.md index 8d48a43c..1c19c5ee 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,17 @@ platform, memory/ledger system, and constrained agent runtime built around one r The project is under active development and should be treated as **alpha software**. +The Python package release is separate from the Linux OS effort. The Linux target +is an unpublished x86_64 UEFI Arch-based Wayfire/PhiShell development preview. +The exact normal candidate passed VM live/installed boot, persistent data, +matched OS recovery and one restricted Linux proof effect. A separate QA image +passed bounded signed-package update/interruption tests. The desktop candidate +also passed virtual network/audio, manual PAM screen locking and session cleanup, +with all nine aggregate jobs green. Physical hardware, +the actual final signed transition, source/license delivery and public release +remain open; Secure Boot is unsupported. See the [OS release contract](docs/os/RELEASE_CONTRACT.md), +[exact evidence](docs/os/IMPLEMENTATION_STATUS.md) and [release handoff](docs/os/RELEASE_HANDOFF.md). + ## What PhiOS is PhiOS is designed for systems that can observe, reason, retrieve, plan, and act without diff --git a/build/build_iso.sh b/build/build_iso.sh index c36601de..38ef6b55 100755 --- a/build/build_iso.sh +++ b/build/build_iso.sh @@ -1,63 +1,17 @@ #!/usr/bin/env bash -set -e - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -PROFILE_DIR="$ROOT_DIR/build/archiso-profile" -DIST_DIR="$ROOT_DIR/dist" -WORK_DIR="$ROOT_DIR/build/work" -OUT_DIR="$ROOT_DIR/build/out" - -VERSION="$(python - <<'PY' -from phios import __version__ -print(__version__) -PY -)" -ISO_NAME="phios-v${VERSION}-x86_64.iso" - -echo "[1/6] Validating mkarchiso availability" -if ! command -v mkarchiso >/dev/null 2>&1; then - echo "Error: mkarchiso not found. Install archiso first." - exit 1 -fi - -echo "[2/6] Preparing profile directories" -mkdir -p "$PROFILE_DIR/airootfs/etc/skel/.config/waybar" "$PROFILE_DIR/airootfs/usr/share/pixmaps" "$DIST_DIR" - -echo "[3/6] Generating Wayfire/Waybar defaults" -python - <<'PY' -from pathlib import Path -from phios.desktop.waybar_config import WAYBAR_CSS, render_waybar_config -from phios.desktop.wayfire_config import WayfireConfigGenerator - -profile = Path("build/archiso-profile/airootfs/etc/skel/.config") -profile.mkdir(parents=True, exist_ok=True) -WayfireConfigGenerator().generate(str(profile / "wayfire.ini")) -waybar = profile / "waybar" -waybar.mkdir(parents=True, exist_ok=True) -(waybar / "config.jsonc").write_text(render_waybar_config(), encoding="utf-8") -(waybar / "style.css").write_text(WAYBAR_CSS, encoding="utf-8") -PY - -echo "[4/6] Writing default shell login bootstrap" -cat > "$PROFILE_DIR/airootfs/etc/skel/.bashrc" <<'BASHRC' -if command -v phi >/dev/null 2>&1; then - phi -fi -BASHRC - -if [[ -f "$ROOT_DIR/build/assets/phios-splash.png" ]]; then - cp "$ROOT_DIR/build/assets/phios-splash.png" "$PROFILE_DIR/airootfs/usr/share/pixmaps/phios-splash.png" || true -fi - -echo "[5/6] Building ISO via mkarchiso" -rm -rf "$WORK_DIR" "$OUT_DIR" -mkarchiso -v -w "$WORK_DIR" -o "$OUT_DIR" "$PROFILE_DIR" - -echo "[6/6] Finalizing artifact" -FOUND_ISO="$(find "$OUT_DIR" -maxdepth 1 -name '*.iso' | head -n 1)" -if [[ -z "$FOUND_ISO" ]]; then - echo "Error: mkarchiso completed but no ISO found." - exit 1 -fi -cp "$FOUND_ISO" "$DIST_DIR/$ISO_NAME" -echo "ISO ready: $DIST_DIR/$ISO_NAME" +set -euo pipefail +repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +command -v docker >/dev/null || { echo 'Docker is required for the isolated Arch image builder.' >&2; exit 1; } +command -v python3 >/dev/null || { echo 'Python 3 is required to read the release contract.' >&2; exit 1; } +git -C "$repo" diff --quiet HEAD -- phios phishell packaging build/build_iso.sh || { echo 'Commit candidate inputs before building an exact-source ISO.' >&2; exit 1; } +source_commit=$(git -C "$repo" rev-parse HEAD) +git_common=$(git -C "$repo" rev-parse --path-format=absolute --git-common-dir) +builder_image=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["builder_image"])' "$repo/packaging/linux/release.json") +mkdir -p "$repo/dist/linux" +docker pull "$builder_image" +docker image inspect "$builder_image" > "$repo/dist/linux/builder-image.json" +docker run --rm --privileged \ + -v "$repo:$repo:ro" -v "$git_common:$git_common:ro" \ + -v "$repo/dist/linux:/artifacts" -w "$repo" \ + -e PHIOS_SOURCE_COMMIT="$source_commit" -e PHIOS_OUTPUT_DIR=/artifacts \ + "$builder_image" bash packaging/linux/build-linux.sh diff --git a/docs/OPERATOR_AUTHORIZATION.md b/docs/OPERATOR_AUTHORIZATION.md new file mode 100644 index 00000000..2e0866f6 --- /dev/null +++ b/docs/OPERATOR_AUTHORIZATION.md @@ -0,0 +1,49 @@ +# Operator authorization boundary + +The PhiShell and GhostWalk HTTP surfaces expose observation and proposal +interfaces. POSTs to authorization-console `decisions`, `bindings`, and `leases` +return **403 operator_channel_required**, before parsing or calling a service. +A loopback address, a browser origin, or a PhiVessel session does not identify +an operator. Other HTTP writes require the exact loopback Host, JSON content +type, and a matching Origin when present; cross-site fetches are rejected. +These checks reduce browser request forgery; they do not authenticate agents. + +Install the Python package to obtain `phi-operator`, or run +`python -m phios.ghostwalk_operator` from the source checkout. Use the same +protected state root and policy environment as the host: + +```sh +phi-operator --state-root ~/.phios --target inspect +phi-operator --state-root ~/.phios --target decide APPROVE +phi-operator --state-root ~/.phios --target decide HOLD +phi-operator --state-root ~/.phios --target decide DENY +phi-operator --state-root ~/.phios --target bind +phi-operator --state-root ~/.phios --target lease +``` + +Each mutation displays the current normalized evidence as escaped JSON and +requires typing the action and full snapshot digest. There is no `--yes` or +unattended option. Cancellation does not mutate authority. Changed evidence +requires a new review, and the existing services still check their exact +request, previous decision, mapping, policy, enforcement and epoch hashes. +Approval does not create a binding or lease. The command never executes an +effect or mounts an executor. Refresh PhiShell after terminal operations. + +Without a valid trusted execution manifest, only inspection and decisions +are available. Binding and lease issuance currently require the supported +Windows desktop host. Linux previews must report this capability unavailable. +The CLI requires its manifest inside the protected state root, rejects +symlinked state, and on POSIX rejects state owned by another user or writable +by group/others. It does not silently repair existing permissions. + +## Trust and remaining release gates + +A TTY is an explicit interaction requirement, **not proof of human identity**. +A malicious process sharing the operator's OS account can create a pseudo-TTY, +import Python services, or edit that account's files. Run untrusted agents as +separate OS principals without access to operator state, terminal or desktop. +On Windows, protect the state with an owner-only ACL; this CLI does not attest +Windows ACLs. The Linux OS release remains held until principal separation, +broker authentication, concurrent writer safety and durable state recovery +have independent evidence. Do not describe this patch as universal human +authentication or whole-OS sandboxing. diff --git a/docs/RELEASE_SETUP.md b/docs/RELEASE_SETUP.md index 331b50f3..8dcf1108 100644 --- a/docs/RELEASE_SETUP.md +++ b/docs/RELEASE_SETUP.md @@ -20,9 +20,11 @@ No API token is needed. ## 3) Triggering releases -- Automatic: push/merge to `main` (per workflow). +- Automatic: push a `v*` tag matching the Python package version (per workflow). - Manual: use `workflow_dispatch` from Actions tab. +This workflow publishes Python wheels and source distributions, not an OS image. OS candidate tags use the separate `phios-linux-v` prefix and must not trigger PyPI publishing. + The pipeline runs tests, builds packages, publishes to PyPI via OIDC, generates release notes from `CHANGELOG.md`, and creates a GitHub Release. ## Security posture diff --git a/docs/os/BUILD_AND_QUALIFY.md b/docs/os/BUILD_AND_QUALIFY.md new file mode 100644 index 00000000..023f68c9 --- /dev/null +++ b/docs/os/BUILD_AND_QUALIFY.md @@ -0,0 +1,128 @@ +# Build and qualify the Linux development preview + +Use the always-triggered `PhiOS qualification` workflow. Its reusable +`Linux development image` job builds the separate QA artifact in a pinned +x86_64 Arch container, downgrades/synchronizes to the fixed Arch repository +snapshot in `packaging/linux/release.json`, checks the Archiso package version, +and builds the Python and UI packages from a hashed archive of the exact source +commit. Arch repository packages require signatures; the two local development +packages are unsigned and must not be presented as a signed public OS release. +`npm ci` uses the committed lockfile. No floating git checkout is used as source. + +The image profile is staged from the installed complete Archiso releng template +and keeps its UEFI and initramfs inputs. The staging step removes root autologin, +SSH, cloud-init and unrelated services. It selects a graphical session for the +non-root `phios` user, with no wheel membership. In this **volatile live preview** +the public login is `phios` / `phios`, and root is locked. Never reuse that login +for an installed system or place private data in this live image. The reserved +`phios-agent` account cannot read the operator home and runs no agent by default. + +The browser keeps Chromium's sandbox. The compositor's autostart imports its +Wayland environment before starting `phios-session.target`. Transport, curiosity +projection, optional history, browser and Waybar have separate user services. +Session exit stops the target. Default state is `%h/.local/state/phios` with +umask 0077. History is not auto-enabled: an operator must create and review +`~/.config/phios/memory.json` before that reader starts. Windows GhostWalk and +the curiosity authority broker are not started in this Linux preview. + +For a local build, from a committed source checkout on an x86_64 Docker host: + +```sh +bash build/build_iso.sh +# Or, after reviewing the privileged container build: +phi build iso --yes +``` + +The source mount is read-only; the privileged build runs inside the container, +with only `dist/linux` writable. It changes that container's pacman mirror, +never the host's mirror. The build must fail with a nonzero exit status if an +input, package install, UI build, profile assembly or mkarchiso step fails. +Do not run `packaging/linux/build-linux.sh` on a personal Arch installation: +it is the internal root-container entrypoint and rewrites its builder environment. + +## Evidence + +The Actions artifact includes the ISO, local packages, source archive/hash, +source commit, fixed release inputs, builder image identity, builder and image +package inventories, complete builder/Archiso logs, license history and SHA256SUMS. The CI-only +qualification fixture waits for the non-root compositor and browser, checks the +built page, native package observation and unified system state, verifies private state permissions, +and confirms all three approval HTTP routes return 403. QEMU runs with no +network and no target disk, using x64 UEFI firmware. The harness uses KVM when +the runner exposes it and records the selected accelerator; software TCG has +a longer explicit deadline. Wayfire permits software GLES rendering for this +virtual display, and its startup log remains in the private state directory. +The exact source marker, +ISO hash, VM command, serial log and screen capture are preserved, including a +display capture on failed qualification when QEMU is still running. The fixture +also kills the observer to verify supervised restart, ends the compositor to +verify service cleanup, and restarts greetd to prove a fresh graphical login. +The harness then resets the VM and requires the complete fixture on a second, +distinct kernel boot ID. Both desktop captures are preserved. This fixture +is omitted from normal locally built previews. + +A fixture pass is evidence for the checks it performs. Review the screenshot +and session behavior. It does not prove installation, persisted receipts, +crash recovery, whole-OS updates, hardware compatibility or a Linux effect +executor. Those remain explicit gates in RELEASE_CONTRACT.md. CI never tags, +signs, publishes or automatically promotes this candidate. The later installed +and normal-image gates have their own scopes and receipts in IMPLEMENTATION_STATUS.md. + +## Always-reported qualification gate + +`release-qualification.yml` runs for every pull request, every main push, +OS `phios-linux-v*` tag and manual invocation. It calls the existing Python, +PhiShell, normal image and QA image workflows from the same source revision; +it does not poll or borrow another commit's successful runs. The called +workflows retain independent manual entrypoints and their existing tests and +artifact retention. Automatic calls are centralized to avoid duplicate builds. + +Python tests, installed wheel, native vector and ledger-report checks always +run. Only a complete observed documentation-only PR may omit the expensive +image jobs. PhiShell contract docs still request UI checks. Unknown files, +deleted runtime files, build/test/workflow inputs, unreadable diff, main pushes, +OS tags and manual runs require both images and UI. The classifier uses the +complete local Git trees, including deletions, without an API pagination or +300-file workflow-path cutoff. + +The final job is named **`release-gate`**, with `if: always()`. It fails when +scope determination fails, any required result is missing/failed/cancelled/ +skipped, or scope outputs disagree. A skipped image is acceptable only when +explicitly unrequested for that documentation-only PR; this is not a new image +qualification. The job reports `release_ready: false` and no publication authority. +All jobs have read-only contents permissions and inherit no release secrets. + +After reviewing this change and observing a successful run, the maintainer +should configure **`release-gate`** from GitHub Actions as the required status +on protected main and the applicable release rules. Require current-branch +checks and review, restrict bypass/force push/deletion and protect the OS tag +namespace as appropriate to the chosen release ownership. Those repository +settings are not changed by a workflow commit. A green aggregate does not +replace hardware evidence, authentic signing, final transition qualification, +source/license delivery or explicit release authorization. + +Configure the requirement against the complete integration candidate containing +this controller after its same-source run passes. Earlier component heads +predate the controller and cannot emit `release-gate`; they are review references +for the integration. The complete candidate repeated all nine jobs in run +36823086807, including exact normal live/install/recovery, restricted virtual +DHCP/audio and actual PAM locking, plus the separate signed-update QA cases. +See RELEASE_HANDOFF.md and `evidence/qualification-gate-a7bcd986.json` for exact +identities, verified compact hashes, preserved failures and remaining gates. + +## Retained retries and compact review metadata + +Normal and QA artifact names include both the run ID and attempt number. A +same-source failed-job retry preserves earlier failure artifacts rather than +colliding with or overwriting them. Display conversion imports Pillow only when +actual PPM captures exist, so an early builder/download failure retains its +original error without an unrelated missing-Pillow cleanup exception. + +An always-run bounded metadata step emits the actual receipt JSON (without VM +command arrays), source identity, inventory counts and small-file hashes to CI +logs. It cross-checks report source identities against this run's checked-out +source and preserves failed receipts as failures. These are producer metadata, +not an independent archive download verification or publication authority. +Use the emitted metadata when a review host cannot extract the compact archive; +record that limitation explicitly. Exact VM and aggregate assertions still +must pass, and every attempt retains its own source/artifact identity. diff --git a/docs/os/DESKTOP_OPERATION.md b/docs/os/DESKTOP_OPERATION.md new file mode 100644 index 00000000..7195c9be --- /dev/null +++ b/docs/os/DESKTOP_OPERATION.md @@ -0,0 +1,134 @@ +# Experimental desktop operation + +The candidate adds NetworkManager, a user PipeWire/WirePlumber audio stack, +Wayfire session locking and a non-root graphical PolicyKit authentication agent. +These are ordinary Linux desktop/administration paths. They do not create PhiOS +operator decisions, bindings or leases and do not authorize an agent or browser +to perform a general desktop effect. The restricted installed proof broker and +its UID separation remain described in LINUX_PROOF_WORKFLOW.md. + +## Open, lock and end the session + +| Action | Current path | +| --- | --- | +| PhiOS terminal | Super+Enter | +| Ordinary Linux terminal | Super+Alt+Enter | +| Application launcher | Super+Space | +| PhiShell window | Super+P | +| Lock current Wayfire session | Super+L or the `Lock PhiOS session` launcher entry | +| Network settings | Super+N or the `Network settings` launcher entry | +| Logout | From the ordinary desktop terminal, `loginctl terminate-session "$XDG_SESSION_ID"`; the supervised session target stops | +| Restart / shutdown | `systemctl reboot` / `systemctl poweroff`, under ordinary logind/PolicyKit permission | + +`phios-lock` runs the packaged swaylock under the current non-root Wayfire +session. Wayfire's session-lock plugin supplies the protocol; swaylock waits for +the compositor's locked acknowledgement before its daemonizing caller returns. +Unlock uses the current account's ordinary PAM password. The volatile live +password is public `phios`; installed users keep the fresh password they chose. +Root/headless invocation is refused. Automatic idle/suspend locking is not +enabled by this candidate; lock explicitly before a suspend test with +`phios-lock && systemctl suspend`, then observe the actual resume/unlock. +Suspend remains a physical hardware gate. No protection +against arbitrary root or malicious same-UID administrator code is inferred. + +For deliberate ordinary administration, use the terminal's normal +password-authenticated sudo account on an installed system. The live account +retains only its narrow maintenance sudo commands. The graphical PolicyKit agent +uses the distribution's existing policies and PAM; it changes no policy to make +the live user an administrator or to bypass an authentication request. Its startup +is tested separately from any future specific graphical administration operation. + +## Wired and wireless configuration + +NetworkManager owns wired and Wi-Fi address/DNS configuration; systemd-resolved +provides the resolver. A second networkd/iwd configuration owner is not enabled. +NetworkManager's HTTP connectivity URL polling is explicitly disabled. Connect +a wired cable and inspect `nmcli device status`. The terminal interface is +`nmtui`; account or system-wide changes may require normal administrator +authentication. A driver/radio must actually exist before Wi-Fi can work. + +For a user-private Wi-Fi connection from the real desktop terminal: + +```sh +nmcli device wifi list +nmcli --ask device wifi connect 'YOUR_SSID' private yes +``` + +Replace the SSID. `--ask` prompts for credentials instead of placing a password +in arguments/history. Connection files belong to NetworkManager's protected +system store with their selected user permissions; they are outside PhiOS's +data-only backup. The live overlay is volatile. Matched root checkpoints include +installed system configuration, so a deliberate root restore also restores its +network profiles. Record hardware/DHCP/DNS results without publishing personal +SSID, passwords, MAC/IP details or private connection files. + +## User audio + +`phios-audio.target` starts PipeWire, its PulseAudio compatibility server, +WirePlumber and their sockets as the desktop user. The session stops these units +on logout and starts them again on reauthentication. No root audio daemon or +automatic microphone recording is added. Inspect actual devices/streams with +`wpctl status`; adjust the observed default output with `wpctl`, for example: + +```sh +wpctl set-volume @DEFAULT_AUDIO_SINK@ 50% +wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle +``` + +An unavailable output/microphone remains unavailable. Actual playback/capture, +device choice, mute/volume, HDMI/USB and suspend/resume on the named physical +machine are separate hardware tests. + +## Candidate qualification scope + +The new exact normal live gate attaches only a restricted QEMU user-network +Ethernet device on the documentation range `192.0.2.0/24`, without port forwarding, +and an emulated HDA device with a null audio backend. It checks the actual DHCP +address/server and the absence of an IPv4 gateway/DNS advertisement in this +restricted network, non-root service/process ownership and actual +PCM playback through the emulated ALSA sink. This does not test Internet DNS, +Wi-Fi association, physical speakers/microphones or a GPU driver. + +The external QMP test invokes the actual Super+L binding, observes the lock, +tries a wrong password, then unlocks with the real public disposable PAM +credential. The installed lane repeats with the installer-created account's +fresh test password. Tests preserve lock/refusal/unlock screenshots, exact +source/ISO and serial evidence. The installed/update/recovery VM retains no NIC, +host disk, host audio device or shared folders. + +The first normal attempt rejected the probe's incorrect expectation of gateway +and DNS DHCP options. libslirp deliberately omits both in restricted mode; the +corrected probe requires their absence and the actual lease/server. The failed +image/source, serial log and screenshot hashes are retained in +`evidence/desktop-attempts.json`. The installed signed QA lane passed its added +audio and PAM lock checks, but that does not qualify the failed normal image. +The second normal attempt captured the correct lease and isolation, then failed +because nmcli joined its DHCP options on one line. The corrected parser accepts +the observed joined/line forms while retaining exact unique server identity; +captured-output regression tests reject static, wrong, duplicate and forwarding +configurations. Service checks require each named unit individually; the live +lifecycle requires all session/audio/socket units inactive at logout and repeats +actual service/audio/network checks after graphical reauthentication. + +The complete added VM qualification passed in +[run 36823086807](https://github.com/MichaelWave369/PhiOS/actions/runs/36823086807) +for source `a7bcd9863eea12a87c1a9ef1fcbd26211542cd91`. The exact normal ISO passed +two distinct live boots with four service/audio/DHCP observations, 13 inactive +units at each logout, two real live PAM lock/refusal/unlock checks, and three +installed no-ISO boots with audio, installed PAM locking, data/proof and matched +recovery. The separate QA artifact repeated installed audio/locking and its +ephemeral signed-package/refusal/interruption/recovery cases. The aggregate gate +and all nine jobs passed, with 2,287 Python tests and six existing optional skips. +The exact file/image/source/archive hashes and bounds are in +`evidence/desktop-normal-a7bcd986.json`, `desktop-signed-a7bcd986.json` and +`qualification-gate-a7bcd986.json`. Wrong-password and recovered/failed-boot +screenshots were inspected. Earlier artifacts retain their earlier scopes; +later integration or publication bytes require their own qualification. +Physical hardware, the actual final signed transition and distribution delivery +remain open. A PolicyKit agent's startup is not a specific GUI administrator test. + +Upstream references: [Wayfire configuration](https://github.com/WayfireWM/wayfire/blob/master/wayfire.ini), +[swaylock](https://github.com/swaywm/swaylock), +[NetworkManager/nmcli](https://www.networkmanager.dev/docs/api/latest/nmcli.html), +[WirePlumber](https://pipewire.pages.freedesktop.org/wireplumber/daemon/running.html), +[libslirp DHCP implementation](https://qemu.googlesource.com/libslirp/+/refs/heads/master/src/bootp.c). diff --git a/docs/os/HARDWARE_QUALIFICATION.md b/docs/os/HARDWARE_QUALIFICATION.md new file mode 100644 index 00000000..5b612e3d --- /dev/null +++ b/docs/os/HARDWARE_QUALIFICATION.md @@ -0,0 +1,82 @@ +# Named hardware qualification handoff + +The proposed first physical target is Mikey's Windows 11 Skytech desktop: +Core Ultra 9 285K, RTX 5070 12 GB and 32 GB DDR5. These are supplied candidate +details, not observed Linux compatibility. No physical hardware is qualified. +The successful QEMU tests use software rendering and provide no evidence for +this GPU, motherboard firmware, audio, network radios or physical power loss. + +| Target | Current evidence | Gate | +| --- | --- | --- | +| Disposable x64 UEFI/KVM VM, 2 CPUs, 4 GiB RAM, 32-GiB disk | Exact normal live/install/data/recovery/Linux proof, virtual DHCP/audio and manual PAM locking passed in 36823086807; separate ephemeral signed-update/interruption QA passed in the same source run | Future final artifact and actual signed release transition must be qualified separately | +| Supplied Skytech/Core Ultra 9/RTX 5070 machine | No boot or driver observations | Live boot, GPU/input/network/audio/firmware tests first | +| Dedicated empty physical test disk | No selected disk or test | Exact installer identity/blankness/confirmation, no-media boot, persistence, update and recovery | + +## Exact candidate first + +Use only the normal image from the **Fixture-free OS candidate (unpublished)** +workflow, after its exact source/ISO receipt passes. Do not use the separate +QA image containing disposable test credentials/services. These images are +unsigned unpublished previews, not supported installers. Verify the downloaded +ISO against its exact `SHA256SUMS`, provenance and recorded qualification +receipt before preparing removable media. On Windows: + +```powershell +(Get-FileHash .\phios-linux-0.1.0-alpha.1-x86_64.iso -Algorithm SHA256).Hash.ToLowerInvariant() +``` + +Compare the complete digest, not a filename or another build's successful test. +The first physical gate is a live removable-media boot with no installation. +Document actual firmware configuration, UEFI mode and Secure Boot status; this +candidate does not support Secure Boot or BIOS. Preserve the existing Windows +installation and its independent backup. A hardware installation test requires +a separately identified dedicated empty disk; the current installer does not +support dual boot, partition reuse or preserving contents on its target. + +## Observations and manual results + +Inside the exact normal live image, run as the ordinary user: + +```bash +phios-hardware-report --iso-sha256 VERIFIED_ISO_SHA256 > hardware-observation.json +``` + +Replace the placeholder. The collector reads public source/kernel/UEFI, +board/firmware, PCI IDs/bound drivers and audio-card count. It performs no +effects, probes no credentials and records no hostname, account name, disk +serial, MAC/IP address, Wi-Fi SSID or user-state content. It marks the supplied +ISO hash as supplied, because it does not independently read the downloaded +ISO bytes. Absence of virtualization detection does not prove physical hardware. +All compatibility results remain `not tested` until actual observations exist. +The live home is temporary; retain this report and the manual results separately +before rebooting. The collector expects the full lowercase ISO digest displayed +by the PowerShell command above. + +Record pass/fail/not available with evidence for resolution/rendering and +multiple displays; keyboard/mouse/keymap; wired networking and Wi-Fi association, +DHCP/DNS; audio playback/recording; manual locking, wrong-password hold and PAM +unlock; sleep/resume; shutdown/restart; and storage +visibility. Record missing drivers and services honestly. The later desktop +candidate adds NetworkManager, user audio and manual PAM locking; its new +software/VM scope is recorded in DESKTOP_OPERATION.md. Physical audio and Wi-Fi +remain unqualified until actual observations exist. A blank +audio-card count or successful PCI enumeration is not audio/GPU compatibility. +Resolve observed blockers, build a new exact candidate and repeat affected +tests before moving to installation. + +Only after choosing a dedicated empty test disk should the operator review the +production installer plan and explicit confirmation described in INSTALLATION.md. +Then prove password-authenticated no-media boots, acknowledged canonical data +after restart, separate verified data-only backup, the actual signed target +transition, interrupted update, matched live-media recovery, preserved data and +inactive old authority. Physical power-loss testing is a separate storage gate, +not implied by terminating QEMU. Preserve failures and identify the exact +machine, source, ISO and transition; do not infer a supported hardware family. + +## Release holds + +Hardware results, the independently authenticated maintainer release public key +and full fingerprint, actual signed final transition, and third-party source/ +license delivery review are still missing. RELEASE_ARTIFACTS.md describes the +remaining signing/publication gates. No release key is generated on behalf of +the maintainer and no test key becomes a release identity. diff --git a/docs/os/IMPLEMENTATION_STATUS.md b/docs/os/IMPLEMENTATION_STATUS.md new file mode 100644 index 00000000..f337c726 --- /dev/null +++ b/docs/os/IMPLEMENTATION_STATUS.md @@ -0,0 +1,143 @@ +# Linux OS implementation register + +Controlling input: the operator-approved *PhiOS OS Release Audit and Plan*, +2026-09-30, SHA-256 `aba53c05f18ac2f874236a1b6566b74096eabff9422e9e0fee0b5da54b54a676`, audited source `dad7a7d7cd53874926ad366f19d3fc0fa6b99a49`. +This register tracks candidate implementation, not permission to publish or +proof that PhiOS is a completed OS. Preserve the repository AGENTS.md rules. + +| Requirement | Candidate change | Evidence / remaining gate | +| --- | --- | --- | +| R1: HTTP callers cannot mint operator authority | Decision, binding and lease POSTs held; explicit terminal review | HTTP rejection, cancellation and stale-review tests; installed UID-separated fixed proof passed. Arbitrary same-UID administrator isolation is outside this claim; Windows qualification remains separate | +| R2: Freeze a truthful Linux release contract | Candidate contract and generated metadata corrected | docs/os/RELEASE_CONTRACT.md and packaging/linux/release.json; Python and OS release tracks separate | +| R3: Install current Python and UI packages | Current-source PKGBUILDs, JS lock, native pacman adapter, NetworkManager and user audio/PAM lock stack | Exact normal and QA image package/install gates passed in 36823086807; signed pinned upstream inputs; local development packages remain unsigned | +| R4: Real non-root graphical login and supervised services | Wayfire and user services, audio/session cleanup, manual PAM lock and ordinary PolicyKit agent | 36823086807 passed live/installed PAM desktop, sidecar restart, all 13 units inactive at logout, service/audio/network reauthentication and lock/wrong/correct-password cases; physical and specific graphical administration tests remain separate | +| R5: Produce and UEFI boot exact live ISO | Isolated Archiso/QEMU workflow | Exact normal source/tree/ISO hashes in desktop-normal-a7bcd986.json; two distinct live boots and three no-ISO installed boots passed; no physical support inference | +| R6: Recover durable private state | Locking/sync, transactional outbox and data-only recovery | Contention, interruption, backup/restore and schema refusal tests; installed acknowledged state survived abrupt VM restart in 36798467774; physical power-loss qualification pending | +| R7: Explicit blank-disk installation | Experimental root-owned offline CLI and disposable qualification lane | 20 local refusal/cancellation/identity tests; cancellation, actual installation, no-ISO desktop boot and fresh data restoration passed on the named disposable VM; hardware beta pending | +| R8: Whole-OS update and recovery | Explicit public-key enrollment, signed verifier, staged package application and matched root/EFI checkpoints | Full 2,218-test CI and bounded end-to-end VM run 36805999628 passed: valid update, invalid/cancelled/replayed/dependency refusal, abrupt termination during a real package hook, unchanged active system, deliberate kernel boot failure, matched live recovery and three password-authenticated disk-only boots; arbitrary transitions and hardware remain unqualified | +| R9: Qualify hardware and one Linux governed workflow | UID-separated installed-only proof-note broker, canonical bound single-use lease, independent protected ledger and read-only hardware collector/protocol | 21 focused tests and actual sudo/PAM/UID 1001 proof, cancellation, denial, replay, expiry and historical-authority refusal after restart/recovery passed on the exact normal ISO in run 36812104386; supplied Skytech target remains physically unqualified | +| R10: Sign and publish the exact qualified artifact | Actual native/Python/npm and bundled frontend inventory, supplier notices, CycloneDX SBOM and exact source/ISO/artifact provenance | 11 focused inventory/refusal tests, pinned CycloneDX schema validation and exact fixture-free live/install/state/recovery VM qualification passed in run 36812104386; final signed transition, hardware, source/license delivery, release identity and publication remain held | + +## Latest desktop and aggregate qualification + +[Run 36823086807](https://github.com/MichaelWave369/PhiOS/actions/runs/36823086807) +passed all nine jobs for source `a7bcd9863eea12a87c1a9ef1fcbd26211542cd91`, +the same tree as reviewed code head `9c98475274442595c59370113b9c1e0dee595ec9`. +Full Python CI passed 2,287 tests with six existing optional skips, Ruff and +mypy (304 source files); wheel/vector/ledger/PhiShell jobs passed. The normal +ISO repeated installed data/proof/recovery and added restricted DHCP, synthetic +HDA/user PCM, non-root PolicyKit startup, actual Super+L and PAM password +refusal/unlock, complete session shutdown and audio/network reauthentication. +The separate QA artifact repeated signed-package/refusal/interruption/recovery +with an ephemeral test signer and its own different ISO. + +`evidence/qualification-gate-a7bcd986.json` links the normal and signed receipts +and their hashes. The normal inventory has 501 components and 746 captured +notice files; the QA inventory has 502 components. Both compact archive hashes, +15 checksum payloads per archive and available provenance sidecars were checked. +Actual lock/refusal, restored desktop and failed-kernel-boot screenshots were +inspected. Large payload hashes remain the producer's hashes; the ISO/source/ +package/notice archives were not redownloaded into the review host. The earlier +failed DHCP expectations, captured nmcli parsing regression, Arch download +failure and aggregate holds remain in `evidence/desktop-attempts.json`. + +Later integration/documentation/main/tag identities require their own checks. +The complete main-targeted integration includes the qualification controller; +earlier component heads predate that status and remain focused review references. +Physical hardware, the actual authenticated maintainer-signed transition, +source/license delivery, repository protection and publication remain open. +`release_ready` and publication authority remain false. + +## First builder handoff + +The approval boundary is a bounded candidate repair. Core normalized +contracts, adapter selection, advisory rollout behavior and private PhiKernel +internals remain untouched. Existing terminal services perform each stage +separately; no capability payload or lease lifetime is selected by the CLI. + +Focused security tests and Python lint/type checks are required before review. +The full existing suite must also run in GitHub CI: the local execution host +restricts AF_UNIX, network enumeration and bubblewrap preflight. Environment +failures must be preserved and reported separately, never silently skipped to +claim a pass. Reviewers should rerun the boundary tests and assess the stated +same-user trust limitation before merging. Later milestones must update this +register with actual artifact identities and evidence, rather than readiness +percentages or forecast dates. + +Validation: 73 focused Python tests passed; Ruff and mypy (301 source files) passed. PhiShell production build and 12 targeted HTTP boundary/proposal tests passed. Full PhiShell TypeScript suite passed; three existing Node integration tests fail on this host due to restricted network enumeration and absent systemd, as recorded in the audit. GitHub CI remains the required full-platform check. + +## Linux foundation handoff + +The candidate implements release-contract, package, session and live-image build milestones. 85 focused Python release/desktop/profile tests, lint and types pass locally. PhiShell build and the Arch inventory/security transport tests pass. Image run [36786368318](https://github.com/MichaelWave369/PhiOS/actions/runs/36786368318) qualified the live lifecycle for source `5339f180ad9f8dbac11906c5e962728f80853e91`, ISO SHA-256 `5f3eacd5ce24c6cb8ea0067aad23054f5ca33caa146c5600eb4d625942c049ca`. Root autologin and unrelated releng services are removed. The CI-only qualification fixture is excluded from normal local previews. + +## Installed VM evidence + +Image run [36798467774](https://github.com/MichaelWave369/PhiOS/actions/runs/36798467774) passed for source `0253b6e0fb27251fe2da37b6d8c1e31245a64290`, ISO SHA-256 `8599bbc7ff2ed35432bae23692464d4d5afa9ffdfc787699a7be88f2cfc62f5c`. A newly created 32-GiB disk, serial `PHIOS_CI_BLANK`, was the only target. The VM had x64 UEFI/KVM, two CPUs, 4 GiB RAM, no network or shared folders, and no attached host disk. Cancellation preserved the blank target; production installation, normal password/PAM and greetd logins, the actual Wayfire/PhiShell desktop, verified backup/fresh restore, and acknowledged state after abrupt virtual restart passed. Installed boot IDs were `e5ba8528af464b8192312d9aab0db869` and `caa9695c41c64c3d898e12c1bd3234f5`. + +Evidence receipt: `docs/os/evidence/installation-0253b6e0.json`. [Reviewable logs and screenshots](https://github.com/MichaelWave369/PhiOS/actions/runs/36798467774/artifacts/11135321615) and [unsigned image/packages](https://github.com/MichaelWave369/PhiOS/actions/runs/36798467774/artifacts/11134958214) expire 2026-10-08 under the seven-day CI retention policy. CI-only serial-console injection and public disposable credentials are recorded; they are excluded from normal installations. The screenshot was visually inspected. Ordinary CI runs 36798467750 and 36798463744 also passed for installer head `f135a24d3d88173f611829317e4ad04ebc22eff3`. + +These are bounded VM qualifications. Later update/recovery and Linux proof qualifications are recorded below. Physical power loss, named hardware support and signed public release remain held. No adapter is promoted and no publication authority follows from the receipts. + +## Signed update and matched recovery VM evidence + +Image run [36805999628](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999628) passed for source `29def30a3079c99972f1606ae44ea3478d0f79d1`, ISO SHA-256 `391efdfd41e0217706b2b4028c47e9d37f7014762afc5d6831a30eb6bb2dba4b`. The disposable 32-GiB disk, two CPUs, 4 GiB RAM, UEFI/KVM, no network/host disks/shared folders and CI-only fixture bounds are unchanged. Production public-key enrollment cancellation and acceptance passed with an ephemeral test key. A real signed package was installed; missing/wrong-key/tampered/expired/replayed bundles, cancellation and a real dependency failure were refused. Abrupt termination occurred inside a real pacman installation hook; a second live boot verified the retained interrupted stage and unchanged active root, EFI and counter. + +Three distinct password/PAM and greetd disk-only desktop boots passed. After deliberate default/fallback initramfs corruption, the kernel actually panicked because it could not mount its root. Explicit live-media recovery restored the matched root/EFI checkpoint, removed the added test package and rolled-back signing trust, advanced the independent generation to two, and preserved the canonical data/acknowledged receipt hash. Root/EFI switching remains non-atomic. The successful added-package fixture does not qualify arbitrary kernel upgrades or an actual future signed release transition. + +Receipt: `docs/os/evidence/recovery-29def30a.json`. [Logs/screenshots](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999628/artifacts/11137448503) and [unsigned QA image/packages](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999628/artifacts/11137807998) expire 2026-10-08. The recovered desktop screenshot was visually inspected. Ordinary CI [36805999618](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999618) passed 2,218 tests with six existing optional skips, including eight actual signature/expiry/revocation cases and four actual enrollment cases. All four prior failures remain in `docs/os/evidence/recovery-attempts.json`. Later exact normal-image evidence is below; physical hardware, the final signed transition, source/license delivery and maintainer signing/publication remain held. + +## Exact normal-image and Linux workflow qualification + +[Run 36812104386](https://github.com/MichaelWave369/PhiOS/actions/runs/36812104386) +passed for checked-out source `5145b4dabd0e70d4b8d35691041a4d9f797affe9`, +ISO SHA-256 `e60b64623a0008b27439f98eacd22cc9d4e0ce714d4b7b8684276f425988349b`. +This prospective PR merge commit has the same tree as reviewed branch head +`0ea1fced470abf75701a4cad8f806551078b1b76`. This is the normal image, with no +image QA fixtures, test package, enrolled PhiOS trust or installed live password. +The external probes run through ordinary terminals and are excluded from the ISO. + +Two distinct live boots passed normal PAM/greetd login, actual non-root desktop +and observations, sidecar restart, logout cleanup and reauthentication. The same +ISO then passed cancellation and blank-disk installation through the public live +user's narrow maintenance sudo. The installer explicitly reviewed its standard +serial password/PAM option; there was no privileged console injection. Three +distinct disk-only PAM/greetd desktop boots passed canonical data/backup/fresh +restore, acknowledged data after abrupt VM termination, deliberate default and +fallback initramfs failure, actual failed boot and matched root/EFI recovery +through the same normal live image. Root/EFI recovery remains non-atomic. + +The actual installed UID 1001 proposer and password-authenticated UID 1000 +operator passed protected-store/broker permission denial, cancellation, exact +single-use approval/binding/lease, one fixed 57-byte note and independent readback, +replay refusal and real expiry. Old approvals remained inactive after reboot and +matched OS recovery. This qualifies only the fixed broker effect, not generic +desktop automation, malicious administrator/root isolation or Windows Ghost Walk. + +The actual final image inventories contain 386 native, 39 Python, 12 installed +npm and four bundled frontend origin records: 441 CycloneDX components. Bundled +React, ReactDOM, Scheduler and Vite's injected helper are included, even when +already represented by a separate installed origin. There are 620 captured +supplier notice files. Labels/notices do not establish source/license compliance. + +Receipt: `docs/os/evidence/normal-installed-5145b4da.json`. +[Unsigned exact normal image and payloads](https://github.com/MichaelWave369/PhiOS/actions/runs/36812104386/artifacts/11140626238) +and [compact logs/screenshots/inventories](https://github.com/MichaelWave369/PhiOS/actions/runs/36812104386/artifacts/11140895800) +expire 2026-10-08. The recovered desktop screenshot was visually inspected; +downloaded compact payload hashes were checked against provenance and SHA256SUMS. +The large ISO/source/package archives were not downloaded again into the review +host; their hashes are the producer's recorded hashes. + +The separate QA [run 36812104411](https://github.com/MichaelWave369/PhiOS/actions/runs/36812104411) +also passed the signed-package addition/refusals/interruption and matched recovery +at the same source, with ephemeral test identity and its own different ISO hash. +Receipt: `docs/os/evidence/signed-proof-5145b4da.json`. Its qualification cannot +substitute for a real future maintainer-signed transition on the normal artifact. +Ordinary [CI 36812078517](https://github.com/MichaelWave369/PhiOS/actions/runs/36812078517) +passed 2,250 tests with six existing optional skips, Ruff and mypy (304 source +files); PhiShell CI also passed. The previous schema-validator and external +probe failures remain in `fixture-free-attempts.json` and `linux-proof-attempts.json`. + +These receipts identify tested bytes, not every later documentation commit or +final merge/tag. Requalify the final publication source and signed transition. +See RELEASE_HANDOFF.md for the ordered review and remaining physical/signing/ +source-delivery work. `release_ready` remains false. diff --git a/docs/os/INSTALLATION.md b/docs/os/INSTALLATION.md new file mode 100644 index 00000000..c3d9d56d --- /dev/null +++ b/docs/os/INSTALLATION.md @@ -0,0 +1,149 @@ +# Experimental blank-disk installation + +The candidate manual installer is `phios-install`, packaged behind a root-owned +isolated Python launcher. The disposable installed-image gate passed in +[run 36798467774](https://github.com/MichaelWave369/PhiOS/actions/runs/36798467774). +This remains an experimental development installation; a hardware-supported beta additionally +requires update/recovery and the declared hardware matrix. Keep the verified +live media available. An installed filesystem alone is not a completed OS +release. + +## Scope + +Supported candidate shape: x86_64, x64 UEFI with Secure Boot disabled, one +canonical disk with a stable serial/WWN, at least 16 GiB, no partitions, +mounts, swap, holders, slaves or recognized signatures. Before installation +the tool reads every byte and requires zeroed contents, including unsigned data +that has no filesystem signature. This can take time on large hardware. +Existing data is refused. There is no automatic disk selection, erase-existing +option, unattended mode, HTTP installer or confirmation bypass. + +The layout is a 1 GiB FAT32 ESP and a Btrfs filesystem with separate `@root`, +`@home`, `@log` and `@snapshots` subvolumes. Installation is unencrypted and has +no swap/hibernation setup. Btrfs subvolumes prepare a recovery layout; they do +not by themselves implement OS rollback or protect against drive failure. +BIOS, dual boot, Secure Boot, disk encryption, RAID, existing partitions and +storage migration are held. + +## Review and install + +Boot the configured PhiOS live preview. Open Foot and inspect the real disks: + +```sh +lsblk --bytes --paths --output NAME,TYPE,SIZE,MODEL,SERIAL,WWN,MOUNTPOINTS +``` + +Replace both placeholders below with a reviewed canonical path and a new +lowercase account name. `--plan` performs read-only inventory and reports the +source, disk, account, hostname, unencrypted layout and held release status: + +```sh +sudo phios-install --disk /dev/DEVICE --username YOURNAME --plan +sudo phios-install --disk /dev/DEVICE --username YOURNAME +``` + +The public volatile `phios` account can invoke this one interactive installer +through sudo; it receives no general passwordless root shell. Root/TTY checks +do not prove a human or isolate a malicious same-user process. The supported +custody boundary is the operator-controlled live boot and reviewed device. + +The tool validates the target, checks zeroed contents, requests a fresh password +(at least 12 characters), and displays a confirmation containing the exact +device path and SHA-256 of the complete reviewed plan. Type that full phrase +or cancel. A wrong phrase, EOF or cancellation before the first disk command +does not change the disk. The disk inventory and zeroed contents are rechecked +after confirmation; stale identity is held. Passwords are passed through stdin +only, never argv, logs or receipts. + +The first destructive command creates GPT on the selected empty disk. The tool +copies the immutable live squashfs, never the current live overlay or another +user's state. It creates a fresh account and private state, locks root, removes +live credentials/autologin/test fixtures, installs a normal greetd/PAM login, +generates an installed initramfs and installs systemd-boot's fallback loader. +It leaves firmware boot variables/order unchanged. Select the installed disk +in firmware if needed. The live password is never installed as an account +credential. + +Installed package repositories remain on the signed pinned Arch snapshot. +The transient unsigned local build repository is removed. A supported PhiOS +package update channel and signed OS publication are separate pending gates; +do not change mirrors or perform partial package upgrades to imply a supported +update policy. + +## Failure and first boot + +The tool preserves private stage/error evidence under `/run/phios-install-*`. +After disk writes begin, failure does not undo a partial installation or make +the disk blank again. Preserve the evidence off volatile media, inspect the +reported stage and mounts, and recover deliberately. A cleanup failure reports +remaining mounts and returns nonzero; do not reboot while cleanup is held. +There is no implicit retry or automatic wiping of failed targets. + +Successful installation writes `/var/lib/phios/install-receipt.json` with exact +source, target identity and filesystem UUIDs. `release_ready` remains false and +installed boot remains unqualified until observed. Remove the ISO, boot the +disk, authenticate the new account and verify Wayfire/PhiShell, private memory +state, package observations and services. Optional memory configuration stays +disabled unless the operator explicitly enables it. See STATE_RECOVERY.md for +data-only migration and backup; authority is never imported from the live +session. + +## Disposable qualification + +The CI lane creates a new 32 GiB qcow2 image with serial `PHIOS_CI_BLANK`; its +driver accepts no existing image or host device. Networking and shared folders +are absent. A root qualification fixture exists only in the CI live profile +and refuses any other target. It drives the same production CLI through a PTY, +first cancels and checks the disk, then types the exact reviewed confirmation. + +The fixture seeds a zero-authority canonical memory record and verified backup +as the new user, confirms removal of live credentials/test fixtures/autologin, +and injects a serial console solely into the disposable installed test target. +The host then boots without the ISO, authenticates through normal password/PAM +login, types credentials at the real greetd greeter, observes the non-root +desktop/services, restores data into a fresh root, and checks an acknowledged +write again after an abrupt virtual restart. Serial-console injection is +recorded in the receipt; no installed automatic login is introduced. Exact +ISO/source hashes, serial logs, boot IDs and screenshots accompany success or +failure. A VM restart is not hardware power-loss qualification. + +The qualified source is `0253b6e0fb27251fe2da37b6d8c1e31245a64290`; ISO SHA-256 +is `8599bbc7ff2ed35432bae23692464d4d5afa9ffdfc787699a7be88f2cfc62f5c`. +The exact receipt and evidence identities are in +`docs/os/evidence/installation-0253b6e0.json`. CI credentials +are public test-only values; normal local profiles and production installs +contain neither the fixture nor those credentials. + +References: [bootctl](https://man.archlinux.org/man/bootctl.1.en), +[lsblk](https://man.archlinux.org/man/lsblk.8.en), +[wipefs](https://man.archlinux.org/man/wipefs.8.en), +[Btrfs subvolumes](https://btrfs.readthedocs.io/en/latest/btrfs-subvolume.html). + +## Explicit serial password login and normal-image gate + +`--serial-console` is an optional installer setting, default off. It appears as +`serial_console_password_login` in the reviewed plan and changes its full +confirmation digest. When explicitly selected, both boot entries log to tty0 +and ttyS0 at 115200 baud, and ttyS0 uses the standard password/PAM getty. It +creates no root or account autologin and changes no sudo permissions. This is +useful for serial administration and reviewable isolated VM diagnostics. + +The fixture-free candidate workflow now installs the exact normal ISO through +the public live user's limited production sudo commands. Its external test +program runs in live RAM after real phios/phios PAM login; no test service or +root console is added to the image. It explicitly selects serial password +login in the production installer review, cancels first, completes installation +and creates a matched checkpoint through the production recovery command. +The normal installed administrator then creates/verifies its own canonical +data and backup, runs the bounded Linux proof workflow, and exercises three +password/PAM/greetd disk-only boots, abrupt termination, actual boot-file +corruption and matched recovery through the same normal ISO. The receipt +records explicit serial login and no privileged serial-console injection. + +This exact-artifact gate passed in +[run 36812104386](https://github.com/MichaelWave369/PhiOS/actions/runs/36812104386). +Its source/ISO identities, three disk-only boot IDs, data/proof hashes and +matched recovery generation are in `docs/os/evidence/normal-installed-5145b4da.json`. +The separate QA image also passed ephemeral signed package addition/interruption; +neither proves a future maintainer-signed transition or physical hardware. +Every qualification retains its own exact source/ISO identity and failure evidence. diff --git a/docs/os/LINUX_PROOF_WORKFLOW.md b/docs/os/LINUX_PROOF_WORKFLOW.md new file mode 100644 index 00000000..55fa9cae --- /dev/null +++ b/docs/os/LINUX_PROOF_WORKFLOW.md @@ -0,0 +1,83 @@ +# Bounded installed Linux proof workflow + +This candidate demonstrates one harmless real Linux filesystem effect. It +creates one fixed 57-byte proof note inside an independent protected store. +It is not a desktop automation API, AI agent, shell executor or generic file +writer. The existing Ghost Walk browser decision/binding/lease routes remain +held. Public EffectIntent, EnforcementProfile, AuthorityEpoch and ActionLease +contracts are reused without modifying private PhiKernel/TIEKAT internals. + +## Operator sequence + +Use an experimental installed PhiOS system, with the installer-created UID +1000 account and its ordinary password-authenticated sudo administration. +The public volatile live account cannot run this broker. There is no new +NOPASSWD rule and no unattended approval flag. + +```bash +sudo systemctl start phios-proof-proposer.service +sudo phios-linux-proof inspect +sudo phios-linux-proof approve +sudo phios-linux-proof execute --approval APPROVAL_SHA256 +``` + +Replace `APPROVAL_SHA256` with the exact identity returned by approval. Review +the captured proposal, actual source/boot identity, fixed note hash, protected +store, single use and 60-second lifetime. Approval requires typing the complete +`APPROVE SHA256` review phrase. Anything else cancels before creating an +approval, binding, lease or effect. The proposal and actual OS identity are +checked again after review. Run the separately requested effect within 60 +seconds. If it expires, make and review a new approval; do not edit records. + +The static one-shot proposer runs as UID 1001 `phios-agent`, with a nologin +account, no sudo, no capabilities, no privilege escalation, a private network, +protected home/system paths and one writable private proposal directory. It +is not enabled at boot. It observes public source/boot identity and writes an +untrusted, zero-authority proposal for the fixed note. A browser, pseudo-TTY +or agent-owned proposal is never approval. A malicious process running as the +installed administrator, cached administrator sudo or arbitrary root remains +outside this principal-separation boundary; TTY access alone is not human +authentication. Sudo/PAM separates the installed administrator from the +agent principal, rather than authenticating an AI judgment. + +The root-owned Python-isolated broker accepts only that fixed proposal path, +principal, capability and text. It opens bounded regular singly linked input +without following links and captures bytes before review. It binds the actual +source and boot to the decision, exact intent, enforcement profile, capability +binding and canonical single-use ActionLease. The note destination cannot be +supplied by the agent or caller. Root-owned directory descriptors, exclusive +creation and fixed bytes constrain this effect; signed administrator code is +trusted, and a compromised root is not sandboxed by these checks. + +## Consumption, verification and recovery + +`/.snapshots/phios-linux-proof` stores immutable SHA-256-named approvals, +consumption records, notes and post-effect receipts. It is in the independent +`@snapshots` subvolume, outside `@root` rollback snapshots and user data-only +backups. Records are root-owned; directories are created 0700 and files 0600. +The broker flushes the consumption record before creating a note. A failure or +interruption may leave a consumed lease and incomplete effect requiring review; +it never silently makes that lease reusable. It flushes the note, independently +opens and verifies its exact bytes, then flushes a separate linked receipt. +No executable authority follows from viewing a receipt. + +Both wall-clock validity and Linux `CLOCK_BOOTTIME` expiry are enforced, including +time spent suspended. A new boot or source identity invalidates old approvals. +OS recovery preserves the independent ledger; it cannot reinstate a rolled-back +lease. Canonical user data and its zero-authority history stay separate. This +extends the maintenance boundary only for this fixed broker store; custom +authority stores still need an explicit reviewed recovery procedure. Losing +the disk loses this ledger, and copying files is not authority enrollment. + +Twenty-one focused tests passed for exact binding/readback, cancellation, changed +review, scope/principal/source/boot denial, expiry including clock rollback, +replay, corrupt/linked records, symlink redirection and durable consumption +failure. The external installed-VM fixture uses ordinary sudo/PAM, the actual +UID 1001 service and production commands. It must prove agent store/broker +denial, cancellation, one verified note, replay and real 60-second expiry, then +historical-authority refusal after restart and matched OS recovery. End-to-end +VM qualification passed on both the separate signed-update QA image and the +exact normal image in runs 36812104411 and 36812104386. The normal receipt is +`docs/os/evidence/normal-installed-5145b4da.json`; it records actual UID/PAM, +effect/readback, refusals and three distinct installed boots including matched +recovery. Physical hardware and final release readiness remain unqualified. diff --git a/docs/os/OS_MAINTENANCE.md b/docs/os/OS_MAINTENANCE.md new file mode 100644 index 00000000..2e5c6085 --- /dev/null +++ b/docs/os/OS_MAINTENANCE.md @@ -0,0 +1,233 @@ +# Experimental whole-OS maintenance + +The candidate beta strategy is conventional signed Arch package transitions, +with an offline Btrfs root checkpoint and a matching copy of the entire EFI +system partition. This is not an atomic or immutable OS. Application rollback +does not restore Linux, initramfs, system configuration or the bootloader. + +## Signed transition intake + +`phios-update-verify --bundle /absolute/path/to/offline-bundle` verifies bytes +only. It cannot install packages, switch a boot entry, promote an adapter or +create execution authority. The normal image intentionally ships no enrolled +maintainer signing key. Verification holds until the operator independently +authenticates and installs a public key and full fingerprint. No test key is a +release identity, and no signing private key belongs in this repository/image. + +The volatile live account has no general root shell. Enroll through the +root-owned narrow command instead, using the full independently authenticated +fingerprint: + +```bash +sudo phios-update-enroll --public-key /absolute/current-public-key.gpg --fingerprint FULL_UPPERCASE_FINGERPRINT --plan +sudo phios-update-enroll --public-key /absolute/current-public-key.gpg --fingerprint FULL_UPPERCASE_FINGERPRINT +``` + +The placeholders must be replaced. Review the exact captured public-key hash, +full fingerprint, current trust hashes and source environment, then type +`ENROLL /etc/phios SHA256`. Missing/changed identity, multiple primary keys, +secret-key material, expired/revoked keys or cancellation do not enroll trust. +The tool captures the input once, exports only the selected public key, +rechecks validity/current trust after review, and flushes protected key/policy +files before readback. It has no unattended bypass or network retrieval. +Terminal access is not proof of human identity; an administrator remains +responsible for independent fingerprint authentication. Signing-trust rotation +is an explicit local administration action, not an adapter promotion. + +An installed administrator can also perform manual Linux administration: +create root-owned `/etc/phios` +without group/other write access, install the independently authenticated +exported public key at `/etc/phios/os-update-keyring.gpg` (root:root, 0644), and +install `/etc/phios/os-update-trust.json` (root:root, 0644): + +```json +{ + "schema_version": "phios.os-update-trust.v1", + "primary_fingerprint": "REPLACE_WITH_THE_INDEPENDENTLY_AUTHENTICATED_FULL_UPPERCASE_FINGERPRINT", + "channel": "experimental" +} +``` + +The placeholder is deliberately invalid. Authenticate the fingerprint through +a separately trusted maintainer channel; downloading a key beside its own +signature does not establish trust. Key rotation/revocation requires an explicit +administrator replacement of this trust policy/keyring. No keyserver, network +retrieval, automatic enrollment or web-of-trust inference is used. GnuPG's +machine-readable status must identify the pinned primary key, SHA-256/384/512, +and an unexpired, nonrevoked key/signature. GPGV alone would not provide the +required expiry/revocation checks. + +The offline bundle contains `manifest.json`, its detached `.sig`, and each +listed package plus a detached `.sig`. Every signature must chain to the pinned +maintainer primary key. Upstream package provenance still belongs in release +build evidence; a signed release transition is not a source/license audit. +Inputs are singly linked bounded regular files, opened without following links, +copied into a private temporary directory, then hashed and signature-checked. +Only captured bytes can reach a later package consumer. Replacing the supplied +bundle after verification cannot replace those bytes. + +The strict `phios.os-package-update.v1` manifest requires exactly these fields: + +| Field | Requirement | +| --- | --- | +| `schema_version`, `channel`, `architecture` | Exact schema, `experimental`, `x86_64` | +| `from_source_commit`, `source_commit` | Exact base and target 40-character commit identities | +| `base_sequence`, `sequence` | Installed generation and exactly its successor; no replay | +| `created_at`, `expires_at` | Timezone-aware validity window, at most 90 days; accurate clock required | +| `arch_snapshot` | Valid, fixed `YYYY/MM/DD` Arch archive date | +| `state_schemas` | Exactly `{"memory":1,"data_backup":"phios.data-backup.v1"}`; unknown migrations held | +| `base_packages`, `target_packages` | Complete name/version inventories; exact base; removals held | +| `packages` | Unique name/version/filename/SHA-256/size records for every changed or added package | + +Each package record has exactly `name`, `version`, `filename`, `sha256`, `size`. +The inventory bound is 20,000 packages; the transition bound is 2,000 archives, +2 GiB per archive and 16 GiB total. Archives use `.pkg.tar.zst` or `.pkg.tar.xz`. +The source, installed package inventory and persisted generation are checked +again for every verification. Initial installation has generation zero. + +Signature verification proves authenticated bytes and a declared complete +transition. Pacman must still validate package format, dependencies and the +resulting full inventory in a prepared system root. Unsupported schema changes, +data migrations, removals or dependency conflicts must hold the update. The +verifier does not claim package installation or boot compatibility. + +## Recovery qualification gate + +`sudo phios-os-recover checkpoint --disk /dev/REPLACE --plan` performs a +read-only probe from the PhiOS UEFI live image. Supply the canonical device +path of the already installed, offline disk. It requires the installer's exact +GPT/1-GiB-ESP/single-device-Btrfs layout, stable serial/WWN, filesystem UUIDs, +and a matching installation receipt. Mounted disks, swap, holders, unexpected +filesystems, extra partitions and noncanonical aliases are refused. A Btrfs +read-only probe uses `ro,rescue=nologreplay,subvolid=5` to disable log replay +([Btrfs mount documentation](https://btrfs.readthedocs.io/en/latest/btrfs-man5.html#mount-options)). No target write occurs for `--plan` or +cancellation. The tool exposes no unattended confirmation bypass. + +Run the command without `--plan`, review the complete disk/source/boot-file +hash plan, and type the exact `CHECKPOINT /dev/... SHA256` phrase. The checkpoint +ID and metadata are stored in `@snapshots/recovery//checkpoint.json`. +Each checkpoint has an immutable root snapshot, its Btrfs UUID, SHA-256/length +inventory of the complete EFI contents, and a read-only home snapshot retained +for forensic review. The home snapshot is never activated by OS recovery. + +To restore, boot the same live media and use: + +```bash +sudo phios-os-recover restore --disk /dev/REPLACE --generation CHECKPOINT_ID --plan +sudo phios-os-recover restore --disk /dev/REPLACE --generation CHECKPOINT_ID +``` + +The placeholder paths/ID must be replaced after reviewing the actual probe. +The exact `RESTORE /dev/... SHA256` phrase binds the selected disk, immutable +root snapshot, source and matching EFI hashes. Current `/home` and `/var/log` +stay in their own subvolumes. Canonical memory schema/integrity/content hashes +and published zero-authority memory receipts are checked. Unknown schemas, +incomplete database journals, enabled memory configuration, active decisions, +bindings, leases, claims or other unknown spine state hold recovery before +activation. Use verified data-only recovery and explicitly revalidate such +state first; the tool does not guess how to invalidate a custom authority root. +Only the packaged state path and legacy `~/.phios` are covered by this preview. + +Recovery clones the immutable root into a fresh writable subvolume, retains +the failed root under a unique `@failed-...` name and preserves the prior EFI +contents beside a durable transaction journal. It then switches the root and +copies/verifies the matched EFI files. Root and EFI changes are **not atomic**. +An interruption between them requires another live-media restore of the same +checkpoint; never reboot merely because one step completed. Failed roots and +transaction evidence are never deleted automatically. Cleanup failures hold +the operation and identify remaining mounts. Filesystem/hardware corruption +that prevents mounting needs a separate storage recovery procedure. + +Restoration discards old system/EFI entropy seeds, removes rolled-back update +trust files so an earlier signing policy cannot be silently reinstated, and +increments the highest observed update generation rather than replaying its +counter. The root generation is paired with a root-owned counter in +`@snapshots/os-update-counter.json`, outside the rollback snapshots. This counter +is flushed before root activation. A missing root after an interrupted rename +therefore cannot reset an already consumed update sequence. An inconsistent +root/counter pair holds updates for explicit live recovery. Re-enroll the independently authenticated current public key before +subsequent updates. Normal password/PAM login remains required. Same-user +terminal access is not proof of human identity and arbitrary administrator +processes remain outside PhiOS's narrow governed-effect boundary. + +Before any supported installed beta, prove all of the following on the exact +image: offline root/EFI checkpoint; valid signed package installation; missing, +wrong-key, expired and tampered update refusal; interrupted package transaction; +unbootable root or initramfs; recovery using the live media; normal password +reauthentication; preservation and verification of canonical user data; inactive +historical authority; and a second disk-only boot. Root snapshots alone do not +back up `/home`, and same-disk checkpoints do not survive loss of that disk. +Maintain a verified data-only backup on separately owned storage. + +## Offline signed package application + +Boot PhiOS UEFI live media, keep the installed disk offline, and enroll the +independently authenticated current public key into the **live** environment. +The updater does not inherit trust from the disk it is about to change. + +```bash +sudo phios-os-update --disk /dev/REPLACE --bundle /absolute/offline-bundle --plan +sudo phios-os-update --disk /dev/REPLACE --bundle /absolute/offline-bundle +``` + +The read-only plan binds the explicit disk, exact current source, complete +package inventory, independent counter, entire EFI hash inventory, signed +manifest digest, pinned signer and fresh checkpoint ID. Review and type the +exact `UPDATE /dev/... SHA256` phrase. Cancellation changes no target files. +Trust, validity and every captured package signature are checked again after +confirmation. Downgrades and package removals require recovery rather than an +update. Accurate time and enough live temporary storage for the bounded bundle +are prerequisites; insufficient space holds the operation. + +The command first creates a matched recovery checkpoint, then prepares a +writable `@update-...` root. Pacman requires signatures for each captured +archive, with only the enrolled keyring and no remote repositories. Package +format/dependency failures or an incorrect complete target inventory leave +the active root and EFI unchanged. The staged root must carry exactly the +signed PhiOS source identity. Kernel/initramfs/EFI preparation occurs against +a private copy of `/boot`; only after verification does the tool retain the +prior root, activate the new root and copy/verify matching EFI contents. +No user-home snapshot or historical authorization is activated. + +Signed package scripts run with administrator privileges. The staging chroot +is not a security sandbox against a malicious signer or administrator. A +maintainer must qualify the actual complete package transition, its hooks, +state compatibility, licenses and boot behavior before signing it. + +The update journal lives beside its exact checkpoint as +`@snapshots/recovery//update-transaction.json`. Failed stage roots, +previous roots and transaction evidence remain for review. An interruption +before activation leaves the active root in place. Root/EFI activation remains +non-atomic: if interrupted during that switch, boot live media and explicitly +restore the journal's checkpoint. Success reports activation only; a disk-only +boot is still required to qualify the target. Keep a separate verified data +backup and the matching live recovery image. + +CI uses only a newly created named 32-GiB VM disk, with no network, host disks +or shared folders. It generates ephemeral signing keys in live RAM and builds +real packages with makepkg. The new fixture tests invalid/missing/wrong-key/ +expired/replayed signatures or manifests, cancellation, a valid added package, +a real dependency failure, abrupt VM termination during a pacman installation +hook, unchanged active root/EFI after that interruption, deliberate boot +corruption, matched live-media recovery and normal password/PAM desktop boots. +Those test packages and credentials are excluded from normal images and +installations. A successful fixture qualifies that bounded transition only; +it does not qualify arbitrary kernel upgrades, real hardware or a release key. + +Current status: the bounded end-to-end VM qualification passed in run +[36805999628](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999628), +including enrollment, successful signed addition, refusal cases, actual +interrupted installation, a kernel boot failure, matched live recovery and +three authenticated disk-only desktop boots. Exact source/ISO hashes and +evidence digests are in `docs/os/evidence/recovery-29def30a.json`. The QA image +contains disposable fixtures and ephemeral signing identity; this evidence +does not qualify another artifact, arbitrary upgrades or hardware. +`whole_os_rollback_available` remains false for the supported product. +See IMPLEMENTATION_STATUS.md and RELEASE_CONTRACT.md for remaining gates. + +The bounded Linux proof broker stores its protected history in the independent +`@snapshots/phios-linux-proof` directory. Its single-use approvals are bound to +the current boot and source, and expire by both wall clock and CLOCK_BOOTTIME. +Root/EFI recovery preserves that ledger and cannot make an old-boot approval +active. See LINUX_PROOF_WORKFLOW.md; custom authority stores remain outside +this fixed procedure. diff --git a/docs/os/RELEASE_ARTIFACTS.md b/docs/os/RELEASE_ARTIFACTS.md new file mode 100644 index 00000000..93636bf1 --- /dev/null +++ b/docs/os/RELEASE_ARTIFACTS.md @@ -0,0 +1,108 @@ +# Exact OS candidate and release evidence + +`Fixture-free OS candidate (unpublished)` builds the checked-out source with +`PHIOS_CI_SMOKE=0`. It has read-only repository permissions and uploads +seven-day review artifacts. It cannot create a GitHub Release, push a tag, +enroll a production signing key or publish to PyPI. The OS version remains +`0.1.0-alpha.1`; a build does not confer supported-beta status. + +The normal profile excludes live QA scripts/services, disposable credentials, +test packages and enrolled PhiOS update trust. The inventory generator checks +actual image paths and refuses a mismatch with the requested fixture scope. +The normal volatile `phios`/`phios` account remains the documented live login; +that public live account does not become an installed user/password. + +The external normal live VM harness uses only the finished ISO and fresh OVMF +variables, without a target disk or shared folders. Its added desktop gate uses +restricted virtual Ethernet with no external forwarding and synthetic HDA with +a null audio backend; no host audio is attached. It logs in through normal +serial PAM using that public live account, observes the actual non-root +Wayfire/Chromium/HTTP services, tests an observer restart, logs out, enters the +same account at the real greetd keyboard/PAM prompt and checks the restarted +desktop. It resets and repeats with a distinct boot ID. Probe commands are +sent through the normal user terminal; no test code or QA service is inserted +into the image. Logs/screenshots and the exact ISO/source hash are retained. +The separate exact normal-image installed lane described below adds bounded +installation/data/recovery/Linux proof evidence for that same ISO. Real hardware +and the future final signed update transition remain additional release gates. +The installed/recovery lanes retain no NIC or shared folders. See +DESKTOP_OPERATION.md for the precise DHCP, user-audio and PAM-lock scope. + +## Artifact inventory + +| Artifact | Observed scope | +| --- | --- | +| `SHA256SUMS` | Every release payload/provenance sidecar; excludes itself and mutable CI logs | +| `provenance.json` | Exact source commit/archive, ISO/hash, Arch date, Archiso, builder digest, artifact hashes and explicit unqualified flags | +| `native-packages.json` | Actual local pacman database, name/version/architecture/base, declared license labels and metadata hashes; cross-checked against pacman output | +| `python-packages.json` | Actual installed dist-info identity/version and declared license metadata | +| `javascript-packages.json` | Actual installed production npm lock, each package.json name/version, declared licenses and supplied lock integrity | +| `javascript-bundled-packages.json` | Actual Rollup chunk participants, package/module identities, emitted chunk hashes and captured supplier notices, including generated runtime helpers | +| `sbom.cdx.json` | CycloneDX 1.6 inventory across native/Python/npm and bundled origins, with origin paths and supplier-declared license names | +| `third-party-notices.tar.gz`, `.json` | Bundled notice bytes and file hashes from native/Python/npm package paths; guest symlinks resolved inside the image | +| `source-review.json` | Exact first-party source archive and explicit pending source-delivery review for each component | +| `fixture-inventory.json` | Requested fixture scope and actual observed paths; separate from readiness | + +SBOM validation uses hash-pinned official CycloneDX schemas from the reviewed +1.6 tag. A changed schema download fails validation. No supplier label is +silently translated into a concluded SPDX license, and dependency graphs or +vulnerability results are not inferred from inventory alone. Bundled notices +and a valid SBOM do not establish full distribution source/license compliance. +The exact source material, delivery terms and required notices for each +component must receive a maintainer review under its applicable license. +Arch binary archive URLs alone are not recorded as delivered source code. + +## Remaining publication gates + +1. Preserve the passed exact normal-image live/install/state/recovery/fixed + workflow evidence, then qualify the final publication source/artifact and its + actual maintainer-signed update transition. Earlier QA-image evidence is + informative but does not silently qualify a different ISO or transition. +2. Complete the declared real-hardware matrix and record limitations, recovery + procedure, support owner and maintenance policy for that release scope. +3. Complete the component-by-component source/notice review; deliver required + corresponding source material with exact hashes and custody references. +4. Authenticate a maintainer-controlled public signing fingerprint through an + independent channel. Keep its private key outside this repo, image and CI + fixture. Sign the final checksums/provenance and verify the signed bytes + against the authenticated current public key. +5. Review the exact final commit, artifact hashes, evidence and release notes, + then have the human release owner authorize a prerelease in the independent + `phios-linux-v*` tag namespace. Publish ISO, signatures, inventories, source, + supported scope and recovery/support documentation together. + +All generated reports remain `release_ready: false`; they do not grant +execution, signing, adapter-promotion or publication authority. Main/release +branch protection and required-check settings have not been changed by this +candidate workflow. Protecting them remains a maintainer repository setting. +The always-reported `release-gate` aggregates the same-source Python/UI/normal/ +QA jobs; see BUILD_AND_QUALIFY.md for its required-status configuration and +explicit documentation-only scope. It cannot attest to hardware or sign/publish. + +The builder also captures actual Rollup chunk participants before npm pruning, +including Vite-generated runtime helpers. Bundled supplier metadata and license +notices are retained in the installed dist tree; the collector checks final +chunk and notice hashes and emits a separate javascript-bundled inventory. +A pruned runtime package list alone cannot describe all generated frontend code. + +The normal candidate workflow also invokes `qemu_install.py --fixture-free +--recovery` against that same ISO. It uses the public live account's narrow +maintenance sudo, an explicitly reviewed standard serial password login, +user-owned canonical data/backup, the actual installed proof broker, deliberate +boot corruption and matched recovery. It introduces no root autologin or QA +service into the image. This exact installed-artifact qualification passed in +[run 36812104386](https://github.com/MichaelWave369/PhiOS/actions/runs/36812104386), +with 441 actual SBOM components and 620 captured supplier notice files. See +`docs/os/evidence/normal-installed-5145b4da.json` and RELEASE_HANDOFF.md for exact +identities and remaining gates. The real final signed package transition and +physical hardware remain separate gates. + +The later desktop/aggregate [run 36823086807](https://github.com/MichaelWave369/PhiOS/actions/runs/36823086807) +passed all nine same-source jobs. Its exact normal ISO repeated live/install/ +state/proof/recovery and added the bounded network/audio/PAM-lock qualification; +it contains 501 components and 746 supplier notice files. The separate signed +QA artifact has 502 components. The two compact archives and 15 checksum payloads +per archive were independently checked against hashes/provenance; the large +ISO/package/source/notice archives were not redownloaded into the review host. +See `evidence/qualification-gate-a7bcd986.json` and its two linked receipts. +Source delivery, maintainer signing and physical support remain open. diff --git a/docs/os/RELEASE_CONTRACT.md b/docs/os/RELEASE_CONTRACT.md new file mode 100644 index 00000000..7322cab6 --- /dev/null +++ b/docs/os/RELEASE_CONTRACT.md @@ -0,0 +1,61 @@ +# PhiOS Linux release contract + +Target: **0.1.0-alpha.1 development preview**, x86_64, x64 UEFI, Arch Linux, +Wayfire and PhiShell. Linux supplies the kernel. Private PhiKernel/TIEKAT +implementation is not part of this image or a prerequisite to boot it. +`packaging/linux/release.json` supplies machine-readable candidate identity. +Python package versions and OS versions are independent. OS tags start with +`phios-linux-v`; the existing `v*` workflow publishes Python artifacts only. + +## Included preview + +- Current PhiOS Python code and built PhiShell, installed as pacman packages. +- Local observation of host, services, processes, devices and native packages. +- A non-root Wayfire session, Chromium application window, Waybar and terminal. +- Supervised user services with bounded loopback ports and private state umask. +- Candidate NetworkManager wired/Wi-Fi configuration, user audio and manual + PAM screen locking; exact new qualification is described in DESKTOP_OPERATION.md. +- Optional governed history when an operator supplies an enabled memory config. +- Curiosity projection access, with consequential persistence approval held. + +The default preview does not run an AI model or an autonomous agent. Ollama, +vector memory, OCR, Windows UI Automation/GhostWalk and hardware bridges are +optional or platform-specific. Missing capabilities must show unavailable. +No general Linux desktop effect executor or lease issuance is advertised. A +separate installed-only, explicitly invoked proof-note candidate is described +in LINUX_PROOF_WORKFLOW.md; its untrusted agent proposal grants no authority. The browser +cannot mint operator approvals; see OPERATOR_AUTHORIZATION.md. + +## Deliberately unqualified capabilities + +This preview is a volatile live image. Its experimental blank-disk installer +passed the named disposable VM gate (see INSTALLATION.md); it has no supported +hardware installer, supported whole-OS rollback, Secure Boot or BIOS support. +Installed data backup/restoration, abrupt VM restart and a bounded signed +package/update plus matched root/EFI recovery passed in disposable VMs +(see IMPLEMENTATION_STATUS.md). Physical power loss, actual future release +transitions remain separate gates. The exact fixture-free live/install/data/ +recovery and fixed Linux proof workflow passed in run 36812104386. No hardware +compatibility claim follows from a VM boot. Agent +isolation requires separate OS principals and a verified restricted broker; +an operator-owned shell or pseudo-TTY is not human authentication. + +## Acceptance gates + +| Gate | Required evidence | +| --- | --- | +| Candidate packages | Source commit/archive hash, JS lock, signed Arch snapshot, installed wheel/entrypoints and UI smoke | +| Live boot | Exact ISO hash, UEFI VM serial log, non-root compositor/browser, local HTTP observations, screenshot | +| Session lifecycle | Login, sidecar failure/restart, logout stopping services, reboot, no sandbox bypass | +| Durable state | Private permissions, concurrent writers, abrupt termination, verified backup/restore and schema migration | +| Installed system | Explicit blank-disk identity/confirmation, disposable VM install, no-ISO reboot and persisted receipts | +| Updates/recovery | Verified signed update, interrupted update, recovery boot and restore; application rollback alone does not satisfy this | +| Linux workflow | Explicit operator decision, exact binding, single-use lease, Linux effect and independent post-effect verification | +| Hardware beta | Named machines, firmware/GPU/network/input/audio/storage results and recovery evidence | +| Public OS release | All applicable gates passed for the exact artifact; SHA256SUMS, signature, SBOM, third-party licenses/source provenance, notes and maintainer decision | + +CI artifacts are unsigned **test candidates**. A successful build or boot does +not automatically promote an adapter, establish readiness or publish a release. +Maintain historical documents and licensing provenance rather than rewriting +past releases. PhiOS source is MIT; Linux and bundled packages retain their own +licenses. Full distribution source/license compliance remains a release gate. diff --git a/docs/os/RELEASE_HANDOFF.md b/docs/os/RELEASE_HANDOFF.md new file mode 100644 index 00000000..e273e65a --- /dev/null +++ b/docs/os/RELEASE_HANDOFF.md @@ -0,0 +1,129 @@ +# PhiOS Linux candidate handoff + +Current outcome: an unpublished experimental `0.1.0-alpha.1` Linux distribution +candidate has passed actual UEFI VM live boot, normal non-root desktop lifecycle, +blank-disk installation, durable canonical data/backup/restore, bounded governed +Linux effect and matched root/EFI recovery. A separate QA artifact passed a real +ephemerally signed package transaction, refusals and interruption. Physical +hardware, the final signed transition and distribution delivery remain open. +This is not a supported beta or OS 1.0. Nothing has been merged or published by +this handoff; no private PhiKernel/TIEKAT implementation is needed to boot it. + +## Exact candidate for physical observation + +| Identity | Value | +| --- | --- | +| Reviewed branch head | `9c98475274442595c59370113b9c1e0dee595ec9` | +| Tested prospective merge source | `a7bcd9863eea12a87c1a9ef1fcbd26211542cd91` | +| Identical source tree | `a85700b2c08e54a066a77a2f4a4db7494b7579ff` | +| Normal ISO SHA-256 | `3b26a7334b36254b4e686843e84924ee14cdb6ef2d6748fd771e09a02e5f79a2` | +| First-party source archive SHA-256 | `41ed0a19a811f7ac6c22edbb555adbc4b55d5421f8ea6b9e73481cd58116d8b7` | +| Normal image qualification | [36823086807](https://github.com/MichaelWave369/PhiOS/actions/runs/36823086807) | +| Download normal ISO and payloads | [11144157950](https://github.com/MichaelWave369/PhiOS/actions/runs/36823086807/artifacts/11144157950) | +| Compact evidence | [11144167873](https://github.com/MichaelWave369/PhiOS/actions/runs/36823086807/artifacts/11144167873) | +| Persisted receipt | [desktop-normal-a7bcd986.json](evidence/desktop-normal-a7bcd986.json) | + +These unsigned review downloads expire **2026-10-08**. A later build, branch +update, final merge or tag has a separate identity. Download the normal payload, +verify its complete ISO/source/artifact hashes against SHA256SUMS and provenance, +and retain the receipts with that exact build. The separate QA image contains +test fixtures and is not the physical observation candidate. + +## Ordered code review + +Review the component PRs in dependency order after assessing each boundary: + +| PR | Scope | +| --- | --- | +| [270](https://github.com/MichaelWave369/PhiOS/pull/270) | Browser/operator authority boundary | +| [271](https://github.com/MichaelWave369/PhiOS/pull/271) | Linux contract, packages, non-root desktop and live image | +| [272](https://github.com/MichaelWave369/PhiOS/pull/272) | Private durable state and data-only backup/recovery | +| [273](https://github.com/MichaelWave369/PhiOS/pull/273) | Explicit whole blank-disk installation | +| [274](https://github.com/MichaelWave369/PhiOS/pull/274) | Explicit signing trust, signed package updates and matched root/EFI recovery | +| [275](https://github.com/MichaelWave369/PhiOS/pull/275) | Exact inventories, notices, SBOM/provenance and normal live-image gate | +| [276](https://github.com/MichaelWave369/PhiOS/pull/276) | Restricted Linux proof broker, hardware handoff and bundled frontend inventory | +| [277](https://github.com/MichaelWave369/PhiOS/pull/277) | Exact normal-image installed/recovery gate and explicit serial password login | +| [278](https://github.com/MichaelWave369/PhiOS/pull/278) | Always-reported same-source `release-gate` and reusable qualification jobs | +| [279](https://github.com/MichaelWave369/PhiOS/pull/279) | NetworkManager, user audio, manual PAM locking and their actual desktop probes | + +Use the complete main-targeted integration PR as the merge vehicle after its +own exact-source qualification passes. It contains the candidate and aggregate +controller together, so main can require its observed `release-gate` before +integration. The component PRs above remain focused review references. Requiring +`release-gate` on the earlier component heads would leave them pending because +they predate that controller. Keep every merge and release under maintainer review. + +The latest aggregate gate passed all nine jobs in +[run 36823086807](https://github.com/MichaelWave369/PhiOS/actions/runs/36823086807) +for source `a7bcd9863eea12a87c1a9ef1fcbd26211542cd91`, with 2,287 Python tests +passed and six existing optional skips. `evidence/qualification-gate-a7bcd986.json` +links the independently hash-checked normal and signed QA receipts. The normal +image has 501 inventoried components and 746 captured supplier notice files. +Virtual DHCP/audio, actual Super+L/PAM lock/refusal/unlock, complete session +shutdown/reauthentication and installed recovery/proof passed. Physical network, +audio, Wi-Fi, GPU and suspend remain unqualified. + +The earlier aggregate gate passed all nine jobs in run 36816117488 for source +`5a1431f4758029a9c04abfb5471351e9abf88a3f`, with 2,279 Python tests passed and +six existing optional skips. Its actual normal and signed QA scopes and exact +hashes are in `evidence/qualification-gate-5a1431f4.json`. Each later integration, +documentation commit, main merge or tag has a separate source/artifact identity. +The aggregate normal and QA jobs reuse the existing exact-image procedures. See +BUILD_AND_QUALIFY.md for the `release-gate` required-status handoff. +Review source and tests, not just a green check. Main and OS release-tag protection +still require maintainer configuration. Keep publication separate from the +existing Python `v*`/PyPI workflow. Evidence never promotes an adapter, enrolls a +signing identity or grants execution/publication authority. + +Repository protection was rechecked on 2026-10-01. Main still points to +`dad7a7d7cd53874926ad366f19d3fc0fa6b99a49`; its branch response reports no +required checks. The sole active branch ruleset `protec` (13863077) contains +deletion/non-fast-forward rules and no required status or review rule. Configure +the reviewed `release-gate` requirement and main/OS-tag release protections +through maintainer administration before merging/publishing. This candidate +does not claim those settings were applied. + +## Remaining work in order + +1. **Observe the supplied Skytech on the exact normal live media.** Follow + HARDWARE_QUALIFICATION.md, initially without installation. Save the read-only + hardware report plus actual GPU/display/input, network, audio, firmware, + suspend and shutdown/restart results. RTX 5070 support is not inferred from + software rendering in QEMU. Virtual audio, restricted DHCP and manual PAM locking passed on this + candidate; physical audio/network/radio/lock/suspend behavior still requires + observation. Resolve blockers and requalify changed artifacts before promising them. Preserve Windows and its independent backup. +2. **Qualify installation on a separately identified dedicated empty disk.** + Review the entire blank target and exact installer phrase. The installer + supports no dual boot or partition reuse. Prove no-media logins, persistent + acknowledged data, a separate verified backup, the fixed Linux proof workflow, + actual signed target transition, interruption and matched recovery. Record + physical power-loss evidence separately from virtual process termination. +3. **Prepare the actual supported transition and maintainer signing identity.** + Select the final base/target source and complete package inventories and + migration policy. Authenticate the maintainer's public key and complete + fingerprint independently, enroll it explicitly and test the actual signed + target bundle on the normal base artifact. Never submit a private key to the + repo, image, test harness or this handoff; the ephemeral QA signer is not a + release identity. Arbitrary kernel/driver upgrades are not qualified by the + passed added-package fixture. Preserve failures and successful target hashes. +4. **Complete source and notice delivery for that exact final inventory.** + Start with source-review.json's component records. Identify applicable terms, + actual corresponding source and build/patch material where required, custody, + exact hashes and delivery references. Bundle or accompany the distribution + with the required materials and notices. Have the release owner review the + result. Supplier labels, an Arch binary archive link, captured license files + and valid CycloneDX syntax alone do not complete this gate. +5. **Freeze support scope and qualify final bytes before publication.** + Record supported machines/features, known issues, maintenance/security update + and recovery procedures, support contact/owner and the retained evidence. + Run the package/UI/live/install/recovery gates on the final release source; + previous PR checks cannot authorize a different final image or transition. + Sign final SHA256SUMS/provenance externally with the authenticated maintainer + key and verify the exact signed bytes. After explicit human release-owner + authorization, publish a prerelease in `phios-linux-v*` with the ISO, + signatures/public-key verification instructions, inventories/notices/source, + qualification receipts and support/recovery notes together. + +No readiness percentage or forecast date replaces these missing observations. +The requirement register and every generated report continue to distinguish +qualified VM cases from pending physical/signing/delivery work. diff --git a/docs/os/STATE_RECOVERY.md b/docs/os/STATE_RECOVERY.md new file mode 100644 index 00000000..c883c0d6 --- /dev/null +++ b/docs/os/STATE_RECOVERY.md @@ -0,0 +1,98 @@ +# Durable state and data recovery + +The packaged session selects `PHIOS_STATE_ROOT=$HOME/.local/state/phios`. +Memory uses `memory/canonical.sqlite3`, Spine uses `spine-v0.1/ledger`, and +Curiosity uses `curiosity`. Memory configuration is +`$XDG_CONFIG_HOME/phios/memory.json` (normally `~/.config/phios/memory.json`). +CLI processes inherit the same root. Outside the session, the existing +`~/.phios` location remains the legacy default. A relative or empty state-root +environment is an error. Legacy data is copied through backup/restore into a +new root; it is never silently moved or enabled. + +New files use mode 0600 and new directories 0700. Existing permissions are not +silently changed. Files must be caller-owned, regular, singly linked and not +writable by other users. POSIX traversal refuses symlinks at every ancestor. +These checks do not authenticate a human, isolate a malicious same-user process, +attest Windows ACLs or encrypt data. + +## Acknowledged writes + +Spine, Mandala and Curiosity JSONL writers hold an exclusive process lock, +validate history, write a complete record and sync file/directory before +returning. Readers hold a shared lock and reject malformed, duplicate-key, +non-finite, oversize and incomplete records. The per-record bound is 16 MiB. +Reading never repairs or discards evidence. A caught failed write truncates only +that unacknowledged append; a killed writer can leave an incomplete tail that +blocks normal reads and later writes. + +Memory transactions reserve the SQLite writer before reading idempotency keys +or revision heads, use FULL synchronization and close each connection. Outbox +publication is idempotent under the ledger lock. Publishing an older revision +cannot mark a newer pending revision readable. Binding, lease and run claim +files are synced before an executor can be entered. No permission or adapter +promotion follows from these changes. + +## Backup and restore + +Backups are private, unencrypted directories with a versioned manifest and +exact file hashes. Keep them under operator-controlled storage. The manifest +establishes internal integrity, not external authenticity. SQLite's online +backup API captures canonical database state; ledger capture can span a later +moment, recorded by the manifest's capture window. + +```sh +phi-state backup --state-root "$PHIOS_STATE_ROOT" --output "$HOME/phios-backup-001" +phi-state verify "$HOME/phios-backup-001" +phi-state restore "$HOME/phios-backup-001" --new-state-root "$HOME/.local/state/phios-restored" +``` + +Both operations require a new destination, including refusal of an existing +empty directory. Restore verifies all file hashes, SQLite structure, canonical +record hashes and exact published memory receipts before creating output. +Unknown backup/database schemas are held without speculative migration. +Failure preserves partial output for review and returns a nonzero status. + +| Data | Restore behavior | +| --- | --- | +| Canonical memory | New memory database; pending outbox stays pending | +| Published memory receipts | Exact receipts in the active Mandala ledger | +| Curiosity artifacts/pointers | Active data paths after zero-authority validation | +| Effect, approval, binding, lease and session history | `recovered-audit/`, outside active lookup paths | +| Claims, enabled configuration, credentials, caches and vector indexes | Excluded; no replay or enabling | + +Stop the old session before selecting a restored root. Review a disabled memory +configuration before enabling readers or reconciling a pending memory outbox. +Rebuild derived indexes explicitly. Historical authority stays historical; +restore creates no active decision, binding, lease or executor. + +## Interrupted final records + +Normal backup holds an incomplete tail. This explicit option preserves a +verified complete prefix and all original bytes in a new backup: + +```sh +phi-state backup --state-root "$PHIOS_STATE_ROOT" \ + --output "$HOME/phios-recovery-001" --preserve-incomplete-tail +phi-state verify "$HOME/phios-recovery-001" +``` + +The manifest lists incomplete audit files; original bytes are archived as +`.jsonl.bin` outside active paths. The original root remains untouched and held. +Malformed complete rows still fail. Published memory must retain its exact +valid receipt. After restore into a fresh root, a reviewed memory runtime can +reconcile pending canonical memory publication once. The option never resumes +an uncertain effect, infers a missing receipt or releases an old claim. Preserve +the original root and assess uncertain operations separately. + +## Qualification limits + +Focused tests cover contention, duplicate publication, disk-full interruption, +SIGKILL, backup/restore, hash tampering, authority injection and unknown schemas. +An installed-system lane must still prove no-ISO reboot and abrupt power-loss +recovery. Whole-OS recovery, hardware storage behavior, Windows custody and +agent isolation remain separate gates. A volatile live image loses its state +on reboot unless a verified backup has been copied off the image. + +References: [Python SQLite APIs](https://docs.python.org/3/library/sqlite3.html), +[SQLite transactions](https://www.sqlite.org/lang_transaction.html), and +[SQLite synchronization](https://www.sqlite.org/pragma.html#pragma_synchronous). diff --git a/docs/os/evidence/desktop-attempts.json b/docs/os/evidence/desktop-attempts.json new file mode 100644 index 00000000..bbe8274b --- /dev/null +++ b/docs/os/evidence/desktop-attempts.json @@ -0,0 +1,213 @@ +{ + "attempts": [ + { + "actual_guest_error": "restricted virtual Ethernet did not receive exact DHCP address/gateway/DNS configuration", + "compact_checksum_payloads_verified": [ + "builder-image.json", + "builder-packages.txt", + "fixture-inventory.json", + "image-packages.txt", + "javascript-bundled-packages.json", + "javascript-packages.json", + "native-packages.json", + "provenance.json", + "python-packages.json", + "release.json", + "sbom.cdx.json", + "source-archive-sha256.txt", + "source-commit.txt", + "source-review.json", + "third-party-notices.json" + ], + "evidence_archive_sha256": "beb6b807aab21268b313ab16d4c87ece8acbd197755096746136dd99c8c3180d", + "evidence_artifact_id": 11143486098, + "evidence_files": { + "PhiOS/PhiOS/dist/fixture-free/SHA256SUMS": "9131d7681b9afe0e89d768cbcf04447d188aaffea7c35db663bdeab058b58909", + "PhiOS/PhiOS/dist/fixture-free/build.log": "be279f0d32c20e1764674758984ac42a6667f4ab155fc1ba7883278b2ad603fb", + "PhiOS/PhiOS/dist/fixture-free/builder-image.json": "bde5aff2d12494b6d1d9fc4979d0b85ba84f2b8613e32592f607a8be28be75d5", + "PhiOS/PhiOS/dist/fixture-free/builder-packages.txt": "374d8ffd2ec34f22d8ef7f28110927eef7d17586faba2954e1906a2c5229c35f", + "PhiOS/PhiOS/dist/fixture-free/fixture-inventory.json": "14ce1577031ab6cc9b29967bc57b054661ce36d3a5ec0ada86a0bba9ddc9627e", + "PhiOS/PhiOS/dist/fixture-free/image-packages.txt": "742b3c4ce23cb82cdc8eb10f95152fc1b39422bdf9dd4532b66693d2fa92b202", + "PhiOS/PhiOS/dist/fixture-free/javascript-bundled-packages.json": "04402e02c14a791ffc99968668594c1943081f1f7237a36e8b440dd0d896bf1f", + "PhiOS/PhiOS/dist/fixture-free/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/fixture-free/mkarchiso.log": "4c92e2985abb0192291c5d3e686105d2b07f169823dd72bc9a763eb0dd89ef4f", + "PhiOS/PhiOS/dist/fixture-free/native-packages.json": "c4512631417cb2abe68bad762536a4f6feeab4da38af48644de488fc1a78f057", + "PhiOS/PhiOS/dist/fixture-free/provenance.json": "64d2f01fd4269c749f49c41fc20d638f82c321a74da3b7ad98176364ae4cc655", + "PhiOS/PhiOS/dist/fixture-free/python-packages.json": "ef6655e03b4fd5a1bac84e505582a2b14bef22d7f45ee034f9339bffa61b8f7e", + "PhiOS/PhiOS/dist/fixture-free/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/fixture-free/sbom.cdx.json": "2d08a3d9a6700401ef4eec5c23a1f9a9d230335c3371d79fdc49c18766869638", + "PhiOS/PhiOS/dist/fixture-free/source-archive-sha256.txt": "eaf2f7b867da61feb8a20479acdde6ab6c8e292023557ca0ce061eb98fd28d7c", + "PhiOS/PhiOS/dist/fixture-free/source-commit.txt": "bda5090c07a832f2b1461815a7f709b704d81f9040f4c3292765e3ccb6ce3404", + "PhiOS/PhiOS/dist/fixture-free/source-review.json": "e36d4fe555e3d15c73ba0e9826682228dbf9d87c9e5f99bf0ea686f993d417df", + "PhiOS/PhiOS/dist/fixture-free/third-party-notices.json": "840a10e3dac4ffac473e0f68ba6d078c85ddf1e4120518fa598d1876fe3cc71f", + "_temp/phios-preview/preview-evidence.json": "9598837cee4c62f950998a92364249fd565af31fee933d8249b188a4ab6c7c32", + "_temp/phios-preview/qemu.log": "8b7b90f1a933779d1b1bf072091c730c259ef12a92f551f43ffea63c0a06c701", + "_temp/phios-preview/screen.png": "ed1682dd47ec6f913ee7ebc4c0f7843c4bd99d05315cac94e10f304cf58f942c", + "_temp/phios-preview/serial.log": "341e0fc53dd2bec5e0ebb7e9ac452e93e67ded8d7d6aff24e2754b02684f39ea" + }, + "failure": "External live probe incorrectly expected DHCP gateway/DNS options from restricted libslirp. Upstream deliberately omits both; require exact lease/server and absence of gateway/DNS advertisement. Shell OSC prompt metadata preceded the guest Traceback, so the newline-prefixed host detector missed it and reported a timeout; detect the unprefixed exception and disable Python color in the external probe. No production network isolation or mandatory qualification is relaxed.", + "hardware_qualified": false, + "image_artifact_id": 11143011854, + "image_built": true, + "iso_sha256": "66abc718e7a96f9fdc4cd0d6a835bfcc26c1aae332978491528d94858beafc38", + "job_id": 110229803799, + "large_payloads_redownloaded_and_verified_locally": false, + "normal_installed_qualified": false, + "normal_live_qualified": false, + "observed": [ + "normal non-root PAM login", + "user audio service/ALSA sink/PCM checks returned before DHCP rejection", + "non-root PolicyKit agent startup/ownership checks returned before DHCP rejection", + "actual desktop rendered in preserved failure screenshot" + ], + "release_gate_job_id": 110235250413, + "release_gate_result": "failure", + "release_ready": false, + "reported_error": "normal PAM/desktop qualification timed out", + "reviewed_branch_head": "5dc73d7a5b2ab8cdf27ded5386600f3af4a5ab14", + "separate_qa_does_not_qualify_normal_image": true, + "separate_qa_iso_sha256": "d27e9ea0215e4c353ea908ae287e8a429c4e5f6846cbda0ddfeea224fe715185", + "separate_qa_job_id": 110229803728, + "separate_qa_result": "success", + "separate_qa_scope": [ + "installed audio on three distinct no-ISO PAM/desktop boots", + "actual Super+L binding, wrong-password hold and correct-password PAM unlock", + "signed package/refusal/interruption/matched root+EFI recovery and governed Linux proof" + ], + "source_commit": "83259a24a82a72d279abc4e6f873a07f428817c9", + "tested_source_tree": "a8fc9083997f74975eccdbea37267990b033bd3d", + "workflow_run": 36818833863 + }, + { + "evidence_archive_sha256": "8e54545d7cff97db3a2889534d6fc76eefdf6a8880402ddfb89f65460d1accf3", + "evidence_artifact_id": 11143976856, + "evidence_files": { + "PhiOS/PhiOS/dist/linux/build.log": "a3d6820c9f8f66574db37d784b331e0605aa2c9e063404a44109d51ed55796ab", + "PhiOS/PhiOS/dist/linux/builder-image.json": "3fcc731f1842caf946f756ba362033255ade51cff5ae5d1abddd7dbe2d65dff6" + }, + "failure": "Arch archive transfers stalled below pacman minimum speed for uvicorn, vulkan-icd-loader signature and spdlog. Pacman refused the transaction and the builder exited nonzero before producing an ISO. The always-run display conversion additionally failed because QEMU/Pillow setup was never reached; both evidence uploads still succeeded. Retry only the failed same-source jobs; keep signed pinned inputs and all assertions.", + "image_built": false, + "job_id": 110238876766, + "phase": "signed_pinned_arch_builder_download", + "qa_image_qualified": false, + "release_gate_job_id": 110240951871, + "release_gate_result": "failure", + "release_ready": false, + "reviewed_branch_head": "cda880f273a7d68afdd95670e2555c4f766884f6", + "run_attempt": 1, + "source_commit": "afe3795528e11107eeafbb74088c255cd97f356f", + "tested_source_tree": "49571965ef7717c427d049b2a4e01ae3941b4fb4", + "workflow_run": 36821774229 + }, + { + "actual_network_capture": { + "DHCP4.OPTION": [ + "dhcp_client_identifier = 01\\:52\\:54\\:00\\:12\\:34\\:56 | dhcp_lease_time = 86400 | dhcp_server_identifier = 192.0.2.2 | expiry = 1790920696 | ip_address = 192.0.2.15 | next_server = 192.0.2.2 | requested_broadcast_address = 1 | requested_domain_name = 1 | requested_domain_name_servers = 1 | requested_domain_search = 1 | requested_host_name = 1 | requested_interface_mtu = 1 | requested_ms_classless_static_routes = 1 | requested_nis_domain = 1 | requested_nis_servers = 1 | requested_ntp_servers = 1 | requested_rfc3442_classless_static_routes = 1 | requested_root_path = 1 | requested_routers = 1 | requested_static_routes = 1 | requested_subnet_mask = 1 | requested_time_offset = 1 | requested_wpad = 1 | subnet_mask = 255.255.255.0" + ], + "IP4.ADDRESS": [ + "192.0.2.15/24" + ], + "IP4.DNS": [], + "IP4.GATEWAY": [] + }, + "evidence_archive_sha256": "2d2e06f84c0018f5e811584814eaa9916fa8a868439ffb3fa9b425b34cb07581", + "evidence_artifact_id": 11142998500, + "evidence_files": { + "PhiOS/PhiOS/dist/fixture-free/SHA256SUMS": "0c4e780a4b37f979ee915bdc91bd2bb4e7c4b7ee2a6ac5c67e953a19b7df5538", + "PhiOS/PhiOS/dist/fixture-free/build.log": "4c77cff2c1db5b96492b567095eb0c99a2f2c3d343aae969a15be06c464b6897", + "PhiOS/PhiOS/dist/fixture-free/builder-image.json": "a11a8a03b44daf3a1e6ca96d563def4a236f01fb35140dd4d229ad49176001ce", + "PhiOS/PhiOS/dist/fixture-free/builder-packages.txt": "374d8ffd2ec34f22d8ef7f28110927eef7d17586faba2954e1906a2c5229c35f", + "PhiOS/PhiOS/dist/fixture-free/fixture-inventory.json": "14ce1577031ab6cc9b29967bc57b054661ce36d3a5ec0ada86a0bba9ddc9627e", + "PhiOS/PhiOS/dist/fixture-free/image-packages.txt": "742b3c4ce23cb82cdc8eb10f95152fc1b39422bdf9dd4532b66693d2fa92b202", + "PhiOS/PhiOS/dist/fixture-free/javascript-bundled-packages.json": "04402e02c14a791ffc99968668594c1943081f1f7237a36e8b440dd0d896bf1f", + "PhiOS/PhiOS/dist/fixture-free/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/fixture-free/mkarchiso.log": "c0bd1bec93c442f3e95e85e9dc2461325e89eeea36b177fc1d7091dd3cc76018", + "PhiOS/PhiOS/dist/fixture-free/native-packages.json": "464a726110ee270a9a237a1b758137d425cb83e1e65ee6f9d2db9023bc9f86f1", + "PhiOS/PhiOS/dist/fixture-free/provenance.json": "46f81f32a80012c4c571bc9a8b2935677dc2f784cb5c3f53373d7aedc48f75e6", + "PhiOS/PhiOS/dist/fixture-free/python-packages.json": "ef6655e03b4fd5a1bac84e505582a2b14bef22d7f45ee034f9339bffa61b8f7e", + "PhiOS/PhiOS/dist/fixture-free/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/fixture-free/sbom.cdx.json": "9cbf7086bb3545b3541cad2ca649af5ffc7cafdc849ba0bb4708c638851eb13b", + "PhiOS/PhiOS/dist/fixture-free/source-archive-sha256.txt": "7755b1db23a1052ff8b2165151cd14fd7ffe653592c1a5964299dc09e82c595e", + "PhiOS/PhiOS/dist/fixture-free/source-commit.txt": "f4f56dc35aaf63f31c440e9885fcbcbf53a819ddc4c62e708b9920b686260543", + "PhiOS/PhiOS/dist/fixture-free/source-review.json": "e49eb757dd811267a88e3d09b637c24b550e08aadfe674cc05aebd816fa6a972", + "PhiOS/PhiOS/dist/fixture-free/third-party-notices.json": "840a10e3dac4ffac473e0f68ba6d078c85ddf1e4120518fa598d1876fe3cc71f", + "_temp/phios-preview/preview-evidence.json": "0687f88e4aa349d220b0f5c37b0d6164731ec80ea105f8761d1a97110d7d10e8", + "_temp/phios-preview/qemu.log": "a7186e646536fd7526e73c107126ab08199a744baea9a78e5e4dc44ce79d58ae", + "_temp/phios-preview/screen.png": "22cea81cdd83da53b78a4186a04dbe315d75c395ac316673f3dbded190c0bc67", + "_temp/phios-preview/serial.log": "b21a9026e686adcbde033102c03d09a9c5da19df0220ab7fcdf7f236cc782636" + }, + "failure": "The actual restricted lease/address/server and absent gateway/DNS were correct. nmcli get-values joined the array-valued DHCP4.OPTION with pipes on one line, while the external probe assumed one option per line. Parse both observed array formats, retain exact DHCP-server uniqueness and gateway/DNS isolation checks, and regress the captured output plus static/wrong/ambiguous/forwarding refusals. The fixed guest exception detector correctly failed promptly; installation was skipped.", + "image_artifact_id": 11143427981, + "image_built": true, + "iso_sha256": "776ef8cc2ec673f27e1a3ce0d50eb70c1a2d4eb16e5e0e873e56739a9975203c", + "job_id": 110238876821, + "normal_installed_qualified": false, + "normal_live_qualified": false, + "release_gate_job_id": 110240951871, + "release_gate_result": "failure", + "release_ready": false, + "reported_error": "normal-user preview probe failed; see preserved serial log", + "reviewed_branch_head": "cda880f273a7d68afdd95670e2555c4f766884f6", + "run_attempt": 1, + "source_commit": "afe3795528e11107eeafbb74088c255cd97f356f", + "tested_source_tree": "49571965ef7717c427d049b2a4e01ae3941b4fb4", + "workflow_run": 36821774229 + }, + { + "workflow_run": 36825649652, + "run_attempt": 1, + "reviewed_branch_head": "57a55730b036a11d9e496701336999bf406bdaf5", + "source_commit": "d62011220805bfa5bb2313248a172e22cfc7b4cc", + "tested_source_tree": "b3bf00f59b147a5824466d93045eb3c11a835a23", + "job_id": 110250655210, + "phase": "signed_pinned_arch_builder_download", + "image_built": false, + "normal_live_qualified": false, + "normal_installed_qualified": false, + "evidence_artifact_id": 11145515404, + "evidence_archive_sha256_github": "642757c7426862f47310a94ae7d225e8cf0fde8a5f15cd9390ab446d70c5612a", + "evidence_archive_independently_verified": false, + "evidence_files_downloaded": false, + "job_logs_read": true, + "failure": "Pinned Arch archive transfers for iptables/readline signatures, iana-etc and brotli stalled below pacman's minimum speed. The signed package transaction held and no ISO was produced. Display conversion also failed because Pillow setup was not reached. Workspace execution/download service subsequently disconnected, so the archive digest is GitHub's producer digest rather than an independent review hash. Retry artifact names now include run_attempt to preserve failed and successful artifacts; empty display conversion avoids a spurious cleanup exception. Bounded source-bound receipt/file-hash metadata is emitted to CI logs for review without requiring binary archive extraction.", + "hardware_qualified": false, + "release_ready": false, + "release_gate_job_id": 110255621791, + "release_gate_result": "failure", + "separate_qa_job_id": 110250655131, + "separate_qa_result": "success", + "separate_qa_does_not_qualify_failed_normal_image": true, + "artifact_metadata": [ + { + "id": 11146055612, + "name": "phios-linux-evidence-36825649652", + "size_in_bytes": 4187814, + "digest": "sha256:15a003d8dee582fc87fda21fc987fd855cfe395f3de7dcef8f0716c438f6052e", + "expires_at": "2026-10-08T06:53:53Z" + }, + { + "id": 11145931386, + "name": "phios-linux-development-36825649652", + "size_in_bytes": 1803559635, + "digest": "sha256:0cb43a7b32ee68882fd76a7844fc955834437ee42621ea4a96e70bd8225211ab", + "expires_at": "2026-10-08T06:52:59Z" + }, + { + "id": 11145520372, + "name": "phios-fixture-free-candidate-36825649652", + "size_in_bytes": 37593, + "digest": "sha256:642757c7426862f47310a94ae7d225e8cf0fde8a5f15cd9390ab446d70c5612a", + "expires_at": "2026-10-08T06:39:16Z" + }, + { + "id": 11145515404, + "name": "phios-fixture-free-evidence-36825649652", + "size_in_bytes": 37593, + "digest": "sha256:642757c7426862f47310a94ae7d225e8cf0fde8a5f15cd9390ab446d70c5612a", + "expires_at": "2026-10-08T06:39:17Z" + } + ] + } + ], + "schema_version": "phios.desktop-attempts.v1" +} diff --git a/docs/os/evidence/desktop-normal-a7bcd986.json b/docs/os/evidence/desktop-normal-a7bcd986.json new file mode 100644 index 00000000..e46a589e --- /dev/null +++ b/docs/os/evidence/desktop-normal-a7bcd986.json @@ -0,0 +1,431 @@ +{ + "artifact_expiry": "2026-10-08", + "bounds": { + "actual_maintainer_signed_transition_qualified": false, + "automatic_idle_suspend_locking_enabled": false, + "external_network_forwarding": false, + "hardware_qualified": false, + "host_audio_attached": false, + "host_disks_attached": false, + "installed_network_attached": false, + "license_source_compliance_reviewed": false, + "physical_audio_qualified": false, + "publication_authority": false, + "release_ready": false, + "shared_folders": false, + "specific_graphical_admin_operation_qualified": false, + "wifi_radio_qualified": false + }, + "compact_checksum_payloads_verified": [ + "builder-image.json", + "builder-packages.txt", + "fixture-inventory.json", + "image-packages.txt", + "javascript-bundled-packages.json", + "javascript-packages.json", + "native-packages.json", + "provenance.json", + "python-packages.json", + "release.json", + "sbom.cdx.json", + "source-archive-sha256.txt", + "source-commit.txt", + "source-review.json", + "third-party-notices.json" + ], + "compact_provenance_hashes_verified": true, + "evidence_archive_sha256": "bf9998e13cd8c156ec0e3bad2673acd05edd213a6d711f2b01a4f1eed85d936a", + "evidence_artifact_id": 11144167873, + "evidence_files": { + "PhiOS/PhiOS/dist/fixture-free/SHA256SUMS": "65bd791dab33862ecaddebdbc4e2062e9287e2b533ddc7897d7167169c186d17", + "PhiOS/PhiOS/dist/fixture-free/build.log": "32a6a40e4b3cf6da66e8dca47709d0a74a33cf54cc46304433bfdca22c186482", + "PhiOS/PhiOS/dist/fixture-free/builder-image.json": "8e7834260abbc1e2c1270407d07c3d4e00d4123b7c44bc78caa7a1559d01f7d7", + "PhiOS/PhiOS/dist/fixture-free/builder-packages.txt": "374d8ffd2ec34f22d8ef7f28110927eef7d17586faba2954e1906a2c5229c35f", + "PhiOS/PhiOS/dist/fixture-free/fixture-inventory.json": "14ce1577031ab6cc9b29967bc57b054661ce36d3a5ec0ada86a0bba9ddc9627e", + "PhiOS/PhiOS/dist/fixture-free/image-packages.txt": "742b3c4ce23cb82cdc8eb10f95152fc1b39422bdf9dd4532b66693d2fa92b202", + "PhiOS/PhiOS/dist/fixture-free/javascript-bundled-packages.json": "04402e02c14a791ffc99968668594c1943081f1f7237a36e8b440dd0d896bf1f", + "PhiOS/PhiOS/dist/fixture-free/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/fixture-free/mkarchiso.log": "877ce1da964a0174b1ce57d6e2f40556e7c965c00c12c5ac2bece633fb9c7271", + "PhiOS/PhiOS/dist/fixture-free/native-packages.json": "a7dcc15677518924faab0a79805a98943b6ab60d4827df53144f74521c7b555c", + "PhiOS/PhiOS/dist/fixture-free/provenance.json": "7806b6deb9139ac240ace8cbe56829458f6699f3f9f4b917c50c67929295ed98", + "PhiOS/PhiOS/dist/fixture-free/python-packages.json": "ef6655e03b4fd5a1bac84e505582a2b14bef22d7f45ee034f9339bffa61b8f7e", + "PhiOS/PhiOS/dist/fixture-free/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/fixture-free/sbom.cdx.json": "7aeb3ca79787ca37e2d955ff8946b43bec5219f3b3a905f1f71b17005f4afa73", + "PhiOS/PhiOS/dist/fixture-free/source-archive-sha256.txt": "84dd99f77dd427879bceb3b38c0914a95290197a1233a008808b6e139d958b8b", + "PhiOS/PhiOS/dist/fixture-free/source-commit.txt": "1751ef173e9a317fb316d09772ed7b9ba44324ed8d64ded2830656386481ff6f", + "PhiOS/PhiOS/dist/fixture-free/source-review.json": "d770fb25e7450aa5dc3ac50baeb357c5406c974d8d376abbfc3fc5ad1dda8adc", + "PhiOS/PhiOS/dist/fixture-free/third-party-notices.json": "840a10e3dac4ffac473e0f68ba6d078c85ddf1e4120518fa598d1876fe3cc71f", + "_temp/phios-normal-installed/failed-boot-qemu.log": "d5769a9e9b307dbf480fe18b6ec059bad020803c312688d1f6f67d8ba5269b80", + "_temp/phios-normal-installed/failed-boot-serial.log": "16588375fb72bcf70bd4a86a56acf6cd6058fb8098354f0da13297cf2b0ccd63", + "_temp/phios-normal-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-normal-installed/installed-1-serial.log": "22b9d6556d486a82a21dc831aec64328dab607289f01c8898d6eb8e92d7d6553", + "_temp/phios-normal-installed/installed-2-qemu.log": "d5769a9e9b307dbf480fe18b6ec059bad020803c312688d1f6f67d8ba5269b80", + "_temp/phios-normal-installed/installed-2-serial.log": "4fdb9a5c2bb742faddca0902d767c0db64d5d7cd243998ae866bdc83f25e74f3", + "_temp/phios-normal-installed/installed-3-qemu.log": "d5769a9e9b307dbf480fe18b6ec059bad020803c312688d1f6f67d8ba5269b80", + "_temp/phios-normal-installed/installed-3-serial.log": "5eb795cfe7a4641c84ea6b813fa2e20ee559435413f14778d68f9fc36c5e10ad", + "_temp/phios-normal-installed/installed-evidence.json": "ff818e25ec6790c1e20b65b2985743aaa74e16d92279cfeb691148800422f8cf", + "_temp/phios-normal-installed/normal-install-live-qemu.log": "d5769a9e9b307dbf480fe18b6ec059bad020803c312688d1f6f67d8ba5269b80", + "_temp/phios-normal-installed/normal-install-live-serial.log": "7027e300ce4d23465cdad24afa4a7bd82b44e2bf5286bf9c495b4f3444b547a3", + "_temp/phios-normal-installed/normal-restore-live-qemu.log": "d5769a9e9b307dbf480fe18b6ec059bad020803c312688d1f6f67d8ba5269b80", + "_temp/phios-normal-installed/normal-restore-live-serial.log": "8233a03458933e31669625be46b002d2b793b70e0a45dd4211d7425d559d614f", + "_temp/phios-normal-installed/screen-failed-boot.png": "edae7f73081ea57d2acb727eaec72ce77e9df0e742746b63d45dfa931cf8279f", + "_temp/phios-normal-installed/screen-installed-1-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-normal-installed/screen-installed-1.png": "afb01a59382b9f9b622473c682d7e248fd36b33cec6c16708afc3468b0300f6d", + "_temp/phios-normal-installed/screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-normal-installed/screen-installed-2.png": "0cea019d751ea58845bfd64b7baf9614c3709501ba687ba9003fbc0dc2a98109", + "_temp/phios-normal-installed/screen-installed-3-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-normal-installed/screen-installed-3.png": "596a3f4bccd0296f4793c626d2c186afa52d477900b6a7374ed1f100a222901f", + "_temp/phios-normal-installed/screen-installed-locked.png": "59177e6ea22128f4b436b1f0df7222f9aa18a3416631c8ebf732c6196ed2a1f6", + "_temp/phios-normal-installed/screen-installed-unlocked.png": "afb01a59382b9f9b622473c682d7e248fd36b33cec6c16708afc3468b0300f6d", + "_temp/phios-normal-installed/screen-installed-wrong-password.png": "5ccb466a16a200c652f30646c549ba909a258553fbb8714c085012c71dfcc860", + "_temp/phios-normal-installed/screen-normal-install-live.png": "ae6620401d2952447d31f7ce14220c2299e66b685d8322c896e5e8266a4f5c66", + "_temp/phios-normal-installed/screen-normal-restore-live.png": "e2746716dddb6b90c01a2050ce2ce2da753eec8202291ae275c60c7ba443899e", + "_temp/phios-preview/preview-evidence.json": "f8d49c5140683a265c5f5fcdc42a10254899b2ed9be18bfac6081d47e1eecfe0", + "_temp/phios-preview/qemu.log": "142c7138b5b68d71a66113e71739c3e9cebb18ff023e0e44299b5c5f6febb610", + "_temp/phios-preview/screen-1-first.png": "6e3de4d0736e5801be13b7c14bc9526ab850374b9d31f0ebd2beea5b5ad5f2fa", + "_temp/phios-preview/screen-1-reauthenticated.png": "47ed9487f0f0fdfe7f9cde82094a9bf2a49cc6c930f6a64ee17f2f9597cca4b2", + "_temp/phios-preview/screen-2-first.png": "6e3de4d0736e5801be13b7c14bc9526ab850374b9d31f0ebd2beea5b5ad5f2fa", + "_temp/phios-preview/screen-2-reauthenticated.png": "8e38ef588389203442d8b0ff39b1db193008fc640d21de0290b8a54143a5e82d", + "_temp/phios-preview/screen-live-1-locked.png": "6e3de4d0736e5801be13b7c14bc9526ab850374b9d31f0ebd2beea5b5ad5f2fa", + "_temp/phios-preview/screen-live-1-unlocked.png": "0bcf9661f36d8d7d1425de9f02a62bd7c1083351fe768b840376b5d597ec0206", + "_temp/phios-preview/screen-live-1-wrong-password.png": "5ccb466a16a200c652f30646c549ba909a258553fbb8714c085012c71dfcc860", + "_temp/phios-preview/screen-live-2-locked.png": "6e3de4d0736e5801be13b7c14bc9526ab850374b9d31f0ebd2beea5b5ad5f2fa", + "_temp/phios-preview/screen-live-2-unlocked.png": "9204a71db2b24a65fc2e0553fbafb8e1d368e33e69cf81d152f066999c9ce2e6", + "_temp/phios-preview/screen-live-2-wrong-password.png": "5ccb466a16a200c652f30646c549ba909a258553fbb8714c085012c71dfcc860", + "_temp/phios-preview/screen.png": "8e38ef588389203442d8b0ff39b1db193008fc640d21de0290b8a54143a5e82d", + "_temp/phios-preview/serial.log": "6787ff156ad4ca9e812f977617cb393fdb60f5225b1dcc6b3ba146826ab41993" + }, + "image_artifact_id": 11144157950, + "installed_evidence": { + "abrupt_virtual_restart_passed": true, + "accelerator": "kvm", + "boot_ids": [ + "7ce293c136bb41a5894dbb7ac1b71a3a", + "38b15c5f9a1a41dd846223965e6e705c", + "579e92c903ad4bd2b7a3da1149396938" + ], + "ci_serial_console_injected": false, + "desktop_service_boots": [ + { + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "user_audio_services": true, + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": false + }, + { + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "user_audio_services": true, + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": false + }, + { + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "user_audio_services": true, + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": false + } + ], + "disk_bytes": 34359738368, + "disk_serial": "PHIOS_CI_BLANK", + "explicit_serial_console_password_login": true, + "fixture_free_installed_qualified": true, + "fixture_free_requested": true, + "hardware_qualified": false, + "installed": true, + "installed_screen_lock": { + "actual_super_l_shortcut": true, + "boot_id": "7ce293c136bb41a5894dbb7ac1b71a3a", + "correct_pam_password_unlocked": true, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "wrong_password_held": true + }, + "interrupted_signed_transaction_observed": false, + "interrupted_update_active_root_preserved": false, + "iso_sha256": "3b26a7334b36254b4e686843e84924ee14cdb6ef2d6748fd771e09a02e5f79a2", + "linux_governed_workflow": { + "actual_agent_uid": 1001, + "agent_broker_denied": true, + "agent_store_denied": true, + "approval_sha256": "8cbe660d391509128e68440c06d9646dbdf45040830e915ce0e042a0a908ff61", + "cancel_passed": true, + "expired_approval_sha256": "29d8c825d5d1d6a4d46a8f7d45081ba0a9f476620c6ce4a1f59d34691ff35d25", + "expiry_refused": true, + "hardware_qualified": false, + "receipt": { + "approval_sha256": "8cbe660d391509128e68440c06d9646dbdf45040830e915ce0e042a0a908ff61", + "authority_replayable": false, + "binding_sha256": "af96c055d7fe94094c4d3fe4de15487692493f87c987c9b8ac798e067fae4b3f", + "boot_id": "7ce293c136bb41a5894dbb7ac1b71a3a", + "decision_sha256": "a141ccf3bbbeff27ad9d63112641a5cdacf8c2beada034f591a28c72de86d68f", + "effect_performed": true, + "execution_authority": false, + "lease_sha256": "0f79baeacaf750adbffaa86143e6560d1c0421ccc6cd35d7f610b00fdf50f011", + "note_bytes": 57, + "note_sha256": "e2e3a3855d190c74791ad81fdc9a5dd8742363fcede860ef07439ce9e9058ba8", + "operator_uid": 1000, + "post_effect_verified": true, + "principal_uid": 1001, + "release_ready": false, + "schema_version": "phios.linux-proof-receipt.v1", + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91" + }, + "release_ready": false, + "replay_refused": true, + "schema_version": "phios.linux-proof-qualification.v1", + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "sudo_password_authentication": true + }, + "linux_governed_workflow_qualified": true, + "matched_root_efi_restored": true, + "no_iso_boot_passed": true, + "record_sha256": "c481900567db858427663a26909e82a9d30fe2e083c929cb68683a9823e87bb4", + "recovery_checkpoint_generation": "65ff80ee9fb94acca6ba7473e5bb021d", + "recovery_requested": true, + "release_ready": false, + "schema_version": "phios.installed-boot-evidence.v1", + "signed_package_application_qualified": false, + "signed_update_refusals_observed": false, + "signed_update_requested": false, + "simulated_boot_failure_observed": true, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "whole_os_recovery_passed": true + }, + "inventory_counts": { + "bundled_frontend_origins": 4, + "cyclonedx_components": 501, + "installed_npm": 12, + "native": 446, + "python": 39, + "supplier_notice_files": 746 + }, + "iso_sha256": "3b26a7334b36254b4e686843e84924ee14cdb6ef2d6748fd771e09a02e5f79a2", + "job_id": 110242720431, + "large_payloads_redownloaded_and_verified_locally": false, + "live_evidence": { + "accelerator": "kvm", + "boots": [ + { + "first": { + "boot_id": "cb5c8a0c10394a9dba1a84d6148cf2cb", + "fixture_free": true, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "stage": "first", + "uid": 1000 + }, + "lifecycle": { + "all_session_units_inactive": true, + "boot_id": "cb5c8a0c10394a9dba1a84d6148cf2cb", + "new_observer_pid": "992", + "old_observer_pid": "652", + "stopped_session_units": [ + "phios-session.target", + "phios-observer.service", + "phios-browser.service", + "phios-waybar.service", + "phios-curiosity-reader.service", + "phios-history-reader.service", + "phios-policykit.service", + "phios-audio.target", + "pipewire.service", + "pipewire-pulse.service", + "wireplumber.service", + "pipewire.socket", + "pipewire-pulse.socket" + ] + }, + "reauthenticated": { + "boot_id": "cb5c8a0c10394a9dba1a84d6148cf2cb", + "fixture_free": true, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "stage": "reauthenticated", + "uid": 1000 + } + }, + { + "first": { + "boot_id": "5f6efcbc10dd4d8facdab5b302d33ab4", + "fixture_free": true, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "stage": "first", + "uid": 1000 + }, + "lifecycle": { + "all_session_units_inactive": true, + "boot_id": "5f6efcbc10dd4d8facdab5b302d33ab4", + "new_observer_pid": "1002", + "old_observer_pid": "662", + "stopped_session_units": [ + "phios-session.target", + "phios-observer.service", + "phios-browser.service", + "phios-waybar.service", + "phios-curiosity-reader.service", + "phios-history-reader.service", + "phios-policykit.service", + "phios-audio.target", + "pipewire.service", + "pipewire-pulse.service", + "wireplumber.service", + "pipewire.socket", + "pipewire-pulse.socket" + ] + }, + "reauthenticated": { + "boot_id": "5f6efcbc10dd4d8facdab5b302d33ab4", + "fixture_free": true, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "stage": "reauthenticated", + "uid": 1000 + } + } + ], + "desktop_service_boots": [ + { + "boot_id": "cb5c8a0c10394a9dba1a84d6148cf2cb", + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "restricted_dhcp_address": "192.0.2.15/24", + "restricted_dhcp_server": "192.0.2.2", + "restricted_ipv4_default_route": false, + "restricted_ipv4_dns_advertised": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "stage": "first", + "uid": 1000, + "user_audio_services": true, + "virtual_network_scope": "QEMU restricted user network 192.0.2.0/24; no forwarding", + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": true + }, + { + "boot_id": "cb5c8a0c10394a9dba1a84d6148cf2cb", + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "restricted_dhcp_address": "192.0.2.15/24", + "restricted_dhcp_server": "192.0.2.2", + "restricted_ipv4_default_route": false, + "restricted_ipv4_dns_advertised": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "stage": "reauthenticated", + "uid": 1000, + "user_audio_services": true, + "virtual_network_scope": "QEMU restricted user network 192.0.2.0/24; no forwarding", + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": true + }, + { + "boot_id": "5f6efcbc10dd4d8facdab5b302d33ab4", + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "restricted_dhcp_address": "192.0.2.15/24", + "restricted_dhcp_server": "192.0.2.2", + "restricted_ipv4_default_route": false, + "restricted_ipv4_dns_advertised": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "stage": "first", + "uid": 1000, + "user_audio_services": true, + "virtual_network_scope": "QEMU restricted user network 192.0.2.0/24; no forwarding", + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": true + }, + { + "boot_id": "5f6efcbc10dd4d8facdab5b302d33ab4", + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "restricted_dhcp_address": "192.0.2.15/24", + "restricted_dhcp_server": "192.0.2.2", + "restricted_ipv4_default_route": false, + "restricted_ipv4_dns_advertised": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "stage": "reauthenticated", + "uid": 1000, + "user_audio_services": true, + "virtual_network_scope": "QEMU restricted user network 192.0.2.0/24; no forwarding", + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": true + } + ], + "external_network_forwarding": false, + "fixture_free_qualified": true, + "hardware_qualified": false, + "host_audio_attached": false, + "iso_sha256": "3b26a7334b36254b4e686843e84924ee14cdb6ef2d6748fd771e09a02e5f79a2", + "public_volatile_credentials": true, + "release_ready": false, + "restricted_virtual_ethernet": true, + "schema_version": "phios.fixture-free-live-evidence.v1", + "screen_lock_boots": [ + { + "actual_super_l_shortcut": true, + "boot_id": "cb5c8a0c10394a9dba1a84d6148cf2cb", + "correct_pam_password_unlocked": true, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "wrong_password_held": true + }, + { + "actual_super_l_shortcut": true, + "boot_id": "5f6efcbc10dd4d8facdab5b302d33ab4", + "correct_pam_password_unlocked": true, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "wrong_password_held": true + } + ], + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "test_code_injected_into_image": false + }, + "qualification_scope": "Restricted virtual Ethernet DHCP address/server and absent IPv4 gateway/DNS, synthetic HDA PCM with null host backend, UID 1000 services/audio and PolicyKit agent startup, real Super+L/PAM wrong/correct password, all 13 session units inactive after logout and service/audio/network checks after reauthentication; exact normal ISO production install/data/proof/abrupt restart/deliberate failed boot/matched root+EFI recovery.", + "reviewed_branch_head": "9c98475274442595c59370113b9c1e0dee595ec9", + "schema_version": "phios.desktop-normal-qualification.v1", + "source_archive_sha256": "41ed0a19a811f7ac6c22edbb555adbc4b55d5421f8ea6b9e73481cd58116d8b7", + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "tested_source_tree": "a85700b2c08e54a066a77a2f4a4db7494b7579ff", + "visually_inspected": [ + "screen-live-2-wrong-password.png", + "screen-installed-3.png", + "screen-failed-boot.png" + ], + "workflow_run": 36823086807 +} diff --git a/docs/os/evidence/desktop-signed-a7bcd986.json b/docs/os/evidence/desktop-signed-a7bcd986.json new file mode 100644 index 00000000..72f8398e --- /dev/null +++ b/docs/os/evidence/desktop-signed-a7bcd986.json @@ -0,0 +1,247 @@ +{ + "artifact_expiry": "2026-10-08", + "bounds": { + "actual_maintainer_signed_transition_qualified": false, + "ephemeral_qa_signer_is_a_release_identity": false, + "hardware_qualified": false, + "host_audio_attached": false, + "host_disks_attached": false, + "license_source_compliance_reviewed": false, + "network_attached": false, + "physical_audio_qualified": false, + "publication_authority": false, + "release_ready": false, + "shared_folders": false, + "test_fixtures_and_disposable_credentials_in_qa_only": true, + "wifi_radio_qualified": false + }, + "compact_checksum_payloads_verified": [ + "builder-image.json", + "builder-packages.txt", + "fixture-inventory.json", + "image-packages.txt", + "javascript-bundled-packages.json", + "javascript-packages.json", + "native-packages.json", + "provenance.json", + "python-packages.json", + "release.json", + "sbom.cdx.json", + "source-archive-sha256.txt", + "source-commit.txt", + "source-review.json", + "third-party-notices.json" + ], + "compact_provenance_hashes_verified": true, + "evidence_archive_sha256": "f1aaa1e361e0e0016cfd67dd86e34a6abf88662810a340e28cf75a5a2e9f0e62", + "evidence_artifact_id": 11144925813, + "evidence_files": { + "PhiOS/PhiOS/dist/linux/SHA256SUMS": "12f822c8e44d852120a58e81902d64222cde250169d979afa7d6e249756f802d", + "PhiOS/PhiOS/dist/linux/build.log": "7aa2972c25486a2c7d84a66c607e0b7ee6f244a617d15c790cbc39ed7365153e", + "PhiOS/PhiOS/dist/linux/builder-image.json": "9fb7fbcfbd741f40497c4adbd11dbbbfa7a5c8698a90d65cd77f695e005e159d", + "PhiOS/PhiOS/dist/linux/builder-packages.txt": "374d8ffd2ec34f22d8ef7f28110927eef7d17586faba2954e1906a2c5229c35f", + "PhiOS/PhiOS/dist/linux/fixture-inventory.json": "2ebf26541ddaa6d1e239b1a3be944946f18e8d08e78837065d11eed7921d7a60", + "PhiOS/PhiOS/dist/linux/image-packages.txt": "aaa20387817ce8190c61b9408185f5e77809a25b730ca2902936f751d23613c1", + "PhiOS/PhiOS/dist/linux/javascript-bundled-packages.json": "04402e02c14a791ffc99968668594c1943081f1f7237a36e8b440dd0d896bf1f", + "PhiOS/PhiOS/dist/linux/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/linux/mkarchiso.log": "d3ad4aba64609618eb559fa9f2ba0049dfaad9c8b9438e74a158cacdfe69982d", + "PhiOS/PhiOS/dist/linux/native-packages.json": "3255b1b3d25c93136575b34a4e09093c747bf7a84b0fc213a94e0193af50d88c", + "PhiOS/PhiOS/dist/linux/provenance.json": "448972fd213d3d6bea6c91bd64a72afc14092cb8c20f1d58dc143737d2e8b012", + "PhiOS/PhiOS/dist/linux/python-packages.json": "ef6655e03b4fd5a1bac84e505582a2b14bef22d7f45ee034f9339bffa61b8f7e", + "PhiOS/PhiOS/dist/linux/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/linux/sbom.cdx.json": "c1028c93c66ced5a152a75e3d5b6feb831947b49330aa711276f51968efca23e", + "PhiOS/PhiOS/dist/linux/source-archive-sha256.txt": "84dd99f77dd427879bceb3b38c0914a95290197a1233a008808b6e139d958b8b", + "PhiOS/PhiOS/dist/linux/source-commit.txt": "1751ef173e9a317fb316d09772ed7b9ba44324ed8d64ded2830656386481ff6f", + "PhiOS/PhiOS/dist/linux/source-review.json": "eeead9f2941fe4a3c04a9c3daabdae3f4f3f6dcff7dc07894231e9880b0cb06e", + "PhiOS/PhiOS/dist/linux/third-party-notices.json": "840a10e3dac4ffac473e0f68ba6d078c85ddf1e4120518fa598d1876fe3cc71f", + "_temp/phios-boot/boot-evidence.json": "3db9af0242bda6ee98ac9154e9dd378d637d28f1e2054a6f7987cb75bccf53b5", + "_temp/phios-boot/qemu.log": "1ac2cb77c2583e1cb26c2da9c99ce6ad91bccca80f93ab544954e2196403680c", + "_temp/phios-boot/screen-first.png": "1c5e4b3a188e4300d3142550b4bf90678aafcb31b1ecf34585d67a5488b4902e", + "_temp/phios-boot/screen.png": "99e9217ff43f1498d1e8db57d4e7760317919b095a8722ca337503df744f9594", + "_temp/phios-boot/serial.log": "3d85b5585260137324fbe1b1adb1fb5e955722db0400dd6d9ec35124cad1459b", + "_temp/phios-installed/failed-boot-qemu.log": "de9567dfb668cecb59e1264f3f53ca1888bf1c50537018e1b765ba1d533b80cb", + "_temp/phios-installed/failed-boot-serial.log": "b71939ca936ca96b3b552f80698f989a5a86e98a2c2926c935086e079fa1186d", + "_temp/phios-installed/install-live-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/install-live-serial.log": "d695790077ca0a24f32844a88c11bb1b00d1596edcf0b5ea897371649faaffaf", + "_temp/phios-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/installed-1-serial.log": "7692c9dfcbb7de9003523007d9466084f867642669bb12bc86091d72624668de", + "_temp/phios-installed/installed-2-qemu.log": "de9567dfb668cecb59e1264f3f53ca1888bf1c50537018e1b765ba1d533b80cb", + "_temp/phios-installed/installed-2-serial.log": "1ebe224dd815a208199ad4f0a6f9cac2cd157c823191f1aa57b4f1be35c03fd9", + "_temp/phios-installed/installed-3-qemu.log": "de9567dfb668cecb59e1264f3f53ca1888bf1c50537018e1b765ba1d533b80cb", + "_temp/phios-installed/installed-3-serial.log": "8e31aca27ba9f9795d0f848dcb3dd81cea5f27f11cfddb30e08c28506dd3c157", + "_temp/phios-installed/installed-evidence.json": "1fbbd4f7b89be64b4b365221d466696e96b6bd56682b02796d68d1bf0caa9e3b", + "_temp/phios-installed/interrupted-resume-live-qemu.log": "de9567dfb668cecb59e1264f3f53ca1888bf1c50537018e1b765ba1d533b80cb", + "_temp/phios-installed/interrupted-resume-live-serial.log": "f0db9199d641cefaf90f5f00ad3dabeef59f8a7dddecb5229f04a6a5120a09df", + "_temp/phios-installed/recovery-live-qemu.log": "de9567dfb668cecb59e1264f3f53ca1888bf1c50537018e1b765ba1d533b80cb", + "_temp/phios-installed/recovery-live-serial.log": "341051985972f3691c67461eb5a1de6d4724ec979aafcf70c01939e1a542f25d", + "_temp/phios-installed/screen-failed-boot.png": "da01492ec757bcc04ca936d7d9333bee04415ad20cd594281b8e11c33bae8a22", + "_temp/phios-installed/screen-install-live.png": "f4975acf1c281371ca49664446bd15b673c1858f1fcb1f7392bd14357aadd54b", + "_temp/phios-installed/screen-installed-1-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-installed/screen-installed-1.png": "715792c99942409c936538311c62e11084069ee9a343cc1f8ef00e5782114e6e", + "_temp/phios-installed/screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-2.png": "74ba0199d47a868a12e139845ca1603228dab7d2f00b10b84ebd2acadfa4872e", + "_temp/phios-installed/screen-installed-3-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-3.png": "080af65940193b0d1347e6e8777be8640f71751d05958c202a329d641eaa643f", + "_temp/phios-installed/screen-installed-locked.png": "59177e6ea22128f4b436b1f0df7222f9aa18a3416631c8ebf732c6196ed2a1f6", + "_temp/phios-installed/screen-installed-unlocked.png": "715792c99942409c936538311c62e11084069ee9a343cc1f8ef00e5782114e6e", + "_temp/phios-installed/screen-installed-wrong-password.png": "5ccb466a16a200c652f30646c549ba909a258553fbb8714c085012c71dfcc860", + "_temp/phios-installed/screen-interrupted-resume-live.png": "b46a9e55a6450cc78abf5a0f2391ae388dbd3d7a478af489faa5fa77d5f0f615", + "_temp/phios-installed/screen-recovery-live.png": "b46bf99675a0a5075bdd3680c4bb83314952165a44cfffe62df79bf7503e24df" + }, + "image_artifact_id": 11144596210, + "installed_evidence": { + "abrupt_virtual_restart_passed": true, + "accelerator": "kvm", + "boot_ids": [ + "3c134f4a286e489aa1dbeb0136640220", + "fbb27653fd8f4a9c97a0b561172389c6", + "2cb0ae6c74fc4ddf9fc44d7e14e3086c" + ], + "ci_serial_console_injected": true, + "desktop_service_boots": [ + { + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "user_audio_services": true, + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": false + }, + { + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "user_audio_services": true, + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": false + }, + { + "emulated_alsa_device_observed": true, + "host_audio_attached": false, + "nonroot_graphical_policykit_agent": true, + "physical_audio_qualified": false, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "user_audio_services": true, + "virtual_pcm_playback_completed": true, + "wifi_radio_qualified": false, + "wired_dhcp_observed": false + } + ], + "disk_bytes": 34359738368, + "disk_serial": "PHIOS_CI_BLANK", + "explicit_serial_console_password_login": false, + "fixture_free_installed_qualified": false, + "fixture_free_requested": false, + "hardware_qualified": false, + "installed": true, + "installed_screen_lock": { + "actual_super_l_shortcut": true, + "boot_id": "3c134f4a286e489aa1dbeb0136640220", + "correct_pam_password_unlocked": true, + "release_ready": false, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "uid": 1000, + "wrong_password_held": true + }, + "interrupted_signed_transaction_observed": true, + "interrupted_update_active_root_preserved": true, + "iso_sha256": "c0dd9a93ceeda3897f7c5d5b16785f4cf418935e1c5d3ec312ec3130d8446f2e", + "linux_governed_workflow": { + "actual_agent_uid": 1001, + "agent_broker_denied": true, + "agent_store_denied": true, + "approval_sha256": "ea730837392c38d44775ed08dae5bd4be036f04197db84e5af198d6d4c656b16", + "cancel_passed": true, + "expired_approval_sha256": "c0ba058d1e0f91b4939dcbf9d4ad889b13cec48a7caec7e395c669a3b4c77ce8", + "expiry_refused": true, + "hardware_qualified": false, + "receipt": { + "approval_sha256": "ea730837392c38d44775ed08dae5bd4be036f04197db84e5af198d6d4c656b16", + "authority_replayable": false, + "binding_sha256": "051d4e24a38f568bc7bfb2898ddaf04564df05aeedceb729ad689aeb8c63d8f9", + "boot_id": "3c134f4a286e489aa1dbeb0136640220", + "decision_sha256": "238981b9eddcb9452767b7a85f22f4a62072546a9c9996c898ea291bd83b57fe", + "effect_performed": true, + "execution_authority": false, + "lease_sha256": "dbf6f4a500908106b8708179572fa08dc12528056b01c6ce342dac512df6b74c", + "note_bytes": 57, + "note_sha256": "e2e3a3855d190c74791ad81fdc9a5dd8742363fcede860ef07439ce9e9058ba8", + "operator_uid": 1000, + "post_effect_verified": true, + "principal_uid": 1001, + "release_ready": false, + "schema_version": "phios.linux-proof-receipt.v1", + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91" + }, + "release_ready": false, + "replay_refused": true, + "schema_version": "phios.linux-proof-qualification.v1", + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "sudo_password_authentication": true + }, + "linux_governed_workflow_qualified": true, + "matched_root_efi_restored": true, + "no_iso_boot_passed": true, + "record_sha256": "c481900567db858427663a26909e82a9d30fe2e083c929cb68683a9823e87bb4", + "recovery_checkpoint_generation": "ac673f7d5fa34c3c82c0c2c9d89d5cc7", + "recovery_requested": true, + "release_ready": false, + "schema_version": "phios.installed-boot-evidence.v1", + "signed_package_application_qualified": true, + "signed_update_refusals_observed": true, + "signed_update_requested": true, + "signed_update_transaction": { + "ephemeral_test_key": true, + "generation": "ac673f7d5fa34c3c82c0c2c9d89d5cc7", + "sequence": 1, + "signer": "A99AE8655DA39A743B129437E5675DD9D6A31B72" + }, + "simulated_boot_failure_observed": true, + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "whole_os_recovery_passed": true + }, + "inventory_counts": { + "bundled_frontend_origins": 4, + "cyclonedx_components": 502, + "installed_npm": 12, + "native": 447, + "python": 39, + "supplier_notice_files": 746 + }, + "iso_sha256": "c0dd9a93ceeda3897f7c5d5b16785f4cf418935e1c5d3ec312ec3130d8446f2e", + "job_id": 110242720445, + "large_payloads_redownloaded_and_verified_locally": false, + "live_evidence": { + "accelerator": "kvm", + "boot_ids": [ + "21b37f5d9bf64e85b8ec4427f8e21006", + "bd8b0309b95546ec9a5d4830b73abff6" + ], + "boot_passed": true, + "hardware_qualified": false, + "iso_sha256": "c0dd9a93ceeda3897f7c5d5b16785f4cf418935e1c5d3ec312ec3130d8446f2e", + "reboot_passed": true, + "release_ready": false, + "schema_version": "phios.live-boot-evidence.v1", + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "timeout_seconds": 600 + }, + "reviewed_branch_head": "9c98475274442595c59370113b9c1e0dee595ec9", + "schema_version": "phios.desktop-signed-qa-qualification.v1", + "source_archive_sha256": "41ed0a19a811f7ac6c22edbb555adbc4b55d5421f8ea6b9e73481cd58116d8b7", + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "tested_source_tree": "a85700b2c08e54a066a77a2f4a4db7494b7579ff", + "workflow_run": 36823086807 +} diff --git a/docs/os/evidence/fixture-free-attempts.json b/docs/os/evidence/fixture-free-attempts.json new file mode 100644 index 00000000..1f4ae13b --- /dev/null +++ b/docs/os/evidence/fixture-free-attempts.json @@ -0,0 +1,37 @@ +{ + "attempts": [ + { + "evidence_artifact_id": 11137864737, + "evidence_files": { + "PhiOS/PhiOS/dist/fixture-free/build.log": "3e7bb609dd75c63c3e7f38d75057cab48ce9dd35343a5a3832e2cd2d4309bf97", + "PhiOS/PhiOS/dist/fixture-free/builder-image.json": "4c24272571dc26166f660640fd3fb3cd97a77b799b032876e507afe933679d64", + "PhiOS/PhiOS/dist/fixture-free/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/fixture-free/fixture-inventory.json": "14ce1577031ab6cc9b29967bc57b054661ce36d3a5ec0ada86a0bba9ddc9627e", + "PhiOS/PhiOS/dist/fixture-free/image-packages.txt": "f2c4bf4ca37189cec44b2fb77826e39e2528df2011ff23b94000e3408a4ad93c", + "PhiOS/PhiOS/dist/fixture-free/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/fixture-free/mkarchiso.log": "9940448095210ce1fdb903b06d641d2b68e3664114c6b9bbde1bc9712f34b2cc", + "PhiOS/PhiOS/dist/fixture-free/native-packages.json": "ce5aad0f6e2580b0b0a7b4c19aba64bbf11fc1c979555dfb662aca2756cf8754", + "PhiOS/PhiOS/dist/fixture-free/provenance.json": "374f469246ce0c6589ddbe1a56d2d2a7b09d6f86aefa962693ac1d3ccb10017e", + "PhiOS/PhiOS/dist/fixture-free/python-packages.json": "9af1ad8db48a4e1a528d082984d07efbf34539b52ddac7026ea4e9923073d5a0", + "PhiOS/PhiOS/dist/fixture-free/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/fixture-free/sbom.cdx.json": "a98584f3eed17d1f632cca4dc4c7ff4441162650248b1fe377f3421b8184fa01", + "PhiOS/PhiOS/dist/fixture-free/source-archive-sha256.txt": "1c6673eded8f2cb947fcd753a6be0a4c14e33323bcb517ec4c3a9b6324cdc705", + "PhiOS/PhiOS/dist/fixture-free/source-commit.txt": "385b6ff6df10f358702bcdd516aa329296354ab5259990529ff07dd128aabc05", + "PhiOS/PhiOS/dist/fixture-free/source-review.json": "c9be6272f62b1694480c9c0056de4420244354c50861769045cb8996e2723964", + "PhiOS/PhiOS/dist/fixture-free/third-party-notices.json": "137316e3c393079fd72aa7234611db782aa5f7c540b69648dd42729f35e25493" + }, + "failure": "Ubuntu distribution JSON Schema validator raised TypeError while sorting dicts during valid actual-image SBOM validation, before QEMU. The complete 437-component SBOM validates against the pinned official CycloneDX schemas in the newer local validator. CI now installs jsonschema==4.26.0 in a dedicated virtual environment.", + "fixture_free_vm_qualified": false, + "head": "83d2feb42a3dbd506bd6479ff60f73ce7ff7961f", + "image_artifact_id": 11137889468, + "image_built": true, + "iso_sha256": "0fc3d6fc787d636b0d85ea2c78e73069048486cfce6f57f4380062c158194ef4", + "job_id": 110195126187, + "native_python_npm_components": 437, + "release_ready": false, + "source_commit": "923a61567be61e0f25a6d4cf07ed427c998abd89", + "workflow_run": 36807539115 + } + ], + "schema_version": "phios.fixture-free-attempts.v1" +} diff --git a/docs/os/evidence/installation-0253b6e0.json b/docs/os/evidence/installation-0253b6e0.json new file mode 100644 index 00000000..987e31b8 --- /dev/null +++ b/docs/os/evidence/installation-0253b6e0.json @@ -0,0 +1,60 @@ +{ + "abrupt_virtual_restart_passed": true, + "accelerator": "kvm", + "artifact_expiry": "2026-10-08", + "ci_serial_console_injected": true, + "cpus": 2, + "disk_bytes": 34359738368, + "disk_serial": "PHIOS_CI_BLANK", + "evidence_artifact_id": 11135321615, + "evidence_files": { + "boot-evidence.json": "9948a5f3823363d90d34aa84b05df6d54b64f8e9fcdac3e705583ce01e6b13ae", + "builder-image.json": "9526e9737def8b23a3d1297bf6c7a593b19ba1ec039ed5d3b9d10d57ed16df34", + "install-live-qemu.log": "33c482cb34b64de8cea0bd9b94549dcb837ea35745e324744900915ce1a24b8d", + "install-live-serial.log": "522b00042c3bc8ba0207e73c88d0ec37a210d325bdd4b039aba9286589b525aa", + "installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "installed-1-serial.log": "ae2a4903354f29b6618951c131ef72d54adc48dade1e7f5259da43e454a0b2fa", + "installed-2-qemu.log": "33c482cb34b64de8cea0bd9b94549dcb837ea35745e324744900915ce1a24b8d", + "installed-2-serial.log": "cd0438faa633b6c8199cdc01756bbf0bd1f09fe51e7a89b3ff46615be2b315e5", + "installed-evidence.json": "125aa97b8c4b7bbe96546ec98e5f580499fa3f68a093e584ea2831c4d4457f92", + "mkarchiso.log": "957c60b9135a6747d48e17a0aac118fa602b46124b1fbed4c842b44e0ca9d902", + "qemu.log": "8183afaf3dbaee427198c21759fdbcad0a6ce1a046e59b35ce77e616071ad0a2", + "release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "screen-first.png": "b948c3898cde2934cec3760a9b8cc29f332defe1c6a23333458c3e214e56b610", + "screen-install-live.png": "e77f8927d18f259bbf3bd968fd15eb43007ee346ae2109c26aa1f60652aa4828", + "screen-installed-1-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "screen-installed-1.png": "70606f87e262a8242763c47258fe828d750ea210a5781a973f36fe5a1f9716be", + "screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "screen-installed-2.png": "c4a706b924ef4a742e2b02ce7edac5d948210d489a299f0e41548970c6f7ee98", + "screen.png": "df5a5ac5fddf46461c0e9bd41ef1cdf615e8d4f08777e64d05bc015577a6f4b5", + "serial.log": "b3eaf114a12ca7061bc18e7f4e10590a74bc7cd5739cd788127b85ece305ae2f" + }, + "hardware_qualified": false, + "host_disks_attached": false, + "image_artifact_id": 11134958214, + "installed": true, + "installed_boot_ids": [ + "e5ba8528af464b8192312d9aab0db869", + "caa9695c41c64c3d898e12c1bd3234f5" + ], + "installer_head": "f135a24d3d88173f611829317e4ad04ebc22eff3", + "iso_sha256": "8599bbc7ff2ed35432bae23692464d4d5afa9ffdfc787699a7be88f2cfc62f5c", + "job_id": 110167226382, + "live_boot_ids": [ + "264482abc42a499f80a60606b388f914", + "a02abb74623343f2adfaa01a4f4651a8" + ], + "live_boot_passed": true, + "live_reboot_passed": true, + "network": false, + "no_iso_boot_passed": true, + "public_disposable_credentials": true, + "ram_mib": 4096, + "record_sha256": "c481900567db858427663a26909e82a9d30fe2e083c929cb68683a9823e87bb4", + "release_ready": false, + "schema_version": "phios.os-qualification-summary.v1", + "screenshot_visually_reviewed": true, + "signed": false, + "source_commit": "0253b6e0fb27251fe2da37b6d8c1e31245a64290", + "workflow_run": 36798467774 +} diff --git a/docs/os/evidence/linux-proof-attempts.json b/docs/os/evidence/linux-proof-attempts.json new file mode 100644 index 00000000..f60ca1b3 --- /dev/null +++ b/docs/os/evidence/linux-proof-attempts.json @@ -0,0 +1,62 @@ +{ + "attempts": [ + { + "evidence_artifact_id": 11138998040, + "evidence_files": { + "PhiOS/PhiOS/dist/linux/build.log": "b2926f9e5a138d4ee82246fcb4e7930025a6fad1e062d813ac0163a8e6c7c274", + "PhiOS/PhiOS/dist/linux/builder-image.json": "152a89cdd304d4c82530635a884da51fa7a5667dc36e2124b922b34e1f4a818f", + "PhiOS/PhiOS/dist/linux/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/linux/fixture-inventory.json": "2ebf26541ddaa6d1e239b1a3be944946f18e8d08e78837065d11eed7921d7a60", + "PhiOS/PhiOS/dist/linux/image-packages.txt": "dd6faf936234848a574c0d3125da4eddabaa33b8f02998bc7be070250d3e29f9", + "PhiOS/PhiOS/dist/linux/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/linux/mkarchiso.log": "52dd7695fca50a2a4727e21413070068f5107385a5f5822b48a7444affad7895", + "PhiOS/PhiOS/dist/linux/native-packages.json": "ad9071bcaf5ab74f87b7915aa8e0909f95b577e472c2996aa1e1064427697090", + "PhiOS/PhiOS/dist/linux/provenance.json": "4f546f4e5ad9478f8cb8b1fde934c8bf919b62c5ba7d7e1f90b80b86e656291f", + "PhiOS/PhiOS/dist/linux/python-packages.json": "9af1ad8db48a4e1a528d082984d07efbf34539b52ddac7026ea4e9923073d5a0", + "PhiOS/PhiOS/dist/linux/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/linux/sbom.cdx.json": "b6e74ec4d252a5e5b2b1a884d35ed806fa10d10503903a68160eaf71339f3e84", + "PhiOS/PhiOS/dist/linux/source-archive-sha256.txt": "46c01dbd154317150c0a91ae1931427ab9c15f979e33271e2f67cd87075124d7", + "PhiOS/PhiOS/dist/linux/source-commit.txt": "3b5f0f3cc3d038a55ab34daa3b9637df451584ac29ef77f1fdd433e36a2536d1", + "PhiOS/PhiOS/dist/linux/source-review.json": "0a7b94001b98bf05951f44fc47e518cc008a14cd71b871c16a73d3ff7f7086df", + "PhiOS/PhiOS/dist/linux/third-party-notices.json": "137316e3c393079fd72aa7234611db782aa5f7c540b69648dd42729f35e25493", + "_temp/phios-boot/boot-evidence.json": "89fd0b797b17370b187c1d450cc05c6f5ff51b26fd76e54f33859226de785587", + "_temp/phios-boot/qemu.log": "cfb88d1675b569a5b47b59d2b1fe103919a5649ff0a475d396d1ffde6c6b24f0", + "_temp/phios-boot/screen-first.png": "6bf190581d13131e0dfa84a0d2c48301eee4a9cae68e2d25e547335951f37d24", + "_temp/phios-boot/screen.png": "9e5130dfebfa68d901c9e339e94970c3e370bce4f7422bc196a6f679f227384c", + "_temp/phios-boot/serial.log": "b7a8e5bcd5402a5e2cc78dfca3d5ad035dcc579d174166a321f5544d23c69abb", + "_temp/phios-installed/install-live-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/install-live-serial.log": "74188764f835bf43d87ec7989e4de353cfd75f955defe6e85e1bcba41a92e05b", + "_temp/phios-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/installed-1-serial.log": "b2c8017c2eac119a0a7a087932d9465b3a150fb128ce9aab3433d65142a58956", + "_temp/phios-installed/installed-evidence.json": "0feaec08478a3f9d62f3ef66fe730d7fea3a125345a3184cc3edc7a4f906b85f", + "_temp/phios-installed/interrupted-resume-live-qemu.log": "06733008ca698aa515bfe73217fc56e15a6720fc69302592e9ab9e6c594c2e95", + "_temp/phios-installed/interrupted-resume-live-serial.log": "6330debfc5b90e9c344bc5759c0bab5bf2937f0780c6180f4743074fd8825c44", + "_temp/phios-installed/screen-install-live.png": "52e0cbfba53195e94b8e53e193f093d9b50d93ce7c52d84314ccde8725245f10", + "_temp/phios-installed/screen-installed-1-failure.png": "14e78d7ef364fe1a127090e54d5744d8e4a83a82b5ff9f975957ec858d4321aa", + "_temp/phios-installed/screen-installed-1-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-interrupted-resume-live.png": "612f17fbf548ef2042612b8617cc4b995174213c20e1d1762575d9f9805cd17e" + }, + "failure": "External fixture saved its user QA summary before the older data probe created the qa directory. FileNotFoundError occurred after all proof effect/refusal commands passed, before restart/recovery qualification. Fixture now creates its own private summary directory and flushes it.", + "head": "d4e0c4bda9aca66189a6a4d08f459f0a0a437a6d", + "image_artifact_id": 11138743361, + "iso_sha256": "400dae3ba8cce0ef834b68cd905585ecd7feec372a15abc4268dfbd68f3a02e9", + "job_id": 110201722446, + "linux_workflow_qualified": false, + "observed": [ + "production agent service", + "actual sudo password authentication", + "UID 1001 store/broker denial", + "cancellation", + "canonical bound single-use lease", + "actual note/readback receipt", + "replay refusal", + "real 60-second expiry refusal", + "successful signed package and preserved interrupted stage" + ], + "release_ready": false, + "source_commit": "0133997a0ac8b2d202170dd28a6f9c19b23c51fe", + "workflow_run": 36809656268 + } + ], + "schema_version": "phios.linux-proof-attempts.v1" +} diff --git a/docs/os/evidence/normal-installed-5145b4da.json b/docs/os/evidence/normal-installed-5145b4da.json new file mode 100644 index 00000000..7599f621 --- /dev/null +++ b/docs/os/evidence/normal-installed-5145b4da.json @@ -0,0 +1,181 @@ +{ + "abrupt_virtual_restart_passed": true, + "accelerator": "kvm", + "actual_maintainer_signed_transition_qualified": false, + "artifact_expiry": "2026-10-08", + "boot_ids": [ + "fd9f0d822cb84b73899801ad86c186cf", + "06a12b02336b46bb9556a91491b85fee", + "0ebc7fcbe8c5456d977707f0d5bccb1d" + ], + "ci_serial_console_injected": false, + "compact_provenance_payload_hashes_verified": [ + "builder-image.json", + "builder-packages.txt", + "fixture-inventory.json", + "image-packages.txt", + "javascript-bundled-packages.json", + "javascript-packages.json", + "native-packages.json", + "python-packages.json", + "release.json", + "sbom.cdx.json", + "source-archive-sha256.txt", + "source-commit.txt", + "source-review.json", + "third-party-notices.json" + ], + "cpus": 2, + "disk_bytes": 34359738368, + "disk_serial": "PHIOS_CI_BLANK", + "evidence_archive_sha256": "9357a742254a7cda1cd2a4efcb3058036795e2b82e7dfdcc2d9ec3081ccf52a5", + "evidence_artifact_id": 11140895800, + "evidence_files": { + "PhiOS/PhiOS/dist/fixture-free/SHA256SUMS": "4e4e47842876694d10d18433717d17c20d06417f0a5f815c82ef054e0ee962c9", + "PhiOS/PhiOS/dist/fixture-free/build.log": "cae804a9129c08cfbfb105ca3a66c16d258aba206c389ee5f7def6b7fb137799", + "PhiOS/PhiOS/dist/fixture-free/builder-image.json": "c47259d39789c5af5d5cc6e2756a07673af16dd7fe1ebf88ca89227d3b892736", + "PhiOS/PhiOS/dist/fixture-free/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/fixture-free/fixture-inventory.json": "14ce1577031ab6cc9b29967bc57b054661ce36d3a5ec0ada86a0bba9ddc9627e", + "PhiOS/PhiOS/dist/fixture-free/image-packages.txt": "f2c4bf4ca37189cec44b2fb77826e39e2528df2011ff23b94000e3408a4ad93c", + "PhiOS/PhiOS/dist/fixture-free/javascript-bundled-packages.json": "04402e02c14a791ffc99968668594c1943081f1f7237a36e8b440dd0d896bf1f", + "PhiOS/PhiOS/dist/fixture-free/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/fixture-free/mkarchiso.log": "daa278b774b0da7225de2ce5c5bcf21e887ba544ea6c329662b502193d45eb14", + "PhiOS/PhiOS/dist/fixture-free/native-packages.json": "b41861d2e9feb155a623c836190733159870ed475a1bd3146a7463145c6d0334", + "PhiOS/PhiOS/dist/fixture-free/provenance.json": "be405f80acf349d781619c1fb0db3c995ffba42b931217800179bae602f17ebe", + "PhiOS/PhiOS/dist/fixture-free/python-packages.json": "9af1ad8db48a4e1a528d082984d07efbf34539b52ddac7026ea4e9923073d5a0", + "PhiOS/PhiOS/dist/fixture-free/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/fixture-free/sbom.cdx.json": "21a4efa80d8e49bb944d1f233c98352df0f961d099f12e6b97a37e0a571222ac", + "PhiOS/PhiOS/dist/fixture-free/source-archive-sha256.txt": "025f68a4a8d5dd4a3fdcde3d0e7d76632b4b6a76da627990f0896e0794af864e", + "PhiOS/PhiOS/dist/fixture-free/source-commit.txt": "0a64980244f024fbc21ff85bb81dd08d3435fa1363e90805d2b1f0362e8798dc", + "PhiOS/PhiOS/dist/fixture-free/source-review.json": "09a41fefb39b191ee06ca86db6f58d85fb10cb7b198316d4a3084e068f249cc5", + "PhiOS/PhiOS/dist/fixture-free/third-party-notices.json": "5427cd9b367f04e2bc89be5ffc4454d2f2d4a1b480bd049551d10a2c15f478cf", + "_temp/phios-normal-installed/failed-boot-qemu.log": "08f8dea0fd0e74fd298d59265b0a67149dcfc31c4512c6bee3fc10f307de4678", + "_temp/phios-normal-installed/failed-boot-serial.log": "e7840667c258632d5fc6f7a4158c3213a570bd161949424e455ad751d730531c", + "_temp/phios-normal-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-normal-installed/installed-1-serial.log": "4058bbeee22f6a0336414f681a2a24e5ba8c81cc9a76bf4f92e04582623af78f", + "_temp/phios-normal-installed/installed-2-qemu.log": "08f8dea0fd0e74fd298d59265b0a67149dcfc31c4512c6bee3fc10f307de4678", + "_temp/phios-normal-installed/installed-2-serial.log": "130bda780e1f6c7dc181221396ee6761d53261815572151194fb08b1733cc78a", + "_temp/phios-normal-installed/installed-3-qemu.log": "08f8dea0fd0e74fd298d59265b0a67149dcfc31c4512c6bee3fc10f307de4678", + "_temp/phios-normal-installed/installed-3-serial.log": "669e07913adeff3d94adce77c3c7ef098e55080409b8a28d12d24003f63032ab", + "_temp/phios-normal-installed/installed-evidence.json": "69e3103622afaba9f3a24a4687b0e9f1bc226ffdf1d18f9a154f5692edca584a", + "_temp/phios-normal-installed/normal-install-live-qemu.log": "08f8dea0fd0e74fd298d59265b0a67149dcfc31c4512c6bee3fc10f307de4678", + "_temp/phios-normal-installed/normal-install-live-serial.log": "6ed549e24fc824607773a40c63fde1b0d3a1674b01a7639f05e4b03141c04902", + "_temp/phios-normal-installed/normal-restore-live-qemu.log": "08f8dea0fd0e74fd298d59265b0a67149dcfc31c4512c6bee3fc10f307de4678", + "_temp/phios-normal-installed/normal-restore-live-serial.log": "49321ac04b0a4c235cb3c8b46db3bdd9414023311d952bcfc8223309cf49679c", + "_temp/phios-normal-installed/screen-failed-boot.png": "1bfae885ec5ebf2fcd9e131ff8809c27e531336cdcdc2272f081e48692a10c9a", + "_temp/phios-normal-installed/screen-installed-1-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-normal-installed/screen-installed-1.png": "a91c817a40e0b116e68db90e5d420083985c816444fc86a20519823715363d37", + "_temp/phios-normal-installed/screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-normal-installed/screen-installed-2.png": "9229ddf6919421383cd82ef782f550549620a621b222041579eb4b4356a50fd6", + "_temp/phios-normal-installed/screen-installed-3-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-normal-installed/screen-installed-3.png": "6498c2d54f3d6d37344ec0b55c786a478519fd5311b3f53cf73c1e539aaad354", + "_temp/phios-normal-installed/screen-normal-install-live.png": "48966bbd7c0f6da2e75bf49750f790e00f44e6ebdf62ff99dd7ed9226ad3b40e", + "_temp/phios-normal-installed/screen-normal-restore-live.png": "f90f6ae011499b53d229194c16044192df04a1d45793fdb4e6131c9a8d28e25b", + "_temp/phios-preview/preview-evidence.json": "916ea001a1c1221904a1b85791ca075205ad3c1f73334aee783b2598982fd36f", + "_temp/phios-preview/qemu.log": "a21b531feada57520326f1b948ca872b74280ca8378e7f8ea32a62520ceaccf4", + "_temp/phios-preview/screen-1-first.png": "a9ae2ad9e6b1547cf644d3c25e8fbed046cc5344300168b747036c433551902d", + "_temp/phios-preview/screen-1-reauthenticated.png": "5b3e3307dc92ff201bf87a01b6e69945a110e71fb8a22f89ce76d22e30838e31", + "_temp/phios-preview/screen-2-first.png": "6e1b5a139e4190faecdfbb5cd482a75870b846cf04a7d3d140479e2fe268df19", + "_temp/phios-preview/screen-2-reauthenticated.png": "c695dba2389bc52b909d5fe5b42771958db5c54fb65159793fb7b1840172b370", + "_temp/phios-preview/screen.png": "c695dba2389bc52b909d5fe5b42771958db5c54fb65159793fb7b1840172b370", + "_temp/phios-preview/serial.log": "8c6624e1c1345d6385bf331c62b2cdf85738a078a725e5cbec250aee98ba1031" + }, + "explicit_serial_console_password_login": true, + "fixture_free": true, + "fixture_free_installed_qualified": true, + "fixture_free_live_qualified": true, + "fixture_free_requested": true, + "hardware_qualified": false, + "historical_approval_refused_after_reboot_and_recovery": true, + "host_disks_attached": false, + "image_artifact_id": 11140626238, + "installed": true, + "interrupted_signed_transaction_observed": false, + "interrupted_update_active_root_preserved": false, + "inventory_origin_counts": { + "javascript": 12, + "javascript-bundled": 4, + "native": 386, + "python": 39 + }, + "iso_sha256": "e60b64623a0008b27439f98eacd22cc9d4e0ce714d4b7b8684276f425988349b", + "iso_signed": false, + "job_id": 110209194727, + "large_payloads_independently_downloaded_for_this_review": false, + "license_source_compliance_reviewed": false, + "linux_governed_workflow": { + "actual_agent_uid": 1001, + "agent_broker_denied": true, + "agent_store_denied": true, + "approval_sha256": "b9f40f0ee49614225eedde8c62e64c98ab40a845ddc2b6e49d6246c63c01e271", + "cancel_passed": true, + "expired_approval_sha256": "5ba66b6fd46705baeb6dd4b72b15711a265f2322e2c0ab52d92819ca00a1d92b", + "expiry_refused": true, + "hardware_qualified": false, + "receipt": { + "approval_sha256": "b9f40f0ee49614225eedde8c62e64c98ab40a845ddc2b6e49d6246c63c01e271", + "authority_replayable": false, + "binding_sha256": "a5250a3768fbd9e38215d38fbbc24f2775c8c628dd42acffe0f057bea7c6f929", + "boot_id": "fd9f0d822cb84b73899801ad86c186cf", + "decision_sha256": "7f3ada6549edfed7e62962ec1c6c65802628e859e66a882c471cbd8866b73294", + "effect_performed": true, + "execution_authority": false, + "lease_sha256": "58008145a62eafae2a3b88a284f098c70bfeffccfed12d97812dfa35bce057b4", + "note_bytes": 57, + "note_sha256": "e2e3a3855d190c74791ad81fdc9a5dd8742363fcede860ef07439ce9e9058ba8", + "operator_uid": 1000, + "post_effect_verified": true, + "principal_uid": 1001, + "release_ready": false, + "schema_version": "phios.linux-proof-receipt.v1", + "source_commit": "5145b4dabd0e70d4b8d35691041a4d9f797affe9" + }, + "release_ready": false, + "replay_refused": true, + "schema_version": "phios.linux-proof-qualification.v1", + "source_commit": "5145b4dabd0e70d4b8d35691041a4d9f797affe9", + "sudo_password_authentication": true + }, + "linux_governed_workflow_qualified": true, + "live_boot_ids": [ + "d7e8973840e14c1b8fda19f764371136", + "61338a9221a24fe99a1f5554e02d5a8b" + ], + "matched_root_efi_restored": true, + "network": false, + "no_iso_boot_passed": true, + "observer_restart_pids": [ + { + "new": "916", + "old": "680" + }, + { + "new": "928", + "old": "689" + } + ], + "ordinary_ci_existing_skips": 6, + "ordinary_ci_passed": 2250, + "ordinary_ci_run": 36812078517, + "ram_mib": 4096, + "record_sha256": "c481900567db858427663a26909e82a9d30fe2e083c929cb68683a9823e87bb4", + "recovery_checkpoint_generation": "551fbcbf57004325860be7cc60c3f3fc", + "recovery_requested": true, + "release_ready": false, + "reproducible_build_demonstrated": false, + "reviewed_branch_head": "0ea1fced470abf75701a4cad8f806551078b1b76", + "sbom_components": 441, + "schema_version": "phios.os-qualification-summary.v1", + "screenshot_visually_reviewed": true, + "shared_folders": false, + "signed_package_application_qualified": false, + "signed_update_refusals_observed": false, + "signed_update_requested": false, + "simulated_boot_failure_observed": true, + "source_archive_sha256": "19a5f6e6a51242d9d7e989b7e6579c95b3cbe5778ac39b643380876240eb5911", + "source_commit": "5145b4dabd0e70d4b8d35691041a4d9f797affe9", + "supplier_notice_files": 620, + "tested_source_tree": "59ec972739f5293bb3de57d7369892b98b68c4b3", + "whole_os_recovery_passed": true, + "workflow_run": 36812104386 +} diff --git a/docs/os/evidence/qualification-gate-5a1431f4.json b/docs/os/evidence/qualification-gate-5a1431f4.json new file mode 100644 index 00000000..bcc85af2 --- /dev/null +++ b/docs/os/evidence/qualification-gate-5a1431f4.json @@ -0,0 +1,171 @@ +{ + "actual_job_results": { + "changes": "success", + "normal-image / fixture-free-candidate": "success", + "phishell / build": "success", + "python-tests / installed-artifact": "success", + "python-tests / ledger-reports": "success", + "python-tests / memory-vector": "success", + "python-tests / test": "success", + "qa-image / live-image": "success", + "release-gate": "success" + }, + "actual_maintainer_signed_transition_qualified": false, + "artifact_expiry": "2026-10-08", + "hardware_qualified": false, + "images": { + "fixture-free": { + "boot_ids": [ + "94116ff083d04325a48641ef7f4c820f", + "60457827002c4e1698dd59c684418eeb", + "036c837f072a404d967523325ddbd4cc" + ], + "evidence_archive_sha256": "7f01bcd279d9ef325e9d03c374c7a3cb7fd4cb46db7ceb89e231dd597fed7614", + "evidence_artifact_id": 11142385019, + "evidence_files": { + "PhiOS/PhiOS/dist/fixture-free/SHA256SUMS": "c95b948360c2cb6e56b7db1d7518a86467df64496960cb4564bf74afd548ba17", + "PhiOS/PhiOS/dist/fixture-free/build.log": "3521dc587ab04a94e266f40d984e902001dbba8c0ed9b86946530c7ca6b86fb4", + "PhiOS/PhiOS/dist/fixture-free/builder-image.json": "c2cadefbff7ce8c115f5cf099818a7302bf6132627e3b616177cc7e3ca40f377", + "PhiOS/PhiOS/dist/fixture-free/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/fixture-free/fixture-inventory.json": "14ce1577031ab6cc9b29967bc57b054661ce36d3a5ec0ada86a0bba9ddc9627e", + "PhiOS/PhiOS/dist/fixture-free/image-packages.txt": "f2c4bf4ca37189cec44b2fb77826e39e2528df2011ff23b94000e3408a4ad93c", + "PhiOS/PhiOS/dist/fixture-free/javascript-bundled-packages.json": "04402e02c14a791ffc99968668594c1943081f1f7237a36e8b440dd0d896bf1f", + "PhiOS/PhiOS/dist/fixture-free/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/fixture-free/mkarchiso.log": "ed3023c67353e36793b5337211fa22878320b806a7c4d20bb634b610e6568845", + "PhiOS/PhiOS/dist/fixture-free/native-packages.json": "d46a645d7bb0bc2438e6c4c9c8ca9326e70d6954779e0bd725671663d9aaea3b", + "PhiOS/PhiOS/dist/fixture-free/provenance.json": "ef1b2de74330bdf210ba1cfc407262680fd452f2a0a990d8a5ed3c9407b0cf31", + "PhiOS/PhiOS/dist/fixture-free/python-packages.json": "ef6655e03b4fd5a1bac84e505582a2b14bef22d7f45ee034f9339bffa61b8f7e", + "PhiOS/PhiOS/dist/fixture-free/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/fixture-free/sbom.cdx.json": "68526345f9e4d4503ff4ea0b7855e474188580c47c1c3b81daefe57c24a745f6", + "PhiOS/PhiOS/dist/fixture-free/source-archive-sha256.txt": "1355dd2b65364a50bb567bc0c1af172bf2f4ea54a16b96368f0ff38f0733f097", + "PhiOS/PhiOS/dist/fixture-free/source-commit.txt": "eb43fc4d3ab53e56118c52f056e6ebaef2d9dac5d9c2cd4843308ed1b7aa6d2d", + "PhiOS/PhiOS/dist/fixture-free/source-review.json": "2e463c8917b28fd8dd42f5f30fc40b8653ac75eed44c364ae88638319a772097", + "PhiOS/PhiOS/dist/fixture-free/third-party-notices.json": "5427cd9b367f04e2bc89be5ffc4454d2f2d4a1b480bd049551d10a2c15f478cf", + "_temp/phios-normal-installed/failed-boot-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-normal-installed/failed-boot-serial.log": "6fe5d1ad11bcdac88e1f3422a1ecc42afac1d784ddcc7ea674974c37fcf0cca8", + "_temp/phios-normal-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-normal-installed/installed-1-serial.log": "88bda2b35ffb1e47b5d3d752ca049041cc722ff59d1d07db48173b8eae65c85a", + "_temp/phios-normal-installed/installed-2-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-normal-installed/installed-2-serial.log": "eee63649d87844c7a3e32a521b8fdff143792c62e1f77ca8f1ecc9166c59ed18", + "_temp/phios-normal-installed/installed-3-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-normal-installed/installed-3-serial.log": "71ee28fb6cd1bf6646df742d86d72df5c80e8357fe1b6dfa8d0b6b2aa7e026bb", + "_temp/phios-normal-installed/installed-evidence.json": "15a8e3917e2180130278e316c721f49976ae011fcd37e5574d1a0e37ba0ebbff", + "_temp/phios-normal-installed/normal-install-live-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-normal-installed/normal-install-live-serial.log": "707f78767b8fd769b0712b02ded35d2882125008e81f5feef6a9a8e1d13a1323", + "_temp/phios-normal-installed/normal-restore-live-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-normal-installed/normal-restore-live-serial.log": "ccdd86820c8bc6d3a2378c80d9468419e4d38ef8280776cd79db6a09ced4ebf1", + "_temp/phios-normal-installed/screen-failed-boot.png": "fa9c0e12d578182e0df1d4cc0b864b675b4f786546e27c6d67ef8f8045fd3334", + "_temp/phios-normal-installed/screen-installed-1-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-normal-installed/screen-installed-1.png": "c6ebd659a5428c24fb9c72d8e6fb8dc38d77aedbbd5d5c6e24b9a92d973034d0", + "_temp/phios-normal-installed/screen-installed-2-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-normal-installed/screen-installed-2.png": "e42d43a591ee6b5259b003d05b61caf2c567b473c5179f60318c393047310981", + "_temp/phios-normal-installed/screen-installed-3-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-normal-installed/screen-installed-3.png": "e310314c2848d9901eb9586a12a3f5178f64bcc17a3af8a66603b7b17035a661", + "_temp/phios-normal-installed/screen-normal-install-live.png": "527186390ec2bc1dda8081004f832ae433e993034d483bab414eeb3fddb2aaaa", + "_temp/phios-normal-installed/screen-normal-restore-live.png": "05037adaa0394388d17b617db0606bdde0df9ecc65cb82746f5fc7172886c09b", + "_temp/phios-preview/preview-evidence.json": "7a95cd27f6a20cb305b1a4a88eefb1ed3a59bbc784c1e605a2bb5613b994b81e", + "_temp/phios-preview/qemu.log": "928b7c7a217c94779d8adce0b55555f2677002e653cbd02c8e3186f2ba90ad4a", + "_temp/phios-preview/screen-1-first.png": "bb3d3110e1bb54b8b4e53ad0a7b2673486812ed7642be816b7488a3badc110b9", + "_temp/phios-preview/screen-1-reauthenticated.png": "fcc70ef0687744d9fe989895df1625d05ed8d7beb3a095952ca6fe6747fcead3", + "_temp/phios-preview/screen-2-first.png": "104a0f098d52a2eeead570ec9e515cd0a9eb3ddfc27f6f8d28c5c4f7c9ff50ce", + "_temp/phios-preview/screen-2-reauthenticated.png": "b2a84152607bdbb91f42fc223ad9a8cc876a7ff74844f504532eeea119d80efd", + "_temp/phios-preview/screen.png": "b2a84152607bdbb91f42fc223ad9a8cc876a7ff74844f504532eeea119d80efd", + "_temp/phios-preview/serial.log": "49efdc085e59c66bef0f7e5b8d1dc5449ec766a3c46b0a697395fbcacac62c04" + }, + "fixture_free_installed_qualified": true, + "image_artifact_id": 11141254782, + "iso_sha256": "875f867310afc172124e7c5fa063b24b808099a4bd8e25843be65db681fc0cd0", + "linux_governed_workflow_qualified": true, + "sbom_components": 441, + "signed_package_application_qualified": false, + "source_archive_sha256": "897628d3b061f467c085d03a078cbdf89011888722ab1456d2a8959be026a9fc", + "whole_os_recovery_passed": true + }, + "linux": { + "boot_ids": [ + "f7b3725c7db04a1dbede23ca3bb60cb8", + "2cace2fca4124c32b6e39ef9bae07b11", + "3420d73921304d418bfbc6f9d0ffcb3a" + ], + "evidence_archive_sha256": "9b7d43b7ed1bb030c268d1658a00c7ae46087076afa9ffc7ba99f225af1f683f", + "evidence_artifact_id": 11141931796, + "evidence_files": { + "PhiOS/PhiOS/dist/linux/SHA256SUMS": "b62387969608a080a1c7b1d2243a9115539d6f4e0e581aabb356cd054534191a", + "PhiOS/PhiOS/dist/linux/build.log": "04610e3d6e496aed0037ec80722db880b6f37f017d9be1e8df52411e5c60a854", + "PhiOS/PhiOS/dist/linux/builder-image.json": "642f93358f651b0c82cbd01a641f22ca0788e90863c5db4b2c761ae6a30476e4", + "PhiOS/PhiOS/dist/linux/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/linux/fixture-inventory.json": "2ebf26541ddaa6d1e239b1a3be944946f18e8d08e78837065d11eed7921d7a60", + "PhiOS/PhiOS/dist/linux/image-packages.txt": "dd6faf936234848a574c0d3125da4eddabaa33b8f02998bc7be070250d3e29f9", + "PhiOS/PhiOS/dist/linux/javascript-bundled-packages.json": "04402e02c14a791ffc99968668594c1943081f1f7237a36e8b440dd0d896bf1f", + "PhiOS/PhiOS/dist/linux/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/linux/mkarchiso.log": "9ba3b9184ffec6875bd214771c42b02f6d17f679e28fb9384a2560b737ae8553", + "PhiOS/PhiOS/dist/linux/native-packages.json": "1c4d627f63b0efd69216b8f0bb196a9f2d3f1351fc43843f5384ad85b33a4434", + "PhiOS/PhiOS/dist/linux/provenance.json": "af19fe0ffb0ab785d5934cb78ad70cb1412c513017344d3df102bfbd0b714af4", + "PhiOS/PhiOS/dist/linux/python-packages.json": "ef6655e03b4fd5a1bac84e505582a2b14bef22d7f45ee034f9339bffa61b8f7e", + "PhiOS/PhiOS/dist/linux/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/linux/sbom.cdx.json": "d420441f1fde7bca20189460ef0cacb6764585a4522b615aa3464fb91a7b0182", + "PhiOS/PhiOS/dist/linux/source-archive-sha256.txt": "1355dd2b65364a50bb567bc0c1af172bf2f4ea54a16b96368f0ff38f0733f097", + "PhiOS/PhiOS/dist/linux/source-commit.txt": "eb43fc4d3ab53e56118c52f056e6ebaef2d9dac5d9c2cd4843308ed1b7aa6d2d", + "PhiOS/PhiOS/dist/linux/source-review.json": "67c315821702df44f86cfd21c8218be8aded943d79144226f2812eeb7f2c0d7b", + "PhiOS/PhiOS/dist/linux/third-party-notices.json": "5427cd9b367f04e2bc89be5ffc4454d2f2d4a1b480bd049551d10a2c15f478cf", + "_temp/phios-boot/boot-evidence.json": "d3033f275c816a5cd76d160a5c6e049c7d9bb6aea9c6a27930ebad833b0d3d65", + "_temp/phios-boot/qemu.log": "e01fdd77d03ccd4437dd37a73e9daf5fe3659332a0094e1551234b15c82b2bab", + "_temp/phios-boot/screen-first.png": "a2a52056502c7e160150e349f7fab038c78fe78de21b162c5ece1eab1cc7f902", + "_temp/phios-boot/screen.png": "eeca173ba9b5409d3e4f2474fb46b4c0f49120b63e6e9d202fdb435c9396a99f", + "_temp/phios-boot/serial.log": "7078d3903b44ebf04af135f583b7593f5ea21caf81cc461e3d1f6df087b39319", + "_temp/phios-installed/failed-boot-qemu.log": "2b49c797697893d0c1a2d44d639a74b258b1870cd2c86ddc32db5a535e29c30a", + "_temp/phios-installed/failed-boot-serial.log": "c9ab564bbb14595342d72b9a04b0de46428bbab813260df174cda489d04e85e0", + "_temp/phios-installed/install-live-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/install-live-serial.log": "6c33c150b1f3bf9fcc0e0ec0ab9141820f7419c5ad71f661affcb0cd55472009", + "_temp/phios-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/installed-1-serial.log": "76732be7ae91cc5e11429d206beaac72138806d6a0b67530e531723f8fd271e0", + "_temp/phios-installed/installed-2-qemu.log": "2b49c797697893d0c1a2d44d639a74b258b1870cd2c86ddc32db5a535e29c30a", + "_temp/phios-installed/installed-2-serial.log": "6a67814d3fe6aad65e5d5be476429637fbafc01370dc309c8258c2a9caf7a62c", + "_temp/phios-installed/installed-3-qemu.log": "2b49c797697893d0c1a2d44d639a74b258b1870cd2c86ddc32db5a535e29c30a", + "_temp/phios-installed/installed-3-serial.log": "b27dbb8f04d46f7a1ef47827bf88691f473078cca2451d6128e8068398873c9e", + "_temp/phios-installed/installed-evidence.json": "1a70b4f48a50951d4f41daf16f45e51c411776642c73b1964e7ae9164b876847", + "_temp/phios-installed/interrupted-resume-live-qemu.log": "2b49c797697893d0c1a2d44d639a74b258b1870cd2c86ddc32db5a535e29c30a", + "_temp/phios-installed/interrupted-resume-live-serial.log": "db83b9c8695251b02d45de9a413c3429cb8b9c0cf49c74e5e74dd470bbf2a1b5", + "_temp/phios-installed/recovery-live-qemu.log": "2b49c797697893d0c1a2d44d639a74b258b1870cd2c86ddc32db5a535e29c30a", + "_temp/phios-installed/recovery-live-serial.log": "b71ded13415d6b429dce59576d7207a8d4a13400a3a208fef6ce4e4887df724a", + "_temp/phios-installed/screen-failed-boot.png": "cb47acbf16d5547d800e433840075d7c2472a1d9fcafcac6ce5cef8cc210a381", + "_temp/phios-installed/screen-install-live.png": "a9630dde996c4767c33e3268970cebafe82897017c42f31a72e632c65daa08e5", + "_temp/phios-installed/screen-installed-1-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-1.png": "be207000735ec55c508eba714da1871bf844775307d833045b322a2bbfb61c93", + "_temp/phios-installed/screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-2.png": "7cbfe87f5c058b411cb296a4db4130b04180d938db6c9577dda2385581459158", + "_temp/phios-installed/screen-installed-3-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-installed/screen-installed-3.png": "70788bdb9bfe2464f75126529b780fe637979a6cf3785f3d87ea3d39fc7e1063", + "_temp/phios-installed/screen-interrupted-resume-live.png": "b7af29929490f8fb3429f4d87cbeb8dce1eca2248ba0304390c0aaeb747a25f8", + "_temp/phios-installed/screen-recovery-live.png": "2dc9ee6b09239b3aa3dca17a063824d3b3d51b87e28a86fb73f015d1bb473c99" + }, + "fixture_free_installed_qualified": false, + "image_artifact_id": 11142136278, + "iso_sha256": "a80c74b2a58560ff6d725a2195ce4d3cfd388c2e6433ab0e5b6141ad67ef4730", + "linux_governed_workflow_qualified": true, + "sbom_components": 442, + "signed_package_application_qualified": true, + "source_archive_sha256": "897628d3b061f467c085d03a078cbdf89011888722ab1456d2a8959be026a9fc", + "whole_os_recovery_passed": true + } + }, + "license_source_compliance_reviewed": false, + "ordinary_ci_existing_skips": 6, + "ordinary_ci_passed": 2279, + "publication_authority": false, + "release_gate_job_id": 110225078875, + "release_ready": false, + "repository_protection_configured": false, + "required_jobs_skipped": false, + "required_scope": { + "normal_image": true, + "python": true, + "qa_image": true, + "ui": true + }, + "reviewed_branch_head": "ee441f5db4ac015512ae9caaeed7c29dfd24bac7", + "schema_version": "phios.ci-qualification-summary.v1", + "source_commit": "5a1431f4758029a9c04abfb5471351e9abf88a3f", + "tested_source_tree": "6217ef309e8d5843d6b84366d18123c452ceb4e8", + "workflow_run": 36816117488 +} diff --git a/docs/os/evidence/qualification-gate-a7bcd986.json b/docs/os/evidence/qualification-gate-a7bcd986.json new file mode 100644 index 00000000..f72cd1d1 --- /dev/null +++ b/docs/os/evidence/qualification-gate-a7bcd986.json @@ -0,0 +1,123 @@ +{ + "actual_jobs": [ + { + "id": 110242688984, + "name": "changes", + "result": "success", + "status": "completed" + }, + { + "id": 110242720066, + "name": "python-tests / ledger-reports", + "result": "success", + "status": "completed" + }, + { + "id": 110242720134, + "name": "phishell / build", + "result": "success", + "status": "completed" + }, + { + "id": 110242720138, + "name": "python-tests / installed-artifact", + "result": "success", + "status": "completed" + }, + { + "id": 110242720145, + "name": "python-tests / test", + "result": "success", + "status": "completed" + }, + { + "id": 110242720167, + "name": "python-tests / memory-vector", + "result": "success", + "status": "completed" + }, + { + "id": 110242720431, + "name": "normal-image / fixture-free-candidate", + "result": "success", + "status": "completed" + }, + { + "id": 110242720445, + "name": "qa-image / live-image", + "result": "success", + "status": "completed" + }, + { + "id": 110247102777, + "name": "release-gate", + "result": "success", + "status": "completed" + } + ], + "actual_maintainer_signed_transition_qualified": false, + "artifact_metadata": [ + { + "digest": "sha256:f1aaa1e361e0e0016cfd67dd86e34a6abf88662810a340e28cf75a5a2e9f0e62", + "expires_at": "2026-10-08T06:23:26Z", + "id": 11144925813, + "name": "phios-linux-evidence-36823086807", + "size_in_bytes": 4187659 + }, + { + "digest": "sha256:eeeded3d7dbf207ec6c085cfa708d5d8f5ff1dd0338e63cd37b9b9fd37549b53", + "expires_at": "2026-10-08T06:22:32Z", + "id": 11144596210, + "name": "phios-linux-development-36823086807", + "size_in_bytes": 1803543533 + }, + { + "digest": "sha256:bf9998e13cd8c156ec0e3bad2673acd05edd213a6d711f2b01a4f1eed85d936a", + "expires_at": "2026-10-08T06:19:19Z", + "id": 11144167873, + "name": "phios-fixture-free-evidence-36823086807", + "size_in_bytes": 6723600 + }, + { + "digest": "sha256:876b3b01d61069b3603c9ae96cbb6902135c516f3fe2c9103ede0f14090c3616", + "expires_at": "2026-10-08T06:18:32Z", + "id": 11144157950, + "name": "phios-fixture-free-candidate-36823086807", + "size_in_bytes": 1805985935 + } + ], + "hardware_qualified": false, + "license_source_compliance_reviewed": false, + "ordinary_ci_existing_skips": 6, + "ordinary_ci_passed": 2287, + "publication_authority": false, + "receipts": { + "desktop-normal-a7bcd986.json": { + "evidence_archive_sha256": "bf9998e13cd8c156ec0e3bad2673acd05edd213a6d711f2b01a4f1eed85d936a", + "evidence_artifact_id": 11144167873, + "iso_sha256": "3b26a7334b36254b4e686843e84924ee14cdb6ef2d6748fd771e09a02e5f79a2", + "sha256": "0647a24449e8315ca38409f9d3c2a0eea42d69741156167f074649717ab9f92b" + }, + "desktop-signed-a7bcd986.json": { + "evidence_archive_sha256": "f1aaa1e361e0e0016cfd67dd86e34a6abf88662810a340e28cf75a5a2e9f0e62", + "evidence_artifact_id": 11144925813, + "iso_sha256": "c0dd9a93ceeda3897f7c5d5b16785f4cf418935e1c5d3ec312ec3130d8446f2e", + "sha256": "2cc32ae78c23e0361730c2752a8ad8a32add6144d028ef6693ae1ca809459a48" + } + }, + "release_gate_job_id": 110247102777, + "release_ready": false, + "repository_protection_configured": false, + "required_jobs_skipped": false, + "required_scope": { + "normal_image": true, + "python": true, + "qa_image": true, + "ui": true + }, + "reviewed_branch_head": "9c98475274442595c59370113b9c1e0dee595ec9", + "schema_version": "phios.ci-qualification-summary.v1", + "source_commit": "a7bcd9863eea12a87c1a9ef1fcbd26211542cd91", + "tested_source_tree": "a85700b2c08e54a066a77a2f4a4db7494b7579ff", + "workflow_run": 36823086807 +} diff --git a/docs/os/evidence/recovery-29def30a.json b/docs/os/evidence/recovery-29def30a.json new file mode 100644 index 00000000..404c6abb --- /dev/null +++ b/docs/os/evidence/recovery-29def30a.json @@ -0,0 +1,99 @@ +{ + "abrupt_virtual_restart_passed": true, + "accelerator": "kvm", + "artifact_expiry": "2026-10-08", + "boot_ids": [ + "2b19aac63c44448d9c9372326fcb82a8", + "a8117303e2984624b453f988e09881f7", + "1b3506e3a89a4c21ad31f135dc06833f" + ], + "ci_serial_console_injected": true, + "cpus": 2, + "disk_bytes": 34359738368, + "disk_serial": "PHIOS_CI_BLANK", + "ephemeral_test_key": true, + "evidence_artifact_id": 11137448503, + "evidence_files": { + "PhiOS/PhiOS/dist/linux/build.log": "0ac6084d51ac0f394a01301150e7e969142d3558e0f3832894fe59efffe0f2e6", + "PhiOS/PhiOS/dist/linux/builder-image.json": "d56dea8dbf2a26f43c9ada63bd04bc31a7365f0db7811a09ba230bad1192b6c5", + "PhiOS/PhiOS/dist/linux/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/linux/image-packages.txt": "dd6faf936234848a574c0d3125da4eddabaa33b8f02998bc7be070250d3e29f9", + "PhiOS/PhiOS/dist/linux/mkarchiso.log": "210fe06c25e034b3b8c06dbdf7e32143824db443429ae8c2434cb1f5494790ee", + "PhiOS/PhiOS/dist/linux/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/linux/source-archive-sha256.txt": "be474ea9b44dca648d68c2a4b9f8971b2fbdbe699875af342e00e8324db6c022", + "PhiOS/PhiOS/dist/linux/source-commit.txt": "ba4278e899cd49006cff064e993e77669321afa243429bc7ce92db7639539f9e", + "_temp/phios-boot/boot-evidence.json": "8f9fc704ea011747ee80d029b77a5310be263490d45c8f078ce377cb40aeb1bd", + "_temp/phios-boot/qemu.log": "7e93b93909628e9b8dc122fb8e38c80eadcb005ae59eebc2389f10dad2a5c6c3", + "_temp/phios-boot/screen-first.png": "119720e9fd849fb46101ec2b2e37febb8ae5b047a92d4a5cc805c3bf6dfab1f4", + "_temp/phios-boot/screen.png": "6d9ec1bb565b61d9b611f0990846e1676eda1df8e885a2415efdde6775ea34b8", + "_temp/phios-boot/serial.log": "58dfdeb763934e146954e8f77e931071d1e7b4132ebe35e981911bf73a5e975e", + "_temp/phios-installed/failed-boot-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/failed-boot-serial.log": "bf7aa9bdf1919f5cf386f81f3d333cead38295c3a8f48f2c016a5e9ea7ffbcfd", + "_temp/phios-installed/install-live-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/install-live-serial.log": "713c18dba07963505a9d697efd58e3ccdb1b6f0dcda3d0f6c57bd24d9c265574", + "_temp/phios-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/installed-1-serial.log": "069926fbd0102fc95fee13bccccc63d331d1056e3693d659d955b77d76aabf5c", + "_temp/phios-installed/installed-2-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/installed-2-serial.log": "cc21a0726b72c15dad5884d86e383ceef3a8b3d47c493cb37b6fb76965c978c6", + "_temp/phios-installed/installed-3-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/installed-3-serial.log": "c3c16fcb40e7375a74afd31580149848e3145d17fac6c189814f73537225a753", + "_temp/phios-installed/installed-evidence.json": "ba4b6a1fff1c4306b69080ffc7e15b90843be35ba555f5728c074c4616c4ba05", + "_temp/phios-installed/interrupted-resume-live-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/interrupted-resume-live-serial.log": "a016304728dc00b63de3e8e9e39bd83218ab6599ec441d6960219f227a354290", + "_temp/phios-installed/recovery-live-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/recovery-live-serial.log": "b89678271414d6a10d4eb28f552c1fc2f39a1016354faac05a06da0c9a06d86d", + "_temp/phios-installed/screen-failed-boot.png": "2cdd8a3c4c53bb7404010369d7aa1cff488f9740ac6ce5809c06c6eee545707f", + "_temp/phios-installed/screen-install-live.png": "6a3a045d248fe3842923183b859dab9516506191ef743d9c7f5553cba12735eb", + "_temp/phios-installed/screen-installed-1-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-installed/screen-installed-1.png": "d597e9a1637fd8bb4a56fd19a1545da8cf643c89514180000f67ca04a783684a", + "_temp/phios-installed/screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-2.png": "7dab04b52ac853b325b9d3f4d9b38deccd143cec10df7e44846b3f2a66376775", + "_temp/phios-installed/screen-installed-3-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-3.png": "9b5ded8d8dfb09063f51e79931f78ef324ca7f3ce0d0c44ecb63df623e1f5e50", + "_temp/phios-installed/screen-interrupted-resume-live.png": "4e6b5724fd7a17cfd8e449dd4f681bc6a89007f3c579e5a755010b883f8403cf", + "_temp/phios-installed/screen-recovery-live.png": "73a96888001aacb49325bc6680d5bcf561122e2ee0d3621de6c48fbb3493e500" + }, + "fixture_free": false, + "hardware_qualified": false, + "host_disks_attached": false, + "image_artifact_id": 11137807998, + "installed": true, + "interrupted_signed_transaction_observed": true, + "interrupted_update_active_root_preserved": true, + "iso_sha256": "391efdfd41e0217706b2b4028c47e9d37f7014762afc5d6831a30eb6bb2dba4b", + "iso_signed": false, + "job_id": 110190346637, + "live_boot_ids": [ + "6385ea7a68784bd4bbbd1c613f66661d", + "73e4c51c65d14265b729a226ebc0647a" + ], + "maintenance_head": "bb127d34227df6a7182580eaaca1ed04eb419bc2", + "matched_root_efi_restored": true, + "network": false, + "no_iso_boot_passed": true, + "ordinary_ci_existing_skips": 6, + "ordinary_ci_passed": 2218, + "ordinary_ci_run": 36805999618, + "public_disposable_credentials": true, + "ram_mib": 4096, + "record_sha256": "c481900567db858427663a26909e82a9d30fe2e083c929cb68683a9823e87bb4", + "recovery_checkpoint_generation": "aa3e52dc779a4c47a7fe9dff1a3092ce", + "recovery_requested": true, + "release_ready": false, + "schema_version": "phios.os-qualification-summary.v1", + "screenshot_visually_reviewed": true, + "shared_folders": false, + "signed_package_application_qualified": true, + "signed_update_refusals_observed": true, + "signed_update_requested": true, + "signed_update_transaction": { + "ephemeral_test_key": true, + "generation": "aa3e52dc779a4c47a7fe9dff1a3092ce", + "sequence": 1, + "signer": "39B4F5E46B179B7D91E7550F1C5219F76EBB7BB3" + }, + "simulated_boot_failure_observed": true, + "source_commit": "29def30a3079c99972f1606ae44ea3478d0f79d1", + "whole_os_recovery_passed": true, + "workflow_run": 36805999628 +} diff --git a/docs/os/evidence/recovery-attempts.json b/docs/os/evidence/recovery-attempts.json new file mode 100644 index 00000000..7dd1d251 --- /dev/null +++ b/docs/os/evidence/recovery-attempts.json @@ -0,0 +1,107 @@ +{ + "schema_version": "phios.recovery-attempt-evidence.v1", + "scope": "isolated UEFI KVM; fresh named 32-GiB disk; no network, host disks or shared folders", + "attempts": [ + { + "run_id": 36800067643, + "job_id": 110172173242, + "evidence_artifact_id": 11135382068, + "source_commit": "960bd3261b6b52df3335cdc9bec6a31980036d92", + "iso_sha256": "3e92086a8fad705e0edb9e6075a51d7a357830aae010e985af9c933113139817", + "checkpoint_created": false, + "whole_os_recovery_passed": false, + "release_ready": false, + "cause": "partition sysfs has no slaves directory", + "guest_error": "OS maintenance held: [Errno 2] No such file or directory: '/sys/dev/block/254:1/slaves'", + "files": { + "installed-evidence.json": { + "sha256": "84a2f5a6b02a765a237f10f2d5200251308acba6cd419014c6a94ff05edbf7bb", + "size": 1915 + }, + "install-live-serial.log": { + "sha256": "3e5d07c6e03c82f5d0010eb730a0bc13a702b7d21ec5ac4d90f45758c28ec6df", + "size": 57478 + } + }, + "evidence_url": "https://github.com/MichaelWave369/PhiOS/actions/runs/36800067643/artifacts/11135382068" + }, + { + "run_id": 36801548013, + "job_id": 110176775131, + "evidence_artifact_id": 11135933656, + "source_commit": "344667c3df6b0c2d5d223a5cf24a5ccb8760da8d", + "iso_sha256": "6e42c980e2f2fb81c0f396efd1c2384def52e5cc017e424003b393a51d4cc73b", + "checkpoint_created": false, + "whole_os_recovery_passed": false, + "release_ready": false, + "cause": "kernel rejected standalone nologreplay; use rescue=nologreplay", + "guest_error": "OS maintenance held: mount failed (exit 32): mount: /run/phios-recovery-r5kj676i/top: fsconfig() failed: btrfs: Unknown parameter 'nologreplay'.", + "files": { + "installed-evidence.json": { + "sha256": "4288acb8787d190ffbd181d79c6f6acf09593c55bcfd107b800848db3686a126", + "size": 1915 + }, + "install-live-serial.log": { + "sha256": "7493a51c566db4200dba78f93775962f3cb019a4a2330c424cdab7c94b17446d", + "size": 62870 + } + }, + "evidence_url": "https://github.com/MichaelWave369/PhiOS/actions/runs/36801548013/artifacts/11135933656" + }, + { + "run_id": 36802991205, + "job_id": 110181227245, + "evidence_artifact_id": 11136259045, + "source_commit": "1067477a6a389f364fc178f38e04a8847b046a2d", + "iso_sha256": "54c3cffa72ca4ab155e27952f3a99cab01f3a93626d130adb0d2b6001e19a02d", + "checkpoint_created": true, + "signature_refusals_observed": [], + "whole_os_recovery_passed": false, + "release_ready": false, + "cause": "makepkg fixture omitted source-file declarations; package() lacked data", + "guest_error": "see preserved package-builder traceback", + "files": { + "installed-evidence.json": { + "sha256": "17ca79b71182175e398e4f0fc3cfe26e5487218641e2d89c5eaf71ab7e14cc1b", + "size": 2199 + }, + "install-live-serial.log": { + "sha256": "a81a31bb7dafda38979895d25ed593afe5a377b7cedea7140bc035996d87f941", + "size": 62458 + } + }, + "evidence_url": "https://github.com/MichaelWave369/PhiOS/actions/runs/36802991205/artifacts/11136259045" + }, + { + "run_id": 36804253734, + "job_id": 110185006892, + "evidence_artifact_id": 11137416163, + "source_commit": "91f5ed68d1134add6b2bee025ec62ef967c01126", + "iso_sha256": "50fac795aae54942a4f0eb0a95a8df6e9604d6bc630b7db579409270fa9c12a1", + "checkpoint_created": true, + "signature_refusals_observed": [ + "missing-signature", + "wrong-key", + "tampered", + "expired" + ], + "whole_os_recovery_passed": false, + "release_ready": false, + "cause": "staged subvolume was not a mountpoint; mkinitcpio root detection error correctly held activation", + "guest_error": "OS update held: arch-chroot failed (exit 0): ==> Building image from preset: /etc/mkinitcpio.d/linux.preset: 'default'", + "files": { + "installed-evidence.json": { + "sha256": "db14179be3170434eaf7a2d6cfe035a147dbef255ba12871328ff036ffbdb0fb", + "size": 2199 + }, + "install-live-serial.log": { + "sha256": "ace627dfa8e1d1834581a47f4d748ba7474fd35269e2fd27cc98bff9062dc287", + "size": 274612 + } + }, + "evidence_url": "https://github.com/MichaelWave369/PhiOS/actions/runs/36804253734/artifacts/11137416163" + } + ], + "hardware_qualified": false, + "release_ready": false +} diff --git a/docs/os/evidence/signed-proof-5145b4da.json b/docs/os/evidence/signed-proof-5145b4da.json new file mode 100644 index 00000000..17199f0b --- /dev/null +++ b/docs/os/evidence/signed-proof-5145b4da.json @@ -0,0 +1,173 @@ +{ + "abrupt_virtual_restart_passed": true, + "accelerator": "kvm", + "actual_maintainer_signed_transition_qualified": false, + "artifact_expiry": "2026-10-08", + "boot_ids": [ + "f5b5e59d41d14b2b992ea27ab705393f", + "b0bc6b762e314562bab0288aa3480273", + "fb8a8e8ab34b47f5a14a80849b869f0f" + ], + "ci_serial_console_injected": true, + "compact_provenance_payload_hashes_verified": [ + "builder-image.json", + "builder-packages.txt", + "fixture-inventory.json", + "image-packages.txt", + "javascript-bundled-packages.json", + "javascript-packages.json", + "native-packages.json", + "python-packages.json", + "release.json", + "sbom.cdx.json", + "source-archive-sha256.txt", + "source-commit.txt", + "source-review.json", + "third-party-notices.json" + ], + "cpus": 2, + "disk_bytes": 34359738368, + "disk_serial": "PHIOS_CI_BLANK", + "ephemeral_test_key": true, + "evidence_archive_sha256": "26ee78f835c676591b4d8180700434da0f1ce35de333365a130ebe66433208b3", + "evidence_artifact_id": 11140033164, + "evidence_files": { + "PhiOS/PhiOS/dist/linux/SHA256SUMS": "d78577731178ba7cf1e61a12113b38997f2380cbbdd45d17bafb13f05b7a57c0", + "PhiOS/PhiOS/dist/linux/build.log": "5ad6f16178b82891b7001c7b73873e24dcbb8d845d09cc20ca6bbbe62f84cc05", + "PhiOS/PhiOS/dist/linux/builder-image.json": "38887d627ec9abbd7e1c91ea23b36d5c4364c4d9eea8fb0da23d1831a96f1d0c", + "PhiOS/PhiOS/dist/linux/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/linux/fixture-inventory.json": "2ebf26541ddaa6d1e239b1a3be944946f18e8d08e78837065d11eed7921d7a60", + "PhiOS/PhiOS/dist/linux/image-packages.txt": "dd6faf936234848a574c0d3125da4eddabaa33b8f02998bc7be070250d3e29f9", + "PhiOS/PhiOS/dist/linux/javascript-bundled-packages.json": "04402e02c14a791ffc99968668594c1943081f1f7237a36e8b440dd0d896bf1f", + "PhiOS/PhiOS/dist/linux/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/linux/mkarchiso.log": "e7921a0415e92e2c67bd875906ba26f2f1586d33a7cb8a1022b36fa830f70ca6", + "PhiOS/PhiOS/dist/linux/native-packages.json": "ac7c7ed40d311f4a6dde04ac01af4d3c313f7af03790e338298bf5c4c4463e6c", + "PhiOS/PhiOS/dist/linux/provenance.json": "bbd37c53abd83e54e424242999e327304762d8aa3b45cf3fec9c42ae7cbd483d", + "PhiOS/PhiOS/dist/linux/python-packages.json": "9af1ad8db48a4e1a528d082984d07efbf34539b52ddac7026ea4e9923073d5a0", + "PhiOS/PhiOS/dist/linux/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/linux/sbom.cdx.json": "971bcf64d61ac521a22273908ce53efb7f2c7a46c66b05599fc94be10194df91", + "PhiOS/PhiOS/dist/linux/source-archive-sha256.txt": "025f68a4a8d5dd4a3fdcde3d0e7d76632b4b6a76da627990f0896e0794af864e", + "PhiOS/PhiOS/dist/linux/source-commit.txt": "0a64980244f024fbc21ff85bb81dd08d3435fa1363e90805d2b1f0362e8798dc", + "PhiOS/PhiOS/dist/linux/source-review.json": "5913301f6eccd1d87fa540c700d728a80fc6dca0147cbc83abf4af6f3e2894cc", + "PhiOS/PhiOS/dist/linux/third-party-notices.json": "5427cd9b367f04e2bc89be5ffc4454d2f2d4a1b480bd049551d10a2c15f478cf", + "_temp/phios-boot/boot-evidence.json": "8de30dfbf38cecc2f9403185ca9d3d5e0bc851850b09f988f8b9841d087075d7", + "_temp/phios-boot/qemu.log": "415b15bdc288894e73f8f276fbe6c95b0fcce67905068d4c9953d22c417d29ad", + "_temp/phios-boot/screen-first.png": "73ddc2ce8b727a9dbb8b946749179545c7a752a8c77eda557ae53c14571222e4", + "_temp/phios-boot/screen.png": "a2611d709bbfb9e578709908e657fcb0e873b6ff9bee6e9676b6372375432376", + "_temp/phios-boot/serial.log": "0b59c1899fc61ddcdb792b5a3b08d17d7fd35c05840ab43c98d23a63b1d92146", + "_temp/phios-installed/failed-boot-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-installed/failed-boot-serial.log": "e16723a1077f4fe019eb800ab0cebb49ad54c0908ce9367ae97649fd51140eb7", + "_temp/phios-installed/install-live-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/install-live-serial.log": "b2661a478c69464049280923f16143c00cc18d16529cafd9711f46ce732cd137", + "_temp/phios-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/installed-1-serial.log": "d1c97f4f577295db20fffef830549f1cbe6baea4e10c871da2d89ddffd4b2430", + "_temp/phios-installed/installed-2-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-installed/installed-2-serial.log": "9aad995af141862c4ad947be9c7d46520738aa78b5163677f11396f3ca9b158f", + "_temp/phios-installed/installed-3-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-installed/installed-3-serial.log": "c97be95fc078e029e0550b24750ae54b83256bb43220eab99f51d28db8bdff3d", + "_temp/phios-installed/installed-evidence.json": "c8b29cc108f93aed49ac352e70c0b07ee26c1066d360f9e9a0f47c8225c46d22", + "_temp/phios-installed/interrupted-resume-live-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-installed/interrupted-resume-live-serial.log": "d29e7852f392628b116ae5b1e6be64e3470b20a5724c1cfa142428f928bd2cc4", + "_temp/phios-installed/recovery-live-qemu.log": "5fbf889470e27f179720fae8b5698f1626e456ffa295326adc12d3d89b13dc5a", + "_temp/phios-installed/recovery-live-serial.log": "f54d66558cbbedb9183f0b4b9cce651a830e5a210ed65e20ec836798baf3acfe", + "_temp/phios-installed/screen-failed-boot.png": "3c6fc25694da7780c3712c2b799341ba04d5b2c0d0b4b0728e9419494dff8559", + "_temp/phios-installed/screen-install-live.png": "48cc0ec433980d9359864c1c48ca4b0f04061e2d8a2f7401c00d0f1009a7a3e3", + "_temp/phios-installed/screen-installed-1-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-installed/screen-installed-1.png": "09358096df7e27d36d64e5c7d5e4f60029e4c47e70a0cf97e1e5aa2b6dd1c917", + "_temp/phios-installed/screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-2.png": "3223930ce96ac090dbcb9578778b54c86fd776c69100f288b380b107fbc3faa5", + "_temp/phios-installed/screen-installed-3-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-3.png": "a0c082d2e0ad5fc48fdfcad9d6af06618493556bade2d01c1cdd6517cb0ae22d", + "_temp/phios-installed/screen-interrupted-resume-live.png": "c27a2880c90726d8dd8b161fbbe08c89f2cb3bd2b26969cc3da7c1de4cecaa31", + "_temp/phios-installed/screen-recovery-live.png": "87d722b0fa02bd8c9744d212c045f722f4ed52479efb2db604b15b9ec66d40d3" + }, + "explicit_serial_console_password_login": false, + "fixture_free": false, + "fixture_free_installed_qualified": false, + "fixture_free_requested": false, + "hardware_qualified": false, + "historical_approval_refused_after_reboot_and_recovery": true, + "host_disks_attached": false, + "image_artifact_id": 11140023212, + "installed": true, + "interrupted_signed_transaction_observed": true, + "interrupted_update_active_root_preserved": true, + "inventory_origin_counts": { + "javascript": 12, + "javascript-bundled": 4, + "native": 387, + "python": 39 + }, + "iso_sha256": "f798c2f7b966277c30fc41b2be6896ce540a48767ca0923416d0dcd5b19c2474", + "iso_signed": false, + "job_id": 110209194771, + "large_payloads_independently_downloaded_for_this_review": false, + "license_source_compliance_reviewed": false, + "linux_governed_workflow": { + "actual_agent_uid": 1001, + "agent_broker_denied": true, + "agent_store_denied": true, + "approval_sha256": "3dc5cbc9522889ee79f88116bd821197c8031338f4bb5e6f5b40dbe4c7c43f56", + "cancel_passed": true, + "expired_approval_sha256": "faac21f8cf4555eec229c35648bd472dcd9032ce12a72f90c68a6556c2bdc305", + "expiry_refused": true, + "hardware_qualified": false, + "receipt": { + "approval_sha256": "3dc5cbc9522889ee79f88116bd821197c8031338f4bb5e6f5b40dbe4c7c43f56", + "authority_replayable": false, + "binding_sha256": "68b78f685cadb2a50f99414d036fefe767be1cd27311ea352481c3beee66e8cf", + "boot_id": "f5b5e59d41d14b2b992ea27ab705393f", + "decision_sha256": "10c1fc6ba860c9f1682afabfea4b4c3f6838dde70f6139e248471a02ffc21089", + "effect_performed": true, + "execution_authority": false, + "lease_sha256": "00ad8eb71fbe6ab892e7a5a71534fb1791b99582fd130d740284c5f25224f3f4", + "note_bytes": 57, + "note_sha256": "e2e3a3855d190c74791ad81fdc9a5dd8742363fcede860ef07439ce9e9058ba8", + "operator_uid": 1000, + "post_effect_verified": true, + "principal_uid": 1001, + "release_ready": false, + "schema_version": "phios.linux-proof-receipt.v1", + "source_commit": "5145b4dabd0e70d4b8d35691041a4d9f797affe9" + }, + "release_ready": false, + "replay_refused": true, + "schema_version": "phios.linux-proof-qualification.v1", + "source_commit": "5145b4dabd0e70d4b8d35691041a4d9f797affe9", + "sudo_password_authentication": true + }, + "linux_governed_workflow_qualified": true, + "matched_root_efi_restored": true, + "network": false, + "no_iso_boot_passed": true, + "ordinary_ci_existing_skips": 6, + "ordinary_ci_passed": 2250, + "ordinary_ci_run": 36812078517, + "ram_mib": 4096, + "record_sha256": "c481900567db858427663a26909e82a9d30fe2e083c929cb68683a9823e87bb4", + "recovery_checkpoint_generation": "456778b299c64a169944fd64a217d85c", + "recovery_requested": true, + "release_ready": false, + "reproducible_build_demonstrated": false, + "reviewed_branch_head": "0ea1fced470abf75701a4cad8f806551078b1b76", + "sbom_components": 442, + "schema_version": "phios.os-qualification-summary.v1", + "screenshot_visually_reviewed": false, + "shared_folders": false, + "signed_package_application_qualified": true, + "signed_update_refusals_observed": true, + "signed_update_requested": true, + "signed_update_transaction": { + "ephemeral_test_key": true, + "generation": "456778b299c64a169944fd64a217d85c", + "sequence": 1, + "signer": "BC6F69868138B96E6533061BF6006184E58E97F1" + }, + "simulated_boot_failure_observed": true, + "source_archive_sha256": "19a5f6e6a51242d9d7e989b7e6579c95b3cbe5778ac39b643380876240eb5911", + "source_commit": "5145b4dabd0e70d4b8d35691041a4d9f797affe9", + "supplier_notice_files": 620, + "tested_source_tree": "59ec972739f5293bb3de57d7369892b98b68c4b3", + "whole_os_recovery_passed": true, + "workflow_run": 36812104411 +} diff --git a/packaging/arch/phios/PKGBUILD b/packaging/arch/phios/PKGBUILD new file mode 100644 index 00000000..8a7f1e76 --- /dev/null +++ b/packaging/arch/phios/PKGBUILD @@ -0,0 +1,41 @@ +# Build only from the local, hashed archive made by build-linux.sh. +pkgname=phios +pkgver=1.0.0 +pkgrel=1 +pkgdesc='PhiOS operator shell, verification spine and governed local runtime' +arch=('any') +url='https://github.com/MichaelWave369/PhiOS' +license=('MIT') +depends=('python' 'python-psutil' 'python-mcp>=1.26' 'python-mcp<2' 'gnupg') +makedepends=('python-build' 'python-installer' 'python-setuptools' 'python-wheel') +source=('phios-source.tar.gz') +sha256sums=("${PHIOS_SOURCE_SHA256:?hashed source archive required}") + +build() { + cd "$srcdir/phios-source" + python -m build --wheel --no-isolation +} + +package() { + cd "$srcdir/phios-source" + python -m installer --destdir="$pkgdir" dist/*.whl + install -Dm644 LICENSE "$pkgdir/usr/share/licenses/phios/LICENSE" + install -Dm644 LICENSE_HISTORY.md "$pkgdir/usr/share/doc/phios/LICENSE_HISTORY.md" + install -Dm644 packaging/linux/release.json "$pkgdir/usr/share/phios/linux-release.json" + install -Dm644 PHIOS_SOURCE_COMMIT "$pkgdir/usr/share/phios/source-commit" + install -Dm644 packaging/linux/installer/install.py "$pkgdir/usr/lib/phios-installer/install.py" + install -Dm755 packaging/linux/installer/phios-install "$pkgdir/usr/bin/phios-install" + install -Dm644 packaging/linux/updates/verify.py "$pkgdir/usr/lib/phios-updates/verify.py" + install -Dm755 packaging/linux/updates/phios-update-verify "$pkgdir/usr/bin/phios-update-verify" + install -Dm644 packaging/linux/updates/recover.py "$pkgdir/usr/lib/phios-updates/recover.py" + install -Dm755 packaging/linux/updates/phios-os-recover "$pkgdir/usr/bin/phios-os-recover" + install -Dm644 packaging/linux/updates/apply.py "$pkgdir/usr/lib/phios-updates/apply.py" + install -Dm755 packaging/linux/updates/phios-os-update "$pkgdir/usr/bin/phios-os-update" + install -Dm644 packaging/linux/updates/enroll.py "$pkgdir/usr/lib/phios-updates/enroll.py" + install -Dm755 packaging/linux/updates/phios-update-enroll "$pkgdir/usr/bin/phios-update-enroll" + install -Dm644 packaging/linux/proof/broker.py "$pkgdir/usr/lib/phios-proof/broker.py" + install -Dm644 packaging/linux/proof/propose.py "$pkgdir/usr/lib/phios-proof/propose.py" + install -Dm755 packaging/linux/proof/phios-linux-proof "$pkgdir/usr/bin/phios-linux-proof" + install -Dm644 packaging/linux/proof/phios-proof-proposer.service "$pkgdir/usr/lib/systemd/system/phios-proof-proposer.service" + install -Dm755 packaging/linux/hardware_report.py "$pkgdir/usr/bin/phios-hardware-report" +} diff --git a/packaging/arch/phishell/PKGBUILD b/packaging/arch/phishell/PKGBUILD new file mode 100644 index 00000000..54c9a58e --- /dev/null +++ b/packaging/arch/phishell/PKGBUILD @@ -0,0 +1,44 @@ +pkgname=phishell +pkgver=0.16.0 +pkgrel=2 +pkgdesc='PhiShell browser interface and local observation transport' +arch=('any') +url='https://github.com/MichaelWave369/PhiOS' +license=('MIT') +depends=('nodejs' 'phios' 'wayfire' 'waybar' 'wofi' 'foot' 'chromium' 'ttf-dejavu' + 'pipewire' 'pipewire-audio' 'pipewire-pulse' 'pipewire-alsa' 'wireplumber' 'swaylock' + 'lxqt-policykit' 'qt6-wayland') +makedepends=('npm') +source=('phios-source.tar.gz') +sha256sums=("${PHIOS_SOURCE_SHA256:?hashed source archive required}") + +build() { + cd "$srcdir/phios-source/phishell" + npm ci --no-audit --no-fund + npm run build + npm prune --omit=dev --no-audit --no-fund +} + +package() { + cd "$srcdir/phios-source" + install -dm755 "$pkgdir/usr/lib/phishell" + cp -a phishell/dist phishell/host phishell/node_modules phishell/package.json "$pkgdir/usr/lib/phishell/" + find "$pkgdir/usr/lib/phishell" -name '*.test.mjs' -delete + install -Dm644 LICENSE "$pkgdir/usr/share/licenses/phishell/LICENSE" + install -Dm755 packaging/linux/session/phios-session "$pkgdir/usr/bin/phios-session" + install -Dm755 packaging/linux/session/phios-open-shell "$pkgdir/usr/bin/phios-open-shell" + install -Dm755 packaging/linux/session/phios-lock "$pkgdir/usr/bin/phios-lock" + install -Dm755 packaging/linux/session/phios-session-ready "$pkgdir/usr/lib/phishell/session-ready" + install -Dm644 packaging/linux/session/phios.desktop "$pkgdir/usr/share/wayland-sessions/phios.desktop" + for unit in packaging/linux/session/*.service packaging/linux/session/*.target; do + install -Dm644 "$unit" "$pkgdir/usr/lib/systemd/user/${unit##*/}" + done + for unit in pipewire.service pipewire-pulse.service wireplumber.service pipewire.socket pipewire-pulse.socket; do + install -Dm644 packaging/linux/session/audio-session.conf \ + "$pkgdir/usr/lib/systemd/user/$unit.d/50-phios-session.conf" + done + install -Dm644 packaging/linux/session/phios-lock.desktop "$pkgdir/usr/share/applications/phios-lock.desktop" + install -Dm644 packaging/linux/session/phios-network.desktop "$pkgdir/usr/share/applications/phios-network.desktop" + install -Dm644 packaging/linux/session/wayfire.ini "$pkgdir/etc/xdg/phios/wayfire.ini" + install -Dm644 packaging/linux/session/waybar.json "$pkgdir/etc/xdg/phios/waybar.json" +} diff --git a/packaging/linux/build-linux.sh b/packaging/linux/build-linux.sh new file mode 100755 index 00000000..4751c059 --- /dev/null +++ b/packaging/linux/build-linux.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail +repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +if [[ $EUID -ne 0 || $(uname -m) != x86_64 ]]; then + echo 'The isolated image builder requires an x86_64 Arch Linux root environment.' >&2 + exit 1 +fi +snapshot=$(sed -n 's/.*"arch_snapshot": "\([0-9/]\{10\}\)".*/\1/p' "$repo/packaging/linux/release.json") +expected_archiso=$(sed -n 's/.*"archiso_version": "\([0-9-]\+\)".*/\1/p' "$repo/packaging/linux/release.json") +[[ $snapshot =~ ^[0-9]{4}/[0-9]{2}/[0-9]{2}$ && $expected_archiso =~ ^[0-9]+-[0-9]+$ ]] || exit 1 +cat > /etc/pacman.d/mirrorlist <&2; exit 1; } +[[ -n ${PHIOS_SOURCE_COMMIT:-} ]] || { echo 'PHIOS_SOURCE_COMMIT is required.' >&2; exit 1; } +[[ $(git -c safe.directory="$repo" -C "$repo" rev-parse HEAD) == "$PHIOS_SOURCE_COMMIT" ]] || { echo 'Source commit mismatch.' >&2; exit 1; } +export SOURCE_DATE_EPOCH +SOURCE_DATE_EPOCH=$(git -c safe.directory="$repo" -C "$repo" show -s --format=%ct HEAD) +work=$(mktemp -d /tmp/phios-build.XXXXXXXX) +output="${PHIOS_OUTPUT_DIR:-$repo/dist/linux}" +mkdir -p "$output" "$work/source" "$work/packages" +git -c safe.directory="$repo" -C "$repo" archive --format=tar --prefix=phios-source/ HEAD | tar -xf - -C "$work/source" +printf '%s\n' "$PHIOS_SOURCE_COMMIT" > "$work/source/phios-source/PHIOS_SOURCE_COMMIT" +tar --sort=name --mtime="@$SOURCE_DATE_EPOCH" --owner=0 --group=0 --numeric-owner --use-compress-program='gzip -n' -cf "$work/phios-source.tar.gz" -C "$work/source" phios-source +export PHIOS_SOURCE_SHA256 +PHIOS_SOURCE_SHA256=$(sha256sum "$work/phios-source.tar.gz" | cut -d' ' -f1) +id phios-build &>/dev/null || useradd -m phios-build +chmod 755 "$work" +for package in phios phishell; do + mkdir "$work/$package" + cp "$repo/packaging/arch/$package/PKGBUILD" "$work/$package/" + cp "$work/phios-source.tar.gz" "$work/$package/" + chown -R phios-build:phios-build "$work/$package" + runuser -u phios-build -- env PHIOS_SOURCE_SHA256="$PHIOS_SOURCE_SHA256" SOURCE_DATE_EPOCH="$SOURCE_DATE_EPOCH" bash -c 'cd "$1"; makepkg --noconfirm --cleanbuild' _ "$work/$package" + cp "$work/$package/"*.pkg.tar.zst "$work/packages/" + pacman -U --noconfirm "$work/$package/"*.pkg.tar.zst +done +(cd /tmp; python -c 'import phios, phios.mcp.server, phios.ghostwalk_operator; assert phios.__file__.startswith("/usr/lib/"); print(phios.__version__)'; phi version; phi-operator --help) +node "$repo/phishell/host/packageObserver.mjs" --require-native +repo-add "$work/packages/phios-local.db.tar.gz" "$work/packages/"*.pkg.tar.zst +smoke_args=() +[[ ${PHIOS_CI_SMOKE:-0} == 1 ]] && smoke_args+=(--smoke) +python "$repo/packaging/linux/prepare_profile.py" --upstream /usr/share/archiso/configs/releng --destination "$work/profile" --repo "$repo" --package-repo "$work/packages" "${smoke_args[@]}" +mkarchiso -v -w "$work/archiso-work" -o "$output" "$work/profile" 2>&1 | tee "$output/mkarchiso.log" +# Pacman hooks can print an initramfs error while the package transaction and +# mkarchiso still return zero. Preserve it and hold the candidate explicitly. +if grep -Eq '==> ERROR:|error: command failed to execute correctly' "$output/mkarchiso.log"; then + echo 'Image contains a failed build hook; candidate qualification is held.' >&2 + exit 1 +fi +cp "$work/packages/"*.pkg.tar.zst "$output/" +cp "$work/phios-source.tar.gz" "$output/" +cp "$repo/packaging/linux/release.json" "$output/" +pacman -Q > "$output/builder-packages.txt" +pacman --root "$work/archiso-work/x86_64/airootfs" -Q > "$output/image-packages.txt" +printf '%s\n' "$PHIOS_SOURCE_COMMIT" > "$output/source-commit.txt" +printf '%s\n' "$PHIOS_SOURCE_SHA256" > "$output/source-archive-sha256.txt" +cp "$repo/LICENSE_HISTORY.md" "$output/LICENSE_HISTORY.md" +inventory_args=() +[[ ${PHIOS_CI_SMOKE:-0} == 1 ]] && inventory_args+=(--ci-fixtures) +python "$repo/packaging/linux/release_inventory.py" \ + --root "$work/archiso-work/x86_64/airootfs" --output "$output" \ + --source "$PHIOS_SOURCE_COMMIT" --epoch "$SOURCE_DATE_EPOCH" "${inventory_args[@]}" +echo "Unsigned development candidate and provenance: $output" diff --git a/packaging/linux/hardware_report.py b/packaging/linux/hardware_report.py new file mode 100644 index 00000000..b3f52743 --- /dev/null +++ b/packaging/linux/hardware_report.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +"""Collect bounded public hardware observations; no qualification or authority.""" +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +from datetime import UTC, datetime +from pathlib import Path + + +def value(path: Path, maximum: int = 256) -> str | None: + try: + with path.open() as handle: + data = handle.read(maximum + 1).strip() + return data if len(data) <= maximum and all(ord(c) >= 32 for c in data) else None + except OSError: + return None + + +def observe(iso_sha256: str | None) -> dict[str, object]: + source = value(Path('/usr/share/phios/source-commit')) + if not source or not re.fullmatch('[0-9a-f]{40}', source): + raise ValueError('run this inside the built PhiOS image') + if iso_sha256 is not None and not re.fullmatch('[0-9a-f]{64}', iso_sha256): + raise ValueError('supplied ISO identity must be a lowercase SHA-256') + devices = [] + for device in sorted(Path('/sys/bus/pci/devices').iterdir()): + if len(devices) >= 1024: + raise ValueError('PCI observation exceeds its bound') + devices.append({'pci_address': device.name, 'vendor_id': value(device / 'vendor'), + 'device_id': value(device / 'device'), 'class_id': value(device / 'class'), + 'bound_driver': (device / 'driver').resolve().name if (device / 'driver').exists() else None}) + try: + detected = subprocess.run(['/usr/bin/systemd-detect-virt'], text=True, capture_output=True, timeout=5) + virtualization = detected.stdout.strip()[:64] if detected.returncode == 0 else 'not detected; physical hardware unproven' + except (OSError, subprocess.SubprocessError): + virtualization = 'unavailable' + return {'schema_version': 'phios.hardware-observation.v1', 'observed_at': datetime.now(UTC).isoformat(), + 'source_commit': source, 'supplied_iso_sha256': iso_sha256, 'iso_bytes_independently_verified': False, + 'kernel': os.uname().release, 'architecture': os.uname().machine, + 'uefi_observed': Path('/sys/firmware/efi').is_dir(), 'virtualization_observation': virtualization, + 'board_vendor': value(Path('/sys/class/dmi/id/board_vendor')), + 'board_model': value(Path('/sys/class/dmi/id/board_name')), + 'firmware_version': value(Path('/sys/class/dmi/id/bios_version')), 'pci_devices': devices, + 'audio_cards_observed': len(list(Path('/sys/class/sound').glob('card[0-9]*'))), + 'physical_hardware_qualified': False, 'release_ready': False, 'execution_authority': False, + 'manual_tests': {name: 'not tested' for name in ['display_gpu', 'keyboard_mouse', 'wired_network', + 'wifi', 'audio', 'sleep_resume', 'shutdown_restart', 'dedicated_disk_install', 'data_persistence', + 'signed_update', 'interrupted_update', 'matched_recovery']}} + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--iso-sha256', help='Previously verified candidate hash; marked supplied, not independently verified here') + args = parser.parse_args() + try: + print(json.dumps(observe(args.iso_sha256), indent=2, sort_keys=True, allow_nan=False)) + except (OSError, ValueError) as exc: + parser.exit(1, 'Hardware observation held: ' + str(exc) + '\n') diff --git a/packaging/linux/installer/install.py b/packaging/linux/installer/install.py new file mode 100644 index 00000000..50f08756 --- /dev/null +++ b/packaging/linux/installer/install.py @@ -0,0 +1,373 @@ +"""Experimental offline UEFI installer; only an explicitly confirmed zeroed disk. + +Installed behind a root-owned `python -I` wrapper. No automatic disk selection, +erase-existing mode, confirmation bypass, remote request handler or shell eval. +""" +from __future__ import annotations + +import argparse +import fcntl +import getpass +import hashlib +import json +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +ENV = {"PATH": "/usr/bin", "LANG": "C.UTF-8", "HOME": "/root"} +SOURCE = Path("/run/archiso/bootmnt/arch/x86_64/airootfs.sfs") +IDENTITY = Path("/usr/share/phios/source-commit") +MINIMUM = 16 * 1024**3 +REQUIRED = ("lsblk", "wipefs", "sgdisk", "udevadm", "mkfs.fat", "mkfs.btrfs", + "mount", "umount", "rsync", "chroot", "arch-chroot", "btrfs", "blkid", "bootctl") + + +def run(*args: str, data: str | None = None) -> str: + executable = shutil.which(args[0], path=ENV["PATH"]) + if executable is None: + raise ValueError(f"required program unavailable: {args[0]}") + result = subprocess.run([executable, *args[1:]], input=data, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + env=ENV, check=False) + if result.returncode or "==> ERROR:" in result.stdout: + # Password input is never included in a command, exception or receipt. + raise RuntimeError(f"{args[0]} failed (exit {result.returncode}): {result.stdout[-4000:]}") + return result.stdout + + +def validate_inventory(row: dict[str, Any], signatures: list[Any], *, busy: bool) -> dict[str, Any]: + if row.get("type") != "disk" or row.get("ro") not in (False, 0): + raise ValueError("target must be a writable whole disk") + path = row.get("path") + if not isinstance(path, str) or re.fullmatch(r"/dev/(sd[a-z]+|vd[a-z]+|nvme[0-9]+n[0-9]+|mmcblk[0-9]+)", path) is None: + raise ValueError("unsupported or noncanonical disk path") + if row.get("children") or any(row.get("mountpoints") or []) or busy: + raise ValueError("mounted disks, swap, partitions and device holders are refused") + if signatures or row.get("fstype") or row.get("pttype"): + raise ValueError("used disks are refused; existing data is never erased by this installer") + if type(row.get("size")) is not int or row["size"] < MINIMUM: + raise ValueError("a disk of at least 16 GiB is required") + serial = row.get("serial") or row.get("wwn") + if not isinstance(serial, str) or not serial.strip(): + raise ValueError("a stable serial number or WWN is required") + if any(ord(c) < 32 or ord(c) == 127 for c in serial): + raise ValueError("disk identity contains unsafe control characters") + return {"path": path, "size_bytes": row["size"], "serial_or_wwn": serial.strip(), + "model": row.get("model"), "major_minor": row.get("maj:min")} + + +def inventory(device: str) -> dict[str, Any]: + path = Path(device) + if not path.is_absolute() or path.resolve() != path or not stat.S_ISBLK(path.stat().st_mode): + raise ValueError("use the canonical /dev path of a real whole disk") + run("udevadm", "settle") + rows = json.loads(run("lsblk", "--json", "--bytes", "--paths", "--tree", "--output", + "NAME,PATH,TYPE,SIZE,RO,MODEL,SERIAL,WWN,MOUNTPOINTS,FSTYPE,PTTYPE,MAJ:MIN", device))["blockdevices"] + if len(rows) != 1: + raise ValueError("target inventory is ambiguous") + info = path.stat() + number = f"{os.major(info.st_rdev)}:{os.minor(info.st_rdev)}" + sys_device = Path("/sys/dev/block") / number + holders = sys_device / "holders" + slaves = sys_device / "slaves" + busy = bool(list(holders.iterdir()) or list(slaves.iterdir())) + # lsblk sees mounts in this namespace; inspect swap and kernel mount IDs too. + if any(line.split()[2] == number for line in Path("/proc/self/mountinfo").read_text().splitlines()): + busy = True + for line in Path("/proc/swaps").read_text().splitlines()[1:]: + swap = Path(line.split()[0]) + if swap.exists() and swap.stat().st_rdev == info.st_rdev: + busy = True + signatures = json.loads(run("wipefs", "--no-act", "--json", device))["signatures"] + identity = validate_inventory(rows[0], signatures, busy=busy) + if identity["path"] != device or identity["major_minor"] != number: + raise ValueError("block device identity changed during inventory") + return identity + + +def verify_zeroed(device: str, size: int) -> None: + """Probe every byte, including unsigned data with no filesystem signature.""" + fd = os.open(device, os.O_RDONLY | os.O_NOFOLLOW) + try: + total = 0 + while chunk := os.read(fd, 8 * 1024**2): + if chunk.count(0) != len(chunk): + raise ValueError("target is not fully zeroed; no disk writes were performed") + total += len(chunk) + if total != size: + raise ValueError("disk size changed or a read was incomplete") + finally: + os.close(fd) + + +def confirmation(identity: dict[str, Any], source: str, username: str, hostname: str, *, serial_console: bool = False) -> tuple[dict[str, Any], str]: + plan = {"schema_version": "phios.blank-disk-install-plan.v1", "target": identity, + "source_commit": source, "username": username, "hostname": hostname, + "serial_console_password_login": serial_console, + "layout": {"gpt": True, "esp_bytes": 1024**3, "filesystem": "btrfs", + "subvolumes": ["@root", "@home", "@log", "@snapshots"]}, + "encrypted": False, "secure_boot": False, "firmware_variables_changed": False, + "experimental": True, "release_ready": False} + digest = hashlib.sha256(json.dumps(plan, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + return plan, f"INSTALL {identity['path']} {digest}" + + +def validate_account(username: str, hostname: str) -> None: + if re.fullmatch(r"[a-z][a-z0-9_-]{0,30}", username) is None or username in { + "root", "phios", "phios-agent", "phios-greeter", "nobody", + }: + raise ValueError("choose a new lowercase account name; live/system accounts are reserved") + if re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", hostname) is None: + raise ValueError("invalid hostname") + + +def write(root: Path, name: str, content: str, *, mode: int = 0o644) -> None: + path = root / name + # The immutable source is trusted, but generated files must not follow its + # absolute symlinks out of the installation target (notably /etc/os-release). + if path.is_symlink(): + path.unlink() + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, mode) + with os.fdopen(fd, "w") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.chmod(path, mode) + + +def configure(root: Path, username: str, password: str, hostname: str, root_uuid: str, esp_uuid: str, *, serial_console: bool = False) -> None: + for pattern in ["etc/sysusers.d/phios-live.conf", "etc/tmpfiles.d/phios-live.conf", + "etc/mkinitcpio.conf.d/archiso.conf", "etc/systemd/system/phios-live-*.service", + "etc/systemd/system/multi-user.target.wants/phios-live-*.service", + "etc/systemd/system/greetd.service.d/phios.conf", "usr/local/bin/phios-live-*", + "etc/sudoers.d/phios-live-installer", "etc/systemd/system/serial-getty@ttyS0.service"]: + for path in root.glob(pattern): + path.unlink() + if (root / "etc/machine-id").exists(): + write(root, "etc/machine-id", "") + random_seed = root / "var/lib/systemd/random-seed" + random_seed.unlink(missing_ok=True) + passwd = (root / "etc/passwd").read_text().splitlines() + if any(line.split(":")[0] == username for line in passwd): + raise ValueError("account already exists in source image") + if any(line.startswith("phios:") for line in passwd): + run("chroot", str(root), "userdel", "--force", "phios") + if any(line.split(":")[2] == "1000" and not line.startswith("phios:") for line in passwd): + raise ValueError("source has an unexpected UID 1000 account") + groups = (root / "etc/group").read_text().splitlines() + for line in groups: + if line.split(":")[2] == "1000": + if not line.startswith("phios:"): + raise ValueError("source has an unexpected GID 1000 group") + run("chroot", str(root), "groupdel", "phios") + run("chroot", str(root), "groupadd", "--gid", "1000", username) + run("chroot", str(root), "useradd", "--uid", "1000", "--gid", username, "--create-home", + "--groups", "wheel", "--shell", "/bin/bash", username) + run("chroot", str(root), "chpasswd", data=f"{username}:{password}\n") + run("chroot", str(root), "usermod", "--lock", "root") + home = root / "home" / username + for path in [home, home / ".local", home / ".local/state", home / ".local/state/phios"]: + path.mkdir(parents=True, exist_ok=True, mode=0o700) + os.chmod(path, 0o700) + os.chown(path, 1000, 1000) + write(root, "etc/sudoers.d/phios-admin", "%wheel ALL=(ALL:ALL) ALL\n", mode=0o440) + run("chroot", str(root), "visudo", "--check") + write(root, "etc/hostname", hostname + "\n") + write(root, "etc/hosts", f"127.0.0.1 localhost\n::1 localhost\n127.0.1.1 {hostname}\n") + write(root, "etc/greetd/config.toml", '[terminal]\nvt = 1\n[default_session]\n' + 'command = "tuigreet --cmd phios-session"\nuser = "phios-greeter"\n') + write(root, "etc/sysusers.d/phios-system.conf", 'u phios-agent 1001 "Reserved isolated agent" /var/lib/phios-agent /usr/bin/nologin\n' + 'u phios-greeter - "PhiOS Greeter" /var/lib/phios-greeter /usr/bin/nologin\n') + write(root, "etc/tmpfiles.d/phios-system.conf", "d /var/lib/phios-agent 0700 phios-agent phios-agent -\n") + write(root, "etc/fstab", f"UUID={root_uuid} / btrfs defaults,noatime,compress=zstd,subvol=@root 0 0\n" + f"UUID={root_uuid} /home btrfs defaults,noatime,compress=zstd,subvol=@home 0 0\n" + f"UUID={root_uuid} /var/log btrfs defaults,noatime,compress=zstd,subvol=@log 0 0\n" + f"UUID={root_uuid} /.snapshots btrfs defaults,noatime,compress=zstd,subvol=@snapshots 0 0\n" + f"UUID={esp_uuid} /boot vfat defaults,umask=0077 0 2\n") + write(root, "etc/mkinitcpio.conf", "MODULES=(btrfs)\nBINARIES=()\nFILES=()\n" + "HOOKS=(base systemd autodetect microcode modconf kms keyboard sd-vconsole block filesystems fsck)\n") + kernels = list((root / "usr/lib/modules").glob("*/vmlinuz")) + if len(kernels) != 1: + raise ValueError("exactly one packaged Linux kernel is required") + shutil.copyfile(kernels[0], root / "boot/vmlinuz-linux") + write(root, "etc/mkinitcpio.d/linux.preset", 'ALL_config="/etc/mkinitcpio.conf"\nALL_kver="/boot/vmlinuz-linux"\n' + "PRESETS=('default' 'fallback')\ndefault_image=\"/boot/initramfs-linux.img\"\n" + 'fallback_image="/boot/initramfs-linux-fallback.img"\nfallback_options="-S autodetect"\n') + run("arch-chroot", str(root), "mkinitcpio", "-P") + run("bootctl", f"--root={root}", "--esp-path=/boot", "--install-source=image", "--variables=no", "install") + write(root, "boot/loader/loader.conf", "default phios.conf\ntimeout 5\neditor no\n") + console = ' console=tty0 console=ttyS0,115200' if serial_console else '' + if serial_console: + getty = root / 'etc/systemd/system/getty.target.wants/serial-getty@ttyS0.service' + getty.parent.mkdir(parents=True, exist_ok=True) + getty.symlink_to('/usr/lib/systemd/system/serial-getty@.service') + write(root, "boot/loader/entries/phios.conf", "title PhiOS Linux development installation\n" + "linux /vmlinuz-linux\ninitrd /initramfs-linux.img\n" + f"options root=UUID={root_uuid} rw rootflags=subvol=@root{console}\n") + write(root, "boot/loader/entries/phios-fallback.conf", "title PhiOS Linux fallback initramfs\n" + "linux /vmlinuz-linux\ninitrd /initramfs-linux-fallback.img\n" + f"options root=UUID={root_uuid} rw rootflags=subvol=@root{console}\n") + release = json.loads((root / "usr/share/phios/linux-release.json").read_text()) + write(root, "etc/os-release", 'NAME="PhiOS Linux Preview"\nID=phios\nID_LIKE=arch\n' + f'PRETTY_NAME="PhiOS Linux {release["os_version"]} Experimental Installation"\nVERSION_ID="{release["os_version"]}"\n') + # The live file:// package repository lives only in the isolated builder. + write(root, "etc/pacman.conf", "[options]\nArchitecture = x86_64\nCheckSpace\n" + "SigLevel = Required DatabaseOptional\nLocalFileSigLevel = Required\n" + "[core]\nInclude = /etc/pacman.d/mirrorlist\n[extra]\nInclude = /etc/pacman.d/mirrorlist\n") + write(root, "etc/pacman.d/mirrorlist", f'Server = https://archive.archlinux.org/repos/{release["arch_snapshot"]}/$repo/os/$arch\n') + + +def apply(plan: dict[str, Any], password: str) -> dict[str, Any]: + identity = plan["target"] + device = identity["path"] + if inventory(device) != identity: + raise ValueError("disk changed after review; no disk writes performed") + verify_zeroed(device, identity["size_bytes"]) + workspace = Path(tempfile.mkdtemp(prefix="phios-install-", dir="/run")) + receipt = {"schema_version": "phios.blank-disk-install.v1", "plan": plan, + "stage": "prepared", "disk_modified": False, "installed": False, "release_ready": False} + mounts: list[Path] = [] + lock = os.open(device, os.O_RDONLY | os.O_NOFOLLOW) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + if inventory(device) != identity: + raise ValueError("disk changed before partitioning") + source = workspace / "source" + root = workspace / "target" + top = workspace / "top" + for path in [source, root, top]: + path.mkdir(mode=0o700) + run("mount", "-o", "loop,ro,nodev,nosuid", str(SOURCE), str(source)) + mounts.append(source) + if (source / "usr/share/phios/source-commit").read_text().strip() != plan["source_commit"]: + raise ValueError("immutable live source differs from reviewed package source") + receipt.update(stage="partitioning", disk_modified=True) + write(workspace, "receipt.json", json.dumps(receipt, indent=2) + "\n", mode=0o600) + run("sgdisk", "--clear", "--new=1:0:+1G", "--typecode=1:ef00", "--change-name=1:PHIOS_ESP", + "--new=2:0:0", "--typecode=2:8300", "--change-name=2:PHIOS_ROOT", device) + # udev observes the block-device lock. Release it before waiting for + # partition events; otherwise settle can wait on our own open lock. + os.close(lock) + lock = -1 + run("udevadm", "settle") + suffix = "p" if device[-1].isdigit() else "" + esp, system = Path(device + suffix + "1"), Path(device + suffix + "2") + for _ in range(30): + if esp.exists() and system.exists(): + break + time.sleep(0.1) + for partition in [esp, system]: + info = partition.stat() + link = (Path("/sys/dev/block") / f"{os.major(info.st_rdev)}:{os.minor(info.st_rdev)}").resolve() + if not stat.S_ISBLK(info.st_mode) or link.parent.name != Path(device).name: + raise ValueError("new partition does not belong to confirmed disk") + run("mkfs.fat", "-F", "32", "-n", "PHIOS_ESP", str(esp)) + run("mkfs.btrfs", "-L", "PHIOS_ROOT", str(system)) + run("mount", str(system), str(top)) + mounts.append(top) + for subvolume in plan["layout"]["subvolumes"]: + run("btrfs", "subvolume", "create", str(top / subvolume)) + run("mount", "-o", "subvol=@root,compress=zstd", str(system), str(root)) + mounts.append(root) + for subvolume, relative in [("@home", "home"), ("@log", "var/log"), ("@snapshots", ".snapshots")]: + path = root / relative + path.mkdir(parents=True) + run("mount", "-o", f"subvol={subvolume},compress=zstd", str(system), str(path)) + mounts.append(path) + (root / "boot").mkdir() + run("mount", str(esp), str(root / "boot")) + mounts.append(root / "boot") + receipt["stage"] = "copying immutable source" + run("rsync", "-aHAX", "--numeric-ids", "--one-file-system", "--exclude=/home/***", + "--exclude=/boot/***", "--exclude=/var/log/***", str(source) + "/", str(root) + "/") + root_uuid = run("blkid", "-s", "UUID", "-o", "value", str(system)).strip() + esp_uuid = run("blkid", "-s", "UUID", "-o", "value", str(esp)).strip() + if not re.fullmatch(r"[0-9a-f-]{36}", root_uuid) or not re.fullmatch(r"[0-9A-F]{4}-[0-9A-F]{4}", esp_uuid): + raise ValueError("invalid new filesystem UUID") + receipt["stage"] = "configuring installed system" + configure(root, plan["username"], password, plan["hostname"], root_uuid, esp_uuid, + serial_console=plan['serial_console_password_login']) + receipt.update(stage="installed; no-ISO boot unqualified", installed=True, + root_uuid=root_uuid, esp_uuid=esp_uuid) + write(root, "var/lib/phios/install-receipt.json", json.dumps(receipt, indent=2) + "\n", mode=0o600) + os.sync() + return receipt + except BaseException as exc: + receipt["error"] = str(exc) + raise + finally: + failures = [] + for path in reversed(mounts): + try: + run("umount", str(path)) + except (ValueError, RuntimeError) as exc: + failures.append(str(exc)) + if lock >= 0: + os.close(lock) + receipt["cleanup_errors"] = failures + write(workspace, "receipt.json", json.dumps(receipt, indent=2) + "\n", mode=0o600) + print(f"Private installation evidence: {workspace}/receipt.json", flush=True) + if failures: + raise RuntimeError("installation mounts remain active; preserve evidence and do not reboot") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--disk", required=True) + parser.add_argument("--username", required=True) + parser.add_argument("--hostname", default="phios") + parser.add_argument('--serial-console', action='store_true', help='Explicit password/PAM login on ttyS0 at 115200 baud; included in the reviewed plan') + parser.add_argument("--plan", action="store_true", help="Read-only inventory; never installs") + args = parser.parse_args() + try: + if os.geteuid() != 0: + raise ValueError("run the root-owned installer with sudo from the live preview") + validate_account(args.username, args.hostname) + if not SOURCE.is_file() or not Path("/sys/firmware/efi").is_dir(): + raise ValueError("the configured PhiOS x64 UEFI live image is required") + for name in REQUIRED: + if shutil.which(name, path=ENV["PATH"]) is None: + raise ValueError(f"required installer program unavailable: {name}") + source = IDENTITY.read_text().strip() + if re.fullmatch(r"[0-9a-f]{40}", source) is None: + raise ValueError("exact installed source identity is required") + identity = inventory(args.disk) + plan, phrase = confirmation(identity, source, args.username, args.hostname, serial_console=args.serial_console) + print(json.dumps(plan, indent=2), flush=True) + if args.plan: + return 0 + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise ValueError("installation requires an interactive terminal; no bypass is provided") + print("Checking every byte of the selected disk for zeroed contents...", flush=True) + verify_zeroed(args.disk, identity["size_bytes"]) + password = getpass.getpass("New account password (12 or more characters): ") + if len(password) < 12 or ":" in password or "\n" in password or "\r" in password: + raise ValueError("password must be at least 12 characters without colon or line breaks") + if getpass.getpass("Repeat new account password: ") != password: + raise ValueError("passwords do not match; no disk writes performed") + print("This creates an unencrypted experimental installation. All selected disk contents will be replaced.", flush=True) + print("Type the exact confirmation below, or press Ctrl-C to cancel:\n" + phrase, flush=True) + if input("> ") != phrase: + raise ValueError("confirmation did not match; no disk writes performed") + result = apply(plan, password) + print(json.dumps(result, indent=2), flush=True) + print("Remove live media and test the installed boot. Keep this preview available for recovery.") + return 0 + except (KeyboardInterrupt, EOFError): + print("Installation cancelled. Preserve any installation evidence if disk writes had begun.") + return 130 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print(f"Installation held: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/linux/installer/phios-install b/packaging/linux/installer/phios-install new file mode 100755 index 00000000..ad107e5c --- /dev/null +++ b/packaging/linux/installer/phios-install @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-installer/install.py "$@" diff --git a/packaging/linux/packages.x86_64 b/packaging/linux/packages.x86_64 new file mode 100644 index 00000000..def08e31 --- /dev/null +++ b/packaging/linux/packages.x86_64 @@ -0,0 +1,24 @@ +base +linux +linux-firmware +mkinitcpio +mkinitcpio-archiso +mkinitcpio-nfs-utils +nbd +syslinux +pv +systemd +systemd-sysvcompat +mesa +greetd +greetd-tuigreet +networkmanager +curl +gptfdisk +dosfstools +btrfs-progs +rsync +arch-install-scripts +sudo +phios +phishell diff --git a/packaging/linux/prepare_profile.py b/packaging/linux/prepare_profile.py new file mode 100644 index 00000000..50635ae5 --- /dev/null +++ b/packaging/linux/prepare_profile.py @@ -0,0 +1,165 @@ +"""Assemble an isolated Archiso 91 profile; never modify the upstream template.""" +from __future__ import annotations + +import argparse +import json +import shutil +from pathlib import Path + + +def prepare(upstream: Path, destination: Path, repo: Path, package_repo: Path, *, smoke: bool) -> None: + release = json.loads((repo / "packaging/linux/release.json").read_text()) + required = ["profiledef.sh", "efiboot/loader/entries/01-archiso-linux.conf", + "airootfs/etc/mkinitcpio.conf.d/archiso.conf"] + for name in required: + if not (upstream / name).is_file(): + raise ValueError(f"complete Archiso releng template required: {name}") + if destination.exists(): + raise ValueError("profile destination must be new; refusing to overwrite an existing build") + shutil.copytree(upstream, destination, symlinks=True) + # Discard root autologin, ssh, cloud-init and unrelated releng customization. + shutil.rmtree(destination / "airootfs") + root = destination / "airootfs" + + def write(name: str, content: str) -> None: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + write("etc/mkinitcpio.conf.d/archiso.conf", (upstream / required[2]).read_text()) + snapshot = release["arch_snapshot"] + pacman = f"""[options] +Architecture = x86_64 +SigLevel = Required DatabaseOptional +LocalFileSigLevel = Optional +CheckSpace +ParallelDownloads = 5 +[core] +Server = https://archive.archlinux.org/repos/{snapshot}/$repo/os/$arch +[extra] +Server = https://archive.archlinux.org/repos/{snapshot}/$repo/os/$arch +[phios-local] +SigLevel = Optional TrustAll +Server = file://{package_repo.resolve()} +""" + (destination / "pacman.conf").write_text(pacman) + shutil.copyfile(repo / "packaging/linux/packages.x86_64", destination / "packages.x86_64") + if smoke: + with (destination / 'packages.x86_64').open('a') as packages: + packages.write('\nfakeroot\n') + version = release["os_version"] + (destination / "profiledef.sh").write_text(f"""#!/usr/bin/env bash +# Built on the signed Archiso {release['archiso_version']} releng template. +iso_name="phios-linux" +iso_label="PHIOS_PREVIEW" +iso_publisher="PHI369 Labs / Parallax" +iso_application="PhiOS Linux development preview" +iso_version="{version}" +install_dir="arch" +arch="x86_64" +buildmodes=('iso') +bootmodes=('uefi.systemd-boot') +pacman_conf="pacman.conf" +airootfs_image_type="squashfs" +airootfs_image_tool_options=('-comp' 'zstd' '-b' '1M') +file_permissions=( + ["/etc/sudoers.d/phios-live-installer"]="0:0:440" + ["/usr/local/bin/phios-live-setup"]="0:0:755" + ["/usr/local/bin/phios-live-smoke"]="0:0:755" +) +""" if smoke else f"""#!/usr/bin/env bash +iso_name="phios-linux" +iso_label="PHIOS_PREVIEW" +iso_publisher="PHI369 Labs / Parallax" +iso_application="PhiOS Linux development preview" +iso_version="{version}" +install_dir="arch" +arch="x86_64" +buildmodes=('iso') +bootmodes=('uefi.systemd-boot') +pacman_conf="pacman.conf" +airootfs_image_type="squashfs" +airootfs_image_tool_options=('-comp' 'zstd' '-b' '1M') +file_permissions=(["/usr/local/bin/phios-live-setup"]="0:0:755" ["/etc/sudoers.d/phios-live-installer"]="0:0:440") +""") + entries = destination / "efiboot/loader/entries" + for path in entries.iterdir(): + if path.name != "01-archiso-linux.conf": + path.unlink() + entry = entries / "01-archiso-linux.conf" + entry.write_text(entry.read_text().replace("Arch Linux", "PhiOS development preview") + + "\n# Console logs are preserved by the qualification harness.\n") + # Keep the upstream identifiers/placeholders needed by mkarchiso. + lines = entry.read_text().splitlines() + entry.write_text("\n".join(line + " console=tty0 console=ttyS0,115200" if line.startswith("options ") + else line for line in lines) + "\n") + (destination / "efiboot/loader/loader.conf").write_text("default 01-archiso-linux.conf\ntimeout 1\n") + write("etc/hostname", "phios-live\n") + write("etc/locale.conf", "LANG=C.UTF-8\n") + write("etc/vconsole.conf", "KEYMAP=us\n") + (root / "etc/localtime").symlink_to("/usr/share/zoneinfo/UTC") + # Releng masks this interactive first-boot wizard. Keep that behavior for + # a configured volatile live session rather than blocking graphical.target. + firstboot = root / "etc/systemd/system/systemd-firstboot.service" + firstboot.parent.mkdir(parents=True, exist_ok=True) + firstboot.symlink_to("/dev/null") + write("etc/sysusers.d/phios-live.conf", 'u phios 1000 "PhiOS Live" /home/phios /bin/bash\n' + 'u phios-agent 1001 "Reserved isolated agent" /var/lib/phios-agent /usr/bin/nologin\n' + 'u phios-greeter - "PhiOS Greeter" /var/lib/phios-greeter /usr/bin/nologin\n') + write("etc/tmpfiles.d/phios-live.conf", "d /home/phios 0700 phios phios -\n" + "d /home/phios/.local 0700 phios phios -\n" + "d /home/phios/.local/state 0700 phios phios -\n" + "d /home/phios/.local/state/phios 0700 phios phios -\n" + "d /var/lib/phios-agent 0700 phios-agent phios-agent -\n") + # The volatile account can invoke only these root-owned interactive + # maintenance commands; it receives no unrestricted sudo shell. + write("etc/sudoers.d/phios-live-installer", "phios ALL=(root) NOPASSWD: /usr/bin/phios-install, /usr/bin/phios-os-recover, /usr/bin/phios-os-update, /usr/bin/phios-update-enroll\n") + write("etc/greetd/config.toml", '[terminal]\nvt = 1\n[default_session]\n' + 'command = "tuigreet --cmd phios-session"\nuser = "phios-greeter"\n' + '[initial_session]\ncommand = "phios-session"\nuser = "phios"\n') + write("etc/systemd/system/greetd.service.d/phios.conf", "[Unit]\n" + "Requires=phios-live-setup.service\nAfter=phios-live-setup.service\n") + write("etc/systemd/system/phios-live-setup.service", "[Unit]\n" + "Description=Configure the volatile PhiOS live session\nAfter=systemd-tmpfiles-setup.service\n" + "[Service]\nType=oneshot\nExecStart=/usr/local/bin/phios-live-setup\nRemainAfterExit=yes\n") + write("usr/local/bin/phios-live-setup", "#!/usr/bin/env bash\nset -euo pipefail\n" + "systemd-sysusers\nsystemd-tmpfiles --create /etc/tmpfiles.d/phios-live.conf\n" + "printf 'phios:phios\\n' | chpasswd\nusermod --lock root\n" + "install -m644 /usr/share/phios/preview-os-release /etc/os-release\n") + write("usr/share/phios/preview-os-release", f'NAME="PhiOS Linux Preview"\nID=phios\nID_LIKE=arch\n' + f'PRETTY_NAME="PhiOS Linux {version} Development Preview"\nVERSION_ID="{version}"\n') + # One owner supplies both wired and Wi-Fi address/DNS configuration. + # Keep connectivity URL polling disabled in this local-first preview. + write("etc/NetworkManager/conf.d/10-phios.conf", "[main]\ndns=systemd-resolved\n" + "[connectivity]\nenabled=false\nuri=\ninterval=0\n") + wants = root / "etc/systemd/system/multi-user.target.wants" + wants.mkdir(parents=True) + for name in ["NetworkManager.service", "systemd-resolved.service"]: + (wants / name).symlink_to(f"/usr/lib/systemd/system/{name}") + graphical = root / "etc/systemd/system/graphical.target.wants" + graphical.mkdir(parents=True) + (graphical / "greetd.service").symlink_to("/usr/lib/systemd/system/greetd.service") + (root / "etc/systemd/system/default.target").symlink_to("/usr/lib/systemd/system/graphical.target") + (root / "etc/resolv.conf").symlink_to("/run/systemd/resolve/stub-resolv.conf") + if smoke: + # The qualification fixture owns this console; an interactive getty + # must not reset/consume its serial evidence. + (root / "etc/systemd/system/serial-getty@ttyS0.service").symlink_to("/dev/null") + write("usr/local/bin/phios-live-smoke", (repo / "packaging/linux/tests/live-smoke.sh").read_text()) + write("usr/local/bin/phios-live-install-smoke.py", (repo / "packaging/linux/tests/install_smoke.py").read_text()) + write("usr/local/bin/phios-live-update-smoke.py", (repo / "packaging/linux/tests/update_smoke.py").read_text()) + write("etc/systemd/system/phios-live-smoke.service", "[Unit]\nDescription=CI live-image qualification fixture\n" + "After=greetd.service\n[Service]\nType=oneshot\nExecStart=/usr/local/bin/phios-live-smoke\n" + "TimeoutStartSec=1800\nStandardOutput=tty\nStandardError=tty\nTTYPath=/dev/ttyS0\n") + (wants / "phios-live-smoke.service").symlink_to("/etc/systemd/system/phios-live-smoke.service") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--upstream", type=Path, required=True) + parser.add_argument("--destination", type=Path, required=True) + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--package-repo", type=Path, required=True) + parser.add_argument("--smoke", action="store_true") + args = parser.parse_args() + prepare(args.upstream, args.destination, args.repo, args.package_repo, smoke=args.smoke) diff --git a/packaging/linux/proof/broker.py b/packaging/linux/proof/broker.py new file mode 100644 index 00000000..61e0dfc7 --- /dev/null +++ b/packaging/linux/proof/broker.py @@ -0,0 +1,370 @@ +"""Installed-only root broker for one boot-bound, single-use proof-note effect.""" +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import os +import pwd +import re +import stat +import sys +import time +import uuid +from contextlib import contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Iterator, TextIO + +from phios.action_lease import ActionLease, evaluate_action_lease +from phios.authority_epoch import AuthorityEpoch +from phios.effect_intent import EffectIntent +from phios.enforcement_profile import EnforcementProfile, EnforcementRule +from phios.mandala import AuthoritativeAuthorityEvent, AuthorityEventKind + +OWNER = 0 +STORE = Path('/.snapshots/phios-linux-proof') +PROPOSAL = Path('/var/lib/phios-agent/proposal.json') +SOURCE = Path('/usr/share/phios/source-commit') +TEXT = 'PhiOS verified one explicitly approved Linux proof note.\n' +LIMIT = 65536 +TTL = 60 + + +def boot_time_ns() -> int: + return time.clock_gettime_ns(time.CLOCK_BOOTTIME) + + +def encode(value: Any) -> bytes: + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, allow_nan=False).encode() + + +def sha(value: Any) -> str: + return hashlib.sha256(encode(value)).hexdigest() + + +def pairs(values: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in values: + if key in result: + raise ValueError('duplicate JSON field') + result[key] = value + return result + + +def reject_constant(value: str) -> None: + raise ValueError('non-finite JSON: ' + value) + + +def decode(data: bytes) -> Any: + return json.loads(data, object_pairs_hook=pairs, parse_constant=reject_constant) + + +def check_info(info: os.stat_result, *, owner: int = 0, directory: bool = False) -> None: + kind = stat.S_ISDIR if directory else stat.S_ISREG + if not kind(info.st_mode) or info.st_uid != owner or info.st_mode & 0o022: + raise ValueError('protected owned directory/regular file required') + if not directory and (info.st_nlink != 1 or info.st_size > LIMIT): + raise ValueError('bounded singly linked regular file required') + + +def read_fd(fd: int, *, owner: int) -> bytes: + before = os.fstat(fd) + check_info(before, owner=owner) + data = os.read(fd, LIMIT + 1) + after = os.fstat(fd) + def stable(row: os.stat_result) -> tuple[int, ...]: + return (row.st_dev, row.st_ino, row.st_uid, row.st_mode, row.st_nlink, row.st_size, row.st_mtime_ns, row.st_ctime_ns) + if len(data) > LIMIT or len(data) != before.st_size or stable(before) != stable(after): + raise ValueError('captured file changed or exceeded bounds') + return data + + +def read_path(path: Path, *, owner: int, protected_parents: bool = True) -> bytes: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for part in path.parts[1:-1]: + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) + os.close(fd) + fd = child + if protected_parents: + check_info(os.fstat(fd), owner=OWNER, directory=True) + child = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd) + try: + return read_fd(child, owner=owner) + finally: + os.close(child) + finally: + os.close(fd) + + +def context() -> dict[str, Any]: + if os.getuid() != 0 or os.geteuid() != 0 or os.environ.get('SUDO_UID') != '1000': + raise ValueError('installed UID 1000 administrator must invoke this broker through sudo') + if Path('/run/archiso/bootmnt').exists(): + raise ValueError('proof effects are disabled in the public volatile live account') + user = pwd.getpwuid(1000) + receipt = decode(read_path(Path('/var/lib/phios/install-receipt.json'), owner=OWNER)) + source = read_path(SOURCE, owner=OWNER).decode().strip() + boot = Path('/proc/sys/kernel/random/boot_id').read_text().strip().replace('-', '') + if (receipt.get('schema_version') != 'phios.blank-disk-install.v1' or receipt.get('installed') is not True + or receipt.get('plan', {}).get('username') != user.pw_name + or not re.fullmatch('[0-9a-f]{40}', source) or not re.fullmatch('[0-9a-f]{32}', boot)): + raise ValueError('installed identity/account receipt required') + mounted = [line.split(' - ', 1) for line in Path('/proc/self/mountinfo').read_text().splitlines()] + if not any(len(row) == 2 and row[0].split()[4] == '/.snapshots' and + row[1].split()[0] == 'btrfs' and '/@snapshots' == row[0].split()[3] for row in mounted): + raise ValueError('independent installed Btrfs snapshot store must be mounted') + check_info(Path('/.snapshots').lstat(), owner=OWNER, directory=True) + return {'source_commit': source, 'boot_id': boot, 'operator_uid': 1000, 'principal_uid': 1001} + + +def validate_proposal(value: Any, observed: dict[str, Any], now: datetime) -> dict[str, Any]: + required = {'schema_version', 'principal_uid', 'source_commit', 'boot_id', 'observed_at', 'nonce', + 'capability_id', 'text', 'execution_authority', 'effect_performed'} + if not isinstance(value, dict) or set(value) != required: + raise ValueError('exact bounded proposal fields required') + if (value['schema_version'] != 'phios.linux-proof-proposal.v1' or type(value['principal_uid']) is not int + or value['principal_uid'] != 1001 or value['source_commit'] != observed['source_commit'] + or value['boot_id'] != observed['boot_id'] or value['capability_id'] != 'linux.proof_note' + or value['text'] != TEXT or value['execution_authority'] is not False or value['effect_performed'] is not False + or not isinstance(value['nonce'], str) or not re.fullmatch('[0-9a-f]{32}', value['nonce'])): + raise ValueError('proposal identity/effect/scope differs from the fixed capability') + stamp = datetime.fromisoformat(value['observed_at']) + if stamp.tzinfo is None or not timedelta(0) <= now - stamp <= timedelta(minutes=10): + raise ValueError('proposal observation is stale or from the future') + return value + + +def capture(observed: dict[str, Any], now: datetime) -> dict[str, Any]: + # Every ancestor is opened without following links. Agent-owned ancestry + # is untrusted; only captured bytes, never a later read, enter the effect. + return validate_proposal(decode(read_path(PROPOSAL, owner=1001, protected_parents=False)), observed, now) + + +class Store: + def __init__(self, root: Path) -> None: + check_info(root.parent.lstat(), owner=OWNER, directory=True) + parent = os.open(root.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + try: + os.mkdir(root.name, mode=0o700, dir_fd=parent) + os.fsync(parent) + except FileExistsError: + pass + self.fd = os.open(root.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + try: + check_info(os.fstat(self.fd), owner=OWNER, directory=True) + except BaseException: + os.close(self.fd) + raise + finally: + os.close(parent) + self.root = root + + def close(self) -> None: + os.close(self.fd) + + @contextmanager + def directory(self, name: str) -> Iterator[int]: + if name not in {'approvals', 'consumed', 'notes', 'receipts'}: + raise ValueError('unsupported broker directory') + try: + os.mkdir(name, mode=0o700, dir_fd=self.fd) + os.fsync(self.fd) + except FileExistsError: + pass + fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=self.fd) + try: + check_info(os.fstat(fd), owner=OWNER, directory=True) + yield fd + finally: + os.close(fd) + + @contextmanager + def locked(self) -> Iterator[None]: + fd = os.open('lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600, dir_fd=self.fd) + try: + check_info(os.fstat(fd), owner=OWNER) + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) + + def publish(self, kind: str, digest: str, data: bytes) -> None: + if not re.fullmatch('[0-9a-f]{64}', digest) or len(data) > LIMIT: + raise ValueError('bounded named broker record required') + with self.directory(kind) as directory: + fd = os.open(digest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory) + try: + view = memoryview(data) + while view: + count = os.write(fd, view) + if count <= 0: + raise OSError('short broker write') + view = view[count:] + os.fsync(fd) + finally: + os.close(fd) + os.fsync(directory) + + def read(self, kind: str, digest: str) -> bytes: + if not re.fullmatch('[0-9a-f]{64}', digest): + raise ValueError('exact SHA-256 broker identity required') + with self.directory(kind) as directory: + fd = os.open(digest, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + try: + return read_fd(fd, owner=OWNER) + finally: + os.close(fd) + + +def contracts(proposal: dict[str, Any], observed: dict[str, Any], decision: dict[str, Any]) -> dict[str, Any]: + start = decision['approved_at'] + until = (datetime.fromisoformat(start) + timedelta(seconds=TTL)).isoformat() + intent = EffectIntent.build(capability_id='linux.proof_note', capability_version='0.1.0', + payload_sha256=hashlib.sha256(TEXT.encode()).hexdigest(), declared_at=proposal['observed_at'], + effects_declared=('filesystem.change',), evidence_ref_sha256s=(sha(proposal),)) + policy = {'source_commit': observed['source_commit'], 'boot_id': observed['boot_id'], + 'principal_uid': 1001, 'operator_uid': 1000, 'capability_id': 'linux.proof_note', + 'fixed_store': str(STORE), 'max_uses': 1, 'ttl_seconds': TTL} + enforcement = EnforcementProfile.build(intent=intent, rules=(EnforcementRule.build( + rule_id='root-owned-single-note', effect_scope=('filesystem.change',), + constraint='Only a new SHA-256-named proof note inside the protected independent store', + layer='broker', boundary='kernel_boundary', status='enforced', + mechanism='UID-separated root-owned broker; no-follow directory FDs; fixed bytes; exclusive creation', + evidence_ref_sha256s=(sha(policy),)),)) + binding = {'schema_version': 'phios.linux-proof-binding.v1', 'decision_sha256': sha(decision), + 'proposal_sha256': sha(proposal), 'intent_sha256': intent.effect_intent_sha256, + 'enforcement_sha256': enforcement.profile_sha256, 'policy_sha256': sha(policy), 'principal_uid': 1001} + epoch = AuthorityEpoch.build(principal_id='linux-uid:1001', policy_sha256=sha(policy), + ceiling=('artifact.write',), events=(AuthoritativeAuthorityEvent( + event_id='proof-' + decision['nonce'], sequence=1, kind=AuthorityEventKind.GRANT, + permission='artifact.write', authority_source='installed-sudo-operator:1000', + effective_at=start, expires_at=until),), observed_at=start) + lease = ActionLease.issue(principal_id='linux-uid:1001', issuer_id='linux-proof-broker', + authorization_receipt_sha256=sha(binding), intent=intent, enforcement=enforcement, + authority_epoch=epoch, permissions_authorized=('artifact.write',), accepted_unenforced_effects=(), + issued_at=start, valid_from=start, valid_until=until) + return {'intent': intent.to_dict(), 'enforcement': enforcement.to_dict(), 'binding': binding, + 'authority_epoch': epoch.to_dict(), 'lease': lease.to_dict()} + + +def review_plan(proposal: dict[str, Any], observed: dict[str, Any]) -> dict[str, Any]: + return {'schema_version': 'phios.linux-proof-review.v1', 'observation': observed, 'proposal': proposal, + 'proposal_sha256': sha(proposal), 'note_sha256': hashlib.sha256(TEXT.encode()).hexdigest(), + 'store': str(STORE), 'max_uses': 1, 'ttl_seconds': TTL, 'execution_authority': False} + + +def approve(proposal: dict[str, Any], observed: dict[str, Any], *, input_stream: TextIO, output_stream: TextIO) -> str | None: + review = review_plan(proposal, observed) + print(json.dumps(review, indent=2, ensure_ascii=True), file=output_stream, flush=True) + if not input_stream.isatty() or not output_stream.isatty(): + raise ValueError('approval requires an interactive installed sudo operator') + print('Type exactly APPROVE ' + sha(review) + ' or anything else to cancel:', file=output_stream, flush=True) + if input_stream.readline().strip() != 'APPROVE ' + sha(review): + print('Cancelled; no approval, binding, lease or effect created.', file=output_stream) + return None + now = datetime.now(UTC) + if context() != observed or capture(observed, now) != proposal: + raise ValueError('proposal/OS identity changed during review') + decision = {'schema_version': 'phios.linux-proof-decision.v1', 'kind': 'APPROVE', 'operator_uid': 1000, + 'review_sha256': sha(review), 'proposal_sha256': sha(proposal), 'approved_at': now.isoformat(), + 'expires_boot_ns': boot_time_ns() + TTL * 10**9, 'nonce': uuid.uuid4().hex} + value = {'schema_version': 'phios.linux-proof-approval.v1', 'observation': observed, 'proposal': proposal, + 'decision': decision, **contracts(proposal, observed, decision)} + digest = sha(value) + store = Store(STORE) + try: + with store.locked(): + store.publish('approvals', digest, encode(value)) + finally: + store.close() + print(json.dumps({'approval_sha256': digest, 'lease_sha256': value['lease']['action_lease_sha256'], + 'execution_authority': False, 'effect_performed': False}), file=output_stream, flush=True) + return digest + + +def execute(store: Store, digest: str, observed: dict[str, Any], now: datetime) -> dict[str, Any]: + with store.locked(): + value = decode(store.read('approvals', digest)) + fields = {'schema_version', 'observation', 'proposal', 'decision', 'intent', 'enforcement', 'binding', 'authority_epoch', 'lease'} + if not isinstance(value, dict) or set(value) != fields or sha(value) != digest: + raise ValueError('approval record integrity/schema mismatch') + if value['schema_version'] != 'phios.linux-proof-approval.v1' or value['observation'] != observed: + raise ValueError('approval belongs to another boot/source/principal') + proposal = validate_proposal(value['proposal'], observed, now) + decision = value['decision'] + if (set(decision) != {'schema_version', 'kind', 'operator_uid', 'review_sha256', 'proposal_sha256', 'approved_at', 'expires_boot_ns', 'nonce'} + or decision['schema_version'] != 'phios.linux-proof-decision.v1' or decision['kind'] != 'APPROVE' + or type(decision['operator_uid']) is not int or decision['operator_uid'] != 1000 + or decision['proposal_sha256'] != sha(proposal) or decision['review_sha256'] != sha(review_plan(proposal, observed)) + or type(decision['expires_boot_ns']) is not int or decision['expires_boot_ns'] <= 0 + or not re.fullmatch('[0-9a-f]{32}', decision['nonce'])): + raise ValueError('exact operator decision required') + if decision['expires_boot_ns'] <= boot_time_ns(): + raise ValueError('effect held: lease_expired') + expected = contracts(proposal, observed, decision) + if any(value[key] != expected[key] for key in expected): + raise ValueError('exact intent/binding/enforcement/epoch/lease mismatch') + lease = ActionLease.from_dict(value['lease']) + try: + store.read('consumed', digest) + used = 1 + except FileNotFoundError: + used = 0 + evaluated = evaluate_action_lease(lease=lease, checked_at=now.isoformat(), + current_authority_epoch_sha256=expected['authority_epoch']['authority_epoch_sha256'], uses_consumed=used) + if not evaluated.usable: + raise ValueError('effect held: ' + evaluated.reason) + # Consume and sync BEFORE the effect. A crash/failure may leave an + # uncompleted note, but never reopens this lease for a second effect. + store.publish('consumed', digest, encode({'schema_version': 'phios.linux-proof-consumption.v1', + 'approval_sha256': digest, 'lease_sha256': lease.action_lease_sha256, 'consumed_at': now.isoformat(), + 'boot_id': observed['boot_id'], 'effect_performed': False})) + store.publish('notes', digest, TEXT.encode()) + actual = store.read('notes', digest) # Independent descriptor/readback. + if actual != TEXT.encode(): + raise ValueError('post-effect content verification failed; lease remains consumed') + receipt = {'schema_version': 'phios.linux-proof-receipt.v1', 'approval_sha256': digest, + 'decision_sha256': sha(decision), 'binding_sha256': sha(value['binding']), + 'lease_sha256': lease.action_lease_sha256, 'source_commit': observed['source_commit'], + 'boot_id': observed['boot_id'], 'principal_uid': 1001, 'operator_uid': 1000, + 'note_sha256': hashlib.sha256(actual).hexdigest(), 'note_bytes': len(actual), + 'post_effect_verified': True, 'effect_performed': True, 'execution_authority': False, + 'authority_replayable': False, 'release_ready': False} + store.publish('receipts', digest, encode(receipt)) + return receipt + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='command', required=True) + commands.add_parser('inspect') + commands.add_parser('approve') + run = commands.add_parser('execute') + run.add_argument('--approval', required=True) + args = parser.parse_args() + try: + observed = context() + if args.command == 'execute': + store = Store(STORE) + try: + print(json.dumps(execute(store, args.approval, observed, datetime.now(UTC)), indent=2)) + finally: + store.close() + else: + proposal = capture(observed, datetime.now(UTC)) + if args.command == 'inspect': + print(json.dumps({'observation': observed, 'proposal': proposal, 'execution_authority': False}, indent=2)) + else: + return 0 if approve(proposal, observed, input_stream=sys.stdin, output_stream=sys.stdout) else 2 + return 0 + except (OSError, ValueError, TypeError, KeyError, EOFError) as exc: + print('Linux proof held: ' + str(exc), file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/proof/phios-linux-proof b/packaging/linux/proof/phios-linux-proof new file mode 100644 index 00000000..14110eeb --- /dev/null +++ b/packaging/linux/proof/phios-linux-proof @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-proof/broker.py "$@" diff --git a/packaging/linux/proof/phios-proof-proposer.service b/packaging/linux/proof/phios-proof-proposer.service new file mode 100644 index 00000000..e8c90b25 --- /dev/null +++ b/packaging/linux/proof/phios-proof-proposer.service @@ -0,0 +1,21 @@ +[Unit] +Description=Propose one harmless Linux proof note as the isolated agent principal + +[Service] +Type=oneshot +User=phios-agent +Group=phios-agent +ExecStart=/usr/bin/python -I /usr/lib/phios-proof/propose.py +UMask=0077 +NoNewPrivileges=yes +CapabilityBoundingSet= +ProtectSystem=strict +ProtectHome=yes +PrivateNetwork=yes +PrivateTmp=yes +RestrictNamespaces=yes +RestrictAddressFamilies=AF_UNIX +LockPersonality=yes +ReadWritePaths=/var/lib/phios-agent +InaccessiblePaths=/.snapshots /var/lib/phios +TimeoutStartSec=20 diff --git a/packaging/linux/proof/propose.py b/packaging/linux/proof/propose.py new file mode 100644 index 00000000..c273b487 --- /dev/null +++ b/packaging/linux/proof/propose.py @@ -0,0 +1,49 @@ +"""Observe public OS identity and propose one fixed harmless note as UID 1001.""" +from __future__ import annotations + +import json +import os +import re +import tempfile +import uuid +from datetime import UTC, datetime +from pathlib import Path + +TEXT = 'PhiOS verified one explicitly approved Linux proof note.\n' + + +def main() -> None: + if os.getuid() != 1001 or os.geteuid() != 1001: + raise ValueError('the isolated phios-agent principal is required') + source = Path('/usr/share/phios/source-commit').read_text().strip() + boot = Path('/proc/sys/kernel/random/boot_id').read_text().strip().replace('-', '') + if not re.fullmatch('[0-9a-f]{40}', source) or not re.fullmatch('[0-9a-f]{32}', boot): + raise ValueError('exact observed OS source and boot identity required') + root = Path('/var/lib/phios-agent') + info = root.lstat() + if root.is_symlink() or info.st_uid != 1001 or info.st_mode & 0o077: + raise ValueError('private agent directory required') + proposal = {'schema_version': 'phios.linux-proof-proposal.v1', 'principal_uid': 1001, + 'source_commit': source, 'boot_id': boot, 'observed_at': datetime.now(UTC).isoformat(), + 'nonce': uuid.uuid4().hex, 'capability_id': 'linux.proof_note', 'text': TEXT, + 'execution_authority': False, 'effect_performed': False} + fd, name = tempfile.mkstemp(prefix='.proposal-', dir=root) + try: + with os.fdopen(fd, 'w') as handle: + json.dump(proposal, handle, sort_keys=True, allow_nan=False) + handle.write('\n') + handle.flush() + os.fsync(handle.fileno()) + os.replace(name, root / 'proposal.json') + directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + Path(name).unlink(missing_ok=True) + print('One proposal recorded; no approval, lease or effect created.') + + +if __name__ == '__main__': + main() diff --git a/packaging/linux/release.json b/packaging/linux/release.json new file mode 100644 index 00000000..a967fe62 --- /dev/null +++ b/packaging/linux/release.json @@ -0,0 +1,20 @@ +{ + "schema_version": "phios.linux-release.v1", + "os_version": "0.1.0-alpha.1", + "stage": "development-preview", + "architecture": "x86_64", + "firmware": "UEFI x64", + "secure_boot": false, + "base": "Arch Linux", + "arch_snapshot": "2026/09/30", + "archiso_version": "91-1", + "archiso_source_commit": "723da192226e1c9d5def9168f13332793c82a85e", + "desktop": "Wayfire", + "interface": "PhiShell", + "installer_available": false, + "whole_os_rollback_available": false, + "linux_desktop_effects_available": false, + "ai_required": false, + "release_tag_prefix": "phios-linux-v", + "builder_image": "archlinux:base@sha256:b21322c663be387c0ed9cbc7bbbfe18e41633ad4e7b7c77cfad45f128be20040" +} diff --git a/packaging/linux/release_inventory.py b/packaging/linux/release_inventory.py new file mode 100644 index 00000000..cbe9d0f4 --- /dev/null +++ b/packaging/linux/release_inventory.py @@ -0,0 +1,335 @@ +"""Inventory the exact image and artifacts without authorizing publication.""" +from __future__ import annotations + +import argparse +import email.parser +import gzip +import hashlib +import io +import json +import os +import re +import stat +import tarfile +from datetime import UTC, datetime +from pathlib import Path, PurePosixPath +from typing import Any +from urllib.parse import quote + +LIMIT = 4 * 1024**2 +FIXTURES = ['usr/local/bin/phios-live-smoke', 'usr/local/bin/phios-live-install-smoke.py', + 'usr/local/bin/phios-live-update-smoke.py', 'etc/systemd/system/phios-live-smoke.service', + 'etc/systemd/system/multi-user.target.wants/phios-live-smoke.service'] + + +def image_path(root: Path, relative: str) -> Path: + """Resolve guest absolute/relative symlinks inside the image, never the host.""" + parts = list(PurePosixPath(relative).parts) + if not parts or parts[0] == '/' or '..' in parts: + raise ValueError('unsafe image-relative path') + resolved: list[str] = [] + links = 0 + while parts: + name = parts.pop(0) + if name in ('', '.'): + continue + if name == '..': + if not resolved: + raise ValueError('image link escapes its root') + resolved.pop() + continue + path = root.joinpath(*resolved, name) + info = path.lstat() + if stat.S_ISLNK(info.st_mode): + links += 1 + if links > 32: + raise ValueError('image symlink cycle or excessive depth') + target = PurePosixPath(os.readlink(path)) + if target.is_absolute(): + resolved = [] + parts = list(target.parts[1:]) + parts + else: + parts = list(target.parts) + parts + else: + resolved.append(name) + return root.joinpath(*resolved) + + +def bounded(path: Path, maximum: int = LIMIT) -> bytes: + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_size > maximum: + raise ValueError('bounded regular metadata required: ' + str(path)) + with path.open('rb') as handle: + data = handle.read(maximum + 1) + if len(data) > maximum: + raise ValueError('metadata exceeded its bound') + return data + + +def digest(path: Path) -> dict[str, Any]: + info = path.lstat() + if not stat.S_ISREG(info.st_mode): + raise ValueError('artifact must be a regular file') + with path.open('rb') as handle: + value = hashlib.file_digest(handle, 'sha256').hexdigest() + return {'sha256': value, 'size': info.st_size} + + +def fields(data: bytes) -> dict[str, list[str]]: + result: dict[str, list[str]] = {} + current: str | None = None + for line in data.decode().splitlines(): + if line.startswith('%') and line.endswith('%'): + current = line.strip('%') + if current in result: + raise ValueError('duplicate package metadata field') + result[current] = [] + elif line and current is not None: + result[current].append(line) + return result + + +def one(data: dict[str, list[str]], name: str) -> str: + values = data.get(name, []) + if len(values) != 1 or not values[0] or any(ord(c) < 32 for c in values[0]): + raise ValueError('exact package ' + name + ' required') + return values[0] + + +def licenses(labels: list[str]) -> list[dict[str, Any]]: + # Preserve supplier declarations; never invent SPDX conclusions. + return [{'license': {'name': label, 'acknowledgement': 'declared'}} for label in sorted(set(labels)) if label] + + +def component(kind: str, name: str, version: str, *, path: str, labels: list[str], namespace: str = '') -> dict[str, Any]: + encoded_name = quote(name, safe='/') + purl = f'pkg:{kind}/{namespace}{encoded_name}@{quote(version, safe="")}' + return {'type': 'application' if kind == 'alpm' else 'library', 'bom-ref': purl + '#' + quote(path, safe=''), + 'name': name, 'version': version, 'purl': purl, 'licenses': licenses(labels), + 'properties': [{'name': 'phios:inventory-path', 'value': path}, + {'name': 'phios:license-review', 'value': 'pending; supplier declarations only'}]} + + +def collect(root: Path) -> tuple[list[dict[str, Any]], dict[str, list[dict[str, Any]]], set[str]]: + components: list[dict[str, Any]] = [] + inventory: dict[str, list[dict[str, Any]]] = {'native': [], 'python': [], 'javascript': [], 'javascript-bundled': []} + notices: set[str] = set() + database = image_path(root, 'var/lib/pacman/local') + rows = sorted(database.glob('*/desc')) + if not 1 <= len(rows) <= 20000: + raise ValueError('complete bounded native package database required') + names: set[str] = set() + for desc in rows: + desc = image_path(root, desc.relative_to(root).as_posix()) + data = fields(bounded(desc, 65536)) + name, version, arch = [one(data, key) for key in ['NAME', 'VERSION', 'ARCH']] + if name in names or re.fullmatch(r'[a-z0-9][a-z0-9@._+\-]{0,127}', name) is None: + raise ValueError('duplicate or invalid native package') + names.add(name) + labels = data.get('LICENSE', []) + path = desc.relative_to(root).as_posix() + item = {'name': name, 'version': version, 'architecture': arch, + 'package_base': data.get('BASE', [name])[0], 'declared_licenses': labels, + 'upstream_urls': data.get('URL', []), 'metadata': digest(desc)} + inventory['native'].append(item) + comp = component('alpm', name, version, path=path, labels=labels, namespace='arch/') + comp['purl'] += '?arch=' + quote(arch, safe='') + components.append(comp) + files = image_path(root, desc.with_name('files').relative_to(root).as_posix()) + for relative in fields(bounded(files)).get('FILES', []): + if not relative.endswith('/') and (relative.startswith('usr/share/licenses/') or + relative.endswith('/copyright') or relative.endswith('/COPYING')): + notices.add(relative) + for path in sorted(root.glob('usr/lib/python*/site-packages/*.dist-info/METADATA')): + path = image_path(root, path.relative_to(root).as_posix()) + metadata = email.parser.BytesParser().parsebytes(bounded(path)) + name, version = metadata.get('Name'), metadata.get('Version') + if not name or not version: + raise ValueError('Python distribution identity missing') + labels = metadata.get_all('License-Expression', []) or metadata.get_all('License', []) + labels = [' '.join(label.split()) for label in labels if label.strip() not in ('', 'UNKNOWN')] + relative = path.relative_to(root).as_posix() + inventory['python'].append({'name': name, 'version': version, 'declared_licenses': labels, + 'metadata': digest(path), 'path': relative}) + components.append(component('pypi', re.sub(r'[-_.]+', '-', name).lower(), version, path=relative, labels=labels)) + for notice in path.parent.rglob('*'): + if notice.is_file() and re.search(r'license|copying|notice|copyright', notice.name, re.I): + notices.add(notice.relative_to(root).as_posix()) + package = json.loads(bounded(image_path(root, 'usr/lib/phishell/package.json'))) + if not package.get('name') or not package.get('version'): + raise ValueError('installed PhiShell identity missing') + lock = json.loads(bounded(image_path(root, 'usr/lib/phishell/node_modules/.package-lock.json'))) + rows = lock.get('packages') + if not isinstance(rows, dict) or len(rows) > 20000: + raise ValueError('bounded installed npm lock required') + for relative, row in sorted(rows.items()): + if not relative: + continue + parts = relative.split('node_modules/')[-1] + name = row.get('name') or parts + version = row.get('version') + if not isinstance(version, str) or not version or row.get('link'): + raise ValueError('installed npm identity/version/link unsupported') + directory = image_path(root, 'usr/lib/phishell/' + relative) + actual = json.loads(bounded(image_path(root, directory.relative_to(root).as_posix() + '/package.json'))) + if actual.get('name') != name or actual.get('version') != version: + raise ValueError('installed npm package differs from lock') + label = actual.get('license') + labels = [label] if isinstance(label, str) and label else [] + path = directory.relative_to(root).as_posix() + inventory['javascript'].append({'name': name, 'version': version, 'declared_licenses': labels, + 'lock_integrity': row.get('integrity'), 'path': path}) + components.append(component('npm', name, version, path=path, labels=labels)) + for notice in directory.iterdir(): + if notice.is_file() and re.search(r'license|copying|notice|copyright', notice.name, re.I): + notices.add(notice.relative_to(root).as_posix()) + bundled = json.loads(bounded(image_path(root, 'usr/lib/phishell/dist/bundled-js-inventory.json'))) + if (not isinstance(bundled, dict) or set(bundled) != {'schema_version', 'packages', 'chunks', 'license_compliance_reviewed'} + or bundled['schema_version'] != 'phios.phishell-bundle.v1' or bundled['license_compliance_reviewed'] is not False + or not isinstance(bundled['packages'], list) or not 1 <= len(bundled['packages']) <= 2000 + or not isinstance(bundled['chunks'], list) or not 1 <= len(bundled['chunks']) <= 512): + raise ValueError('bounded actual frontend bundle inventory required') + chunk_names: set[str] = set() + for chunk in bundled['chunks']: + if set(chunk) != {'filename', 'sha256', 'size'} or chunk['filename'] in chunk_names: + raise ValueError('exact unique frontend chunk records required') + if digest(image_path(root, 'usr/lib/phishell/dist/' + chunk['filename'])) != {key: chunk[key] for key in ['sha256', 'size']}: + raise ValueError('actual frontend chunk differs from build inventory') + chunk_names.add(chunk['filename']) + origins: set[str] = set() + for row in bundled['packages']: + if (set(row) != {'name', 'version', 'license', 'package_json_sha256', 'package_path', 'modules', 'notices'} + or not isinstance(row['name'], str) or not row['name'] or not isinstance(row['version'], str) or not row['version'] + or row['package_path'] in origins or not isinstance(row['modules'], list) or not row['modules'] + or not isinstance(row['notices'], list) or len(row['notices']) > 64): + raise ValueError('exact unique bundled supplier records required') + origins.add(row['package_path']) + for module in row['modules']: + if set(module) != {'id', 'chunk', 'role'} or module['chunk'] not in chunk_names or module['role'] not in ['chunk-module', 'injected-runtime-helper']: + raise ValueError('bundled module refers to an unknown chunk/role') + for notice in row['notices']: + if (set(notice) != {'filename', 'original_name', 'sha256', 'size'} or + re.fullmatch(r'bundled-notices/[0-9a-f]{64}\.txt', notice['filename']) is None): + raise ValueError('exact bounded bundled notice record required') + relative = 'usr/lib/phishell/dist/' + notice['filename'] + if digest(image_path(root, relative)) != {key: notice[key] for key in ['sha256', 'size']}: + raise ValueError('bundled notice differs from captured build input') + notices.add(relative) + path = 'usr/lib/phishell/dist/bundled-js-inventory.json#' + row['package_path'] + labels = [row['license']] if isinstance(row['license'], str) and row['license'] else [] + inventory['javascript-bundled'].append(row) + components.append(component('npm', row['name'], row['version'], path=path, labels=labels)) + inventory['native'].sort(key=lambda row: row['name']) + return sorted(components, key=lambda row: row['bom-ref']), inventory, notices + + +def notice_files(root: Path, notices: set[str]) -> list[str]: + queue = sorted(notices) + result: set[str] = set() + visited_directories: set[str] = set() + while queue: + relative = queue.pop(0) + path = image_path(root, relative) + if path.is_dir(): + canonical = path.relative_to(root).as_posix() + if canonical in visited_directories: + continue + visited_directories.add(canonical) + queue.extend(relative.rstrip('/') + '/' + child.name for child in sorted(path.iterdir())) + elif path.is_file(): + result.add(relative) + else: + raise ValueError('notice is not a directory or regular file') + if len(result) + len(queue) + len(visited_directories) > 20000: + raise ValueError('notice file count exceeds its bound') + return sorted(result) + + +def json_file(path: Path, value: Any) -> None: + with path.open('x') as handle: + json.dump(value, handle, indent=2, sort_keys=True, allow_nan=False) + handle.write('\n') + + +def record(root: Path, output: Path, source: str, *, ci_fixtures: bool, epoch: int) -> None: + if re.fullmatch(r'[0-9a-f]{40}', source) is None or epoch < 0: + raise ValueError('exact source identity and source epoch required') + if bounded(image_path(root, 'usr/share/phios/source-commit')).decode().strip() != source: + raise ValueError('image source differs from build') + release = json.loads(bounded(output / 'release.json')) + observed = [path for path in FIXTURES if (root / path).exists() or (root / path).is_symlink()] + if bool(observed) != ci_fixtures or (ci_fixtures and set(observed) != set(FIXTURES)): + raise ValueError('actual fixture inventory differs from requested build scope') + for path in ['etc/phios/os-update-trust.json', 'etc/phios/os-update-keyring.gpg', + 'usr/share/phios-ci-update/verified.txt']: + if (root / path).exists() or (root / path).is_symlink(): + raise ValueError('enrolled PhiOS trust or test package present in distributable source image') + components, inventory, notice_paths = collect(root) + native_text = ''.join(row['name'] + ' ' + row['version'] + '\n' for row in inventory['native']) + if native_text != bounded(output / 'image-packages.txt').decode(): + raise ValueError('native package database differs from independently recorded pacman inventory') + license_index: list[dict[str, Any]] = [] + total = 0 + with (output / 'third-party-notices.tar.gz').open('xb') as raw: + with gzip.GzipFile(fileobj=raw, mode='wb', mtime=epoch, filename='') as compressed: + with tarfile.open(fileobj=compressed, mode='w|', format=tarfile.PAX_FORMAT) as archive: + for relative in notice_files(root, notice_paths): + path = image_path(root, relative) + data = bounded(path, 16 * 1024**2) + total += len(data) + if total > 128 * 1024**2: + raise ValueError('notice inventory exceeds its bound') + info = tarfile.TarInfo(relative) + info.size, info.mode, info.mtime = len(data), 0o644, epoch + archive.addfile(info, io.BytesIO(data)) + license_index.append({'path': relative, 'resolved_image_path': path.relative_to(root).as_posix(), + 'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()}) + for ecosystem, rows in inventory.items(): + json_file(output / (ecosystem + '-packages.json'), rows) + json_file(output / 'third-party-notices.json', {'schema_version': 'phios.bundled-notices.v1', + 'files': license_index, 'license_compliance_reviewed': False}) + json_file(output / 'fixture-inventory.json', {'schema_version': 'phios.image-fixtures.v1', + 'ci_fixture_build': ci_fixtures, 'observed_fixture_paths': observed, 'fixture_free': not ci_fixtures, + 'release_ready': False}) + json_file(output / 'sbom.cdx.json', {'$schema': 'http://cyclonedx.org/schema/bom-1.6.schema.json', + 'bomFormat': 'CycloneDX', 'specVersion': '1.6', 'version': 1, + 'metadata': {'timestamp': datetime.now(UTC).isoformat(), 'component': {'type': 'operating-system', + 'name': 'PhiOS Linux Preview', 'version': release['os_version']}, + 'properties': [{'name': 'phios:source-commit', 'value': source}, + {'name': 'phios:ci-fixture-build', 'value': str(ci_fixtures).lower()}, + {'name': 'phios:release-ready', 'value': 'false'}]}, 'components': components}) + json_file(output / 'source-review.json', {'schema_version': 'phios.distribution-source-review.v1', + 'source_commit': source, 'first_party_source_archive': digest(output / 'phios-source.tar.gz'), + 'third_party_source_compliance_reviewed': False, 'release_ready': False, + 'required_review': [{'component': row['bom-ref'], 'name': row['name'], 'version': row['version'], + 'declared_licenses': row['licenses'], 'source_delivery_review': 'pending'} for row in components]}) + artifacts = [path for path in output.iterdir() if path.is_file() and path.name not in + ['build.log', 'mkarchiso.log', 'SHA256SUMS', 'provenance.json']] + archive_hash = bounded(output / 'source-archive-sha256.txt').decode().strip() + if digest(output / 'phios-source.tar.gz')['sha256'] != archive_hash: + raise ValueError('source archive digest differs from recorded build input') + isos = [path for path in artifacts if path.suffix == '.iso'] + if len(isos) != 1: + raise ValueError('exactly one ISO required') + json_file(output / 'provenance.json', {'schema_version': 'phios.os-build-provenance.v1', 'source_commit': source, + 'source_date_epoch': epoch, 'arch_snapshot': release['arch_snapshot'], + 'archiso_version': release['archiso_version'], 'builder_image': release['builder_image'], + 'ci_fixture_build': ci_fixtures, 'iso': {'filename': isos[0].name, **digest(isos[0])}, + 'artifacts': {path.name: digest(path) for path in sorted(artifacts)}, + 'signed': False, 'reproducible_build_demonstrated': False, 'hardware_qualified': False, + 'license_source_compliance_reviewed': False, 'release_ready': False}) + artifacts.append(output / 'provenance.json') + with (output / 'SHA256SUMS').open('w') as handle: + for path in sorted(artifacts): + handle.write(digest(path)['sha256'] + ' ' + path.name + '\n') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + parser.add_argument('--source', required=True) + parser.add_argument('--epoch', required=True, type=int) + parser.add_argument('--ci-fixtures', action='store_true') + args = parser.parse_args() + record(args.root, args.output, args.source, ci_fixtures=args.ci_fixtures, epoch=args.epoch) diff --git a/packaging/linux/sbom-schema-lock.json b/packaging/linux/sbom-schema-lock.json new file mode 100644 index 00000000..646b743f --- /dev/null +++ b/packaging/linux/sbom-schema-lock.json @@ -0,0 +1,9 @@ +{ + "schema_version": "phios.sbom-schema-lock.v1", + "base_url": "https://raw.githubusercontent.com/CycloneDX/specification/1.6/schema/", + "files": { + "bom-1.6.schema.json": "3e92dddbc30cf7f6a02b80f0942b1a4cfd4fb1c26f1dfc4310afa9d613cafb93", + "jsf-0.82.schema.json": "8bae002c25e723db7ee1f26afde680ae1a2b1a8f6b4b4b0fd65dc3becb090aae", + "spdx.schema.json": "baa9d3bd1ed57b6751b0887edead6b5063ff53ff7429cf85d476c6c94af0166e" + } +} diff --git a/packaging/linux/session/audio-session.conf b/packaging/linux/session/audio-session.conf new file mode 100644 index 00000000..5c1658a2 --- /dev/null +++ b/packaging/linux/session/audio-session.conf @@ -0,0 +1,2 @@ +[Unit] +PartOf=phios-audio.target diff --git a/packaging/linux/session/phios-audio.target b/packaging/linux/session/phios-audio.target new file mode 100644 index 00000000..16cce7e7 --- /dev/null +++ b/packaging/linux/session/phios-audio.target @@ -0,0 +1,5 @@ +[Unit] +Description=PhiOS user audio session +PartOf=phios-session.target +Wants=pipewire.service pipewire-pulse.service wireplumber.service pipewire.socket pipewire-pulse.socket +After=pipewire.service pipewire-pulse.service wireplumber.service diff --git a/packaging/linux/session/phios-browser.service b/packaging/linux/session/phios-browser.service new file mode 100644 index 00000000..b0b3a37c --- /dev/null +++ b/packaging/linux/session/phios-browser.service @@ -0,0 +1,14 @@ +[Unit] +Description=PhiShell Wayland browser +PartOf=phios-session.target +After=phios-observer.service +Wants=phios-observer.service + +[Service] +ExecStart=/usr/bin/phios-open-shell +Restart=on-failure +RestartSec=3 +UMask=0077 + +[Install] +WantedBy=phios-session.target diff --git a/packaging/linux/session/phios-curiosity-reader.service b/packaging/linux/session/phios-curiosity-reader.service new file mode 100644 index 00000000..70448127 --- /dev/null +++ b/packaging/linux/session/phios-curiosity-reader.service @@ -0,0 +1,18 @@ +[Unit] +Description=PhiOS read-only curiosity projection +PartOf=phios-session.target + +[Service] +ExecStart=/usr/bin/python -m phios.curiosity_projection_server --store-root %h/.local/state/phios/curiosity +Restart=on-failure +RestartSec=2 +UMask=0077 +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=read-only +PrivateTmp=yes +ReadWritePaths=%h/.local/state/phios +RestrictAddressFamilies=AF_UNIX AF_INET + +[Install] +WantedBy=phios-session.target diff --git a/packaging/linux/session/phios-history-reader.service b/packaging/linux/session/phios-history-reader.service new file mode 100644 index 00000000..2bf767e5 --- /dev/null +++ b/packaging/linux/session/phios-history-reader.service @@ -0,0 +1,19 @@ +[Unit] +Description=PhiOS governed history projection (operator configured) +PartOf=phios-session.target +ConditionPathExists=%h/.config/phios/memory.json + +[Service] +ExecStart=/usr/bin/phi-memory --config %h/.config/phios/memory.json --state-root %h/.local/state/phios --allow memory.read serve-system-history +Restart=on-failure +RestartSec=5 +UMask=0077 +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=read-only +PrivateTmp=yes +ReadWritePaths=%h/.local/state/phios +RestrictAddressFamilies=AF_UNIX AF_INET + +[Install] +WantedBy=phios-session.target diff --git a/packaging/linux/session/phios-lock b/packaging/linux/session/phios-lock new file mode 100755 index 00000000..d1f6196b --- /dev/null +++ b/packaging/linux/session/phios-lock @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ $EUID -eq 0 || -z ${WAYLAND_DISPLAY:-} || -z ${XDG_RUNTIME_DIR:-} ]]; then + echo 'Open screen locking from the non-root Wayfire session.' >&2 + exit 1 +fi +# Daemonization returns only after the compositor reports that it is locked. +# PAM requests the current user's password on the lock screen, never via argv. +exec /usr/bin/swaylock --daemonize --ignore-empty-password --color 111318 diff --git a/packaging/linux/session/phios-lock.desktop b/packaging/linux/session/phios-lock.desktop new file mode 100644 index 00000000..8c47f8e5 --- /dev/null +++ b/packaging/linux/session/phios-lock.desktop @@ -0,0 +1,8 @@ +[Desktop Entry] +Type=Application +Name=Lock PhiOS session +Comment=Lock the current Wayfire session using its normal PAM password +Exec=phios-lock +Icon=system-lock-screen +Terminal=false +Categories=System; diff --git a/packaging/linux/session/phios-network.desktop b/packaging/linux/session/phios-network.desktop new file mode 100644 index 00000000..411df90e --- /dev/null +++ b/packaging/linux/session/phios-network.desktop @@ -0,0 +1,8 @@ +[Desktop Entry] +Type=Application +Name=Network settings +Comment=Manage wired and Wi-Fi connections using NetworkManager +Exec=foot nmtui +Icon=network-wireless +Terminal=false +Categories=Settings;Network; diff --git a/packaging/linux/session/phios-observer.service b/packaging/linux/session/phios-observer.service new file mode 100644 index 00000000..5d7819cd --- /dev/null +++ b/packaging/linux/session/phios-observer.service @@ -0,0 +1,19 @@ +[Unit] +Description=PhiShell local observation transport +PartOf=phios-session.target + +[Service] +ExecStart=/usr/bin/node /usr/lib/phishell/host/localTransport.mjs +Restart=on-failure +RestartSec=2 +UMask=0077 +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=read-only +PrivateTmp=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK +ReadWritePaths=%h/.local/state/phios +Environment=PHIOS_STATE_ROOT=%h/.local/state/phios + +[Install] +WantedBy=phios-session.target diff --git a/packaging/linux/session/phios-open-shell b/packaging/linux/session/phios-open-shell new file mode 100755 index 00000000..85af8d01 --- /dev/null +++ b/packaging/linux/session/phios-open-shell @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ $EUID -eq 0 ]]; then + echo 'Refusing to run the PhiShell browser as root.' >&2 + exit 1 +fi +for attempt in {1..60}; do + if /usr/bin/node -e 'fetch("http://127.0.0.1:3969/api/v1/health").then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))'; then + exec chromium --ozone-platform=wayland --app=http://127.0.0.1:3969/ --no-first-run --disable-sync --disable-background-networking + fi + sleep 1 +done +echo 'PhiShell transport did not become healthy; see journalctl --user -u phios-observer.' >&2 +exit 1 diff --git a/packaging/linux/session/phios-policykit.service b/packaging/linux/session/phios-policykit.service new file mode 100644 index 00000000..60c19c63 --- /dev/null +++ b/packaging/linux/session/phios-policykit.service @@ -0,0 +1,13 @@ +[Unit] +Description=PhiOS graphical Linux administration authentication agent +PartOf=phios-session.target +StartLimitIntervalSec=60 +StartLimitBurst=3 + +[Service] +Type=exec +ExecStart=/usr/bin/lxqt-policykit-agent +Environment=QT_QPA_PLATFORM=wayland +Restart=on-failure +RestartSec=2 +UMask=0077 diff --git a/packaging/linux/session/phios-session b/packaging/linux/session/phios-session new file mode 100755 index 00000000..7e2964d2 --- /dev/null +++ b/packaging/linux/session/phios-session @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ $EUID -eq 0 ]]; then + echo 'PhiOS graphical sessions must run as a non-root user.' >&2 + exit 1 +fi +umask 077 +export XDG_CURRENT_DESKTOP=Wayfire +export XDG_SESSION_DESKTOP=phios +export XDG_SESSION_TYPE=wayland +export WLR_RENDERER_ALLOW_SOFTWARE=1 +export PHIOS_STATE_ROOT="$HOME/.local/state/phios" +export PHIOS_CURIOSITY_ROOT="$PHIOS_STATE_ROOT/curiosity" +mkdir -p "$PHIOS_STATE_ROOT" +systemctl --user import-environment PHIOS_STATE_ROOT PHIOS_CURIOSITY_ROOT XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP XDG_SESSION_TYPE +cleanup() { systemctl --user stop phios-session.target; } +trap cleanup EXIT HUP INT TERM +# Autostart starts the user services only after WAYLAND_DISPLAY exists. +wayfire -c /etc/xdg/phios/wayfire.ini >> "$PHIOS_STATE_ROOT/wayfire.log" 2>&1 diff --git a/packaging/linux/session/phios-session-ready b/packaging/linux/session/phios-session-ready new file mode 100755 index 00000000..eebd07d0 --- /dev/null +++ b/packaging/linux/session/phios-session-ready @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +systemctl --user import-environment WAYLAND_DISPLAY DISPLAY XDG_CURRENT_DESKTOP +dbus-update-activation-environment --systemd WAYLAND_DISPLAY XDG_CURRENT_DESKTOP +systemctl --user start phios-session.target diff --git a/packaging/linux/session/phios-session.target b/packaging/linux/session/phios-session.target new file mode 100644 index 00000000..f494fd5f --- /dev/null +++ b/packaging/linux/session/phios-session.target @@ -0,0 +1,3 @@ +[Unit] +Description=PhiOS graphical session services +Wants=phios-observer.service phios-curiosity-reader.service phios-history-reader.service phios-browser.service phios-waybar.service phios-audio.target phios-policykit.service diff --git a/packaging/linux/session/phios-waybar.service b/packaging/linux/session/phios-waybar.service new file mode 100644 index 00000000..747da507 --- /dev/null +++ b/packaging/linux/session/phios-waybar.service @@ -0,0 +1,12 @@ +[Unit] +Description=PhiOS Waybar panel +PartOf=phios-session.target + +[Service] +ExecStart=/usr/bin/waybar -c /etc/xdg/phios/waybar.json +Restart=on-failure +RestartSec=3 +UMask=0077 + +[Install] +WantedBy=phios-session.target diff --git a/packaging/linux/session/phios.desktop b/packaging/linux/session/phios.desktop new file mode 100644 index 00000000..3ca132d7 --- /dev/null +++ b/packaging/linux/session/phios.desktop @@ -0,0 +1,6 @@ +[Desktop Entry] +Name=PhiOS (Wayfire) +Comment=PhiShell local observation desktop preview +Exec=/usr/bin/phios-session +Type=Application +DesktopNames=Wayfire; diff --git a/packaging/linux/session/waybar.json b/packaging/linux/session/waybar.json new file mode 100644 index 00000000..43959845 --- /dev/null +++ b/packaging/linux/session/waybar.json @@ -0,0 +1,9 @@ +{ + "layer": "top", + "position": "top", + "modules-left": ["custom/phi-logo"], + "modules-center": ["custom/preview"], + "modules-right": ["network", "memory", "cpu", "clock"], + "custom/phi-logo": {"format": "φ PhiOS"}, + "custom/preview": {"format": "DEVELOPMENT PREVIEW", "tooltip-format": "Installation, whole-OS recovery and Linux desktop effects are not qualified."} +} diff --git a/packaging/linux/session/wayfire.ini b/packaging/linux/session/wayfire.ini new file mode 100644 index 00000000..96ce6866 --- /dev/null +++ b/packaging/linux/session/wayfire.ini @@ -0,0 +1,30 @@ +# Wayfire 0.11 public configuration options. +[core] +plugins = autostart command decoration move resize place grid vswitch wm-actions session-lock +vwidth = 3 +vheight = 3 +close_top_view = KEY_Q | KEY_F4 + +[autostart] +autostart_wf_shell = false +phios = /usr/lib/phishell/session-ready + +[command] +binding_terminal = KEY_ENTER +command_terminal = foot phi +binding_linux_terminal = KEY_ENTER +command_linux_terminal = foot +binding_launcher = KEY_SPACE +command_launcher = wofi --show drun +binding_shell = KEY_P +command_shell = phios-open-shell +binding_lock = KEY_L +command_lock = phios-lock +binding_network = KEY_N +command_network = foot nmtui + +[move] +activate = BTN_LEFT + +[resize] +activate = BTN_RIGHT diff --git a/packaging/linux/tests/desktop_probe.py b/packaging/linux/tests/desktop_probe.py new file mode 100644 index 00000000..fe6bb8bb --- /dev/null +++ b/packaging/linux/tests/desktop_probe.py @@ -0,0 +1,90 @@ +"""External ordinary-user desktop probe; never installed into the ISO.""" +from __future__ import annotations + +import json +import os +import struct +import subprocess +import tempfile +import time +import wave +from pathlib import Path + + +def restricted_dhcp_lease(network: dict) -> bool: + # nmcli get-values emits array-valued DHCP options either as lines or as + # one " | "-joined value. Parse the actual array before checking identity. + options = [option for row in network['DHCP4.OPTION'] for option in row.split(' | ')] + return (network['IP4.ADDRESS'] == ['192.0.2.15/24'] and not network['IP4.GATEWAY'] + and not network['IP4.DNS'] + and options.count('dhcp_server_identifier = 192.0.2.2') == 1) + + +def desktop_services(source: str, *, wired: bool = False) -> dict: + assert os.getuid() == 1000 and os.geteuid() == 1000 + assert Path('/usr/share/phios/source-commit').read_text().strip() == source + units = ['phios-audio.target', 'pipewire.service', 'pipewire-pulse.service', 'wireplumber.service', 'phios-policykit.service'] + for _ in range(60): + active = all(subprocess.run(['systemctl', '--user', 'is-active', '--quiet', unit]).returncode == 0 + for unit in units) + graph = json.loads(subprocess.check_output(['pw-dump'], text=True, timeout=10)) if active else [] + devices = [item for item in graph if item.get('type') == 'PipeWire:Interface:Device' and + item.get('info', {}).get('props', {}).get('device.api') == 'alsa'] + sinks = [item for item in graph if item.get('type') == 'PipeWire:Interface:Node' and + item.get('info', {}).get('props', {}).get('media.class') == 'Audio/Sink' and + item.get('info', {}).get('props', {}).get('factory.name') == 'api.alsa.pcm.sink'] + if active and devices and sinks: + break + time.sleep(1) + else: + subprocess.run(['journalctl', '--user', '--no-pager', '-n', '60', '-u', 'pipewire', '-u', 'wireplumber']) + raise RuntimeError('user audio session did not expose the actual emulated ALSA device/sink') + for name in ['pipewire', 'pipewire-pulse', 'wireplumber']: + subprocess.run(['pgrep', '-u', '1000', '-x', name], check=True, stdout=subprocess.DEVNULL) + agent_pid = subprocess.check_output(['systemctl', '--user', 'show', 'phios-policykit.service', + '--property=MainPID', '--value'], text=True).strip() + assert agent_pid.isdigit() and int(agent_pid) > 0 + status = (Path('/proc') / agent_pid / 'status').read_text().splitlines() + assert next(line for line in status if line.startswith('Uid:')).split()[1:] == ['1000'] * 4 + # The VM has a synthetic HDA device with a QEMU null backend, not host audio. + # Play actual PCM frames through the selected ALSA sink; hearing/capture is + # a separate physical test and is never inferred from this return code. + with tempfile.TemporaryDirectory(prefix='phios-audio-probe-') as temporary: + path = Path(temporary) / 'probe.wav' + with wave.open(str(path), 'wb') as stream: + stream.setnchannels(1) + stream.setsampwidth(2) + stream.setframerate(48000) + stream.writeframes(b''.join(struct.pack(' str: + return subprocess.check_output(args, input=data, text=True, stderr=subprocess.STDOUT) + + +def drive_installer(*, cancel: bool, recovery: list[str] | None = None, update: Path | None = None, + reject: bool = False, plan: bool = False, interrupt: bool = False, + enroll: tuple[Path, str] | None = None) -> str: + pid, fd = pty.fork() + if pid == 0: + if enroll is not None: + os.execv('/usr/bin/phios-update-enroll', ['phios-update-enroll', '--public-key', str(enroll[0]), + '--fingerprint', enroll[1]]) + if update is not None: + os.execv('/usr/bin/phios-os-update', ['phios-os-update', '--disk', '/dev/vda', '--bundle', str(update), + *(['--plan'] if plan else [])]) + if recovery is not None: + os.execv('/usr/bin/phios-os-recover', ['phios-os-recover', *recovery, '--disk', '/dev/vda']) + os.execv("/usr/bin/phios-install", ["phios-install", "--disk", "/dev/vda", "--username", "operator"]) + text = "" + replied: set[str] = set() + deadline = time.monotonic() + 900 + try: + while time.monotonic() < deadline: + ready, _, _ = select.select([fd], [], [], 1) + if ready: + try: + data = os.read(fd, 65536) + except OSError: + break + if not data: + break + chunk = data.decode(errors="replace") + text += chunk + print(chunk, end="", flush=True) + for prompt in ["New account password (12 or more characters): ", "Repeat new account password: "]: + if prompt in text and prompt not in replied: + os.write(fd, (PASSWORD + "\n").encode()) + replied.add(prompt) + match = re.search(r"(?:INSTALL|CHECKPOINT|RESTORE|UPDATE|ENROLL) (?:/dev/vda|/etc/phios) [0-9a-f]{64}\r?\n", text) + if match and "confirm" not in replied and "> " in text[match.end():]: + os.write(fd, ("cancel\n" if cancel else match[0].strip() + "\n").encode()) + replied.add("confirm") + if interrupt and 'stage' not in replied: + markers = list(Path('/run').glob('phios-recovery-*/top/@update-*/.phios-ci-stage-in-progress')) + if (len(markers) == 1 and markers[0].read_text() == 'staged pacman hook reached\n' and + (markers[0].parent / 'run/phios-ci-signed-hook-ready').is_file()): + print('PHIOS_SIGNED_STAGE_IN_PROGRESS', flush=True) + replied.add('stage') + ended, status = os.waitpid(pid, os.WNOHANG) + if ended: + expected = 1 if cancel or reject else 0 + if os.waitstatus_to_exitcode(status) != expected: + raise RuntimeError("production installer returned an unexpected status") + return text + ended, status = os.waitpid(pid, os.WNOHANG) + for _ in range(50): + if ended: + break + time.sleep(0.1) + ended, status = os.waitpid(pid, os.WNOHANG) + if not ended or os.waitstatus_to_exitcode(status) != (1 if cancel or reject else 0): + raise RuntimeError("production installer failed or timed out") + return text + finally: + try: + ended, _ = os.waitpid(pid, os.WNOHANG) + if not ended: + os.kill(pid, 9) + os.waitpid(pid, 0) + except ChildProcessError: + pass + os.close(fd) + + +def main() -> None: + row = json.loads(command("lsblk", "--nodeps", "--json", "--output", "SERIAL,TYPE,SIZE", "--bytes", "/dev/vda"))["blockdevices"][0] + if os.geteuid() != 0 or row["serial"] != "PHIOS_CI_BLANK" or row["type"] != "disk" or row["size"] != 32 * 1024**3: + raise RuntimeError("CI install fixture requires its exact disposable virtual disk") + command('modprobe', 'qemu_fw_cfg') + mode = Path('/sys/firmware/qemu_fw_cfg/by_name/opt/phios-ci-signed-updates/raw') + signed_updates = mode.exists() and mode.read_bytes() == b'enabled' + updater = None + if signed_updates: + spec = importlib.util.spec_from_file_location('phios_ci_update_fixture', '/usr/local/bin/phios-live-update-smoke.py') + assert spec is not None and spec.loader is not None + updater = importlib.util.module_from_spec(spec) + spec.loader.exec_module(updater) + if Path('/dev/vda1').exists(): + if updater is not None: + updater.resume_or_restore() + return + # Only the host harness's already installed disposable disk reaches + # this branch. The production live profile excludes this fixture. + root = Path('/run/phios-ci-checkpoint-read') + root.mkdir(mode=0o700) + command('mount', '-t', 'btrfs', '-o', 'ro,rescue=nologreplay,subvolid=5', '/dev/vda2', str(root)) + try: + generations = list((root / '@snapshots/recovery').glob('*/checkpoint.json')) + if len(generations) != 1: + raise RuntimeError('exactly one disposable checkpoint is required') + generation = generations[0].parent.name + finally: + command('umount', str(root)) + drive_installer(cancel=True, recovery=['restore', '--generation', generation]) + print('PHIOS_OS_RESTORE_CANCEL_OK', flush=True) + drive_installer(cancel=False, recovery=['restore', '--generation', generation]) + print('PHIOS_OS_RESTORE_OK:' + generation, flush=True) + return + drive_installer(cancel=True) + signatures = json.loads(command("wipefs", "--no-act", "--json", "/dev/vda"))["signatures"] + if signatures: + raise RuntimeError("cancelled installer changed the disk") + print("PHIOS_INSTALL_CANCEL_OK", flush=True) + drive_installer(cancel=False) + root = Path("/run/phios-ci-installed") + root.mkdir(mode=0o700) + mounts = [] + try: + command("mount", "-o", "subvol=@root", "/dev/vda2", str(root)) + mounts.append(root) + command("mount", "-o", "subvol=@home", "/dev/vda2", str(root / "home")) + mounts.append(root / "home") + command("mount", "/dev/vda1", str(root / "boot")) + mounts.append(root / "boot") + if ("initial_session" in (root / "etc/greetd/config.toml").read_text() or + (root / "etc/sudoers.d/phios-live-installer").exists() or + list((root / "usr/local/bin").glob("phios-live-*")) or + list((root / "etc/systemd/system").glob("phios-live-*.service"))): + raise RuntimeError("live credentials, autologin or test fixtures survived installation") + seed = ''' +from pathlib import Path +from phios.memory import MemoryOperatorRuntime, MemoryRecord, MemoryRuntimeConfig +from phios.state_recovery import backup +root=Path('/home/operator/.local/state/phios') +runtime=MemoryOperatorRuntime(state_root=root/'memory', + config=MemoryRuntimeConfig(enabled=True,principal_id='operator',scopes=('private',), + classifications=('operator',),retention_policy_id='retain'), + allowed_permissions=('memory.write','memory.read')) +record=MemoryRecord.build(record_id='installed-proof',revision=1,source_id='operator',source_kind='human', + provenance_refs=(),created_at='2026-09-30T00:00:00+00:00',scope_id='private',classification='operator', + retention_policy_id='retain',expires_at=None,epistemic_kind='source',text='Persist this acknowledged installed-OS record') +assert runtime.put(record,operation_id='installed-proof-put',task_id='ci-only').status=='ok' +assert runtime.store.get('installed-proof')==record +backup(root,root.parent/'phios-ci-data-backup') +print('PHIOS_INSTALLED_SEED_OK:'+record.record_sha256) +''' + print(command("arch-chroot", str(root), "runuser", "-u", "operator", "--", "python", "-c", seed), flush=True) + # Serial access is injected only into this disposable installed test + # target so the host can exercise password/PAM login and data checks. + entry = root / "boot/loader/entries/phios.conf" + entry.write_text(entry.read_text().rstrip() + " console=tty0 console=ttyS0,115200\n") + getty = root / "etc/systemd/system/getty.target.wants/serial-getty@ttyS0.service" + getty.parent.mkdir(parents=True, exist_ok=True) + getty.symlink_to("/usr/lib/systemd/system/serial-getty@.service") + receipt = json.loads((root / "var/lib/phios/install-receipt.json").read_text()) + os.sync() + finally: + for path in reversed(mounts): + command("umount", str(path)) + drive_installer(cancel=False, recovery=['checkpoint']) + root = Path('/run/phios-ci-checkpoint-read') + root.mkdir(mode=0o700) + command('mount', '-t', 'btrfs', '-o', 'ro,rescue=nologreplay,subvolid=5', '/dev/vda2', str(root)) + try: + generations = list((root / '@snapshots/recovery').glob('*/checkpoint.json')) + if len(generations) != 1: + raise RuntimeError('checkpoint creation did not retain exact metadata') + print('PHIOS_OS_CHECKPOINT_OK:' + generations[0].parent.name, flush=True) + finally: + command('umount', str(root)) + if updater is not None: + updater.initial() + raise RuntimeError('signed-update fixture returned without actual host interruption') + print("PHIOS_INSTALLED_DISK_OK:" + receipt["plan"]["source_commit"], flush=True) + + +if __name__ == "__main__": + main() diff --git a/packaging/linux/tests/installed_probe.py b/packaging/linux/tests/installed_probe.py new file mode 100644 index 00000000..d6b28295 --- /dev/null +++ b/packaging/linux/tests/installed_probe.py @@ -0,0 +1,76 @@ +"""Run as the password-authenticated test user on the installed disposable VM.""" +from __future__ import annotations + +import json +import os +import subprocess +import time +import urllib.request +from pathlib import Path + +from phios.memory import MemoryStore +from phios.state_io import append_jsonl, read_jsonl +from phios.state_recovery import restore, verify_backup + + +def probe(source: str, phase: int, *, signed_update: bool = False, desktop_check=None) -> None: + root = Path.home() / ".local/state/phios" + assert os.getuid() == 1000 + assert Path("/usr/share/phios/source-commit").read_text().strip() == source + assert Path("/sys/firmware/efi").is_dir() + assert "archisobasedir" not in Path("/proc/cmdline").read_text() + assert not Path("/run/archiso/bootmnt").exists() + assert root.stat().st_mode & 0o777 == 0o700 + record = MemoryStore(root / "memory/canonical.sqlite3").get("installed-proof") + assert record is not None and record.text == "Persist this acknowledged installed-OS record" + backup = root.parent / "phios-ci-data-backup" + verify_backup(backup) + restored = root.parent / "phios-ci-restored" + if phase == 1: + restore(backup, restored) + append_jsonl(root / "qa/acknowledged.jsonl", {"source_commit": source, "execution_authority": False}) + assert MemoryStore(restored / "memory/canonical.sqlite3").get("installed-proof") == record + assert read_jsonl(root / "qa/acknowledged.jsonl") == [{"source_commit": source, "execution_authority": False}] + assert not (Path.home() / ".config/phios/memory.json").exists() + assert not (root / "spine-v0.1/ledger/ghostwalk-authorization-decisions.jsonl").exists() + if signed_update: + package = Path('/usr/share/phios-ci-update/verified.txt') + if phase < 3: + assert package.read_bytes() == b'authenticated disposable PhiOS package update\n' + assert subprocess.check_output(['pacman', '-Q', 'phios-ci-update'], text=True).strip() == 'phios-ci-update 1.0.0-1' + else: + assert not package.exists() + assert subprocess.run(['pacman', '-Q', 'phios-ci-update'], capture_output=True).returncode == 1 + assert not Path('/usr/share/phios-ci-interrupt/verified.txt').exists() + # The host enters the same fresh account at greetd; the compositor and + # browser must be launched by the configured login/session services. + for _ in range(90): + try: + with urllib.request.urlopen("http://127.0.0.1:3969/api/v1/health", timeout=2) as response: + assert response.status == 200 + with urllib.request.urlopen("http://127.0.0.1:3969/", timeout=2) as response: + assert response.status == 200 + # Observer health precedes browser startup. Require the whole + # supervised desktop to be ready within the same bounded wait. + if any(subprocess.run(["pgrep", "-u", "1000", "-x", name], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode for name in ["wayfire", "chromium"]): + time.sleep(1) + continue + if subprocess.run(["systemctl", "--user", "is-active", "phios-observer.service", "phios-browser.service"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5).returncode: + time.sleep(1) + continue + break + except OSError: + time.sleep(1) + else: + subprocess.run(["journalctl", "--user", "--no-pager", "-n", "60", "-u", "phios-browser.service", + "-u", "phios-curiosity-reader.service", "-u", "phios-observer.service"], timeout=15) + raise RuntimeError("installed graphical login did not start the complete supervised desktop") + time.sleep(2) # Preserve a rendered application screenshot after process readiness. + if desktop_check is None: + raise RuntimeError('external desktop service verifier is required') + desktop_check(source) + boot_id = Path("/proc/sys/kernel/random/boot_id").read_text().strip().replace("-", "") + print("PHIOS_INSTALLED_CHECK_OK:" + json.dumps({"source_commit": source, "phase": phase, + "boot_id": boot_id, "record_sha256": record.record_sha256}), flush=True) diff --git a/packaging/linux/tests/live-smoke.sh b/packaging/linux/tests/live-smoke.sh new file mode 100755 index 00000000..28ce534a --- /dev/null +++ b/packaging/linux/tests/live-smoke.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# CI-only. Disk writes require the install fixture's exact disposable disk. +set -euo pipefail +dump_failure() { + echo PHIOS_BOOT_FAILED + timeout 15 journalctl -b -u greetd --no-pager || true + timeout 15 runuser -u phios -- env XDG_RUNTIME_DIR=/run/user/1000 journalctl --user -b --no-pager || true + cat /home/phios/.local/state/phios/wayfire.log || true +} +trap dump_failure ERR +for attempt in {1..420}; do + if curl -fsS http://127.0.0.1:3969/api/v1/health >/dev/null && + pgrep -u phios -x wayfire >/dev/null && pgrep -u phios -x chromium >/dev/null; then + break + fi + if (( attempt % 60 == 0 )); then + journalctl -b -u greetd --no-pager + cat /home/phios/.local/state/phios/wayfire.log || true + fi + sleep 1 +done +curl -fsS http://127.0.0.1:3969/ | grep -q '
' +curl -fsS http://127.0.0.1:3969/api/v1/package-observation | python -c 'import json,sys; p=json.load(sys.stdin)["observation"]; assert p["adapter"]=="arch-pacman-local" and p["availability"]=="available" and not p["executionAuthority"] and not p["effectPerformed"]' +curl -fsS http://127.0.0.1:3969/api/v1/system-state | python -c 'import json,sys; r=json.load(sys.stdin)["receipt"]; p=next(c for c in r["components"] if c["id"]=="packages"); assert p["source"]=="pacman-local-desc" and p["availability"]=="available" and r["readOnly"] and not r["executionAuthority"] and not r["effectPerformed"]' +test "$(id -u phios)" = 1000 +test "$(stat -c %a /home/phios/.local/state/phios)" = 700 +if id -nG phios | grep -qw wheel; then false; fi +if pgrep -u root -x wayfire; then false; fi +if pgrep -u root -x chromium; then false; fi +for pid in $(pgrep -u phios -x chromium); do + if tr '\0' '\n' < "/proc/$pid/cmdline" | grep -qx -- '--no-sandbox'; then false; fi +done +for endpoint in decisions bindings leases; do + status=$(curl -sS -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' --data '{}' "http://127.0.0.1:3969/api/v1/ghostwalk/authorization-console/$endpoint") + test "$status" = 403 +done +runuser -u phios -- env XDG_RUNTIME_DIR=/run/user/1000 systemctl --user is-active phios-observer.service phios-browser.service phios-curiosity-reader.service +userctl() { runuser -u phios -- env XDG_RUNTIME_DIR=/run/user/1000 systemctl --user "$@"; } +old_pid=$(userctl show phios-observer.service --property=MainPID --value) +[[ $old_pid =~ ^[1-9][0-9]*$ ]] +userctl kill --signal=KILL phios-observer.service +for attempt in {1..60}; do + new_pid=$(userctl show phios-observer.service --property=MainPID --value) + if [[ $new_pid != 0 && $new_pid != "$old_pid" ]] && curl -fsS http://127.0.0.1:3969/api/v1/health >/dev/null; then + break + fi + sleep 1 +done +test "$new_pid" != "$old_pid" +[[ $new_pid =~ ^[1-9][0-9]*$ ]] +curl -fsS http://127.0.0.1:3969/api/v1/health >/dev/null +echo PHIOS_SIDECAR_RESTART_OK +# A compositor exit must stop every PartOf session service. Restarting greetd +# does not repeat initial_session. The VM driver enters the public volatile +# live credentials at the real greeter; production login policy stays intact. +pkill -TERM -u phios -x wayfire +for attempt in {1..30}; do + if ! userctl is-active --quiet phios-session.target && + ! curl -fsS http://127.0.0.1:3969/api/v1/health >/dev/null; then break; fi + sleep 1 +done +if userctl is-active --quiet phios-session.target; then false; fi +if curl -fsS http://127.0.0.1:3969/api/v1/health >/dev/null; then false; fi +printf 'PHIOS_LOGIN_REQUIRED:%s\n' "$(tr -d '-' < /proc/sys/kernel/random/boot_id)" +for attempt in {1..90}; do + if curl -fsS http://127.0.0.1:3969/api/v1/health >/dev/null && + pgrep -u phios -x wayfire >/dev/null && pgrep -u phios -x chromium >/dev/null; then break; fi + sleep 1 +done +userctl is-active phios-observer.service phios-browser.service phios-curiosity-reader.service +curl -fsS http://127.0.0.1:3969/api/v1/health >/dev/null +echo PHIOS_SESSION_RESTART_OK +python -c 'import phios, phios.mcp.server, phios.ghostwalk_operator; print("Installed Python runtime:",phios.__version__)' +phi version +printf 'PHIOS_BOOT_OK:%s:%s\n' "$(cat /usr/share/phios/source-commit)" "$(tr -d '-' < /proc/sys/kernel/random/boot_id)" +if [[ -b /dev/vda ]]; then + python /usr/local/bin/phios-live-install-smoke.py +fi diff --git a/packaging/linux/tests/normal_live_probe.py b/packaging/linux/tests/normal_live_probe.py new file mode 100644 index 00000000..06ab2b72 --- /dev/null +++ b/packaging/linux/tests/normal_live_probe.py @@ -0,0 +1,100 @@ +"""External normal-user VM fixture; the ISO contains none of this test code.""" +from __future__ import annotations + +import errno +import json +import os +import pty +import re +import select +import subprocess +import time +from pathlib import Path + +PASSWORD = 'phios-qa-only-2026' + + +def maintenance(argv: list[str], *, cancel: bool = False) -> str: + child, channel = pty.fork() + if child == 0: + os.execvp('sudo', ['sudo', '-n', *argv]) + text = '' + replied: set[str] = set() + deadline = time.monotonic() + 900 + status = None + try: + while time.monotonic() < deadline: + if select.select([channel], [], [], 0.2)[0]: + try: + data = os.read(channel, 65536) + except OSError as exc: + if exc.errno != errno.EIO: + raise + data = b'' + if data: + text += data.decode(errors='replace') + for prompt in ['New account password (12 or more characters): ', 'Repeat new account password: ']: + if prompt in text and prompt not in replied: + os.write(channel, (PASSWORD + '\n').encode()) + replied.add(prompt) + phrase = re.search(r'(?:INSTALL|CHECKPOINT|RESTORE) /dev/vda [0-9a-f]{64}\r?\n', text) + if phrase and 'confirm' not in replied and '> ' in text[phrase.end():]: + os.write(channel, ('cancel\n' if cancel else phrase[0].strip() + '\n').encode()) + replied.add('confirm') + ended, result = os.waitpid(child, os.WNOHANG) + if ended: + status = result + while select.select([channel], [], [], 0.1)[0]: + try: + tail = os.read(channel, 65536) + except OSError as exc: + if exc.errno != errno.EIO: + raise + break + if not tail: + break + text += tail.decode(errors='replace') + break + print(text, flush=True) + if status is None or os.waitstatus_to_exitcode(status) != (1 if cancel else 0) or 'confirm' not in replied: + raise RuntimeError('normal-user production maintenance command did not pass exact confirmation/status') + return text + finally: + os.close(channel) + if status is None: + os.kill(child, 9) + os.waitpid(child, 0) + + +def drive(stage: str, source: str, generation: str | None) -> None: + assert os.getuid() == 1000 and os.geteuid() == 1000 + assert Path('/usr/share/phios/source-commit').read_text().strip() == source + assert Path('/run/archiso/bootmnt').is_dir() + assert not Path('/usr/local/bin/phios-live-smoke').exists() + assert not Path('/usr/local/bin/phios-live-install-smoke.py').exists() + assert not Path('/etc/systemd/system/phios-live-smoke.service').exists() + assert 'wheel' not in subprocess.check_output(['id', '-nG'], text=True).split() + row = json.loads(subprocess.check_output(['lsblk', '--nodeps', '--json', '--bytes', '--output', 'SERIAL,TYPE,SIZE', '/dev/vda'], text=True))['blockdevices'][0] + assert row['serial'] == 'PHIOS_CI_BLANK' and row['type'] == 'disk' and row['size'] == 32 * 1024**3 + if stage == 'install': + argv = ['phios-install', '--disk', '/dev/vda', '--username', 'operator', '--serial-console'] + maintenance(argv, cancel=True) + # The subsequent actual install rescans every byte for zeroed contents. + # It would hold if cancellation modified any byte of this fresh disk. + installed = maintenance(argv) + assert '"serial_console_password_login": true' in installed + assert '"installed": true' in installed + checkpoint = maintenance(['phios-os-recover', 'checkpoint', '--disk', '/dev/vda']) + values = set(re.findall(r'"generation": "([0-9a-f]{32})"', checkpoint)) + assert len(values) == 1 + generation = values.pop() + elif stage == 'restore': + assert generation is not None and re.fullmatch('[0-9a-f]{32}', generation) + argv = ['phios-os-recover', 'restore', '--disk', '/dev/vda', '--generation', generation] + maintenance(argv, cancel=True) + restored = maintenance(argv) + assert '"stage": "restored; disk-only boot remains unqualified"' in restored + else: + raise ValueError('unsupported normal live stage') + print('PHIOS_NORMAL_MAINTENANCE_OK:' + json.dumps({'stage': stage, 'source_commit': source, + 'generation': generation, 'fixture_free': True, 'uid': os.getuid(), 'limited_live_sudo': True}), flush=True) diff --git a/packaging/linux/tests/normal_seed.py b/packaging/linux/tests/normal_seed.py new file mode 100644 index 00000000..f64c9d31 --- /dev/null +++ b/packaging/linux/tests/normal_seed.py @@ -0,0 +1,19 @@ +"""Create only this disposable user's canonical data before a normal-ISO test.""" +from pathlib import Path + +from phios.memory import MemoryOperatorRuntime, MemoryRecord, MemoryRuntimeConfig +from phios.state_recovery import backup + + +def seed_normal() -> None: + root = Path.home() / '.local/state/phios' + runtime = MemoryOperatorRuntime(state_root=root / 'memory', + config=MemoryRuntimeConfig(enabled=True, principal_id='operator', scopes=('private',), + classifications=('operator',), retention_policy_id='retain'), + allowed_permissions=('memory.write', 'memory.read')) + record = MemoryRecord.build(record_id='installed-proof', revision=1, source_id='operator', source_kind='human', + provenance_refs=(), created_at='2026-09-30T00:00:00+00:00', scope_id='private', classification='operator', + retention_policy_id='retain', expires_at=None, epistemic_kind='source', text='Persist this acknowledged installed-OS record') + assert runtime.put(record, operation_id='installed-proof-put', task_id='ci-only').status == 'ok' + assert runtime.store.get('installed-proof') == record + backup(root, root.parent / 'phios-ci-data-backup') diff --git a/packaging/linux/tests/proof_smoke.py b/packaging/linux/tests/proof_smoke.py new file mode 100644 index 00000000..5ff6df4e --- /dev/null +++ b/packaging/linux/tests/proof_smoke.py @@ -0,0 +1,140 @@ +"""External disposable-VM fixture, run by its password-authenticated UID 1000.""" +from __future__ import annotations + +import errno +import hashlib +import json +import os +import pty +import re +import select +import subprocess +import time +from pathlib import Path + +PASSWORD = 'phios-qa-only-2026' + + +def operator(argv: list[str], *, cancel: bool = False, approval: bool = False, expected: int = 0) -> str: + child, channel = pty.fork() + if child == 0: + os.execvp('sudo', ['sudo', '-k', *argv]) + text = '' + supplied_password = False + supplied_phrase = False + deadline = time.monotonic() + 180 + status = None + try: + while time.monotonic() < deadline: + if select.select([channel], [], [], 0.2)[0]: + try: + data = os.read(channel, 65536) + except OSError as exc: + if exc.errno != errno.EIO: + raise + data = b'' + if data: + text += data.decode(errors='replace') + if 'password for operator:' in text and not supplied_password: + os.write(channel, (PASSWORD + '\n').encode()) + supplied_password = True + match = re.search(r'Type exactly APPROVE ([0-9a-f]{64}) or anything else to cancel:', text) + if match and approval and not supplied_phrase: + answer = 'cancel' if cancel else 'APPROVE ' + match[1] + os.write(channel, (answer + '\n').encode()) + supplied_phrase = True + ended, result = os.waitpid(child, os.WNOHANG) + if ended: + status = result + drain = time.monotonic() + 1 + while time.monotonic() < drain and select.select([channel], [], [], 0.1)[0]: + try: + tail = os.read(channel, 65536) + except OSError as exc: + if exc.errno != errno.EIO: + raise + break + if not tail: + break + text += tail.decode(errors='replace') + break + if status is None: + raise RuntimeError('bounded production sudo proof command timed out') + code = os.waitstatus_to_exitcode(status) + print(text, flush=True) + if code != expected or not supplied_password or (approval and not supplied_phrase): + raise RuntimeError('actual password/production proof command status differs: ' + str(code)) + return text + finally: + os.close(channel) + if status is None: + os.kill(child, 9) + os.waitpid(child, 0) + + +def proof_workflow(source: str) -> dict[str, object]: + assert os.getuid() == 1000 + assert subprocess.run(['systemctl', 'is-active', '--quiet', 'phios-proof-proposer.service']).returncode != 0 + operator(['systemctl', 'start', 'phios-proof-proposer.service']) + report = operator(['phios-linux-proof', 'inspect']) + assert '"principal_uid": 1001' in report and source in report + cancelled = operator(['phios-linux-proof', 'approve'], approval=True, cancel=True, expected=2) + assert 'Cancelled; no approval' in cancelled + approved = operator(['phios-linux-proof', 'approve'], approval=True) + match = re.search(r'"approval_sha256": "([0-9a-f]{64})"', approved) + assert match is not None + digest = match[1] + permission = ("import os\nprint('AGENT_UID:'+str(os.getuid()),flush=True)\ntry:\n" + " open('/.snapshots/phios-linux-proof/approvals/" + digest + "')\n" + "except PermissionError:\n print('AGENT_STORE_DENIED',flush=True)\n raise SystemExit(1)") + denied = operator(['runuser', '-u', 'phios-agent', '--', 'python', '-c', permission], expected=1) + assert 'AGENT_UID:1001' in denied and 'AGENT_STORE_DENIED' in denied + denied_cli = operator(['runuser', '-u', 'phios-agent', '--', 'phios-linux-proof', 'execute', '--approval', digest], expected=1) + assert 'installed UID 1000 administrator' in denied_cli + receipt = operator(['phios-linux-proof', 'execute', '--approval', digest]) + value = json.loads(receipt[receipt.index('{'):receipt.rindex('}') + 1]) + assert value['effect_performed'] is True and value['post_effect_verified'] is True + assert value['execution_authority'] is False and value['authority_replayable'] is False + actual = operator(['cat', '/.snapshots/phios-linux-proof/notes/' + digest]) + assert 'PhiOS verified one explicitly approved Linux proof note.' in actual + replay = operator(['phios-linux-proof', 'execute', '--approval', digest], expected=1) + assert 'lease_consumed' in replay + another = operator(['phios-linux-proof', 'approve'], approval=True) + expired = re.search(r'"approval_sha256": "([0-9a-f]{64})"', another) + assert expired is not None + until = time.monotonic() + 61 + while time.monotonic() < until: + time.sleep(1) + expiry = operator(['phios-linux-proof', 'execute', '--approval', expired[1]], expected=1) + assert 'lease_expired' in expiry + absence = operator(['test', '!', '-e', '/.snapshots/phios-linux-proof/notes/' + expired[1]]) + assert 'Linux proof held' not in absence + result = {'schema_version': 'phios.linux-proof-qualification.v1', 'source_commit': source, + 'approval_sha256': digest, 'expired_approval_sha256': expired[1], 'receipt': value, + 'actual_agent_uid': 1001, 'sudo_password_authentication': True, 'agent_store_denied': True, + 'agent_broker_denied': True, 'cancel_passed': True, 'replay_refused': True, 'expiry_refused': True, + 'hardware_qualified': False, 'release_ready': False} + target = Path.home() / '.local/state/phios/qa/linux-proof.json' + target.parent.mkdir(mode=0o700, exist_ok=True) + fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as handle: + json.dump(result, handle, sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + directory = os.open(target.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(directory) + finally: + os.close(directory) + print('PHIOS_LINUX_PROOF_OK:' + json.dumps(result), flush=True) + return result + + +def historical_proof(source: str) -> None: + value = json.loads((Path.home() / '.local/state/phios/qa/linux-proof.json').read_text()) + assert value['source_commit'] == source + denied = operator(['phios-linux-proof', 'execute', '--approval', value['approval_sha256']], expected=1) + assert 'another boot/source/principal' in denied + note = operator(['cat', '/.snapshots/phios-linux-proof/notes/' + value['approval_sha256']]) + assert 'PhiOS verified one explicitly approved Linux proof note.' in note + print('PHIOS_LINUX_PROOF_HISTORY_INACTIVE:' + hashlib.sha256(note.encode()).hexdigest(), flush=True) diff --git a/packaging/linux/tests/qemu_boot.py b/packaging/linux/tests/qemu_boot.py new file mode 100644 index 00000000..5271e6aa --- /dev/null +++ b/packaging/linux/tests/qemu_boot.py @@ -0,0 +1,144 @@ +"""Boot a disposable, network-disconnected UEFI VM and preserve exact evidence.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import socket +import subprocess +import time +from pathlib import Path +from typing import Any + + +def qmp_request(qmp_path: Path, request: dict[str, Any]) -> None: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(15) + client.connect(str(qmp_path)) + stream = client.makefile("rwb") + json.loads(stream.readline()) + for request in [{"execute": "qmp_capabilities"}, request]: + stream.write(json.dumps(request).encode() + b"\n") + stream.flush() + while True: + response = json.loads(stream.readline()) + if "error" in response: + raise RuntimeError(f"QMP evidence capture failed: {response['error']}") + if "return" in response: + break + + +def capture_display(qmp_path: Path, output: Path, *, name: str = "screen") -> None: + qmp_request(qmp_path, {"execute": "screendump", "arguments": { + "filename": str((output / f"{name}.ppm").resolve())}}) + + +def enter_live_login(qmp_path: Path) -> None: + """Exercise greetd/PAM with the documented public volatile credentials.""" + qmp_request(qmp_path, {"execute": "send-key", "arguments": { + "keys": [{"type": "qcode", "data": key} for key in ["ctrl", "alt", "f1"]]}}) + time.sleep(1) + for field in ["phios", "phios"]: + for key in [*field, "ret"]: + qmp_request(qmp_path, {"execute": "send-key", "arguments": { + "keys": [{"type": "qcode", "data": key}], "hold-time": 80}}) + time.sleep(0.12) + time.sleep(1) + + +def boot(iso: Path, source: str, output: Path, *, timeout: int = 600) -> None: + if re.fullmatch(r"[0-9a-f]{40}", source) is None or not iso.is_file(): + raise ValueError("an existing ISO and exact source commit are required") + if output.exists() and any(output.iterdir()): + raise ValueError("boot evidence destination must be fresh") + output.mkdir(parents=True, exist_ok=True) + code = Path("/usr/share/OVMF/OVMF_CODE_4M.fd") + variables = Path("/usr/share/OVMF/OVMF_VARS_4M.fd") + if not code.is_file() or not variables.is_file(): + raise ValueError("OVMF UEFI firmware is required") + qemu = shutil.which("qemu-system-x86_64") + if qemu is None: + raise ValueError("qemu-system-x86_64 is required") + variables_copy = output / "OVMF_VARS.fd" + shutil.copyfile(variables, variables_copy) + serial = output / "serial.log" + qmp_path = output / "qmp.sock" + accelerated = os.access("/dev/kvm", os.R_OK | os.W_OK) + accelerator = "kvm" if accelerated else "tcg" + if not accelerated: + timeout = max(timeout, 1800) + command = [qemu, "-machine", f"q35,accel={accelerator}", "-cpu", "host" if accelerated else "max", "-m", "4096", "-smp", "2", + "-drive", f"if=pflash,format=raw,readonly=on,file={code}", + "-drive", f"if=pflash,format=raw,file={variables_copy}", + "-cdrom", str(iso.resolve()), "-boot", "d", "-nic", "none", "-vga", "none", + "-device", "virtio-vga", "-display", "none", "-monitor", "none", + "-serial", f"file:{serial}", "-qmp", f"unix:{qmp_path},server=on,wait=off"] + digest = hashlib.sha256() + with iso.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + receipt = {"schema_version": "phios.live-boot-evidence.v1", "source_commit": source, + "iso_sha256": digest.hexdigest(), "command": command, + "accelerator": accelerator, "timeout_seconds": timeout, + "boot_passed": False, "reboot_passed": False, "boot_ids": [], + "hardware_qualified": False, "release_ready": False} + with (output / "qemu.log").open("w") as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + timeout + marker = f"PHIOS_BOOT_OK:{source}" + reset_sent = False + login_ids_sent: set[str] = set() + while time.monotonic() < deadline: + text = serial.read_text(errors="replace") if serial.exists() else "" + if "PHIOS_BOOT_FAILED" in text: + raise RuntimeError("live-image qualification fixture failed") + for login_id in re.findall(r"PHIOS_LOGIN_REQUIRED:([0-9a-f]{32})", text): + if login_id not in login_ids_sent: + enter_live_login(qmp_path) + login_ids_sent.add(login_id) + boot_ids = list(dict.fromkeys(re.findall(re.escape(marker) + r":([0-9a-f]{32})", text))) + receipt["boot_ids"] = boot_ids + if len(boot_ids) >= 2 and reset_sent: + break + if boot_ids and not reset_sent: + capture_display(qmp_path, output, name="screen-first") + qmp_request(qmp_path, {"execute": "system_reset"}) + reset_sent = True + deadline = time.monotonic() + timeout + if process.poll() is not None: + raise RuntimeError(f"QEMU exited before qualification (exit {process.returncode})") + time.sleep(1) + else: + raise RuntimeError("UEFI boot/session qualification timed out") + capture_display(qmp_path, output) + receipt["boot_passed"] = True + receipt["reboot_passed"] = True + print(f"UEFI boot, session restart and second boot passed for ISO {receipt['iso_sha256']}") + finally: + if not (output / "screen.ppm").exists() and process.poll() is None: + try: + capture_display(qmp_path, output) + except (OSError, ValueError, RuntimeError) as exc: + receipt["display_capture_error"] = str(exc) + process.terminate() + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + (output / "boot-evidence.json").write_text(json.dumps(receipt, indent=2) + "\n") + if not receipt["boot_passed"] and serial.exists(): + print("\n".join(serial.read_text(errors="replace").splitlines()[-160:])) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--iso", required=True, type=Path) + parser.add_argument("--source", required=True) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + boot(args.iso, args.source, args.output.resolve()) diff --git a/packaging/linux/tests/qemu_desktop.py b/packaging/linux/tests/qemu_desktop.py new file mode 100644 index 00000000..23fb2a9d --- /dev/null +++ b/packaging/linux/tests/qemu_desktop.py @@ -0,0 +1,64 @@ +"""External QMP screen-lock test using the guest's real shortcut and PAM.""" +from __future__ import annotations + +import json +import re +import secrets +import time +from pathlib import Path +from typing import Callable + +from qemu_boot import capture_display, qmp_request + + +def qualify_lock(qmp: Path, output: Path, *, source: str, password: str, label: str, + program: Callable[[str], None], wait: Callable[[str], re.Match[str]]) -> dict: + if not re.fullmatch('[a-z0-9-]+', password): + raise ValueError('only the public disposable test password is accepted by this key driver') + + def state(locked: bool) -> dict: + nonce = secrets.token_hex(8) + marker = 'PHIOS_LOCK_STATE_' + nonce + ':' + program("import os,json,subprocess,time\nfrom pathlib import Path\n" + "assert os.getuid()==1000\n" + f"expected={locked!r}\n" + "for _ in range(30):\n" + " active=subprocess.run(['pgrep','-u','1000','-x','swaylock'],capture_output=True).returncode==0\n" + " if active==expected: break\n" + " time.sleep(1)\n" + "else: raise RuntimeError('real session lock/PAM state did not match')\n" + f"print({marker!r}+json.dumps({{'locked':active,'uid':os.getuid()," + "'source_commit':Path('/usr/share/phios/source-commit').read_text().strip()," + "'boot_id':Path('/proc/sys/kernel/random/boot_id').read_text().strip().replace('-','')}),flush=True)\n") + result = json.loads(wait(re.escape(marker) + r'(\{[^\r\n]+\})')[1]) + if result['locked'] is not locked or result['uid'] != 1000 or result['source_commit'] != source: + raise RuntimeError('screen-lock identity/state differs') + return result + + def keys(value: str) -> None: + for key in [*value, 'ret']: + code = 'minus' if key == '-' else key + qmp_request(qmp, {'execute': 'send-key', 'arguments': { + 'keys': [{'type': 'qcode', 'data': code}], 'hold-time': 80}}) + time.sleep(0.12) + + state(False) + qmp_request(qmp, {'execute': 'send-key', 'arguments': { + 'keys': [{'type': 'qcode', 'data': key} for key in ['meta_l', 'l']], 'hold-time': 80}}) + locked = state(True) + capture_display(qmp, output, name=f'screen-{label}-locked') + keys('wrong-lock-password') + time.sleep(5) # Allow the actual PAM refusal/delay before another attempt. + state(True) + capture_display(qmp, output, name=f'screen-{label}-wrong-password') + qmp_request(qmp, {'execute': 'send-key', 'arguments': { + 'keys': [{'type': 'qcode', 'data': key} for key in ['ctrl', 'u']], 'hold-time': 80}}) + time.sleep(0.2) + keys(password) + unlocked = state(False) + capture_display(qmp, output, name=f'screen-{label}-unlocked') + if locked['boot_id'] != unlocked['boot_id']: + raise RuntimeError('unlock required an unexpected reboot') + return {'source_commit': source, 'boot_id': unlocked['boot_id'], 'uid': 1000, + 'actual_super_l_shortcut': True, 'wrong_password_held': True, + 'correct_pam_password_unlocked': True, 'release_ready': False} diff --git a/packaging/linux/tests/qemu_install.py b/packaging/linux/tests/qemu_install.py new file mode 100644 index 00000000..f1f28cb1 --- /dev/null +++ b/packaging/linux/tests/qemu_install.py @@ -0,0 +1,400 @@ +"""Qualify installation only on a fresh, locally created 32 GiB virtual disk.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import socket +import subprocess +import time +from pathlib import Path +from typing import Any + +from qemu_boot import capture_display, enter_live_login, qmp_request +from qemu_desktop import qualify_lock + +PASSWORD = "phios-qa-only-2026" # Same public ephemeral test credential as live fixture. + + +def send_text(qmp: Path, value: str) -> None: + for key in [*value, "ret"]: + code = "minus" if key == "-" else key + qmp_request(qmp, {"execute": "send-key", "arguments": { + "keys": [{"type": "qcode", "data": code}], "hold-time": 80}}) + time.sleep(0.12) + + +def stop(process: subprocess.Popen[Any], *, abrupt: bool = False) -> None: + if abrupt: + process.kill() + else: + process.terminate() + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + +def failed_boot(common: list[str], output: Path, receipt: dict[str, Any]) -> None: + """Require an observed kernel/root failure, never treat a timeout as proof.""" + qmp, serial = output / 'failed-boot-qmp.sock', output / 'failed-boot-serial.log' + command = common + ['-serial', f'file:{serial}', '-qmp', f'unix:{qmp},server=on,wait=off'] + receipt['commands'].append(command) + with (output / 'failed-boot-qemu.log').open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + text = serial.read_text(errors='replace') if serial.exists() else '' + if 'Kernel panic' in text or 'Unable to mount root fs' in text: + receipt['simulated_boot_failure_observed'] = True + break + if 'login: ' in text or process.poll() is not None: + raise RuntimeError('the deliberately broken root unexpectedly booted or VM exited') + time.sleep(1) + else: + raise RuntimeError('no specific unbootable-system failure was observed') + finally: + if process.poll() is None: + capture_display(qmp, output, name='screen-failed-boot') + stop(process) + + +def recover_live(common: list[str], iso: Path, output: Path, receipt: dict[str, Any]) -> None: + qmp, serial = output / 'recovery-qmp.sock', output / 'recovery-live-serial.log' + command = common + ['-drive', f'file={iso.resolve()},if=none,id=installation,format=raw,media=cdrom,readonly=on', + '-device', 'ide-cd,drive=installation,bootindex=1', '-serial', f'file:{serial}', + '-qmp', f'unix:{qmp},server=on,wait=off'] + receipt['commands'].append(command) + with (output / 'recovery-live-qemu.log').open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 900 + login_sent = False + while time.monotonic() < deadline: + text = serial.read_text(errors='replace') if serial.exists() else '' + if 'PHIOS_BOOT_FAILED' in text or process.poll() is not None: + raise RuntimeError('live system/root/EFI recovery fixture failed') + if 'PHIOS_LOGIN_REQUIRED:' in text and not login_sent: + enter_live_login(qmp) + login_sent = True + marker = 'PHIOS_OS_RESTORE_OK:' + receipt['recovery_checkpoint_generation'] + if marker in text: + assert 'PHIOS_OS_RESTORE_CANCEL_OK' in text + receipt['matched_root_efi_restored'] = True + break + time.sleep(1) + else: + raise RuntimeError('live-media recovery timed out') + finally: + if process.poll() is None: + capture_display(qmp, output, name='screen-recovery-live') + stop(process) + if not receipt.get('matched_root_efi_restored') and serial.exists(): + print('\n'.join(serial.read_text(errors='replace').splitlines()[-160:])) + + +def install_live(common: list[str], iso: Path, output: Path, source: str, receipt: dict[str, Any], + *, signed_update: bool) -> None: + for attempt in range(2 if signed_update else 1): + prefix = 'install-live' if attempt == 0 else 'interrupted-resume-live' + qmp, serial = output / (prefix + '-qmp.sock'), output / (prefix + '-serial.log') + command = common + ['-drive', f'file={iso.resolve()},if=none,id=installation,format=raw,media=cdrom,readonly=on', + '-device', 'ide-cd,drive=installation,bootindex=1', '-serial', f'file:{serial}', + '-qmp', f'unix:{qmp},server=on,wait=off'] + receipt['commands'].append(command) + interrupted = False + with (output / (prefix + '-qemu.log')).open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + (1800 if receipt['accelerator'] == 'kvm' else 3000) + login_sent = False + while time.monotonic() < deadline: + text = serial.read_text(errors='replace') if serial.exists() else '' + if 'PHIOS_BOOT_FAILED' in text or process.poll() is not None: + raise RuntimeError('live installer or signed package qualification failed') + if 'UEFI Interactive Shell' in text: + raise RuntimeError('firmware did not boot the installation ISO') + if 'PHIOS_LOGIN_REQUIRED:' in text and not login_sent: + enter_live_login(qmp) + login_sent = True + if signed_update and 'PHIOS_SIGNED_STAGE_IN_PROGRESS' in text: + if attempt != 0: + raise RuntimeError('unexpected second package interruption') + updates = re.findall(r'PHIOS_SIGNED_UPDATE_OK:(\{[^\r\n]+\})', text) + if len(updates) != 1: + raise RuntimeError('exact successful signed package transaction not observed') + for case in ['missing-signature', 'wrong-key', 'tampered', 'expired', 'replay', 'dependency']: + if 'PHIOS_SIGNED_REFUSAL_OK:' + case not in text: + raise RuntimeError('signed update refusal case missing: ' + case) + receipt['signed_update_transaction'] = json.loads(updates[0]) + receipt['signed_update_refusals_observed'] = True + receipt['interrupted_signed_transaction_observed'] = True + interrupted = True + break + if f'PHIOS_INSTALLED_DISK_OK:{source}' in text: + if signed_update: + if attempt != 1 or 'PHIOS_INTERRUPTED_UPDATE_HELD_OK' not in text: + raise RuntimeError('actual interrupted-stage recovery not observed') + receipt['interrupted_update_active_root_preserved'] = True + elif 'PHIOS_INSTALL_CANCEL_OK' not in text or 'PHIOS_INSTALLED_SEED_OK:' not in text: + raise RuntimeError('production cancellation and data seed not observed') + generations = re.findall(r'PHIOS_OS_CHECKPOINT_OK:([0-9a-f]{32})', text) + if receipt['recovery_requested']: + if len(generations) != 1: + raise RuntimeError('explicit recovery checkpoint not observed') + receipt['recovery_checkpoint_generation'] = generations[0] + if signed_update and generations[0] != receipt['signed_update_transaction']['generation']: + raise RuntimeError('recovery selected a different update checkpoint') + receipt['installed'] = True + return + time.sleep(1) + else: + raise RuntimeError('live install/update qualification timed out') + finally: + if process.poll() is None: + try: + capture_display(qmp, output, name='screen-' + prefix) + except (OSError, ValueError, RuntimeError) as exc: + receipt['display_capture_error'] = str(exc) + stop(process, abrupt=interrupted) + if not receipt['installed'] and not interrupted and serial.exists(): + print('\n'.join(serial.read_text(errors='replace').splitlines()[-160:])) + raise RuntimeError('disposable installed target never qualified') + + +def qualify(iso: Path, source: str, output: Path, *, recovery: bool = False, signed_update: bool = False, fixture_free: bool = False) -> None: + if not re.fullmatch(r"[0-9a-f]{40}", source) or not iso.is_file() or output.exists(): + raise ValueError("exact source/ISO and a new owned evidence destination are required") + if fixture_free and (signed_update or not recovery): + raise ValueError('normal ISO qualification requires recovery; signed fixture transitions use the separate QA lane') + output.mkdir(mode=0o700, parents=True) + code = Path("/usr/share/OVMF/OVMF_CODE_4M.fd") + variables = output / "OVMF_VARS.fd" + shutil.copyfile("/usr/share/OVMF/OVMF_VARS_4M.fd", variables) + disk = output / "target.qcow2" + # There is no caller-supplied device/disk option. Never attach a host block + # device, existing image, network, shared folder or other user's data. + subprocess.run(["qemu-img", "create", "-f", "qcow2", str(disk), "32G"], check=True) + accelerated = os.access("/dev/kvm", os.R_OK | os.W_OK) + accelerator = "kvm" if accelerated else "tcg" + common = ["qemu-system-x86_64", "-machine", f"q35,accel={accelerator}", "-cpu", + "host" if accelerated else "max", "-m", "4096", "-smp", "2", + "-drive", f"if=pflash,format=raw,readonly=on,file={code}", + "-drive", f"if=pflash,format=raw,file={variables}", + "-drive", f"file={disk},if=none,id=target,format=qcow2", + "-device", "virtio-blk-pci,drive=target,serial=PHIOS_CI_BLANK,bootindex=2", + "-nic", "none", '-audiodev', 'none,id=previewaudio', + '-device', 'intel-hda', '-device', 'hda-duplex,audiodev=previewaudio', + "-vga", "none", "-device", "virtio-vga", + "-display", "none", "-monitor", "none"] + if signed_update: + if not recovery: + raise ValueError('signed-update qualification includes matched root/EFI recovery') + common += ['-fw_cfg', 'name=opt/phios-ci-signed-updates,string=enabled'] + digest = hashlib.sha256() + with iso.open("rb") as handle: + for block in iter(lambda: handle.read(1024**2), b""): + digest.update(block) + receipt: dict[str, Any] = {"schema_version": "phios.installed-boot-evidence.v1", "source_commit": source, + "iso_sha256": digest.hexdigest(), "accelerator": accelerator, "disk_serial": "PHIOS_CI_BLANK", + "disk_bytes": 32 * 1024**3, "commands": [], "installed": False, "no_iso_boot_passed": False, + "abrupt_virtual_restart_passed": False, "boot_ids": [], "ci_serial_console_injected": not fixture_free, + 'explicit_serial_console_password_login': fixture_free, 'fixture_free_requested': fixture_free, + 'fixture_free_installed_qualified': False, + "hardware_qualified": False, "release_ready": False, 'recovery_requested': recovery, + 'simulated_boot_failure_observed': False, 'matched_root_efi_restored': False, + 'whole_os_recovery_passed': False, 'signed_package_application_qualified': False} + receipt.update(signed_update_requested=signed_update, signed_update_refusals_observed=False, + interrupted_signed_transaction_observed=False, interrupted_update_active_root_preserved=False) + try: + if fixture_free: + from qemu_normal_live import drive_live + installed = drive_live(common, iso, source, output, receipt, stage='install') + receipt['recovery_checkpoint_generation'] = installed['generation'] + receipt['installed'] = True + else: + install_live(common, iso, output, source, receipt, signed_update=signed_update) + # Boot the new disk twice with no ISO attached, normal password/PAM + # logins and actual greetd keyboard input. Between boots kill QEMU so + # acknowledged data must survive loss of the guest's memory. + for phase in ([1, 2, 3] if recovery else [1, 2]): + qmp = output / f"installed-{phase}-qmp.sock" + serial_socket = output / f"installed-{phase}-serial.sock" + command = common + ["-serial", f"unix:{serial_socket},server=on,wait=off", + "-qmp", f"unix:{qmp},server=on,wait=off"] + receipt["commands"].append(command) + with (output / f"installed-{phase}-qemu.log").open("w") as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 900 + while not serial_socket.exists() and time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError("installed VM exited before serial transport") + time.sleep(0.1) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as channel: + channel.settimeout(1) + channel.connect(str(serial_socket)) + text = "" + with (output / f"installed-{phase}-serial.log").open("wb") as transcript: + def wait_for(pattern: str) -> re.Match[str]: + nonlocal text + while time.monotonic() < deadline: + match = re.search(pattern, text) + if match: + return match + if process.poll() is not None: + raise RuntimeError("installed guest exited during validation") + try: + chunk = channel.recv(65536) + except socket.timeout: + continue + if not chunk: + raise RuntimeError("installed serial transport closed") + transcript.write(chunk) + transcript.flush() + text += chunk.decode(errors="replace") + if "Traceback (most recent call last)" in text: + # A traceback can arrive in several serial + # reads. Preserve its actual exception and + # failing line before stopping the guest. + drain_deadline = time.monotonic() + 3 + while time.monotonic() < drain_deadline: + try: + extra = channel.recv(65536) + except socket.timeout: + continue + if not extra: + break + transcript.write(extra) + transcript.flush() + text += extra.decode(errors="replace") + print("\n".join(text.splitlines()[-40:])) + raise RuntimeError("installed data or session validation failed") + raise RuntimeError("installed password login/qualification timed out") + + wait_for(r"login: ") + channel.sendall(b"operator\n") + wait_for(r"Password:") + channel.sendall((PASSWORD + "\n").encode()) + time.sleep(2) + channel.sendall(b"printf 'PHIOS_LOGIN_OK:%s\\n' \"$(id -u)\"\n") + wait_for(r"PHIOS_LOGIN_OK:1000") + time.sleep(3) + capture_display(qmp, output, name=f"screen-installed-{phase}-greeter") + qmp_request(qmp, {"execute": "send-key", "arguments": {"keys": [ + {"type": "qcode", "data": key} for key in ["ctrl", "alt", "f1"]]}}) + time.sleep(1) + send_text(qmp, "operator") + time.sleep(1) + send_text(qmp, PASSWORD) + program = Path(__file__).with_name("installed_probe.py").read_text() + \ + f"\nprobe({source!r}, {phase}, signed_update={signed_update!r}, desktop_check=desktop_services)\n" + program = Path(__file__).with_name('desktop_probe.py').read_text() + '\n' + \ + program.replace('from __future__ import annotations\n', '') + if Path(__file__).with_name('proof_smoke.py').exists(): + program = Path(__file__).with_name('proof_smoke.py').read_text() + \ + (f'\nproof_workflow({source!r})\n' if phase == 1 else f'\nhistorical_proof({source!r})\n') + \ + program.replace('from __future__ import annotations\n', '') + if fixture_free and phase == 1: + program = Path(__file__).with_name('normal_seed.py').read_text() + '\nseed_normal()\n' + \ + program.replace('from __future__ import annotations\n', '') + # Keep each input line below the terminal's canonical + # line bound; a growing base64 -c command can exceed it. + channel.sendall(("python - <<'PHIOS_INSTALLED_PROBE'\n" + program + + "\nPHIOS_INSTALLED_PROBE\n").encode()) + result = wait_for(r"PHIOS_INSTALLED_CHECK_OK:(\{[^\r\n]+\})") + details = json.loads(result[1]) + if details["source_commit"] != source or details["phase"] != phase: + raise RuntimeError("installed receipt identity mismatch") + if Path(__file__).with_name('proof_smoke.py').exists(): + if phase == 1: + proof_match = re.search(r'PHIOS_LINUX_PROOF_OK:(\{[^\r\n]+\})', text) + if proof_match is None: + raise RuntimeError('actual governed proof receipt missing') + proof = json.loads(proof_match[1]) + if proof['source_commit'] != source or not all(proof[k] is True for k in + ['sudo_password_authentication', 'agent_store_denied', 'agent_broker_denied', + 'cancel_passed', 'replay_refused', 'expiry_refused']): + raise RuntimeError('governed proof refusal/identity evidence missing') + receipt['linux_governed_workflow'] = proof + elif 'PHIOS_LINUX_PROOF_HISTORY_INACTIVE:' not in text: + raise RuntimeError('old-boot proof authority refusal missing') + if phase == (3 if recovery else 2): + receipt['linux_governed_workflow_qualified'] = True + receipt["boot_ids"].append(details["boot_id"]) + receipt["record_sha256"] = details["record_sha256"] + audio = re.search(r'PHIOS_DESKTOP_SERVICES_OK:(\{[^\r\n]+\})', text) + if audio is None: + raise RuntimeError('actual installed audio/network service evidence missing') + receipt.setdefault('desktop_service_boots', []).append(json.loads(audio[1])) + if phase == 1: + def desktop_program(value: str) -> None: + channel.sendall(("python - <<'PHIOS_DESKTOP_PROBE'\n" + value + '\nPHIOS_DESKTOP_PROBE\n').encode()) + receipt['installed_screen_lock'] = qualify_lock(qmp, output, source=source, + password=PASSWORD, label='installed', program=desktop_program, wait=wait_for) + capture_display(qmp, output, name=f"screen-installed-{phase}") + if recovery and phase == 2: + # Test-only administration through normal sudo + # password authentication; never shipped as a + # production effect or a confirmation bypass. + damage = "from pathlib import Path; import os; " + \ + "[Path('/boot/'+p).write_bytes(b'intentional CI boot corruption') for p in " + \ + "['initramfs-linux.img','initramfs-linux-fallback.img']]; " + \ + "Path('/usr/bin/wayfire').rename('/usr/bin/wayfire.failed-ci'); " + \ + "os.sync(); print('PHIOS_OS_DAMAGE_OK:'+str(os.geteuid()),flush=True)" + channel.sendall((f"printf '%s\\n' '{PASSWORD}' | sudo -S python -c \"{damage}\"\n").encode()) + wait_for(r'PHIOS_OS_DAMAGE_OK:0') + finally: + if process.poll() is None and not (output / f"screen-installed-{phase}.ppm").exists(): + try: + capture_display(qmp, output, name=f"screen-installed-{phase}-failure") + except (OSError, ValueError, RuntimeError): + pass + stop(process, abrupt=(phase == 1)) + if recovery and phase == 2: + failed_boot(common, output, receipt) + if fixture_free: + restored = drive_live(common, iso, source, output, receipt, stage='restore', + generation=receipt['recovery_checkpoint_generation']) + if restored['generation'] != receipt['recovery_checkpoint_generation']: + raise RuntimeError('normal recovery restored a different checkpoint') + receipt['matched_root_efi_restored'] = True + else: + recover_live(common, iso, output, receipt) + if len(set(receipt["boot_ids"])) != (3 if recovery else 2): + raise RuntimeError("a distinct installed reboot was not observed") + receipt["no_iso_boot_passed"] = True + receipt["abrupt_virtual_restart_passed"] = True + if recovery: + receipt['whole_os_recovery_passed'] = (receipt['simulated_boot_failure_observed'] and + receipt['matched_root_efi_restored']) + if signed_update: + receipt['signed_package_application_qualified'] = (receipt['whole_os_recovery_passed'] and + receipt['signed_update_refusals_observed'] and receipt['interrupted_signed_transaction_observed'] and + receipt['interrupted_update_active_root_preserved']) + if fixture_free: + receipt['fixture_free_installed_qualified'] = (receipt['whole_os_recovery_passed'] and + receipt.get('linux_governed_workflow_qualified') is True and len(set(receipt['boot_ids'])) == 3) + print("Disposable installation, no-ISO graphical login, data restore and abrupt virtual restart passed") + except BaseException as exc: + receipt["error"] = str(exc) + raise + finally: + (output / "installed-evidence.json").write_text(json.dumps(receipt, indent=2) + "\n") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--iso", required=True, type=Path) + parser.add_argument("--source", required=True) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument('--recovery', action='store_true', help='Also damage and recover only this disposable installed disk') + parser.add_argument('--signed-update', action='store_true', help='Also qualify signed packages and actual interrupted staging') + parser.add_argument('--fixture-free', action='store_true', help='Install/recover the unmodified normal ISO using its limited live sudo and explicitly reviewed serial-console login') + args = parser.parse_args() + qualify(args.iso, args.source, args.output.resolve(), recovery=args.recovery, signed_update=args.signed_update, fixture_free=args.fixture_free) diff --git a/packaging/linux/tests/qemu_normal_live.py b/packaging/linux/tests/qemu_normal_live.py new file mode 100644 index 00000000..7958b378 --- /dev/null +++ b/packaging/linux/tests/qemu_normal_live.py @@ -0,0 +1,91 @@ +"""Drive the unmodified normal ISO via real public-user PAM and narrow sudo.""" +from __future__ import annotations + +import json +import re +import socket +import subprocess +import time +from pathlib import Path +from typing import Any + +from qemu_boot import capture_display + + +def drive_live(common: list[str], iso: Path, source: str, output: Path, receipt: dict[str, Any], + *, stage: str, generation: str | None = None) -> dict[str, Any]: + prefix = 'normal-' + stage + '-live' + qmp, serial = output / (prefix + '-qmp.sock'), output / (prefix + '-serial.sock') + command = common + ['-drive', f'file={iso.resolve()},if=none,id=installation,format=raw,media=cdrom,readonly=on', + '-device', 'ide-cd,drive=installation,bootindex=1', '-serial', f'unix:{serial},server=on,wait=off', + '-qmp', f'unix:{qmp},server=on,wait=off'] + receipt['commands'].append(command) + with (output / (prefix + '-qemu.log')).open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 1800 + while not serial.exists() and time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError('normal live VM exited before transport') + time.sleep(0.1) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as channel: + channel.settimeout(1) + channel.connect(str(serial)) + text = '' + with (output / (prefix + '-serial.log')).open('wb') as transcript: + def wait(pattern: str) -> re.Match[str]: + nonlocal text + while time.monotonic() < deadline: + match = re.search(pattern, text) + if match: + return match + if process.poll() is not None: + raise RuntimeError('normal live maintenance VM exited') + try: + data = channel.recv(65536) + except socket.timeout: + continue + if not data: + raise RuntimeError('normal live channel closed') + transcript.write(data) + transcript.flush() + text += data.decode(errors='replace') + if 'Traceback (most recent call last)' in text: + drain = time.monotonic() + 3 + while time.monotonic() < drain: + try: + tail = channel.recv(65536) + except socket.timeout: + continue + if not tail: + break + transcript.write(tail) + transcript.flush() + raise RuntimeError('normal-user maintenance failed; preserve serial evidence') + raise RuntimeError('normal live PAM/maintenance timed out') + wait(r'login: ') + channel.sendall(b'phios\n') + wait(r'Password:') + channel.sendall(b'phios\n') + time.sleep(2) + text = '' + program = Path(__file__).with_name('normal_live_probe.py').read_text() + f'\ndrive({stage!r},{source!r},{generation!r})\n' + if max(map(len, program.splitlines())) >= 4096: + raise ValueError('guest program exceeds canonical terminal line bound') + channel.sendall(("python - <<'PHIOS_NORMAL_MAINTENANCE'\n" + program + '\nPHIOS_NORMAL_MAINTENANCE\n').encode()) + result = json.loads(wait(r'PHIOS_NORMAL_MAINTENANCE_OK:(\{[^\r\n]+\})')[1]) + if (result['source_commit'] != source or result['stage'] != stage or result['uid'] != 1000 + or result['fixture_free'] is not True or result['limited_live_sudo'] is not True): + raise RuntimeError('normal maintenance identity/evidence mismatch') + return result + finally: + if process.poll() is None: + try: + capture_display(qmp, output, name='screen-' + prefix) + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + process.kill() + process.wait() diff --git a/packaging/linux/tests/qemu_preview.py b/packaging/linux/tests/qemu_preview.py new file mode 100644 index 00000000..22db233e --- /dev/null +++ b/packaging/linux/tests/qemu_preview.py @@ -0,0 +1,235 @@ +"""Qualify an unmodified fixture-free ISO through normal PAM and user commands.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import socket +import subprocess +import time +from pathlib import Path +from typing import Any + +from qemu_boot import capture_display, enter_live_login, qmp_request +from qemu_install import stop +from qemu_desktop import qualify_lock + +PROBE = ''' +import json,os,subprocess,time,urllib.request +from pathlib import Path +assert os.getuid()==1000 +assert Path('/usr/share/phios/source-commit').read_text().strip()==SOURCE +assert Path('/sys/firmware/efi').is_dir() +assert Path('/run/archiso/bootmnt').is_dir() +assert not list(Path('/usr/local/bin').glob('phios-live-*-smoke*')) +assert not Path('/usr/local/bin/phios-live-smoke').exists() +assert not Path('/etc/systemd/system/phios-live-smoke.service').exists() +assert not Path('/etc/phios/os-update-trust.json').exists() +assert not Path('/etc/phios/os-update-keyring.gpg').exists() +assert not Path('/usr/share/phios-ci-update').exists() +assert Path.home().stat().st_mode&0o777==0o700 +assert (Path.home()/'.local/state/phios').stat().st_mode&0o777==0o700 +assert 'wheel' not in subprocess.check_output(['id','-nG'],text=True).split() +for _ in range(90): + try: + with urllib.request.urlopen('http://127.0.0.1:3969/api/v1/health',timeout=2) as response: + assert response.status==200 + if any(subprocess.run(['pgrep','-u','1000','-x',name],capture_output=True).returncode for name in ['wayfire','chromium']): + time.sleep(1);continue + subprocess.run(['systemctl','--user','is-active','phios-observer.service','phios-browser.service'],check=True) + break + except (OSError,subprocess.CalledProcessError): + time.sleep(1) +else: + raise RuntimeError('complete supervised desktop did not become ready') +with urllib.request.urlopen('http://127.0.0.1:3969/',timeout=3) as response: + assert b'
' in response.read() +with urllib.request.urlopen('http://127.0.0.1:3969/api/v1/package-observation',timeout=3) as response: + value=json.load(response)['observation'] + assert value['adapter']=='arch-pacman-local' and value['availability']=='available' + assert value['executionAuthority'] is False and value['effectPerformed'] is False +for pid in subprocess.check_output(['pgrep','-u','1000','-x','chromium'],text=True).split(): + assert b'--no-sandbox' not in Path('/proc/'+pid+'/cmdline').read_bytes().split(b'\\0') +boot=Path('/proc/sys/kernel/random/boot_id').read_text().strip().replace('-','') +print('PHIOS_PREVIEW_OK:'+json.dumps({'source_commit':SOURCE,'boot_id':boot,'stage':STAGE,'uid':os.getuid(),'fixture_free':True}),flush=True) +''' + +LIFECYCLE = ''' +import json,os,subprocess,time,urllib.request +from pathlib import Path +args=['systemctl','--user'] +def pid(): + return subprocess.check_output(args+['show','phios-observer.service','--property=MainPID','--value'],text=True).strip() +previous=pid() +assert previous.isdigit() and int(previous)>0 +subprocess.run(args+['kill','--signal=KILL','phios-observer.service'],check=True) +for _ in range(60): + current=pid() + try: + with urllib.request.urlopen('http://127.0.0.1:3969/api/v1/health',timeout=2) as response: + if current!=previous and int(current)>0 and response.status==200: break + except OSError: + pass + time.sleep(1) +else: + raise RuntimeError('observer restart failed') +subprocess.run(['pkill','-TERM','-u',str(os.getuid()),'-x','wayfire'],check=True) +units=['phios-session.target','phios-observer.service','phios-browser.service','phios-waybar.service', + 'phios-curiosity-reader.service','phios-history-reader.service','phios-policykit.service','phios-audio.target', + 'pipewire.service','pipewire-pulse.service','wireplumber.service','pipewire.socket','pipewire-pulse.socket'] +for _ in range(30): + states={unit:subprocess.check_output(args+['show',unit,'--property=ActiveState','--value'],text=True).strip() + for unit in units} + try: + urllib.request.urlopen('http://127.0.0.1:3969/api/v1/health',timeout=2).close() + reachable=True + except OSError: + reachable=False + if all(state=='inactive' for state in states.values()) and not reachable: break + time.sleep(1) +else: + raise RuntimeError('logout did not stop the supervised session: '+json.dumps(states)) +boot=Path('/proc/sys/kernel/random/boot_id').read_text().strip().replace('-','') +print('PHIOS_PREVIEW_LOGOUT_OK:'+json.dumps({'boot_id':boot,'old_observer_pid':previous,'new_observer_pid':current, + 'all_session_units_inactive':True,'stopped_session_units':units}),flush=True) +''' + + +def qualify(iso: Path, source: str, output: Path) -> None: + if not re.fullmatch(r'[0-9a-f]{40}', source) or not iso.is_file() or output.exists(): + raise ValueError('exact ISO/source and fresh evidence directory required') + output.mkdir(parents=True, mode=0o700) + variables = output / 'OVMF_VARS.fd' + shutil.copyfile('/usr/share/OVMF/OVMF_VARS_4M.fd', variables) + accelerator = 'kvm' if os.access('/dev/kvm', os.R_OK | os.W_OK) else 'tcg' + qmp, serial = output / 'qmp.sock', output / 'serial.sock' + command = ['qemu-system-x86_64', '-machine', 'q35,accel=' + accelerator, '-cpu', + 'host' if accelerator == 'kvm' else 'max', '-m', '4096', '-smp', '2', + '-drive', 'if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd', + '-drive', 'if=pflash,format=raw,file=' + str(variables), '-cdrom', str(iso.resolve()), '-boot', 'd', + '-netdev', 'user,id=previewnet,restrict=on,net=192.0.2.0/24,dhcpstart=192.0.2.15,dns=192.0.2.3,host=192.0.2.2', + '-device', 'virtio-net-pci,netdev=previewnet', '-audiodev', 'none,id=previewaudio', + '-device', 'intel-hda', '-device', 'hda-duplex,audiodev=previewaudio', + '-vga', 'none', '-device', 'virtio-vga', '-display', 'none', '-monitor', 'none', + '-serial', f'unix:{serial},server=on,wait=off', '-qmp', f'unix:{qmp},server=on,wait=off'] + with iso.open('rb') as handle: + iso_hash = hashlib.file_digest(handle, 'sha256').hexdigest() + receipt: dict[str, Any] = {'schema_version': 'phios.fixture-free-live-evidence.v1', 'source_commit': source, + 'iso_sha256': iso_hash, 'command': command, 'accelerator': accelerator, 'boots': [], + 'fixture_free_qualified': False, 'hardware_qualified': False, 'release_ready': False, + 'public_volatile_credentials': True, 'test_code_injected_into_image': False, + 'restricted_virtual_ethernet': True, 'external_network_forwarding': False, 'host_audio_attached': False} + with (output / 'qemu.log').open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + (900 if accelerator == 'kvm' else 1800) + while not serial.exists() and time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError('VM exited before normal serial transport') + time.sleep(0.1) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as channel: + channel.settimeout(1) + channel.connect(str(serial)) + text = '' + with (output / 'serial.log').open('wb') as transcript: + def wait(pattern: str) -> re.Match[str]: + nonlocal text + while time.monotonic() < deadline: + match = re.search(pattern, text) + if match: + return match + if process.poll() is not None: + raise RuntimeError('VM exited during normal user qualification') + try: + data = channel.recv(65536) + except socket.timeout: + continue + if not data: + raise RuntimeError('normal serial channel closed') + transcript.write(data) + transcript.flush() + text += data.decode(errors='replace') + if 'Traceback (most recent call last)' in text: + # Preserve the actual guest exception before shutting down. + drain_until = time.monotonic() + 3 + while time.monotonic() < drain_until: + try: + tail = channel.recv(65536) + except socket.timeout: + continue + if not tail: + break + transcript.write(tail) + transcript.flush() + raise RuntimeError('normal-user preview probe failed; see preserved serial log') + raise RuntimeError('normal PAM/desktop qualification timed out') + + def program(value: str) -> None: + if max(map(len, value.splitlines()), default=0) >= 4096: + raise ValueError('guest program exceeds canonical terminal line bound') + channel.sendall(("PYTHON_COLORS=0 python -u - <<'PHIOS_NORMAL_PROBE'\n" + value + '\nPHIOS_NORMAL_PROBE\n').encode()) + + for boot in [1, 2]: + wait(r'login: ') + channel.sendall(b'phios\n') + wait(r'Password:') + channel.sendall(b'phios\n') + time.sleep(2) + text = '' + desktop = Path(__file__).with_name('desktop_probe.py').read_text().replace('from __future__ import annotations\n', '') + program(f'SOURCE={source!r}\nSTAGE="first"\n' + desktop + f'\ndesktop_services({source!r}, wired=True)\n' + PROBE) + first = json.loads(wait(r'PHIOS_PREVIEW_OK:(\{[^\r\n]+\})')[1]) + assert first['source_commit'] == source and first['stage'] == 'first' + desktop_result = json.loads(wait(r'PHIOS_DESKTOP_SERVICES_OK:(\{[^\r\n]+\})')[1]) + desktop_result.update({'boot_id': first['boot_id'], 'stage': 'first'}) + receipt.setdefault('desktop_service_boots', []).append(desktop_result) + time.sleep(2) + capture_display(qmp, output, name=f'screen-{boot}-first') + receipt.setdefault('screen_lock_boots', []).append(qualify_lock(qmp, output, source=source, + password='phios', label=f'live-{boot}', program=program, wait=wait)) + text = '' + program(LIFECYCLE) + lifecycle = json.loads(wait(r'PHIOS_PREVIEW_LOGOUT_OK:(\{[^\r\n]+\})')[1]) + assert lifecycle['boot_id'] == first['boot_id'] + enter_live_login(qmp) + text = '' + program(f'SOURCE={source!r}\nSTAGE="reauthenticated"\n' + desktop + f'\ndesktop_services({source!r}, wired=True)\n' + PROBE) + second = json.loads(wait(r'PHIOS_PREVIEW_OK:(\{[^\r\n]+\})')[1]) + assert second['boot_id'] == first['boot_id'] and second['stage'] == 'reauthenticated' + restarted_desktop = json.loads(wait(r'PHIOS_DESKTOP_SERVICES_OK:(\{[^\r\n]+\})')[1]) + restarted_desktop.update({'boot_id': second['boot_id'], 'stage': 'reauthenticated'}) + receipt['desktop_service_boots'].append(restarted_desktop) + time.sleep(2) + capture_display(qmp, output, name=f'screen-{boot}-reauthenticated') + receipt['boots'].append({'first': first, 'lifecycle': lifecycle, 'reauthenticated': second}) + if boot == 1: + qmp_request(qmp, {'execute': 'system_reset'}) + text = '' + deadline = time.monotonic() + (900 if accelerator == 'kvm' else 1800) + if len({boot['first']['boot_id'] for boot in receipt['boots']}) != 2: + raise RuntimeError('second distinct boot not observed') + receipt['fixture_free_qualified'] = True + except BaseException as exc: + receipt['error'] = str(exc) + raise + finally: + if process.poll() is None: + try: + capture_display(qmp, output) + except (OSError, ValueError, RuntimeError) as exc: + receipt['display_capture_error'] = str(exc) + stop(process) + (output / 'preview-evidence.json').write_text(json.dumps(receipt, indent=2) + '\n') + print('Fixture-free UEFI image passed two PAM/graphical/session-lifecycle boots: ' + iso_hash) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--iso', required=True, type=Path) + parser.add_argument('--source', required=True) + parser.add_argument('--output', required=True, type=Path) + args = parser.parse_args() + qualify(args.iso, args.source, args.output.resolve()) diff --git a/packaging/linux/tests/update_smoke.py b/packaging/linux/tests/update_smoke.py new file mode 100644 index 00000000..9be12fd0 --- /dev/null +++ b/packaging/linux/tests/update_smoke.py @@ -0,0 +1,278 @@ +"""CI-only signed package and interrupted-staging qualification fixture. + +Never included in normal images. Private signing keys exist only in the live +VM's volatile /run. Only the named, fresh 32-GiB disposable target is supported. +""" +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import shutil +import subprocess +import tempfile +from contextlib import contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Iterator + +spec = importlib.util.spec_from_file_location('phios_ci_installer', '/usr/local/bin/phios-live-install-smoke.py') +assert spec is not None and spec.loader is not None +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) +spec = importlib.util.spec_from_file_location('phios_ci_application', '/usr/lib/phios-updates/apply.py') +assert spec is not None and spec.loader is not None +apply = importlib.util.module_from_spec(spec) +spec.loader.exec_module(apply) + +PLAN = '@snapshots/phios-ci-qualification.json' +PACKAGE = 'phios-ci-update' +FILE = 'usr/share/' + PACKAGE + '/verified.txt' +CONTENT = b'authenticated disposable PhiOS package update\n' + + +def command(*args: str, **kwargs: Any) -> str: + try: + return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT, **kwargs) + except subprocess.CalledProcessError as exc: + print((exc.output or '')[-6000:], flush=True) + raise + + +@contextmanager +def disk(*, writable: bool = False) -> Iterator[tuple[Path, Path]]: + identity = apply.recover.inventory('/dev/vda') + if identity['serial_or_wwn'] != 'PHIOS_CI_BLANK' or identity['size_bytes'] != 32 * 1024**3: + raise ValueError('signed-update fixture requires its exact disposable disk') + with apply.recover.mounted(identity, writable=writable) as pair: + yield pair + + +def state(top: Path, esp: Path) -> dict[str, Any]: + root = top / '@root' + source = (root / 'usr/share/phios/source-commit').read_text().strip() + return {'source_commit': source, 'packages': apply.packages(root), 'sequence': apply.sequence(top, source), + 'boot_files': apply.recover.boot_inventory(esp)} + + +def signer(base: Path, label: str) -> tuple[Path, str, bytes]: + home = base / label + home.mkdir(mode=0o700) + command('gpg', '--no-options', '--homedir', str(home), '--batch', '--pinentry-mode', 'loopback', + '--passphrase', '', '--quick-generate-key', 'PhiOS Disposable ' + label + ' ', + 'ed25519', 'sign', '1d') + listing = command('gpg', '--no-options', '--homedir', str(home), '--with-colons', '--list-keys') + fingerprint = next(row.split(':')[9] for row in listing.splitlines() if row.startswith('fpr:')) + public = subprocess.check_output(['gpg', '--no-options', '--homedir', str(home), '--export', fingerprint]) + return home, fingerprint, public + + +def sign(home: Path, path: Path) -> None: + command('gpg', '--no-options', '--homedir', str(home), '--batch', '--yes', '--pinentry-mode', 'loopback', + '--passphrase', '', '--detach-sign', str(path)) + + +def package(base: Path, name: str, *, missing_dependency: bool = False, interrupt: bool = False) -> Path: + # Use Arch's actual package builder, including PKGINFO, BUILDINFO and MTREE. + # Only this CI profile adds fakeroot. There are no network dependencies. + work = Path(tempfile.mkdtemp(prefix='phios-ci-package-', dir='/home/phios')) + try: + work.chmod(0o700) + (work / 'data').write_bytes(CONTENT) + shutil.copyfile('/usr/share/licenses/phios/LICENSE', work / 'LICENSE') + build = "pkgname=" + name + "\npkgver=1.0.0\npkgrel=1\narch=('any')\n" + \ + "pkgdesc='Disposable PhiOS qualification package'\nlicense=('MIT')\noptions=('!strip' '!debug')\n" + build += "source=('data' 'LICENSE')\nsha256sums=(" + ' '.join( + "'" + hashlib.sha256((work / source).read_bytes()).hexdigest() + "'" for source in ['data', 'LICENSE']) + ')\n' + if missing_dependency: + build += "depends=('phios-ci-never-exists=999')\n" + if interrupt: + build += "install=interrupt.install\n" + (work / 'interrupt.install').write_text('post_install() {\n' + " printf 'staged pacman hook reached\\n' > /.phios-ci-stage-in-progress\n" + ' /usr/bin/sync\n /usr/bin/touch /run/phios-ci-signed-hook-ready\n /usr/bin/sleep 600\n}\n') + build += 'package() {\n install -Dm644 data "$pkgdir/usr/share/$pkgname/verified.txt"\n' + \ + ' install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"\n}\n' + (work / 'PKGBUILD').write_text(build) + for path in [work, *work.iterdir()]: + os.chown(path, 1000, 1000) + command('runuser', '-u', 'phios', '--', 'bash', '-c', + 'cd "$1"; exec makepkg --nodeps --force --noconfirm', 'phios-ci-build', str(work), timeout=120) + archives = [path for path in work.glob('*.pkg.tar.*') if not path.name.endswith('.sig')] + if len(archives) != 1: + raise ValueError('actual makepkg output must be exactly one archive') + target = base / archives[0].name + shutil.copyfile(archives[0], target) + return target + finally: + shutil.rmtree(work) + + +def bundle(base: Path, name: str, current: dict[str, Any], key: tuple[Path, str, bytes], + *, missing_dependency: bool = False, interrupt: bool = False) -> Path: + destination = base / ('bundle-' + name) + destination.mkdir(mode=0o700) + archive = package(destination, name, missing_dependency=missing_dependency, interrupt=interrupt) + now = datetime.now(UTC) + payload = {'schema_version': 'phios.os-package-update.v1', 'channel': 'experimental', 'architecture': 'x86_64', + 'from_source_commit': current['source_commit'], 'source_commit': current['source_commit'], + 'base_sequence': current['sequence'], 'sequence': current['sequence'] + 1, + 'created_at': now.isoformat(), 'expires_at': (now + timedelta(days=1)).isoformat(), + 'arch_snapshot': '2026/09/30', 'state_schemas': dict(apply.verify.SCHEMAS), + 'base_packages': current['packages'], 'target_packages': sorted([*current['packages'], + {'name': name, 'version': '1.0.0-1'}], key=lambda row: row['name']), + 'packages': [{'name': name, 'version': '1.0.0-1', 'filename': archive.name, + 'sha256': hashlib.sha256(archive.read_bytes()).hexdigest(), 'size': archive.stat().st_size}]} + manifest = destination / 'manifest.json' + manifest.write_text(json.dumps(payload, sort_keys=True)) + sign(key[0], manifest) + sign(key[0], archive) + return destination + + +def initial() -> None: + with tempfile.TemporaryDirectory(prefix='phios-ci-signing-', dir='/run') as temporary: + base = Path(temporary) + accepted, wrong = signer(base, 'accepted'), signer(base, 'untrusted') + try: + # Test-only manual enrollment into the volatile live environment; + # no trust or private key was shipped by the production image. + exported = base / 'enrollment-public-key.gpg' + exported.write_bytes(accepted[2]) + exported.chmod(0o600) + installer.drive_installer(cancel=True, enroll=(exported, accepted[1])) + if apply.verify.TRUST.exists() or apply.verify.KEYRING.exists(): + raise ValueError('cancelled enrollment changed signing trust') + installer.drive_installer(cancel=False, enroll=(exported, accepted[1])) + policy, _public = apply.verify.load_trust() + if policy['primary_fingerprint'] != accepted[1]: + raise ValueError('production enrollment did not retain the authenticated fingerprint') + print('PHIOS_SIGNING_ENROLLMENT_OK', flush=True) + with disk() as (top, esp): + before = state(top, esp) + valid = bundle(base, PACKAGE, before, accepted) + for case in ['missing-signature', 'wrong-key', 'tampered', 'expired']: + invalid = base / case + shutil.copytree(valid, invalid) + manifest = invalid / 'manifest.json' + payload = json.loads(manifest.read_text()) + archive = invalid / payload['packages'][0]['filename'] + if case == 'missing-signature': + (invalid / (archive.name + '.sig')).unlink() + elif case == 'wrong-key': + sign(wrong[0], manifest) + sign(wrong[0], archive) + elif case == 'tampered': + data = bytearray(archive.read_bytes()) + data[-1] ^= 1 + archive.write_bytes(data) + else: + payload.update(created_at=(datetime.now(UTC) - timedelta(days=1)).isoformat(), + expires_at=(datetime.now(UTC) - timedelta(hours=1)).isoformat()) + manifest.write_text(json.dumps(payload, sort_keys=True)) + sign(accepted[0], manifest) + result = installer.drive_installer(cancel=False, update=invalid, reject=True, plan=True) + if 'OS update held:' not in result: + raise ValueError('invalid signed bundle did not fail at the production update boundary') + with disk() as (top, esp): + if state(top, esp) != before: + raise ValueError('rejected bundle changed active root or EFI') + print('PHIOS_SIGNED_REFUSAL_OK:' + case, flush=True) + installer.drive_installer(cancel=True, update=valid) + with disk() as (top, esp): + if state(top, esp) != before: + raise ValueError('cancelled signed update changed the active system') + result = installer.drive_installer(cancel=False, update=valid) + with disk() as (top, esp): + current = state(top, esp) + if current['sequence'] != 1 or (top / '@root' / FILE).read_bytes() != CONTENT: + raise ValueError('signed package or persistent generation was not actually installed') + expected = sorted([*before['packages'], {'name': PACKAGE, 'version': '1.0.0-1'}], key=lambda row: row['name']) + if current['packages'] != expected: + raise ValueError('actual installed inventory differs from the signed complete target') + matches = [path for path in (top / '@snapshots/recovery').glob('*/update-transaction.json') + if json.loads(path.read_text()).get('activated') is True] + if len(matches) != 1: + raise ValueError('exactly one successful update transaction required') + generation = matches[0].parent.name + installer.drive_installer(cancel=False, update=valid, reject=True, plan=True) + with disk() as (top, esp): + if state(top, esp) != current: + raise ValueError('replayed transition changed the active system') + print('PHIOS_SIGNED_REFUSAL_OK:replay', flush=True) + bad = bundle(base, 'phios-ci-bad-dependency', current, accepted, missing_dependency=True) + result = installer.drive_installer(cancel=False, update=bad, reject=True) + if 'phios-ci-never-exists' not in result or 'OS update held:' not in result: + raise ValueError('missing dependency did not fail through actual pacman') + with disk() as (top, esp): + if state(top, esp) != current: + raise ValueError('failed staged dependency transaction changed active root or EFI') + print('PHIOS_SIGNED_REFUSAL_OK:dependency', flush=True) + interrupted = bundle(base, 'phios-ci-interrupt', current, accepted, interrupt=True) + manifest_hash = hashlib.sha256((interrupted / 'manifest.json').read_bytes()).hexdigest() + with disk(writable=True) as (top, _esp): + apply.recover.write_json(top / PLAN, {'schema_version': 'phios.disposable-update-qualification.v1', + 'stage': 'awaiting actual VM interruption', 'restore_generation': generation, + 'before_interruption': current, 'interrupted_manifest_sha256': manifest_hash}) + command('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + print('PHIOS_SIGNED_UPDATE_OK:' + json.dumps({'generation': generation, 'sequence': 1, + 'signer': accepted[1], 'ephemeral_test_key': True}), flush=True) + # The host kills this VM only after the actual pacman post_install + # hook has written and synced its marker inside the staged root. + installer.drive_installer(cancel=False, update=interrupted, interrupt=True) + raise RuntimeError('host did not interrupt the actual staged package transaction') + finally: + for key in [accepted, wrong]: + subprocess.run(['gpgconf', '--homedir', str(key[0]), '--kill', 'all'], capture_output=True, timeout=15) + + +def resume_or_restore() -> None: + with disk() as (top, esp): + plan = json.loads(apply.recover.regular(top / PLAN)) + if plan.get('schema_version') != 'phios.disposable-update-qualification.v1': + raise ValueError('unsupported disposable fixture state') + generation = plan['restore_generation'] + if plan['stage'] == 'awaiting actual VM interruption': + if state(top, esp) != plan['before_interruption'] or (top / '@root/usr/share/phios-ci-interrupt/verified.txt').exists(): + raise ValueError('interrupted staging changed the active installed system') + journals = [path for path in (top / '@snapshots/recovery').glob('*/update-transaction.json') + if json.loads(path.read_text()).get('manifest_sha256') == plan['interrupted_manifest_sha256']] + if len(journals) != 1: + raise ValueError('interrupted transaction journal missing or ambiguous') + journal = json.loads(journals[0].read_text()) + marker = top / journal['staged_root'] / '.phios-ci-stage-in-progress' + if journal['activated'] is not False or not marker.is_file() or 'installing signed packages' not in journal['stage']: + raise ValueError('interruption was not during actual staged pacman execution') + source = plan['before_interruption']['source_commit'] + resumed = True + elif plan['stage'] == 'ready for deliberate boot failure and recovery': + resumed = False + else: + raise ValueError('unexpected disposable fixture stage') + if resumed: + with disk(writable=True) as (top, _esp): + plan['stage'] = 'ready for deliberate boot failure and recovery' + apply.recover.write_json(top / PLAN, plan) + command('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + print('PHIOS_INTERRUPTED_UPDATE_HELD_OK', flush=True) + print('PHIOS_OS_CHECKPOINT_OK:' + generation, flush=True) + print('PHIOS_INSTALLED_DISK_OK:' + source, flush=True) + return + installer.drive_installer(cancel=True, recovery=['restore', '--generation', generation]) + print('PHIOS_OS_RESTORE_CANCEL_OK', flush=True) + installer.drive_installer(cancel=False, recovery=['restore', '--generation', generation]) + with disk() as (top, _esp): + source = (top / '@root/usr/share/phios/source-commit').read_text().strip() + if apply.sequence(top, source) != 2 or (top / '@root' / FILE).exists(): + raise ValueError('recovery did not remove the added package and advance the independent counter') + if (top / '@root/etc/phios/os-update-keyring.gpg').exists() or (top / '@root/etc/phios/os-update-trust.json').exists(): + raise ValueError('rolled-back signing trust remained active') + print('PHIOS_SIGNED_UPDATE_RECOVERY_OK', flush=True) + print('PHIOS_OS_RESTORE_OK:' + generation, flush=True) + + +if __name__ == '__main__': + raise RuntimeError('fixture is invoked only by the exact disposable installer fixture') diff --git a/packaging/linux/updates/apply.py b/packaging/linux/updates/apply.py new file mode 100644 index 00000000..057f4e2b --- /dev/null +++ b/packaging/linux/updates/apply.py @@ -0,0 +1,245 @@ +"""Apply a pinned signed offline transition to a staged experimental OS root.""" +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import os +import shutil +import subprocess +import sys +import uuid +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + + +def sibling(name: str) -> Any: + # Isolated Python does not import the script directory. Load only these + # fixed, packaged root-owned siblings, never a caller-provided module. + spec = importlib.util.spec_from_file_location('phios_os_' + name, Path(__file__).with_name(name + '.py')) + if spec is None or spec.loader is None: + raise ValueError('packaged OS maintenance module missing') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +recover, verify = sibling('recover'), sibling('verify') + + +def packages(root: Path) -> list[dict[str, str]]: + for name in ['var', 'var/lib', 'var/lib/pacman', 'var/lib/pacman/local']: + recover.safe_directory(root / name) + text = recover.run('pacman', '--dbpath', str(root / 'var/lib/pacman'), '-Q') + rows = [dict(zip(['name', 'version'], line.split(), strict=True)) for line in text.splitlines()] + verify.inventory(rows) + return rows + + +def sequence(top: Path, source: str) -> int: + value = recover.generation_record(top / '@root/var/lib/phios/os-update-generation.json', 'phios.os-update-generation.v1') + anchor = recover.generation_record(top / '@snapshots/os-update-counter.json', 'phios.os-update-counter.v1') + if value is None and anchor is None: + return 0 + if (value is None or anchor is None or value['source_commit'] != source or anchor['source_commit'] != source or + value['sequence'] != anchor['sequence']): + raise ValueError('root and independent update counter differ; use explicit live recovery') + return value['sequence'] + + +def generated_file(root: Path, relative: str, data: bytes, *, mode: int = 0o600) -> None: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + recover.safe_directory(path.parent) + if path.is_symlink(): + path.unlink() + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, mode) + with os.fdopen(fd, 'wb') as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + path.chmod(mode) + + +def supported_versions(payload: dict[str, Any], baseline: list[dict[str, str]]) -> None: + before = verify.inventory(baseline) + for row in payload['packages']: + if row['name'] in before and int(recover.run('vercmp', row['version'], before[row['name']]).strip()) < 0: + raise ValueError('package downgrades require explicit OS recovery, not update') + + +def execute(plan: dict[str, Any], payload: dict[str, Any], private: Path, + trust: tuple[dict[str, Any], bytes]) -> dict[str, Any]: + identity, generation = plan['disk'], plan['checkpoint_generation'] + # Recheck key enrollment and validity after terminal review; keep using the + # captured, signature-verified package bytes, never reread the supplied bundle. + if verify.load_trust() != trust: + raise ValueError('signing trust changed after review') + verify.validate_manifest(payload, source=plan['installed']['source_commit'], sequence=plan['base_sequence'], + installed=plan['base_packages'], now=datetime.now(UTC)) + for row in payload['packages']: + verify.verify_signature(private / 'gnupg', private / (row['filename'] + '.sig'), private / row['filename'], + trust[0]['primary_fingerprint'], now=datetime.now(UTC)) + supported_versions(payload, plan['base_packages']) + recover.execute(identity, 'checkpoint', generation, {'installed': plan['installed'], 'boot_files': plan['boot_files']}) + with recover.mounted(identity, writable=True) as (top, esp): + current = recover.installed(top, identity) + if (current != plan['installed'] or packages(top / '@root') != plan['base_packages'] or + sequence(top, current['source_commit']) != plan['base_sequence'] or + recover.boot_inventory(esp) != plan['boot_files']): + raise ValueError('installed source, inventory, generation or boot files changed after review') + recover.ensure_no_active_authority(top, current['install_receipt']['plan']['username']) + folder = top / '@snapshots/recovery' / generation + journal = {'schema_version': 'phios.os-package-update-transaction.v1', 'generation': generation, + 'manifest_sha256': plan['manifest_sha256'], 'source_commit': payload['source_commit'], + 'sequence': payload['sequence'], 'stage': 'preparing staged root', 'activated': False, + 'atomic': False, 'authority_restored': False, 'release_ready': False} + token = uuid.uuid4().hex + staged, previous = top / ('@update-' + token), top / ('@previous-' + token) + journal.update(staged_root=staged.name, previous_root=previous.name) + recover.write_json(folder / 'update-transaction.json', journal) + staged_mounted = False + try: + recover.run('btrfs', 'subvolume', 'snapshot', str(top / '@root'), str(staged)) + # arch-chroot/mkinitcpio need the staged root to be an actual + # mountpoint so root filesystem detection sees Btrfs correctly. + recover.run('mount', '--bind', str(staged), str(staged)) + staged_mounted = True + inputs = staged / '.phios-update-inputs' + inputs.mkdir(mode=0o700) + (inputs / 'cache').mkdir(mode=0o700) + (inputs / 'gnupg').mkdir(mode=0o700) + generated_file(inputs, 'public-keys.gpg', trust[1]) + generated_file(inputs, 'ownertrust.txt', (trust[0]['primary_fingerprint'] + ':6:\n').encode()) + generated_file(inputs, 'gnupg/gpg.conf', b'no-auto-key-retrieve\nauto-key-locate clear\n') + generated_file(inputs, 'pacman.conf', b'[options]\nArchitecture = x86_64\n' + b'SigLevel = Required DatabaseOptional\nLocalFileSigLevel = Required\n' + b'GPGDir = /.phios-update-inputs/gnupg\nCacheDir = /.phios-update-inputs/cache\n') + for row in payload['packages']: + for filename in [row['filename'], row['filename'] + '.sig']: + shutil.copyfile(private / filename, inputs / filename) + (inputs / filename).chmod(0o600) + with (inputs / row['filename']).open('rb') as handle: + if hashlib.file_digest(handle, 'sha256').hexdigest() != row['sha256']: + raise ValueError('captured package changed before staged installation') + recover.run('rsync', '-r', '--exclude=/' + recover.ENTROPY, str(esp) + '/', str(staged / 'boot') + '/') + try: + recover.run('arch-chroot', str(staged), 'gpg', '--no-options', '--homedir', '/.phios-update-inputs/gnupg', + '--batch', '--import', '/.phios-update-inputs/public-keys.gpg') + recover.run('arch-chroot', str(staged), 'gpg', '--no-options', '--homedir', '/.phios-update-inputs/gnupg', + '--batch', '--import-ownertrust', '/.phios-update-inputs/ownertrust.txt') + journal['stage'] = 'installing signed packages in staged root; active root unchanged' + recover.write_json(folder / 'update-transaction.json', journal) + recover.run('arch-chroot', str(staged), 'pacman', '--config', '/.phios-update-inputs/pacman.conf', + '-U', '--noconfirm', *['/.phios-update-inputs/' + row['filename'] for row in payload['packages']]) + finally: + # GnuPG agents retain their chroot. Reap only this private + # staging home's agents before unmounting the selected disk. + recover.run('arch-chroot', str(staged), 'gpgconf', '--homedir', '/.phios-update-inputs/gnupg', '--kill', 'all') + if verify.inventory(packages(staged)) != verify.inventory(payload['target_packages']): + raise ValueError('staged full inventory differs from the signed target') + if recover.regular(staged / 'usr/share/phios/source-commit').decode().strip() != payload['source_commit']: + raise ValueError('staged PhiOS source identity differs from the signed target') + kernels = list((staged / 'usr/lib/modules').glob('*/vmlinuz')) + if len(kernels) != 1: + raise ValueError('exactly one staged Linux kernel is required') + shutil.copyfile(kernels[0], staged / 'boot/vmlinuz-linux') + recover.run('arch-chroot', str(staged), 'mkinitcpio', '-P') + for relative in ['EFI/BOOT/BOOTX64.EFI', 'EFI/systemd/systemd-bootx64.efi']: + shutil.copyfile(staged / 'usr/lib/systemd/boot/efi/systemd-bootx64.efi', staged / 'boot' / relative) + generated_file(staged, 'etc/pacman.d/mirrorlist', + f'Server = https://archive.archlinux.org/repos/{payload["arch_snapshot"]}/$repo/os/$arch\n'.encode(), mode=0o644) + generated_file(staged, 'etc/phios/os-update-trust.json', json.dumps(trust[0], sort_keys=True).encode(), mode=0o644) + generated_file(staged, 'etc/phios/os-update-keyring.gpg', trust[1], mode=0o644) + recover.write_json(staged / 'var/lib/phios/os-update-generation.json', { + 'schema_version': 'phios.os-update-generation.v1', 'sequence': payload['sequence'], + 'source_commit': payload['source_commit']}) + journal['target_boot_files'] = recover.boot_inventory(staged / 'boot') + target_efi = folder / 'efi-target' + target_efi.mkdir(mode=0o700) + recover.run('rsync', '-r', str(staged / 'boot') + '/', str(target_efi) + '/') + shutil.rmtree(inputs) + for path in (staged / 'boot').iterdir(): + shutil.rmtree(path) if path.is_dir() else path.unlink() + recover.run('umount', str(staged)) + staged_mounted = False + journal['stage'] = 'switching root; live recovery may be required' + recover.write_json(folder / 'update-transaction.json', journal) + recover.write_json(top / '@snapshots/os-update-counter.json', { + 'schema_version': 'phios.os-update-counter.v1', 'sequence': payload['sequence'], + 'source_commit': payload['source_commit']}) + recover.run('btrfs', 'filesystem', 'sync', str(top)) + os.rename(top / '@root', previous) + recover.run('btrfs', 'filesystem', 'sync', str(top)) + os.rename(staged, top / '@root') + recover.run('btrfs', 'filesystem', 'sync', str(top)) + journal['stage'] = 'switching matched EFI; do not reboot' + recover.write_json(folder / 'update-transaction.json', journal) + recover.run('rsync', '-r', '--delete', '--exclude=/' + recover.ENTROPY, str(target_efi) + '/', str(esp) + '/') + (esp / recover.ENTROPY).unlink(missing_ok=True) + if recover.boot_inventory(esp) != journal['target_boot_files']: + raise ValueError('updated EFI files failed verification; use live recovery checkpoint') + os.sync() + journal.update(stage='activated; disk-only boot remains unqualified', activated=True) + recover.write_json(folder / 'update-transaction.json', journal) + recover.run('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + return journal + except BaseException as exc: + journal['error'] = str(exc) + recover.write_json(folder / 'update-transaction.json', journal) + recover.run('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + raise + finally: + if staged_mounted: + recover.run('umount', str(staged)) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--disk', required=True) + parser.add_argument('--bundle', type=Path, required=True) + parser.add_argument('--plan', action='store_true', help='Read-only target probe and signed-byte verification') + args = parser.parse_args() + try: + if os.geteuid() != 0 or not Path('/run/archiso/bootmnt').is_dir() or not Path('/sys/firmware/efi').is_dir(): + raise ValueError('run the root-owned updater from PhiOS UEFI live media with the target offline') + identity, trust = recover.inventory(args.disk), verify.load_trust() + with recover.mounted(identity, writable=False) as (top, esp): + installed = recover.installed(top, identity) + recover.ensure_no_active_authority(top, installed['install_receipt']['plan']['username']) + baseline, counter = packages(top / '@root'), sequence(top, installed['source_commit']) + boot = recover.boot_inventory(esp) + with verify.verified_bundle(args.bundle, source=installed['source_commit'], sequence=counter, + installed=baseline, trust=trust) as (payload, private): + supported_versions(payload, baseline) + plan = {'schema_version': 'phios.os-update-plan.v1', 'operation': 'update', 'disk': identity, + 'installed': installed, 'base_sequence': counter, 'base_packages': baseline, 'boot_files': boot, + 'signed_transition': payload, 'signer': trust[0]['primary_fingerprint'], + 'manifest_sha256': hashlib.sha256((private / 'manifest.json').read_bytes()).hexdigest(), + 'checkpoint_generation': uuid.uuid4().hex, 'atomic': False, 'release_ready': False} + print(json.dumps(plan, indent=2, sort_keys=True), flush=True) + if args.plan: + return 0 + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise ValueError('interactive terminal review required; no unattended bypass') + print('A matched recovery checkpoint is created first. Root/EFI activation is not atomic.\n' + 'Keep live recovery media and a separate verified data backup.\n' + 'Type the exact signed transition confirmation, or Ctrl-C to cancel:\n' + recover.phrase(plan), flush=True) + if input('> ') != recover.phrase(plan): + raise ValueError('confirmation did not match; no target writes performed') + print(json.dumps(execute(plan, payload, private, trust), indent=2, sort_keys=True)) + return 0 + except (KeyboardInterrupt, EOFError): + print('OS update cancelled; preserve transaction evidence if writes had begun.') + return 130 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print(f'OS update held: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/updates/enroll.py b/packaging/linux/updates/enroll.py new file mode 100644 index 00000000..b554d261 --- /dev/null +++ b/packaging/linux/updates/enroll.py @@ -0,0 +1,154 @@ +"""Explicitly enroll one independently authenticated public OS-update key.""" +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import os +import re +import stat +import subprocess +import sys +import tempfile +import uuid +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +spec = importlib.util.spec_from_file_location('phios_enroll_verifier', Path(__file__).with_name('verify.py')) +assert spec is not None and spec.loader is not None +verify = importlib.util.module_from_spec(spec) +spec.loader.exec_module(verify) + + +def gpg(home: Path, *args: str) -> bytes: + result = subprocess.run(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', + '--no-auto-key-retrieve', '--auto-key-locate', 'clear', *args], env=verify.ENV, capture_output=True, timeout=60) + if result.returncode: + raise ValueError('public key parsing/import/export failed; no trust enrolled') + return result.stdout + + +def public_key(home: Path, captured: Path, fingerprint: str, *, now: datetime) -> bytes: + if re.fullmatch(r'(?:[0-9A-F]{40}|[0-9A-F]{64})', fingerprint) is None: + raise ValueError('independently authenticated full uppercase fingerprint required') + rows = [line.split(':') for line in gpg(home, '--with-colons', '--import-options', 'show-only', + '--dry-run', '--import', str(captured)).decode().splitlines()] + if any(row[0].startswith(('sec', 'ssb')) for row in rows): + raise ValueError('secret key material refused; provide only an exported public key') + if len([row for row in rows if row[0] == 'pub']) != 1: + raise ValueError('exactly one public primary key required') + found = next((row[9] for row in rows if row[0] == 'fpr'), '') + if found != fingerprint: + raise ValueError('public key differs from independently authenticated fingerprint') + gpg(home, '--import', str(captured)) + rows = [line.split(':') for line in gpg(home, '--with-colons', '--list-keys', fingerprint).decode().splitlines()] + primary = [row for row in rows if row[0] == 'pub'] + if (len(primary) != 1 or primary[0][1] in ('r', 'e', 'd') or + int(primary[0][5]) > int(now.timestamp()) + 300 or + (primary[0][6] not in ('', '0') and int(primary[0][6]) <= int(now.timestamp()))): + raise ValueError('expired, revoked, disabled or future primary key refused') + if any(line.split(':')[0].startswith(('sec', 'ssb')) for line in + gpg(home, '--with-colons', '--list-secret-keys').decode().splitlines()): + raise ValueError('secret keys must never enter enrollment') + exported = gpg(home, '--export', fingerprint) + if not 0 < len(exported) <= 8 * 1024**2: + raise ValueError('bounded public key export required') + return exported + + +def existing() -> dict[str, str | None]: + result: dict[str, str | None] = {} + for path in [verify.TRUST, verify.KEYRING]: + result[path.name] = (hashlib.sha256(verify.protected_file(path, maximum=8 * 1024**2)).hexdigest() + if path.exists() or path.is_symlink() else None) + return result + + +def phrase(plan: dict[str, Any]) -> str: + return 'ENROLL /etc/phios ' + hashlib.sha256(json.dumps(plan, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + + +def write(path: Path, data: bytes) -> None: + temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp') + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as handle: + handle.write(data) + os.fchmod(handle.fileno(), 0o644) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--public-key', required=True, type=Path) + parser.add_argument('--fingerprint', required=True) + parser.add_argument('--plan', action='store_true') + args = parser.parse_args() + try: + if os.geteuid() != 0: + raise ValueError('root-owned enrollment command requires sudo') + source = verify.protected_file(verify.SOURCE).decode().strip() + if re.fullmatch(r'[0-9a-f]{40}', source) is None: + raise ValueError('packaged PhiOS source identity required') + with tempfile.TemporaryDirectory(prefix='phios-key-enrollment-') as temporary: + private = Path(temporary) + home = private / 'gnupg' + home.mkdir(mode=0o700) + try: + directory = os.open(args.public_key.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + verify.capture(directory, args.public_key.name, private / 'public-key', maximum=8 * 1024**2) + finally: + os.close(directory) + exported = public_key(home, private / 'public-key', args.fingerprint, now=datetime.now(UTC)) + before = existing() + policy = {'schema_version': 'phios.os-update-trust.v1', 'channel': 'experimental', + 'primary_fingerprint': args.fingerprint} + plan = {'schema_version': 'phios.os-update-enrollment.v1', 'source_commit': source, + 'public_key_sha256': hashlib.sha256(exported).hexdigest(), 'policy': policy, + 'current_trust_hashes': before, 'release_ready': False} + print(json.dumps(plan, indent=2, sort_keys=True), flush=True) + if args.plan: + return 0 + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise ValueError('interactive terminal review required; no unattended enrollment') + print('Authenticate this full fingerprint through an independently trusted maintainer channel.\n' + 'This explicit local administration changes update signing trust; a key file does not authenticate itself.\n' + 'Type the exact reviewed phrase, or Ctrl-C to cancel:\n' + phrase(plan), flush=True) + if input('> ') != phrase(plan): + raise ValueError('confirmation did not match; no signing trust changed') + if existing() != before or public_key(home, private / 'public-key', args.fingerprint, now=datetime.now(UTC)) != exported: + raise ValueError('public key validity or current trust changed after review') + verify.TRUST.parent.mkdir(mode=0o755, exist_ok=True) + for parent in reversed(verify.TRUST.parents): + info = parent.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError('unsafe signing trust directory') + write(verify.KEYRING, exported) + write(verify.TRUST, (json.dumps(policy, sort_keys=True) + '\n').encode()) + if verify.load_trust() != (policy, exported): + raise ValueError('enrolled trust readback failed; preserve evidence and re-enroll') + print(json.dumps({'trust_enrolled': True, 'primary_fingerprint': args.fingerprint, + 'release_ready': False}, sort_keys=True)) + finally: + subprocess.run(['/usr/bin/gpgconf', '--homedir', str(home), '--kill', 'all'], + env=verify.ENV, capture_output=True, timeout=15) + return 0 + except (KeyboardInterrupt, EOFError): + print('Enrollment cancelled; inspect current trust if writes had begun.') + return 130 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print('Key enrollment held: ' + str(exc), file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/updates/phios-os-recover b/packaging/linux/updates/phios-os-recover new file mode 100755 index 00000000..da55d628 --- /dev/null +++ b/packaging/linux/updates/phios-os-recover @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-updates/recover.py "$@" diff --git a/packaging/linux/updates/phios-os-update b/packaging/linux/updates/phios-os-update new file mode 100755 index 00000000..c0056a5e --- /dev/null +++ b/packaging/linux/updates/phios-os-update @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-updates/apply.py "$@" diff --git a/packaging/linux/updates/phios-update-enroll b/packaging/linux/updates/phios-update-enroll new file mode 100755 index 00000000..df0819bb --- /dev/null +++ b/packaging/linux/updates/phios-update-enroll @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-updates/enroll.py "$@" diff --git a/packaging/linux/updates/phios-update-verify b/packaging/linux/updates/phios-update-verify new file mode 100755 index 00000000..8624d73e --- /dev/null +++ b/packaging/linux/updates/phios-update-verify @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-updates/verify.py "$@" diff --git a/packaging/linux/updates/recover.py b/packaging/linux/updates/recover.py new file mode 100644 index 00000000..77f8b4b1 --- /dev/null +++ b/packaging/linux/updates/recover.py @@ -0,0 +1,489 @@ +"""Offline matched Btrfs/EFI checkpoints for the experimental PhiOS installer.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import uuid +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Iterator + +ENV = {'PATH': '/usr/bin', 'LANG': 'C.UTF-8', 'HOME': '/root'} +FORMAT = 'phios.os-checkpoint.v1' +SCHEMA = {'memory': 1, 'data_backup': 'phios.data-backup.v1'} +GEN = r'[0-9a-f]{32}' +ENTROPY = 'loader/random-seed' + + +def run(*args: str) -> str: + command = shutil.which(args[0], path=ENV['PATH']) + if command is None: + raise ValueError(f'required program unavailable: {args[0]}') + result = subprocess.run([command, *args[1:]], env=ENV, capture_output=True, text=True, timeout=600) + if result.returncode or '==> ERROR:' in result.stdout or '==> ERROR:' in result.stderr: + raise RuntimeError(f'{args[0]} failed (exit {result.returncode}): {(result.stdout + result.stderr)[-6000:]}') + return result.stdout + + +def regular(path: Path, *, owner: int = 0, maximum: int = 2 * 1024**2) -> bytes: + info = path.lstat() + if (not stat.S_ISREG(info.st_mode) or info.st_uid != owner or info.st_mode & 0o022 or + info.st_nlink != 1 or info.st_size > maximum): + raise ValueError('unsafe checkpoint/installed metadata file') + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as handle: + actual = os.fstat(handle.fileno()) + if (actual.st_dev, actual.st_ino, actual.st_size, actual.st_mtime_ns, actual.st_ctime_ns) != ( + info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns): + raise ValueError('metadata changed during intake') + data = handle.read(maximum + 1) + if len(data) > maximum: + raise ValueError('metadata exceeds its bound') + return data + + +def safe_directory(path: Path, *, owner: int = 0) -> None: + info = path.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != owner or info.st_mode & 0o022: + raise ValueError('unsafe checkpoint/installed directory') + + +def write_json(path: Path, data: dict[str, Any]) -> None: + safe_directory(path.parent) + temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp') + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as handle: + json.dump(data, handle, indent=2, sort_keys=True, allow_nan=False) + handle.write('\n') + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(directory) + finally: + os.close(directory) + + +def validate_disk(row: dict[str, Any], *, busy: bool) -> dict[str, Any]: + path = row.get('path') + if (not isinstance(path, str) or re.fullmatch(r'/dev/(sd[a-z]+|vd[a-z]+|nvme[0-9]+n[0-9]+|mmcblk[0-9]+)', path) is None or + row.get('type') != 'disk' or row.get('ro') not in (False, 0) or row.get('pttype') != 'gpt' or + type(row.get('size')) is not int or row['size'] < 16 * 1024**3 or busy): + raise ValueError('an idle, canonical whole PhiOS installation disk is required') + serial = row.get('serial') or row.get('wwn') + if not isinstance(serial, str) or not serial.strip() or any(ord(c) < 32 or ord(c) == 127 for c in serial): + raise ValueError('stable disk identity is required') + children = row.get('children') + suffix = 'p' if path[-1].isdigit() else '' + if not isinstance(children, list) or len(children) != 2: + raise ValueError('only the installer two-partition layout is supported') + children = sorted(children, key=lambda item: item.get('path', '')) + for index, (child, filesystem) in enumerate(zip(children, ['vfat', 'btrfs'], strict=True), start=1): + if (child.get('path') != f'{path}{suffix}{index}' or child.get('type') != 'part' or + child.get('fstype') != filesystem or child.get('children') or + any(child.get('mountpoints') or []) or child.get('ro') not in (False, 0)): + raise ValueError('partition identity, filesystem or mounted state is unsupported') + if any(row.get('mountpoints') or []) or children[0].get('size') != 1024**3: + raise ValueError('mounted target or unexpected ESP size') + root_uuid, esp_uuid = children[1].get('uuid'), children[0].get('uuid') + if (not isinstance(root_uuid, str) or re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', root_uuid) is None or + not isinstance(esp_uuid, str) or re.fullmatch(r'[0-9A-F]{4}-[0-9A-F]{4}', esp_uuid) is None): + raise ValueError('invalid installed filesystem UUID') + return {'path': path, 'serial_or_wwn': serial.strip(), 'size_bytes': row['size'], + 'major_minor': row.get('maj:min'), 'root_uuid': root_uuid, 'esp_uuid': esp_uuid, + 'esp': children[0]['path'], 'system': children[1]['path']} + + +def block_dependencies(sys_device: Path, *, partition: bool) -> bool: + # Kernel partition kobjects have holders and a partition marker, but no + # slaves directory. Only the parent whole-disk kobject has slaves. + if (sys_device / 'partition').is_file() != partition: + raise ValueError('sysfs block type differs from the selected disk layout') + holders = list((sys_device / 'holders').iterdir()) + slaves = [] if partition else list((sys_device / 'slaves').iterdir()) + return bool(holders or slaves) + + +def inventory(device: str) -> dict[str, Any]: + path = Path(device) + if not path.is_absolute() or path.resolve() != path or not stat.S_ISBLK(path.stat().st_mode): + raise ValueError('canonical real whole disk required') + run('udevadm', 'settle') + rows = json.loads(run('lsblk', '--json', '--bytes', '--paths', '--tree', '--output', + 'PATH,TYPE,SIZE,RO,SERIAL,WWN,MOUNTPOINTS,FSTYPE,PTTYPE,UUID,MAJ:MIN', device))['blockdevices'] + if len(rows) != 1: + raise ValueError('ambiguous target') + nodes = [rows[0], *rows[0].get('children', [])] + mounted = {line.split()[2] for line in Path('/proc/self/mountinfo').read_text().splitlines()} + swap_devices = {Path(line.split()[0]).stat().st_rdev for line in Path('/proc/swaps').read_text().splitlines()[1:]} + busy = False + for node in nodes: + info = Path(node['path']).stat() + number = f'{os.major(info.st_rdev)}:{os.minor(info.st_rdev)}' + sys_device = Path('/sys/dev/block') / number + partition = node.get('type') == 'part' + if partition and sys_device.resolve().parent != (Path('/sys/dev/block') / rows[0]['maj:min']).resolve(): + raise ValueError('sysfs partition parent differs from the selected whole disk') + if (number != node.get('maj:min') or number in mounted or info.st_rdev in swap_devices or + block_dependencies(sys_device, partition=partition)): + busy = True + return validate_disk(rows[0], busy=busy) + + +@contextmanager +def mounted(identity: dict[str, Any], *, writable: bool) -> Iterator[tuple[Path, Path]]: + if inventory(identity['path']) != identity: + raise ValueError('disk changed after review; no target writes performed') + workspace = Path(tempfile.mkdtemp(prefix='phios-recovery-', dir='/run')) + top, esp = workspace / 'top', workspace / 'efi' + top.mkdir(mode=0o700) + esp.mkdir(mode=0o700) + mounts: list[Path] = [] + try: + options = 'rw,subvolid=5' if writable else 'ro,rescue=nologreplay,subvolid=5' + run('mount', '-t', 'btrfs', '-o', options, identity['system'], str(top)) + mounts.append(top) + # Multi-device Btrfs would cross the selected-disk boundary. + if len(list((Path('/sys/fs/btrfs') / identity['root_uuid'] / 'devices').iterdir())) != 1: + raise ValueError('multi-device Btrfs is unsupported') + run('mount', '-t', 'vfat', '-o', ('rw' if writable else 'ro') + ',umask=0077', identity['esp'], str(esp)) + mounts.append(esp) + yield top, esp + finally: + failures = [] + for path in reversed(mounts): + try: + run('umount', str(path)) + except (OSError, ValueError, RuntimeError) as exc: + failures.append(str(exc)) + if failures: + raise RuntimeError('recovery mounts remain active; preserve evidence and do not reboot: ' + '; '.join(failures)) + shutil.rmtree(workspace) + + +def boot_inventory(esp: Path, *, owner: int = 0) -> dict[str, dict[str, Any]]: + result: dict[str, dict[str, Any]] = {} + total = 0 + safe_directory(esp, owner=owner) + for current, dirs, files in os.walk(esp, followlinks=False): + directory = Path(current) + for name in dirs: + safe_directory(directory / name, owner=owner) + for name in files: + path = directory / name + relative = path.relative_to(esp).as_posix() + if relative == ENTROPY: + continue + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_uid != owner or info.st_nlink != 1: + raise ValueError('EFI contents contain nonregular files or links') + total += info.st_size + if len(result) >= 512 or total > 1024**3: + raise ValueError('EFI file inventory exceeds its bound') + digest = hashlib.sha256() + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as handle: + for chunk in iter(lambda: handle.read(1024**2), b''): + digest.update(chunk) + result[relative] = {'size': info.st_size, 'sha256': digest.hexdigest()} + if not {'vmlinuz-linux', 'initramfs-linux.img', 'initramfs-linux-fallback.img', + 'EFI/BOOT/BOOTX64.EFI', 'loader/entries/phios.conf'} <= result.keys(): + raise ValueError('matching installed kernel, initramfs and fallback EFI loader required') + return result + + +def installed(top: Path, identity: dict[str, Any]) -> dict[str, Any]: + for name in ['@root', '@home', '@log', '@snapshots']: + safe_directory(top / name) + run('btrfs', 'subvolume', 'show', str(top / name)) + root = top / '@root' + for relative in ['var', 'var/lib', 'var/lib/phios', 'usr', 'usr/share', 'usr/share/phios']: + safe_directory(root / relative) + receipt = json.loads(regular(root / 'var/lib/phios/install-receipt.json')) + target = receipt.get('plan', {}).get('target', {}) + source = regular(root / 'usr/share/phios/source-commit').decode().strip() + if (receipt.get('schema_version') != 'phios.blank-disk-install.v1' or receipt.get('installed') is not True or + receipt.get('root_uuid') != identity['root_uuid'] or receipt.get('esp_uuid') != identity['esp_uuid'] or + target.get('serial_or_wwn') != identity['serial_or_wwn'] or target.get('size_bytes') != identity['size_bytes'] or + re.fullmatch(r'[0-9a-f]{40}', source) is None): + raise ValueError('selected disk does not match a supported PhiOS installation receipt') + return {'source_commit': source, 'install_receipt': receipt} + + +def validate_checkpoint(data: Any, identity: dict[str, Any], generation: str) -> dict[str, Any]: + keys = {'schema_version', 'generation', 'disk', 'source_commit', 'state_schemas', 'root_snapshot_uuid', + 'boot_files', 'installed', 'home_snapshot_restored', 'authority_restored', 'release_ready'} + if (not isinstance(data, dict) or set(data) != keys or data['schema_version'] != FORMAT or + data['generation'] != generation or re.fullmatch(GEN, generation) is None or + data['disk'] != {key: identity[key] for key in ['serial_or_wwn', 'size_bytes', 'root_uuid', 'esp_uuid']} or + data['state_schemas'] != SCHEMA or type(data['state_schemas'].get('memory')) is not int or + not isinstance(data['source_commit'], str) or re.fullmatch(r'[0-9a-f]{40}', data['source_commit']) is None or + any(data[key] is not False for key in ['home_snapshot_restored', 'authority_restored', 'release_ready'])): + raise ValueError('unsupported or wrong-disk checkpoint') + installed_info, boot = data['installed'], data['boot_files'] + if (not isinstance(data['root_snapshot_uuid'], str) or + re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', data['root_snapshot_uuid']) is None or + not isinstance(installed_info, dict) or set(installed_info) != {'source_commit', 'install_receipt'} or + installed_info['source_commit'] != data['source_commit'] or not isinstance(installed_info['install_receipt'], dict) or + installed_info['install_receipt'].get('schema_version') != 'phios.blank-disk-install.v1' or + installed_info['install_receipt'].get('installed') is not True or + installed_info['install_receipt'].get('root_uuid') != identity['root_uuid'] or + installed_info['install_receipt'].get('esp_uuid') != identity['esp_uuid'] or + not isinstance(installed_info['install_receipt'].get('plan'), dict) or + not isinstance(installed_info['install_receipt']['plan'].get('username'), str) or + re.fullmatch(r'[a-z][a-z0-9_-]{0,30}', installed_info['install_receipt']['plan']['username']) is None or + not isinstance(boot, dict) or not 5 <= len(boot) <= 512): + raise ValueError('invalid checkpoint root, installed identity or boot inventory') + total = 0 + for name, file in boot.items(): + if (not isinstance(name, str) or Path(name).is_absolute() or '..' in Path(name).parts or + not isinstance(file, dict) or set(file) != {'size', 'sha256'} or type(file['size']) is not int or + file['size'] < 0 or not isinstance(file['sha256'], str) or re.fullmatch(r'[0-9a-f]{64}', file['sha256']) is None): + raise ValueError('invalid checkpoint boot-file hash or path') + total += file['size'] + if total > 1024**3: + raise ValueError('checkpoint boot inventory exceeds its bound') + return data + + +def snapshot_uuid(path: Path) -> str: + text = run('btrfs', 'subvolume', 'show', str(path)) + matches = re.findall(r'^\s*UUID:\s*([0-9a-f-]{36})\s*$', text, flags=re.M) + if len(matches) != 1: + raise ValueError('ambiguous Btrfs snapshot identity') + return matches[0] + + +def checkpoint_data(top: Path, esp: Path, identity: dict[str, Any], generation: str) -> tuple[dict[str, Any], Path]: + folder = top / '@snapshots/recovery' / generation + for path in [top / '@snapshots', folder.parent, folder, folder / 'root', folder / 'efi']: + safe_directory(path) + data = validate_checkpoint(json.loads(regular(folder / 'checkpoint.json')), identity, generation) + if (run('btrfs', 'property', 'get', '-t', 's', str(folder / 'root'), 'ro').strip() != 'ro=true' or + snapshot_uuid(folder / 'root') != data['root_snapshot_uuid'] or + boot_inventory(folder / 'efi') != data['boot_files'] or + regular(folder / 'root/usr/share/phios/source-commit').decode().strip() != data['source_commit']): + raise ValueError('checkpoint root or matching boot files failed integrity checks') + return data, folder + + +def ensure_no_active_authority(top: Path, username: str, *, uid: int = 1000) -> None: + """Preserve current home data; refuse rollback over active/unknown authority.""" + if re.fullmatch(r'[a-z][a-z0-9_-]{0,30}', username) is None: + raise ValueError('invalid installed account') + home = top / '@home' / username + safe_directory(home, owner=uid) + # Custom state roots need a separately reviewed maintenance procedure. + for relative in ['.local/state/phios', '.phios']: + state = home / relative + if not state.exists(): + continue + for parent in [*reversed(state.parents), state]: + if parent == home or parent.is_relative_to(home): + safe_directory(parent, owner=uid) + database = state / 'memory/canonical.sqlite3' + published: list[dict[str, Any]] = [] + if database.exists(): + safe_directory(database.parent, owner=uid) + info = database.lstat() + if (not stat.S_ISREG(info.st_mode) or info.st_uid != uid or info.st_mode & 0o022 or + info.st_nlink != 1 or any(database.with_name(database.name + suffix).exists() + for suffix in ['-wal', '-journal'])): + raise ValueError('canonical state requires explicit data recovery before OS rollback') + # The trusted live runtime validates schema, structural integrity, + # record hashes and zero-authority outbox receipts without mutation. + from phios.state_recovery import _database + published = [row for row, is_published in _database(database) if is_published] + spine = state / 'spine-v0.1' + if not spine.exists(): + if published: + raise ValueError('published memory has no matching active receipt ledger') + continue + safe_directory(spine, owner=uid) + actual_receipts: list[dict[str, Any]] = [] + for path in spine.rglob('*'): + if path.is_dir() and not path.is_symlink(): + safe_directory(path, owner=uid) + continue + if path.relative_to(spine).as_posix() != 'ledger/mandala-receipts.jsonl': + raise ValueError('active spine/authority history requires data-only recovery and explicit revalidation first') + # This allowlist never restores an old decision/binding/lease. The + # memory ledger remains in current @home and must be zero-authority. + rows = regular(path, owner=uid, maximum=128 * 1024**2).splitlines() + for row in rows: + value = json.loads(row) + if (not isinstance(value, dict) or not isinstance(value.get('operation_id'), str) or + value.get('action_authority') is not False or value.get('execution_authority') is not False): + raise ValueError('memory history contains authority; recovery held') + actual_receipts.append(value) + if sorted(actual_receipts, key=lambda row: row['operation_id']) != sorted(published, key=lambda row: row['operation_id']): + raise ValueError('memory receipt history does not match current canonical state') + config = home / '.config/phios/memory.json' + if config.exists(): + if json.loads(regular(config, owner=uid)).get('enabled') is not False: + raise ValueError('disable memory configuration and review state before OS rollback') + + +def phrase(plan: dict[str, Any]) -> str: + digest = hashlib.sha256(json.dumps(plan, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() + return f"{plan['operation'].upper()} {plan['disk']['path']} {digest}" + + +def generation_record(path: Path, schema: str) -> dict[str, Any] | None: + if not path.exists() and not path.is_symlink(): + return None + value = json.loads(regular(path)) + if (not isinstance(value, dict) or set(value) != {'schema_version', 'sequence', 'source_commit'} or + value['schema_version'] != schema or type(value['sequence']) is not int or value['sequence'] < 0 or + not isinstance(value['source_commit'], str) or re.fullmatch(r'[0-9a-f]{40}', value['source_commit']) is None): + raise ValueError('update generation requires explicit recovery review') + return value + + +def recovery_sequence(top: Path, saved_root: Path) -> int: + # This counter lives outside root snapshots. Even if activation stopped + # between root renames, an older root cannot reset the consumed sequence. + values = [generation_record(top / '@snapshots/os-update-counter.json', 'phios.os-update-counter.v1')] + for root in [top / '@root', saved_root]: + values.append(generation_record(root / 'var/lib/phios/os-update-generation.json', 'phios.os-update-generation.v1')) + return max((value['sequence'] for value in values if value is not None), default=0) + 1 + + +def execute(identity: dict[str, Any], operation: str, generation: str, reviewed: dict[str, Any]) -> dict[str, Any]: + with mounted(identity, writable=True) as (top, esp): + # Recheck reviewed source/checkpoint/boot identity before creating a + # checkpoint or activating restored root/EFI contents. + if operation == 'checkpoint': + current = installed(top, identity) + if current != reviewed['installed'] or boot_inventory(esp) != reviewed['boot_files']: + raise ValueError('installed source or boot files changed after review') + ensure_no_active_authority(top, current['install_receipt']['plan']['username']) + base = top / '@snapshots/recovery' + if not base.exists(): + base.mkdir(mode=0o700) + safe_directory(base) + folder = base / generation + folder.mkdir(mode=0o700) + run('btrfs', 'subvolume', 'snapshot', '-r', str(top / '@root'), str(folder / 'root')) + run('btrfs', 'subvolume', 'snapshot', '-r', str(top / '@home'), str(folder / 'home-forensic-only')) + (folder / 'efi').mkdir(mode=0o700) + run('rsync', '-r', '--exclude=/' + ENTROPY, str(esp) + '/', str(folder / 'efi') + '/') + if boot_inventory(folder / 'efi') != reviewed['boot_files']: + raise ValueError('checkpoint EFI copy differs from reviewed boot files') + data = {'schema_version': FORMAT, 'generation': generation, + 'disk': {key: identity[key] for key in ['serial_or_wwn', 'size_bytes', 'root_uuid', 'esp_uuid']}, + 'source_commit': current['source_commit'], 'state_schemas': SCHEMA, + 'root_snapshot_uuid': snapshot_uuid(folder / 'root'), 'boot_files': reviewed['boot_files'], + 'installed': current, 'home_snapshot_restored': False, 'authority_restored': False, 'release_ready': False} + write_json(folder / 'checkpoint.json', data) + run('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + return data + data, folder = checkpoint_data(top, esp, identity, generation) + if data != reviewed['checkpoint']: + raise ValueError('checkpoint changed after review') + next_sequence = recovery_sequence(top, folder / 'root') + if next_sequence != reviewed['next_sequence']: + raise ValueError('update counter changed after review') + ensure_no_active_authority(top, data['installed']['install_receipt']['plan']['username']) + transaction = folder / ('restore-' + uuid.uuid4().hex) + transaction.mkdir(mode=0o700) + (transaction / 'efi-before').mkdir(mode=0o700) + run('rsync', '-r', '--exclude=/' + ENTROPY, str(esp) + '/', str(transaction / 'efi-before') + '/') + token = uuid.uuid4().hex + staged, failed = top / ('@recovered-' + token), top / ('@failed-' + token) + journal = {'schema_version': 'phios.os-restore-transaction.v1', 'generation': generation, + 'failed_root': failed.name, 'staged_root': staged.name, 'stage': 'preparing', + 'home_restored': False, 'authority_restored': False, 'release_ready': False} + write_json(transaction / 'transaction.json', journal) + run('btrfs', 'subvolume', 'snapshot', str(folder / 'root'), str(staged)) + seed = staged / 'var/lib/systemd/random-seed' + seed.unlink(missing_ok=True) + # An older root must never silently reinstate an earlier trust policy. + for name in ['os-update-trust.json', 'os-update-keyring.gpg']: + (staged / 'etc/phios' / name).unlink(missing_ok=True) + write_json(staged / 'var/lib/phios/os-update-generation.json', { + 'schema_version': 'phios.os-update-generation.v1', + 'sequence': next_sequence, 'source_commit': data['source_commit']}) + write_json(top / '@snapshots/os-update-counter.json', { + 'schema_version': 'phios.os-update-counter.v1', + 'sequence': next_sequence, 'source_commit': data['source_commit']}) + run('btrfs', 'filesystem', 'sync', str(top)) + journal['stage'] = 'switching root; keep live recovery media' + write_json(transaction / 'transaction.json', journal) + if (top / '@root').exists(): + os.rename(top / '@root', failed) + run('btrfs', 'filesystem', 'sync', str(top)) + os.rename(staged, top / '@root') + run('btrfs', 'filesystem', 'sync', str(top)) + journal['stage'] = 'restoring matching EFI; do not reboot' + write_json(transaction / 'transaction.json', journal) + run('rsync', '-r', '--delete', '--exclude=/' + ENTROPY, str(folder / 'efi') + '/', str(esp) + '/') + (esp / ENTROPY).unlink(missing_ok=True) + if boot_inventory(esp) != data['boot_files']: + raise ValueError('restored EFI verification failed; preserve transaction and use live recovery') + os.sync() + journal['stage'] = 'restored; disk-only boot remains unqualified' + write_json(transaction / 'transaction.json', journal) + run('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + return journal + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('operation', choices=['checkpoint', 'restore']) + parser.add_argument('--disk', required=True) + parser.add_argument('--generation', help='Exact checkpoint ID required for restore') + parser.add_argument('--plan', action='store_true', help='Read-only probe; never changes the target') + args = parser.parse_args() + try: + if os.geteuid() != 0 or not Path('/run/archiso/bootmnt').is_dir() or not Path('/sys/firmware/efi').is_dir(): + raise ValueError('run this root-owned tool from a PhiOS UEFI live image with the target offline') + generation = args.generation if args.operation == 'restore' else uuid.uuid4().hex + if generation is None or re.fullmatch(GEN, generation) is None: + raise ValueError('exact checkpoint generation required') + identity = inventory(args.disk) + with mounted(identity, writable=False) as (top, esp): + plan = {'schema_version': 'phios.os-maintenance-plan.v1', 'operation': args.operation, + 'disk': identity, 'generation': generation, 'home_restored': False, + 'authority_restored': False, 'atomic': False, 'release_ready': False} + if args.operation == 'checkpoint': + plan.update(installed=installed(top, identity), boot_files=boot_inventory(esp)) + ensure_no_active_authority(top, plan['installed']['install_receipt']['plan']['username']) + else: + data, folder = checkpoint_data(top, esp, identity, generation) + ensure_no_active_authority(top, data['installed']['install_receipt']['plan']['username']) + plan['checkpoint'] = data + plan['next_sequence'] = recovery_sequence(top, folder / 'root') + print(json.dumps(plan, indent=2, sort_keys=True), flush=True) + if args.plan: + return 0 + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise ValueError('interactive terminal review required; no unattended bypass') + print('Same-disk recovery is not a backup. Preserve a verified data backup on separate storage.\n' + 'Root/EFI activation is not atomic. Keep live recovery media available.\n' + 'Type the exact reviewed confirmation, or Ctrl-C to cancel:\n' + phrase(plan), flush=True) + if input('> ') != phrase(plan): + raise ValueError('confirmation did not match; no target writes performed') + print(json.dumps(execute(identity, args.operation, generation, plan), indent=2, sort_keys=True)) + return 0 + except (KeyboardInterrupt, EOFError): + print('Maintenance cancelled; preserve transaction evidence if writes had begun.') + return 130 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print(f'OS maintenance held: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/updates/verify.py b/packaging/linux/updates/verify.py new file mode 100644 index 00000000..022cb5c7 --- /dev/null +++ b/packaging/linux/updates/verify.py @@ -0,0 +1,255 @@ +"""Verify a complete offline OS package transition; never install or mint authority.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import stat +import subprocess +import tempfile +from contextlib import contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Iterator + +TRUST = Path('/etc/phios/os-update-trust.json') +KEYRING = Path('/etc/phios/os-update-keyring.gpg') +SOURCE = Path('/usr/share/phios/source-commit') +GENERATION = Path('/var/lib/phios/os-update-generation.json') +ENV = {'PATH': '/usr/bin', 'LANG': 'C.UTF-8', 'HOME': '/root'} +SCHEMAS = {'memory': 1, 'data_backup': 'phios.data-backup.v1'} +SHA = r'[0-9a-f]{64}' +PACKAGE = r'[a-z0-9][a-z0-9@._+\-]{0,127}' + + +def stable_identity(info: os.stat_result) -> tuple[int, ...]: + # Reads can update atime. Compare ownership, identity and modification + # fields, including nanoseconds, instead of mistaking atime for mutation. + return (info.st_dev, info.st_ino, info.st_mode, info.st_uid, info.st_gid, + info.st_nlink, info.st_size, info.st_mtime_ns, info.st_ctime_ns) + + +def strict_json(data: bytes) -> Any: + def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in items: + if key in result: + raise ValueError('duplicate JSON key') + result[key] = value + return result + + def invalid(value: str) -> None: + raise ValueError(f'non-finite JSON number: {value}') + + return json.loads(data, object_pairs_hook=pairs, parse_constant=invalid) + + +def protected_file(path: Path, *, maximum: int = 2 * 1024**2) -> bytes: + """Root-owned trust/installed metadata; inspect every ancestor without links.""" + if not path.is_absolute() or '..' in path.parts: + raise ValueError('an absolute protected path is required') + for parent in [*reversed(path.parents), path]: + info = parent.lstat() + if stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError('trust or installed metadata has unsafe owner, permissions or links') + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > maximum: + raise ValueError('protected metadata must be one bounded regular file') + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as handle: + if stable_identity(os.fstat(handle.fileno())) != stable_identity(info): + raise ValueError('protected metadata changed during intake') + data = handle.read(maximum + 1) + if stable_identity(os.fstat(handle.fileno())) != stable_identity(info): + raise ValueError('protected metadata changed during intake') + if len(data) > maximum: + raise ValueError('protected metadata exceeds its bound') + return data + + +def load_trust() -> tuple[dict[str, Any], bytes]: + policy = strict_json(protected_file(TRUST)) + if (not isinstance(policy, dict) or set(policy) != {'schema_version', 'primary_fingerprint', 'channel'} or + policy['schema_version'] != 'phios.os-update-trust.v1' or policy['channel'] != 'experimental' or + not isinstance(policy['primary_fingerprint'], str) or + re.fullmatch(r'(?:[0-9A-F]{40}|[0-9A-F]{64})', policy['primary_fingerprint']) is None): + raise ValueError('unsupported trust policy; maintainer enrollment is required') + return policy, protected_file(KEYRING, maximum=8 * 1024**2) + + +def inventory(rows: Any) -> dict[str, str]: + if not isinstance(rows, list) or not 1 <= len(rows) <= 20000: + raise ValueError('complete bounded package inventory required') + packages: dict[str, str] = {} + for row in rows: + if (not isinstance(row, dict) or set(row) != {'name', 'version'} or + not isinstance(row['name'], str) or re.fullmatch(PACKAGE, row['name']) is None or + not isinstance(row['version'], str) or not 1 <= len(row['version']) <= 256 or + any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in row['version']) or + row['name'] in packages): + raise ValueError('invalid or duplicate package identity') + packages[row['name']] = row['version'] + return packages + + +def validate_manifest(payload: Any, *, source: str, sequence: int, installed: list[dict[str, str]], + now: datetime) -> dict[str, Any]: + keys = {'schema_version', 'channel', 'architecture', 'from_source_commit', 'source_commit', + 'base_sequence', 'sequence', 'created_at', 'expires_at', 'arch_snapshot', + 'state_schemas', 'base_packages', 'target_packages', 'packages'} + if not isinstance(payload, dict) or set(payload) != keys: + raise ValueError('unknown update manifest fields or schema') + if (payload['schema_version'] != 'phios.os-package-update.v1' or payload['channel'] != 'experimental' or + payload['architecture'] != 'x86_64' or payload['state_schemas'] != SCHEMAS or + type(payload['state_schemas'].get('memory')) is not int): + raise ValueError('unsupported channel, architecture or state schema; no implicit migration') + if (payload['from_source_commit'] != source or re.fullmatch(r'[0-9a-f]{40}', source) is None or + not isinstance(payload['source_commit'], str) or + re.fullmatch(r'[0-9a-f]{40}', payload['source_commit']) is None or + type(payload['base_sequence']) is not int or payload['base_sequence'] != sequence or + type(payload['sequence']) is not int or payload['sequence'] != sequence + 1): + raise ValueError('stale, replayed or wrong-source update transition') + if not isinstance(payload['arch_snapshot'], str) or re.fullmatch(r'20\d\d/\d\d/\d\d', payload['arch_snapshot']) is None: + raise ValueError('exact Arch snapshot is required') + datetime.strptime(payload['arch_snapshot'], '%Y/%m/%d') + try: + created, expires = [datetime.fromisoformat(payload[key]) for key in ['created_at', 'expires_at']] + except (TypeError, ValueError) as exc: + raise ValueError('invalid update validity window') from exc + if (created.tzinfo is None or expires.tzinfo is None or created > now + timedelta(minutes=5) or + not created < expires or not now < expires or expires - created > timedelta(days=90)): + raise ValueError('expired, future or unbounded update validity window') + before, after = inventory(payload['base_packages']), inventory(payload['target_packages']) + if before != inventory(installed) or not before.keys() <= after.keys(): + raise ValueError('update requires the exact base inventory; removals are unsupported') + rows = payload['packages'] + if not isinstance(rows, list) or not 1 <= len(rows) <= 2000: + raise ValueError('bounded signed package set required') + names: set[str] = set() + files: set[str] = set() + size = 0 + for row in rows: + if (not isinstance(row, dict) or set(row) != {'name', 'version', 'filename', 'sha256', 'size'} or + not isinstance(row['name'], str) or row['name'] not in after or row['name'] in names or + row['version'] != after[row['name']] or not isinstance(row['filename'], str) or + re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9@._+\-]{0,240}\.pkg\.tar\.(zst|xz)', row['filename']) is None or + row['filename'] in files or not isinstance(row['sha256'], str) or + re.fullmatch(SHA, row['sha256']) is None or type(row['size']) is not int or + not 0 < row['size'] <= 2 * 1024**3): + raise ValueError('invalid, repeated or unsafe update package') + names.add(row['name']) + files.add(row['filename']) + size += row['size'] + if size > 16 * 1024**3 or any(before.get(name) != version and name not in names for name, version in after.items()): + raise ValueError('package set exceeds its bound or omits a target change') + return payload + + +def capture(directory: int, name: str, destination: Path, *, maximum: int) -> dict[str, Any]: + """Copy untrusted bytes once; verify and later use only this private copy.""" + if Path(name).name != name or name.startswith('-'): + raise ValueError('unsafe bundle filename') + fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + digest = hashlib.sha256() + total = 0 + with os.fdopen(fd, 'rb') as reader: + info = os.fstat(reader.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or not 0 < info.st_size <= maximum: + raise ValueError('bundle input is not a bounded, singly linked regular file') + out = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(out, 'wb') as writer: + for data in iter(lambda: reader.read(1024**2), b''): + total += len(data) + if total > maximum: + raise ValueError('bundle input grew beyond its bound') + writer.write(data) + digest.update(data) + writer.flush() + os.fsync(writer.fileno()) + if stable_identity(os.fstat(reader.fileno())) != stable_identity(info) or total != info.st_size: + raise ValueError('bundle input changed during capture') + return {'sha256': digest.hexdigest(), 'size': total} + + +def verify_signature(home: Path, signature: Path, content: Path, fingerprint: str, *, now: datetime) -> None: + result = subprocess.run(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', + '--no-auto-key-retrieve', '--auto-key-locate', 'clear', '--status-fd', '1', '--verify', + str(signature), str(content)], env=ENV, capture_output=True, text=True, timeout=60) + statuses = [line.split()[1:] for line in result.stdout.splitlines() if line.startswith('[GNUPG:] ')] + refused = {'BADSIG', 'ERRSIG', 'EXPSIG', 'EXPKEYSIG', 'REVKEYSIG', 'KEYEXPIRED', 'SIGEXPIRED', 'NO_PUBKEY', 'FAILURE'} + valid = [row[1:] for row in statuses if row[0] == 'VALIDSIG'] + if result.returncode or any(row[0] in refused for row in statuses) or len(valid) != 1: + raise ValueError('signature is missing, invalid, expired, revoked or ambiguous') + row = valid[0] + if (len(row) < 9 or (row[9] if len(row) > 9 else row[0]) != fingerprint or + row[7] not in {'8', '9', '10'} or int(row[2]) > int(now.timestamp()) + 300 or + (int(row[3]) != 0 and int(row[3]) <= int(now.timestamp()))): + raise ValueError('signature signer, digest or validity does not match pinned trust') + + +@contextmanager +def verified_bundle(bundle: Path, *, source: str, sequence: int, installed: list[dict[str, str]], + trust: tuple[dict[str, Any], bytes] | None = None, + now: datetime | None = None) -> Iterator[tuple[dict[str, Any], Path]]: + """Caller must keep this context alive through any eventual package use.""" + policy, public_keys = trust if trust is not None else load_trust() + now = now or datetime.now(UTC) + with tempfile.TemporaryDirectory(prefix='phios-verified-update-') as temporary: + private = Path(temporary) + home = private / 'gnupg' + home.mkdir(mode=0o700) + keys = private / 'public-keys.gpg' + keys.write_bytes(public_keys) + keys.chmod(0o600) + subprocess.run(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', '--import', str(keys)], + env=ENV, capture_output=True, check=True, timeout=60) + directory = os.open(bundle, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + capture(directory, 'manifest.json', private / 'manifest.json', maximum=2 * 1024**2) + capture(directory, 'manifest.json.sig', private / 'manifest.json.sig', maximum=65536) + verify_signature(home, private / 'manifest.json.sig', private / 'manifest.json', policy['primary_fingerprint'], now=now) + payload = validate_manifest(strict_json((private / 'manifest.json').read_bytes()), + source=source, sequence=sequence, installed=installed, now=now) + for package in payload['packages']: + filename = package['filename'] + identity = capture(directory, filename, private / filename, maximum=package['size']) + if identity != {'sha256': package['sha256'], 'size': package['size']}: + raise ValueError('signed package hash or length mismatch') + capture(directory, filename + '.sig', private / (filename + '.sig'), maximum=65536) + verify_signature(home, private / (filename + '.sig'), private / filename, policy['primary_fingerprint'], now=now) + finally: + os.close(directory) + yield payload, private + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bundle', type=Path, required=True) + args = parser.parse_args() + try: + source = protected_file(SOURCE).decode().strip() + sequence = 0 + if GENERATION.exists(): + generation = strict_json(protected_file(GENERATION)) + if (set(generation) != {'schema_version', 'sequence', 'source_commit'} or + generation['schema_version'] != 'phios.os-update-generation.v1' or + generation['source_commit'] != source or type(generation['sequence']) is not int or generation['sequence'] < 0): + raise ValueError('installed update generation is invalid') + sequence = generation['sequence'] + result = subprocess.run(['/usr/bin/pacman', '-Q'], env=ENV, capture_output=True, text=True, check=True, timeout=30) + installed = [dict(zip(['name', 'version'], row.split(), strict=True)) for row in result.stdout.splitlines()] + with verified_bundle(args.bundle, source=source, sequence=sequence, installed=installed) as (payload, _private): + print(json.dumps({'schema_version': 'phios.os-update-verification.v1', + 'source_commit': payload['source_commit'], 'sequence': payload['sequence'], + 'signed_package_count': len(payload['packages']), 'signed_bytes_verified': True, + 'installed': False, 'execution_authority': False, 'release_ready': False}, indent=2)) + return 0 + except (OSError, ValueError, subprocess.SubprocessError) as exc: + print(f'OS update verification held: {exc}') + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/validate_sbom.py b/packaging/linux/validate_sbom.py new file mode 100644 index 00000000..4e7cfc92 --- /dev/null +++ b/packaging/linux/validate_sbom.py @@ -0,0 +1,36 @@ +"""Validate a candidate SBOM against hash-pinned official CycloneDX schemas.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import urllib.request +from pathlib import Path + +import jsonschema + + +def validate(sbom: Path) -> None: + lock = json.loads(Path(__file__).with_name('sbom-schema-lock.json').read_text()) + store = {} + schemas = {} + for name, expected in lock['files'].items(): + with urllib.request.urlopen(lock['base_url'] + name, timeout=30) as response: + data = response.read(1024**2 + 1) + if len(data) > 1024**2 or hashlib.sha256(data).hexdigest() != expected: + raise ValueError('official schema bytes differ from reviewed lock') + schema = json.loads(data) + schemas[name] = schema + for protocol in ['http', 'https']: + store[f'{protocol}://cyclonedx.org/schema/{name}'] = schema + # This supported resolver API also works with the Ubuntu runner's system + # jsonschema package; every external schema is captured and hash checked. + resolver = jsonschema.RefResolver.from_schema(schemas['bom-1.6.schema.json'], store=store) + jsonschema.Draft7Validator(schemas['bom-1.6.schema.json'], resolver=resolver).validate(json.loads(sbom.read_text())) + print('Candidate SBOM matches pinned official CycloneDX 1.6 schemas') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('sbom', type=Path) + validate(parser.parse_args().sbom) diff --git a/phios/core/launch_artifacts.py b/phios/core/launch_artifacts.py index 848b8309..9f15d6de 100644 --- a/phios/core/launch_artifacts.py +++ b/phios/core/launch_artifacts.py @@ -10,7 +10,7 @@ class LaunchArtifactGenerator: def _traction_line(self) -> str: test_files = sorted(Path("tests").glob("test_v*.py")) - return f"{len(test_files)} release generations, full CI-aligned test coverage through {test_files[-1].stem if test_files else 'test_v00'}" + return f"{len(test_files)} historical version test files in this checkout. File counts do not prove passing checks or OS readiness." def generate_distrowatch_submission(self) -> str: text = ( @@ -20,30 +20,30 @@ def generate_distrowatch_submission(self) -> str: "Desktop: Wayfire\n" "Category: Sovereign Computing Shell\n" "Release model: Fixed\n" - "License: GPLv3\n" + "License: MIT (PhiOS source); bundled OS packages retain their own licenses\n" "Homepage: https://enterthefield.org/phios\n" - "Download: \n\n" + "Download: OS image qualification pending; no qualified OS download yet\n\n" "Description:\n" "PhiOS is a local-first sovereign shell operating layer built by PHI369 Labs. " "It couples coherence tracking L(t), secure snapshot workflows, optional TBRC/PHB bridges, and a Wayfire desktop path tuned for auditable local operation. " - "Version 1.0.0 marks the public declaration release with living specification sealing, founding charter exports, and reproducible launch artifacts. " + "The Python package and a future Linux OS image have separate release tracks. The OS is a development preview requiring boot, installation and recovery qualification. " "No cloud dependency is required for core operation.\n" ) return text def generate_announcement_kit(self) -> dict[str, str]: x_post = ( - "PhiOS v1.0 is public. Sovereign. Coherent. Local. Free. " - "pip install phios==1.0.0 · https://enterthefield.org/phios · " + "PhiOS Python shell is available; Linux OS qualification is in progress. " + "pip install phios · https://enterthefield.org/phios · " "Hemavit attribution preserved. #PhiOS #Parallax #PHI369" ) extended = ( - "# PhiOS v1.0 Public Launch\n\n" - "Nine versions forged into one declaration. PhiOS now ships with a sealed living specification, " - "Parallax founding document exports, and reproducible public launch artifacts for operators.\n" + "# PhiOS Development Update\n\n" + "PhiOS provides an alpha operator shell, " + "Parallax founding document exports, and draft public artifacts for operators. A qualified Linux OS release is pending.\n" ) technical = ( - "# PhiOS v1.0 Technical Launch Notes\n\n" + "# PhiOS Python Package Notes\n\n" f"- Version: {__version__}\n" "- Living spec seal workflow: phi spec generate --yes\n" "- Founding export workflow: phi founding export --yes\n" diff --git a/phios/core/living_spec.py b/phios/core/living_spec.py index af413820..e4453bb8 100644 --- a/phios/core/living_spec.py +++ b/phios/core/living_spec.py @@ -61,9 +61,9 @@ def _render(self, seal: str) -> str: "- Name: PhiOS — Sovereign Computing Shell", f"- Version: {__version__}", "- Mission: Sovereign. Coherent. Local. Free.", - "- License: GPLv3", + "- License: MIT; see LICENSE_HISTORY.md for historical licensing", "- Manifesto: https://enterthefield.org/phios", - f"- Launch date: {now}", + f"- Generated at: {now}", "", "## 2. Mathematical Foundation", "- TIEKAT v8.1 is the foundational stack.", diff --git a/phios/curiosity_store.py b/phios/curiosity_store.py index 746d244a..3c7e14f5 100644 --- a/phios/curiosity_store.py +++ b/phios/curiosity_store.py @@ -20,6 +20,7 @@ from typing import Any, Mapping from phios.curiosity import CuriosityArtifact +from phios.state_io import StateIntegrityError, append_jsonl, read_jsonl CURIOSITY_RETURN_POINTER_SCHEMA_VERSION = ( "phios.curiosity_return_pointer.v0.2" @@ -368,30 +369,14 @@ def __init__(self, root: Path) -> None: @staticmethod def _append_json(path: Path, payload: Mapping[str, Any]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(_canonical_json(payload) + "\n") + append_jsonl(path, payload) @staticmethod def _read_jsonl(path: Path) -> list[object]: - if not path.exists(): - return [] - values: list[object] = [] - for index, line in enumerate( - path.read_text(encoding="utf-8").splitlines(), - start=1, - ): - if not line.strip(): - raise CuriosityStoreError( - f"blank line in append-only store at line {index}" - ) - try: - values.append(json.loads(line)) - except json.JSONDecodeError as exc: - raise CuriosityStoreError( - f"invalid JSON at {path.name}:{index}" - ) from exc - return values + try: + return list(read_jsonl(path)) + except StateIntegrityError as exc: + raise CuriosityStoreError(f"invalid JSON at {path.name}: {exc}") from exc def artifacts(self) -> list[CuriosityArtifact]: result: list[CuriosityArtifact] = [] @@ -422,8 +407,8 @@ def append_artifact(self, artifact: CuriosityArtifact) -> bool: digest = artifact.curiosity_artifact_sha256 if self.get_artifact(digest) is not None: return False - self._append_json(self.artifacts_path, artifact.to_dict()) - return True + return append_jsonl(self.artifacts_path, artifact.to_dict(), + identity_field="curiosity_artifact_sha256") def get_artifact( self, @@ -651,11 +636,8 @@ def append_return_pointer( for item in self.return_pointers() ): return False - self._append_json( - self.return_pointers_path, - pointer.to_dict(), - ) - return True + return append_jsonl(self.return_pointers_path, pointer.to_dict(), + identity_field="return_pointer_sha256") def latest_return_pointer( self, diff --git a/phios/desktop/install.py b/phios/desktop/install.py index 6298dbab..66e7a447 100644 --- a/phios/desktop/install.py +++ b/phios/desktop/install.py @@ -34,7 +34,7 @@ def detect_package_manager(self) -> str: def install_packages(self, pkg_manager: str) -> bool: if pkg_manager not in PACKAGES: return False - return True + return all(shutil.which(name) for name in ("wayfire", "waybar", "wofi", "foot", "node", "chromium", "phios-open-shell")) def backup_existing_configs(self) -> list[str]: backups: list[str] = [] @@ -68,13 +68,19 @@ def install(self, dry_run: bool = True) -> dict[str, object]: "would_write_files": [str(self.wayfire_ini), str(self.waybar_dir / "config.jsonc"), str(self.waybar_dir / "style.css")], "backups_made": [], "success": True, + "dry_run": dry_run, + "applied": False, "warnings": [], } if dry_run: return report + if not self.install_packages(pkg): + report["success"] = False + report["warnings"] = ["Desktop dependencies are missing. Install the phishell Arch package before applying this configuration; no packages were installed."] + return report backups = self.backup_existing_configs() report["backups_made"] = backups - self.install_packages(pkg) self.apply_phios_config() + report["applied"] = True return report diff --git a/phios/desktop/phi_tray.py b/phios/desktop/phi_tray.py index 7e301924..e29c2de3 100644 --- a/phios/desktop/phi_tray.py +++ b/phios/desktop/phi_tray.py @@ -50,7 +50,7 @@ def payload(self) -> dict[str, object]: f"Coherence: {float(components.get('A_stability', 0.5)):.3f}", f"Boundary: {1.0 - float(components.get('G_load', 0.5)):.3f}", f"Cadence: {float(components.get('C_variance', 0.5)):.3f}", - "Sovereignty: ON (placeholder)", + "Sovereignty: unverified", "Session: best-effort", f"BrainC: {'Active' if ollama_available() else 'Inactive'}", f"TBRC: {tbrc_info}", @@ -65,7 +65,7 @@ def payload(self) -> dict[str, object]: except Exception: return { "text": "φ 0.500", - "tooltip": "L(t): unavailable\nSovereignty: ON (placeholder)", + "tooltip": "L(t): unavailable\nSovereignty: unverified", "class": "degraded", "percentage": 50, } diff --git a/phios/desktop/sovereignty_indicator.py b/phios/desktop/sovereignty_indicator.py index 9d462a06..54b064a0 100644 --- a/phios/desktop/sovereignty_indicator.py +++ b/phios/desktop/sovereignty_indicator.py @@ -7,10 +7,10 @@ def indicator_payload() -> dict[str, object]: return { - "text": "SOV ON", - "tooltip": "Sovereignty: ON\nMode: local-first", - "class": "coherent", - "percentage": 100, + "text": "UNVERIFIED", + "tooltip": "Sovereignty: unverified\nLocal-first is a design goal, not an attested security state.", + "class": "unverified", + "percentage": 0, } diff --git a/phios/desktop/wayfire_config.py b/phios/desktop/wayfire_config.py index b74f2500..0dc97db7 100644 --- a/phios/desktop/wayfire_config.py +++ b/phios/desktop/wayfire_config.py @@ -33,58 +33,32 @@ def fibonacci_gaps(self, level: int) -> int: return FIBONACCI[level] def _config_text(self) -> str: - return f"""# PhiOS Wayfire Config -# Sacred geometry workspace map: 3x3 with 3/6/9 coherence anchors - + return """# PhiOS Wayfire 0.11 configuration [core] -plugins = grid move resize animate waybar wofi -# custom phi-tray module is integrated through Waybar custom/phi-tray -background_color = {PHIOS_COLORS['deep']} - -[decoration] -border_color = {PHIOS_COLORS['gold']} -border_size = 1 -gap_size = {self.fibonacci_gaps(0)} +plugins = autostart command decoration move resize place grid vswitch wm-actions +vwidth = 3 +vheight = 3 +close_top_view = KEY_Q | KEY_F4 -[grid] -# Golden ratio guidance for primary layout: 61.8 / 38.2 -primary_split = 61.8 -secondary_split = 38.2 +[autostart] +autostart_wf_shell = false +phios = /usr/lib/phishell/session-ready -[workspaces] -rows = 3 -columns = 3 -workspace_1 = 1 -workspace_2 = 2 -workspace_3 = 3 # 3 anchor -workspace_4 = 4 -workspace_5 = 5 -workspace_6 = 6 # 6 anchor -workspace_7 = 7 -workspace_8 = 8 -workspace_9 = 9 # 9 anchor +[command] +binding_terminal = KEY_ENTER +command_terminal = foot phi +binding_launcher = KEY_SPACE +command_launcher = wofi --show drun +binding_coherence = KEY_L +command_coherence = foot phi coherence live +binding_shell = KEY_P +command_shell = phios-open-shell -[keybindings] -super_return = phi -super_space = phi launcher -super_l = phi coherence live -super_s = phi sovereign export ./phi_snapshot_toggle.json -super_shift_q = close -super_1 = workspace 1 -super_2 = workspace 2 -super_3 = workspace 3 -super_4 = workspace 4 -super_5 = workspace 5 -super_6 = workspace 6 -super_7 = workspace 7 -super_8 = workspace 8 -super_9 = workspace 9 +[move] +activate = BTN_LEFT -[animate] -open_animation = fade scale_center -close_animation = fade scale_center -workspace_switch_animation = smooth_slide -duration = 200 +[resize] +activate = BTN_RIGHT """ def generate(self, output_path: str = "~/.config/wayfire.ini") -> str: diff --git a/phios/ghostwalk_operator.py b/phios/ghostwalk_operator.py new file mode 100644 index 00000000..0ac897f6 --- /dev/null +++ b/phios/ghostwalk_operator.py @@ -0,0 +1,209 @@ +"""Explicit terminal review of the existing decision -> binding -> lease chain. + +This process never installs or calls an executor. A terminal is an intentional +operator interface, not proof of a human or isolation from a malicious process +running as the same OS user. Such processes must use a separate OS principal. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import stat +import sys +from datetime import UTC, datetime +from pathlib import Path +from typing import TextIO + +from phios.macro_accepted_intent import GhostWalkAcceptedIntentRegistry +from phios.macro_action_lease_service import GhostWalkActionLeaseService, GhostWalkLeasePolicyRegistry +from phios.macro_authority_request import GhostWalkAuthorityRequestService +from phios.macro_authorization_console import ( + GhostWalkAuthorizationConsoleError, + GhostWalkAuthorizationConsoleService, + GhostWalkAuthorizationConsoleSnapshot, +) +from phios.macro_authorization_decision import ( + GhostWalkAuthorizationDecisionKind, + GhostWalkAuthorizationDecisionService, +) +from phios.macro_capability_binding import ( + GhostWalkCapabilityBindingService, + GhostWalkCapabilityMappingRegistry, +) +from phios.macro_ghostwalk_control_server import DEFAULT_OPERATOR_AUTHOR_ID, default_state_root +from phios.macro_ghostwalk_operator_editor import GhostWalkOperatorEditor +from phios.macro_policy_admission import GhostWalkPolicyAdmissionService, GhostWalkPolicyProfile +from phios.phivessel_local_execution import ( + ManifestAuthorityEpochProvider, + PhiVesselLocalExecutionManifest, + execution_manifest_path, +) +from phios.spine.ledger import RealityLedger + + +def _check_owned_path(path: Path) -> None: + """Reject symlinks and shared-writable state before constructing services.""" + info = path.lstat() + if stat.S_ISLNK(info.st_mode): + raise ValueError(f"operator state must not be a symlink: {path}") + if os.name == "posix": + if info.st_uid != os.getuid() or info.st_mode & 0o022: + raise ValueError(f"operator state must be owned by you and not shared-writable: {path}") + + +def build_operator_console(state_root: Path) -> GhostWalkAuthorizationConsoleService: + root = state_root.expanduser().absolute() + # Existing state is never silently repaired or permission-changed. + root.mkdir(parents=True, exist_ok=True, mode=0o700) + _check_owned_path(root) + for path in root.rglob("*"): + _check_owned_path(path) + ledger_dir = root / "ledger" + ledger_dir.mkdir(exist_ok=True, mode=0o700) + ledger = RealityLedger(ledger_dir / "receipts.jsonl") + editor = GhostWalkOperatorEditor(ledger=ledger, author_id=DEFAULT_OPERATOR_AUTHOR_ID) + intents = GhostWalkAcceptedIntentRegistry(ledger=ledger, accepted_by=DEFAULT_OPERATOR_AUTHOR_ID) + admission = GhostWalkPolicyAdmissionService( + ledger=ledger, accepted_intents=intents, operator_editor=editor, + profile=GhostWalkPolicyProfile.from_environment(os.environ), + ) + requests = GhostWalkAuthorityRequestService( + ledger=ledger, policy_admission=admission, requester_id=DEFAULT_OPERATOR_AUTHOR_ID, + ) + decisions = GhostWalkAuthorizationDecisionService( + ledger=ledger, authority_requests=requests, authorizer_id=DEFAULT_OPERATOR_AUTHOR_ID, + ) + manifest_path = execution_manifest_path(state_root=root) + if not manifest_path.absolute().is_relative_to(root): + raise ValueError("operator execution manifest must be inside the protected state root") + if not manifest_path.exists(): + return GhostWalkAuthorizationConsoleService(authorization_decisions=decisions) + _check_owned_path(manifest_path) + manifest = PhiVesselLocalExecutionManifest.read(manifest_path) + if not manifest.enabled: + return GhostWalkAuthorizationConsoleService(authorization_decisions=decisions) + # The installed desktop executor currently only supports Windows. Linux + # previews must not mint a lease for an unavailable effect implementation. + if sys.platform != "win32" or not manifest.desktop_executor_enabled: + raise ValueError("desktop binding and lease issuance require the supported Windows host") + bindings = GhostWalkCapabilityBindingService( + ledger=ledger, authorization_decisions=decisions, + registry=GhostWalkCapabilityMappingRegistry(manifest.mappings), + ) + leases = GhostWalkActionLeaseService( + ledger=ledger, capability_bindings=bindings, + policies=GhostWalkLeasePolicyRegistry(manifest.lease_policies), + authority_epochs=ManifestAuthorityEpochProvider( + path=manifest_path, expected_static_config_sha256=manifest.static_config_sha256, + ), + ) + return GhostWalkAuthorizationConsoleService( + authorization_decisions=decisions, capability_bindings=bindings, action_leases=leases, + ) + + +def _perform( + console: GhostWalkAuthorizationConsoleService, + snapshot: GhostWalkAuthorizationConsoleSnapshot, + action: str, + decision: str | None, + note: str | None, +) -> dict[str, object]: + target = snapshot.target_inference_receipt_sha256 + if action == "decide": + auth = snapshot.authorization_readiness + if not auth.ready or auth.authority_request_sha256 is None or decision is None: + raise ValueError(f"decision held: {auth.reason.value}") + return console.record_decision( + target_inference_receipt_sha256=target, + expected_authority_request_sha256=auth.authority_request_sha256, + expected_previous_decision_sha256=auth.latest_decision_sha256, + decision=GhostWalkAuthorizationDecisionKind(decision), decision_note=note, + ).to_dict() + if action == "bind": + binding = snapshot.binding_readiness + if (binding is None or not binding.ready or binding.authorization_decision_sha256 is None + or binding.selected_mapping_sha256 is None): + raise ValueError("binding held: current trusted mapping and approval required") + return console.create_binding( + target_inference_receipt_sha256=target, + expected_authorization_decision_sha256=binding.authorization_decision_sha256, + expected_mapping_sha256=binding.selected_mapping_sha256, + expected_mapping_set_sha256=binding.mapping_set_sha256, + bound_at=datetime.now(UTC).isoformat(), + ).to_dict() + lease = snapshot.lease_readiness + if (lease is None or not lease.ready or lease.executable_binding_sha256 is None + or lease.policy_sha256 is None or lease.enforcement_profile_sha256 is None + or lease.authority_epoch_sha256 is None): + raise ValueError("lease held: current binding, policy, enforcement and authority required") + return console.issue_lease( + target_inference_receipt_sha256=target, + expected_executable_binding_sha256=lease.executable_binding_sha256, + expected_policy_sha256=lease.policy_sha256, + expected_policy_set_sha256=lease.policy_set_sha256, + expected_enforcement_profile_sha256=lease.enforcement_profile_sha256, + expected_authority_epoch_sha256=lease.authority_epoch_sha256, + ).to_dict() + + +def review( + console: GhostWalkAuthorizationConsoleService, *, target: str, action: str, + decision: str | None = None, note: str | None = None, + input_stream: TextIO, output_stream: TextIO, +) -> int: + if action not in {"inspect", "decide", "bind", "lease"}: + raise ValueError("unsupported operator action") + if action != "inspect" and not (input_stream.isatty() and output_stream.isatty()): + raise ValueError("operator mutations require an interactive terminal; no unattended flag exists") + snapshot = console.snapshot(target_inference_receipt_sha256=target) + # JSON escaping prevents proposal text from injecting terminal control codes. + print(json.dumps(snapshot.to_dict(), indent=2, ensure_ascii=True), file=output_stream) + if action == "inspect": + return 0 + confirmation = f"{decision if action == 'decide' else action.upper()} {snapshot.snapshot_sha256}" + print(f"Type exactly {confirmation} to confirm, or anything else to cancel:", + file=output_stream, flush=True) + if input_stream.readline().strip() != confirmation: + print("Cancelled; no decision, binding, or lease was created.", file=output_stream) + return 2 + current = console.snapshot(target_inference_receipt_sha256=target) + if current.snapshot_sha256 != snapshot.snapshot_sha256: + raise ValueError("evidence changed during review; inspect and confirm again") + result = _perform(console, snapshot, action, decision, note) + print(json.dumps({"operator_action": action, "result": result, + "execution_authority": False, "effect_performed": False}, indent=2), + file=output_stream) + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--state-root", type=Path, default=default_state_root()) + parser.add_argument("--target", required=True) + actions = parser.add_subparsers(dest="action", required=True) + actions.add_parser("inspect") + decide = actions.add_parser("decide") + decide.add_argument("decision", choices=("APPROVE", "HOLD", "DENY")) + decide.add_argument("--note") + actions.add_parser("bind") + actions.add_parser("lease") + args = parser.parse_args(argv) + try: + if re.fullmatch(r"[0-9a-f]{64}", args.target) is None: + raise ValueError("target must be a lowercase SHA-256 digest") + if args.action != "inspect" and not (sys.stdin.isatty() and sys.stdout.isatty()): + raise ValueError("operator mutations require an interactive terminal") + return review(build_operator_console(args.state_root), target=args.target, action=args.action, + decision=getattr(args, "decision", None), note=getattr(args, "note", None), + input_stream=sys.stdin, output_stream=sys.stdout) + except (ValueError, OSError, GhostWalkAuthorizationConsoleError) as exc: + print(f"Operator action held: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/phios/macro_ghostwalk_control_server.py b/phios/macro_ghostwalk_control_server.py index 65d8ea0f..5c6464a9 100644 --- a/phios/macro_ghostwalk_control_server.py +++ b/phios/macro_ghostwalk_control_server.py @@ -1905,217 +1905,29 @@ def do_GET(self) -> None: def do_POST(self) -> None: parsed = urlsplit(self.path) - if parsed.path == ( - "/api/v1/ghostwalk/authorization-console/decisions" - ): - if parsed.query or parsed.fragment: - self._authorization_console_error( - HTTPStatus.BAD_REQUEST, - "invalid_ghostwalk_authorization_decision_request", - ) - return - if self.server.authorization_console is None: - self._authorization_console_error( - HTTPStatus.SERVICE_UNAVAILABLE, - "ghostwalk_authorization_console_unavailable", - ) - return - try: - ( - target, - request_sha, - previous_sha, - decision, - note, - ) = parse_authorization_console_decision_payload( - self._read_json(max_bytes=8192) - ) - envelope = authorization_console_decision_envelope( - self.server.authorization_console, - target_inference_receipt_sha256=target, - expected_authority_request_sha256=request_sha, - expected_previous_decision_sha256=previous_sha, - decision=decision, - decision_note=note, - ) - except GhostWalkControlBridgeError: - self._authorization_console_error( - HTTPStatus.BAD_REQUEST, - "invalid_ghostwalk_authorization_decision_request", - ) - return - except GhostWalkAuthorizationConsoleError as exc: - message = str(exc) - unavailable = "not mounted" in message - conflict = any( - token in message - for token in ( - "changed before", - "not ready", - "already", - "stale", - ) - ) - self._authorization_console_error( - ( - HTTPStatus.SERVICE_UNAVAILABLE - if unavailable - else HTTPStatus.CONFLICT - if conflict - else HTTPStatus.BAD_REQUEST - ), - ( - "ghostwalk_authorization_console_unavailable" - if unavailable - else "ghostwalk_authorization_decision_conflict" - if conflict - else "ghostwalk_authorization_decision_rejected" - ), - ) - return - self._json(HTTPStatus.OK, envelope) - return - - if parsed.path == ( - "/api/v1/ghostwalk/authorization-console/bindings" - ): - if parsed.query or parsed.fragment: - self._authorization_console_error( - HTTPStatus.BAD_REQUEST, - "invalid_ghostwalk_binding_request", - ) - return - if self.server.authorization_console is None: - self._authorization_console_error( - HTTPStatus.SERVICE_UNAVAILABLE, - "ghostwalk_authorization_console_unavailable", - ) - return - try: - ( - target, - decision_sha, - mapping_sha, - mapping_set_sha, - ) = parse_authorization_console_binding_payload( - self._read_json() - ) - envelope = authorization_console_binding_envelope( - self.server.authorization_console, - target_inference_receipt_sha256=target, - expected_authorization_decision_sha256=decision_sha, - expected_mapping_sha256=mapping_sha, - expected_mapping_set_sha256=mapping_set_sha, - ) - except GhostWalkControlBridgeError: - self._authorization_console_error( - HTTPStatus.BAD_REQUEST, - "invalid_ghostwalk_binding_request", - ) - return - except GhostWalkAuthorizationConsoleError as exc: - message = str(exc) - unavailable = "not mounted" in message - conflict = any( - token in message - for token in ( - "changed before", - "not ready", - "already", - "stale", - ) - ) - self._authorization_console_error( - ( - HTTPStatus.SERVICE_UNAVAILABLE - if unavailable - else HTTPStatus.CONFLICT - if conflict - else HTTPStatus.BAD_REQUEST - ), - ( - "ghostwalk_authorization_console_unavailable" - if unavailable - else "ghostwalk_binding_conflict" - if conflict - else "ghostwalk_binding_rejected" - ), - ) - return - self._json(HTTPStatus.OK, envelope) + if parsed.path in { + "/api/v1/ghostwalk/authorization-console/decisions", + "/api/v1/ghostwalk/authorization-console/bindings", + "/api/v1/ghostwalk/authorization-console/leases", + }: + # Loopback connectivity and agent sessions are not operator approval. + self._authorization_console_error( + HTTPStatus.FORBIDDEN, "operator_channel_required" + ) return - if parsed.path == ( - "/api/v1/ghostwalk/authorization-console/leases" + expected_host = f"{LOOPBACK_HOST}:{self.server.server_address[1]}" + origin = self.headers.get("Origin") + fetch_site = self.headers.get("Sec-Fetch-Site") + mime = self.headers.get("Content-Type", "") + if ( + self.headers.get("Host") != expected_host + or parsed.netloc not in {"", expected_host} + or (origin is not None and origin != f"http://{expected_host}") + or (fetch_site is not None and fetch_site not in {"same-origin", "none"}) + or re.fullmatch(r"application/json(?:\s*;\s*charset=utf-8)?", mime, re.I) is None ): - if parsed.query or parsed.fragment: - self._authorization_console_error( - HTTPStatus.BAD_REQUEST, - "invalid_ghostwalk_lease_request", - ) - return - if self.server.authorization_console is None: - self._authorization_console_error( - HTTPStatus.SERVICE_UNAVAILABLE, - "ghostwalk_authorization_console_unavailable", - ) - return - try: - ( - target, - binding_sha, - policy_sha, - policy_set_sha, - profile_sha, - epoch_sha, - ) = parse_authorization_console_lease_payload( - self._read_json() - ) - envelope = authorization_console_lease_envelope( - self.server.authorization_console, - target_inference_receipt_sha256=target, - expected_executable_binding_sha256=binding_sha, - expected_policy_sha256=policy_sha, - expected_policy_set_sha256=policy_set_sha, - expected_enforcement_profile_sha256=profile_sha, - expected_authority_epoch_sha256=epoch_sha, - ) - except GhostWalkControlBridgeError: - self._authorization_console_error( - HTTPStatus.BAD_REQUEST, - "invalid_ghostwalk_lease_request", - ) - return - except GhostWalkAuthorizationConsoleError as exc: - message = str(exc) - unavailable = "not mounted" in message - conflict = any( - token in message - for token in ( - "changed before", - "not ready", - "already", - "stale", - ) - ) - self._authorization_console_error( - ( - HTTPStatus.SERVICE_UNAVAILABLE - if unavailable - else HTTPStatus.CONFLICT - if conflict - else HTTPStatus.BAD_REQUEST - ), - ( - "ghostwalk_authorization_console_unavailable" - if unavailable - else "ghostwalk_lease_conflict" - if conflict - else "ghostwalk_lease_rejected" - ), - ) - return - self._json(HTTPStatus.OK, envelope) + self._authorization_console_error(HTTPStatus.FORBIDDEN, "invalid_local_write_origin") return if parsed.path == "/api/v1/phivessel/handshake": diff --git a/phios/mandala/ledger.py b/phios/mandala/ledger.py index d34cf660..a4bf9d2f 100644 --- a/phios/mandala/ledger.py +++ b/phios/mandala/ledger.py @@ -1,8 +1,9 @@ from __future__ import annotations -import json from pathlib import Path +from phios.state_io import append_jsonl, read_jsonl + from .receipts import ReceiptEnvelope @@ -13,44 +14,30 @@ def __init__(self, path: Path) -> None: self.path = path.expanduser() def append(self, receipt: ReceiptEnvelope) -> None: - self.path.parent.mkdir(parents=True, exist_ok=True) - with self.path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(self.path, receipt.to_dict()) + + def append_if_absent(self, receipt: ReceiptEnvelope) -> bool: + """Publish exactly once across processes, refusing identity collisions.""" + return append_jsonl(self.path, receipt.to_dict(), identity_field="receipt_id") def recent(self, limit: int = 10) -> list[dict[str, object]]: if isinstance(limit, bool) or not isinstance(limit, int): raise TypeError("recent limit must be an integer") if limit < 0: raise ValueError("recent limit must be non-negative") - if limit == 0 or not self.path.exists(): + if limit == 0: return [] - lines = self.path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(self.path)[-limit:] def has_receipt(self, receipt_id: str) -> bool: """Return whether an exact receipt ID already exists in the append-only ledger.""" - if not self.path.exists(): - return False - for line in self.path.read_text(encoding="utf-8").splitlines(): - try: - payload = json.loads(line) - except json.JSONDecodeError: - continue - if isinstance(payload, dict) and payload.get("receipt_id") == receipt_id: - return True - return False + return self.get_receipt(receipt_id) is not None def get_receipt(self, receipt_id: str) -> dict[str, object] | None: """Return the persisted receipt row for an exact receipt ID.""" - if not self.path.exists(): - return None - for line in self.path.read_text(encoding="utf-8").splitlines(): - try: - payload = json.loads(line) - except json.JSONDecodeError: - continue - if isinstance(payload, dict) and payload.get("receipt_id") == receipt_id: + for payload in read_jsonl(self.path): + if payload.get("receipt_id") == receipt_id: return payload return None diff --git a/phios/memory/cli.py b/phios/memory/cli.py index 6d60320d..25175467 100644 --- a/phios/memory/cli.py +++ b/phios/memory/cli.py @@ -7,6 +7,7 @@ from pathlib import Path from phios.mandala import OriginKind +from phios.state_paths import configured_state_root, memory_config_path from .config import MemoryRuntimeConfig, write_disabled_template from .legacy import plan_legacy_agent_memory_import @@ -15,8 +16,8 @@ from .operator import MemoryOperatorRuntime from .system_history import SystemHistoryPersistenceBridge -DEFAULT_CONFIG = Path.home() / ".phios" / "memory" / "config.json" -DEFAULT_STATE_ROOT = Path.home() / ".phios" / "memory" +DEFAULT_CONFIG = memory_config_path() +DEFAULT_STATE_ROOT = configured_state_root() / "memory" def build_parser() -> argparse.ArgumentParser: diff --git a/phios/memory/publisher.py b/phios/memory/publisher.py index 8e523f7f..a2c1a638 100644 --- a/phios/memory/publisher.py +++ b/phios/memory/publisher.py @@ -18,8 +18,7 @@ def publish_pending(self) -> int: published = 0 for payload in self.store.pending_receipts(): receipt = _receipt_from_payload(payload) - if not self.ledger.has_receipt(receipt.receipt_id): - self.ledger.append(receipt) + self.ledger.append_if_absent(receipt) self.store.mark_receipt_published(receipt.operation_id) published += 1 return published diff --git a/phios/memory/store.py b/phios/memory/store.py index fed943bf..97798c0a 100644 --- a/phios/memory/store.py +++ b/phios/memory/store.py @@ -1,13 +1,17 @@ from __future__ import annotations import json +import hashlib import sqlite3 +from contextlib import contextmanager from datetime import UTC, datetime from pathlib import Path -from typing import Any +from typing import Any, Iterator + +from phios.state_io import StateIntegrityError, prepare_state_file from .models import MemoryRecord -from .validation import strict_canonical_json +from .validation import sha256_json, strict_canonical_json SCHEMA_VERSION = 1 @@ -17,19 +21,36 @@ class MemoryStore: def __init__(self, path: Path) -> None: self.path = path.expanduser() - self.path.parent.mkdir(parents=True, exist_ok=True) + prepare_state_file(self.path) self._initialize() - def _connect(self) -> sqlite3.Connection: - conn = sqlite3.connect(self.path) - conn.row_factory = sqlite3.Row - conn.execute("PRAGMA foreign_keys = ON") - return conn + @contextmanager + def _connect(self) -> Iterator[sqlite3.Connection]: + conn = sqlite3.connect(self.path, timeout=30, isolation_level=None) + try: + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA synchronous = FULL") + # Acquire the writer reservation before reading an idempotency key + # or revision head, not after another writer can change it. + conn.execute("BEGIN IMMEDIATE") + yield conn + conn.commit() + except BaseException: + conn.rollback() + raise + finally: + conn.close() def _initialize(self) -> None: with self._connect() as conn: - conn.executescript( - """ + if conn.execute("SELECT 1 FROM sqlite_master WHERE name='store_metadata'").fetchone(): + prior = conn.execute( + "SELECT value FROM store_metadata WHERE key='schema_version'" + ).fetchone() + if prior is not None and int(prior["value"]) != SCHEMA_VERSION: + raise RuntimeError("unsupported governed-memory schema version") + schema = """ CREATE TABLE IF NOT EXISTS store_metadata ( key TEXT PRIMARY KEY, value TEXT NOT NULL @@ -71,7 +92,11 @@ def _initialize(self) -> None: status TEXT NOT NULL DEFAULT 'pending' ); """ - ) + # executescript implicitly commits in Python's legacy transaction + # mode. Execute this fixed DDL within the same held transaction. + for statement in schema.split(";"): + if statement.strip(): + conn.execute(statement) row = conn.execute( "SELECT value FROM store_metadata WHERE key='schema_version'" ).fetchone() @@ -196,8 +221,8 @@ def mark_receipt_published(self, operation_id: str) -> None: if payload.get("operation") in {"put", "revise"}: record_id = payload["record_versions"][0]["record_id"] conn.execute( - "UPDATE record_heads SET published=1 WHERE record_id=?", - (record_id,), + "UPDATE record_heads SET published=1 WHERE record_id=? AND revision=?", + (record_id, payload["record_versions"][0]["revision"]), ) def pending_receipts(self) -> list[dict[str, object]]: @@ -479,7 +504,7 @@ def _live_record_from_row( @staticmethod def _record_from_payload(payload: dict[str, Any]) -> MemoryRecord: - return MemoryRecord( + record = MemoryRecord( record_id=str(payload["record_id"]), revision=int(payload["revision"]), source_id=str(payload["source_id"]), @@ -507,3 +532,10 @@ def _record_from_payload(payload: dict[str, Any]) -> MemoryRecord: content_sha256=str(payload["content_sha256"]), record_sha256=str(payload["record_sha256"]), ) + body = record.to_dict() + body.pop("record_sha256") + if (record.to_dict() != payload or + hashlib.sha256(record.text.encode("utf-8")).hexdigest() != record.content_sha256 or + sha256_json(body) != record.record_sha256): + raise StateIntegrityError("canonical memory record integrity check failed") + return record diff --git a/phios/memory/system_history_comparison.py b/phios/memory/system_history_comparison.py index 3095a4a5..0a74c592 100644 --- a/phios/memory/system_history_comparison.py +++ b/phios/memory/system_history_comparison.py @@ -111,7 +111,9 @@ def _comparable_state_payload( expected_schema, expected_source = COMPONENT_CONTRACTS[expected_id] if component.get("schemaVersion") != expected_schema: raise ValueError(f"component {expected_id} schema is not canonical") - if component.get("source") != expected_source: + if component.get("source") != expected_source and not ( + expected_id == "packages" and component.get("source") == "pacman-local-desc" + ): raise ValueError(f"component {expected_id} source is not canonical") _timestamp(component.get("capturedAt"), f"component {expected_id} capturedAt") if component.get("readOnly") is not True: diff --git a/phios/shell/phi_commands.py b/phios/shell/phi_commands.py index 6f019f26..a18192f0 100644 --- a/phios/shell/phi_commands.py +++ b/phios/shell/phi_commands.py @@ -2212,7 +2212,7 @@ def cmd_version(_: list[str], session: object | None = None) -> str: "PhiOS v0.1.0 (compat)", "PHI369 Labs / Parallax", "Sovereign. Coherent. Local. Free.", - "License: GPL-3.0", + "License: MIT (PhiOS source; bundled packages retain their own licenses)", ] ) @@ -3971,18 +3971,22 @@ def _iso_status() -> dict[str, object]: dist_dir = Path("dist") latest = None if dist_dir.exists(): - isos = sorted(dist_dir.glob("phios-v*-x86_64.iso")) + isos = sorted([*dist_dir.glob("phios-v*-x86_64.iso"), *(dist_dir / "linux").glob("phios-linux-*-x86_64.iso")], key=lambda path: path.stat().st_mtime) if isos: latest = isos[-1] if latest is None: return {"exists": False, "path": None, "size": None, "sha256": None} - data = latest.read_bytes() + digest = hashlib.sha256() + with latest.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) return { + "release_ready": False, "exists": True, "path": str(latest), "size": latest.stat().st_size, - "sha256": hashlib.sha256(data).hexdigest(), + "sha256": digest.hexdigest(), } @@ -4146,10 +4150,13 @@ def cmd_build(args: list[str], session: object | None = None) -> str: confirmed = len(args) > 1 and args[1] == "--yes" if not confirmed: return "Refusing to build ISO without explicit confirmation. Re-run: phi build iso --yes" - proc = subprocess.run(["bash", "build/build_iso.sh"], capture_output=True, text=True, check=False) + script = Path(__file__).resolve().parents[2] / "build" / "build_iso.sh" + if not script.is_file(): + raise RuntimeError("OS image building requires a source checkout with build/build_iso.sh") + proc = subprocess.run(["bash", str(script)], capture_output=True, text=True, check=False) output = (proc.stdout or "") + (proc.stderr or "") if proc.returncode != 0: - return f"ISO build failed\n{output}" + raise RuntimeError(f"ISO build failed (exit {proc.returncode})\n{output}") return f"ISO build completed\n{output}" return "Usage: build [iso|status|clean]" diff --git a/phios/spine/ledger.py b/phios/spine/ledger.py index 9ff2d1b7..76f8afae 100644 --- a/phios/spine/ledger.py +++ b/phios/spine/ledger.py @@ -1,10 +1,11 @@ from __future__ import annotations -import json import os from pathlib import Path from typing import TYPE_CHECKING +from phios.state_io import append_jsonl, read_jsonl, sync_directory + from .models import ExecutionReceipt if TYPE_CHECKING: @@ -69,9 +70,7 @@ def __init__(self, path: Path) -> None: self.path = path.expanduser() def append(self, receipt: ExecutionReceipt) -> None: - self.path.parent.mkdir(parents=True, exist_ok=True) - with self.path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(self.path, receipt.to_dict()) def recent(self, limit: int = 10) -> list[dict[str, object]]: if isinstance(limit, bool) or not isinstance(limit, int): @@ -80,16 +79,13 @@ def recent(self, limit: int = 10) -> list[dict[str, object]]: raise ValueError("recent limit must be non-negative") if limit == 0 or not self.path.exists(): return [] - lines = self.path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(self.path)[-limit:] def append_macro_receipt(self, receipt: "MacroSpineReceipt") -> None: """Append one immutable macro-to-Spine execution receipt.""" path = self.path.parent / "macro-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_macro_receipts( self, @@ -104,8 +100,7 @@ def recent_macro_receipts( path = self.path.parent / "macro-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_macro_dispatch_receipt( self, @@ -114,9 +109,7 @@ def append_macro_dispatch_receipt( """Append one immutable governed DO dispatch receipt.""" path = self.path.parent / "macro-dispatch-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_macro_dispatch_receipts( self, @@ -135,8 +128,7 @@ def recent_macro_dispatch_receipts( path = self.path.parent / "macro-dispatch-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_macro_run_journal_entry( self, @@ -145,9 +137,7 @@ def append_macro_run_journal_entry( """Append one immutable MacroRunState journal entry.""" path = self.path.parent / "macro-run-journal.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(entry.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, entry.to_dict()) def macro_run_journal_entries( self, @@ -160,8 +150,8 @@ def macro_run_journal_entries( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if run_id is None: return rows @@ -174,9 +164,7 @@ def append_macro_run_resume_receipt( """Append evidence for one validated MacroRun reconstruction.""" path = self.path.parent / "macro-run-resume-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_macro_run_resume_receipts( self, @@ -195,8 +183,7 @@ def recent_macro_run_resume_receipts( path = self.path.parent / "macro-run-resume-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_macro_run_start_receipt( self, @@ -205,9 +192,7 @@ def append_macro_run_start_receipt( """Append one immutable macro run-start admission receipt.""" path = self.path.parent / "macro-run-start-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_macro_run_start_receipts( self, @@ -226,15 +211,14 @@ def recent_macro_run_start_receipts( path = self.path.parent / "macro-run-start-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def claim_macro_start_dedupe(self, dedupe_sha256: str) -> bool: """Atomically reserve one trigger/macro admission identity.""" self._validate_sha256(dedupe_sha256, "dedupe_sha256") claim_dir = self.path.parent / "macro-start-dedupe-claims" - claim_dir.mkdir(parents=True, exist_ok=True) + claim_dir.mkdir(mode=0o700, parents=True, exist_ok=True) claim_path = claim_dir / f"{dedupe_sha256}.claim" try: fd = os.open( @@ -246,6 +230,9 @@ def claim_macro_start_dedupe(self, dedupe_sha256: str) -> bool: return False with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(dedupe_sha256 + "\n") + handle.flush() + os.fsync(handle.fileno()) + sync_directory(claim_dir) return True def release_macro_start_dedupe_claim(self, dedupe_sha256: str) -> None: @@ -258,13 +245,15 @@ def release_macro_start_dedupe_claim(self, dedupe_sha256: str) -> None: / f"{dedupe_sha256}.claim" ) claim_path.unlink(missing_ok=True) + if claim_path.parent.exists(): + sync_directory(claim_path.parent) def claim_macro_run_id(self, run_id_sha256: str) -> bool: """Atomically reserve one requested macro run identity.""" self._validate_sha256(run_id_sha256, "run_id_sha256") claim_dir = self.path.parent / "macro-run-id-claims" - claim_dir.mkdir(parents=True, exist_ok=True) + claim_dir.mkdir(mode=0o700, parents=True, exist_ok=True) claim_path = claim_dir / f"{run_id_sha256}.claim" try: fd = os.open( @@ -276,6 +265,9 @@ def claim_macro_run_id(self, run_id_sha256: str) -> bool: return False with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(run_id_sha256 + "\n") + handle.flush() + os.fsync(handle.fileno()) + sync_directory(claim_dir) return True def release_macro_run_id_claim(self, run_id_sha256: str) -> None: @@ -288,6 +280,8 @@ def release_macro_run_id_claim(self, run_id_sha256: str) -> None: / f"{run_id_sha256}.claim" ) claim_path.unlink(missing_ok=True) + if claim_path.parent.exists(): + sync_directory(claim_path.parent) def append_schedule_service_state( self, @@ -296,9 +290,7 @@ def append_schedule_service_state( """Append one immutable schedule-service cursor/state entry.""" path = self.path.parent / "schedule-service-state.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(entry.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, entry.to_dict()) def schedule_service_state_entries( self, @@ -311,8 +303,8 @@ def schedule_service_state_entries( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if service_id is None: return rows @@ -325,9 +317,7 @@ def append_schedule_service_poll_receipt( """Append one immutable schedule-service poll receipt.""" path = self.path.parent / "schedule-service-poll-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_schedule_service_poll_receipts( self, @@ -346,8 +336,7 @@ def recent_schedule_service_poll_receipts( path = self.path.parent / "schedule-service-poll-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_schedule_worker_lease( self, @@ -356,9 +345,7 @@ def append_schedule_worker_lease( """Append one immutable schedule-worker lease snapshot.""" path = self.path.parent / "schedule-worker-leases.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(lease.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, lease.to_dict()) def latest_schedule_worker_lease( self, @@ -371,8 +358,7 @@ def latest_schedule_worker_lease( if not path.exists(): return None latest: dict[str, object] | None = None - for line in path.read_text(encoding="utf-8").splitlines(): - row = json.loads(line) + for row in read_jsonl(path): if row.get("service_id") == service_id: latest = row return latest @@ -384,9 +370,7 @@ def append_schedule_worker_event( """Append one immutable worker ownership lifecycle event.""" path = self.path.parent / "schedule-worker-events.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(event.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, event.to_dict()) def schedule_worker_events( self, @@ -399,8 +383,8 @@ def schedule_worker_events( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if service_id is None: return rows @@ -413,9 +397,7 @@ def append_schedule_worker_tick_receipt( """Append one immutable schedule-worker cycle receipt.""" path = self.path.parent / "schedule-worker-ticks.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def schedule_worker_tick_receipts( self, @@ -428,8 +410,8 @@ def schedule_worker_tick_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if service_id is None: return rows @@ -463,11 +445,7 @@ def append_operator_log_revision( """Append one immutable operator-log revision.""" path = self.path.parent / "operator-log-revisions.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(revision.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, revision.to_dict()) def operator_log_revisions( self, @@ -480,8 +458,8 @@ def operator_log_revisions( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if note_id is None: return rows @@ -497,11 +475,7 @@ def append_ghostwalk_accepted_intent_revision( self.path.parent / "ghostwalk-accepted-intent-revisions.jsonl" ) - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(revision.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, revision.to_dict()) def ghostwalk_accepted_intent_revisions( self, @@ -517,8 +491,8 @@ def ghostwalk_accepted_intent_revisions( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is None: return rows @@ -539,11 +513,7 @@ def append_ghostwalk_policy_admission_receipt( self.path.parent / "ghostwalk-policy-admission-receipts.jsonl" ) - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(receipt.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, receipt.to_dict()) def ghostwalk_policy_admission_receipts( self, @@ -559,8 +529,8 @@ def ghostwalk_policy_admission_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is None: return rows @@ -578,11 +548,7 @@ def append_ghostwalk_authority_request( """Append one immutable Ghost-Walk authority request.""" path = self.path.parent / "ghostwalk-authority-requests.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(request.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, request.to_dict()) def ghostwalk_authority_requests( self, @@ -595,8 +561,8 @@ def ghostwalk_authority_requests( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is None: return rows @@ -614,11 +580,7 @@ def append_ghostwalk_authorization_decision( """Append one immutable Ghost-Walk authorization decision.""" path = self.path.parent / "ghostwalk-authorization-decisions.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(decision.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, decision.to_dict()) def ghostwalk_authorization_decisions( self, @@ -631,8 +593,8 @@ def ghostwalk_authorization_decisions( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if authority_request_sha256 is None: return rows @@ -650,11 +612,7 @@ def append_ghostwalk_executable_binding( """Append one immutable Ghost-Walk executable binding.""" path = self.path.parent / "ghostwalk-executable-bindings.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(binding.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, binding.to_dict()) def ghostwalk_executable_bindings( self, @@ -668,8 +626,8 @@ def ghostwalk_executable_bindings( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is not None: rows = [ @@ -694,11 +652,7 @@ def append_ghostwalk_action_lease_record( """Append one immutable Ghost-Walk ActionLease custody record.""" path = self.path.parent / "ghostwalk-action-lease-records.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(record.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, record.to_dict()) def ghostwalk_action_lease_records( self, @@ -713,8 +667,8 @@ def ghostwalk_action_lease_records( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is not None: rows = [ @@ -747,11 +701,7 @@ def append_ghostwalk_lease_execution_receipt( """Append one immutable Ghost-Walk leased execution receipt.""" path = self.path.parent / "ghostwalk-lease-execution-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(receipt.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, receipt.to_dict()) def ghostwalk_lease_execution_receipts( self, @@ -764,8 +714,8 @@ def ghostwalk_lease_execution_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if action_lease_sha256 is None: return rows @@ -782,11 +732,7 @@ def append_phivessel_proposal( """Append one zero-authority PhiVessel proposal record.""" path = self.path.parent / "phivessel-proposals.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(proposal.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, proposal.to_dict()) def phivessel_proposals( self, @@ -799,8 +745,8 @@ def phivessel_proposals( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if work_id is None: return rows @@ -817,11 +763,7 @@ def append_interaction_guard_receipt( """Append one immutable GUI interaction guard receipt.""" path = self.path.parent / "interaction-guard-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(receipt.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, receipt.to_dict()) def recent_interaction_guard_receipts( self, @@ -840,8 +782,7 @@ def recent_interaction_guard_receipts( path = self.path.parent / "interaction-guard-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_ghostwalk_session( self, @@ -850,9 +791,7 @@ def append_ghostwalk_session( """Append one immutable ghost-walk demonstration session.""" path = self.path.parent / "ghostwalk-sessions.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(session.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, session.to_dict()) def ghostwalk_sessions( self, @@ -865,8 +804,8 @@ def ghostwalk_sessions( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if session_id is None: return rows @@ -879,11 +818,7 @@ def append_ghostwalk_observation( """Append one immutable ghost-walk observation.""" path = self.path.parent / "ghostwalk-observations.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(observation.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, observation.to_dict()) def ghostwalk_observations( self, @@ -896,8 +831,8 @@ def ghostwalk_observations( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if session_id is None: return rows @@ -910,9 +845,7 @@ def append_ghostwalk_draft_receipt( """Append one immutable ghost-walk draft compilation receipt.""" path = self.path.parent / "ghostwalk-draft-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_ghostwalk_draft_receipts( self, @@ -931,8 +864,7 @@ def recent_ghostwalk_draft_receipts( path = self.path.parent / "ghostwalk-draft-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_ghostwalk_capture_receipt( self, @@ -941,9 +873,7 @@ def append_ghostwalk_capture_receipt( """Append one immutable ghost-walk OS capture receipt.""" path = self.path.parent / "ghostwalk-capture-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_ghostwalk_capture_receipts( self, @@ -962,8 +892,7 @@ def recent_ghostwalk_capture_receipts( path = self.path.parent / "ghostwalk-capture-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_ghostwalk_listener_receipt( self, @@ -972,9 +901,7 @@ def append_ghostwalk_listener_receipt( """Append one immutable Windows ghost-walk listener receipt.""" path = self.path.parent / "ghostwalk-listener-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def ghostwalk_listener_receipts( self, @@ -987,8 +914,8 @@ def ghostwalk_listener_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if listener_id is None: return rows @@ -1031,9 +958,7 @@ def append_uia_element_snapshot( """Append one immutable privacy-bounded UIA element snapshot.""" path = self.path.parent / "uia-element-snapshots.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(snapshot.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, snapshot.to_dict()) def uia_element_snapshots( self, @@ -1046,8 +971,8 @@ def uia_element_snapshots( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if snapshot_sha256 is None: return rows @@ -1064,9 +989,7 @@ def append_uia_lookup_receipt( """Append one immutable Windows UIA semantic lookup receipt.""" path = self.path.parent / "uia-lookup-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_uia_lookup_receipts( self, @@ -1085,8 +1008,7 @@ def recent_uia_lookup_receipts( path = self.path.parent / "uia-lookup-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_semantic_revalidation_receipt( self, @@ -1095,9 +1017,7 @@ def append_semantic_revalidation_receipt( """Append one immutable semantic selector replay receipt.""" path = self.path.parent / "semantic-revalidation-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_semantic_revalidation_receipts( self, @@ -1116,8 +1036,7 @@ def recent_semantic_revalidation_receipts( path = self.path.parent / "semantic-revalidation-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_desktop_interaction_receipt( self, @@ -1126,9 +1045,7 @@ def append_desktop_interaction_receipt( """Append one immutable governed desktop interaction receipt.""" path = self.path.parent / "desktop-interaction-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_desktop_interaction_receipts( self, @@ -1147,8 +1064,7 @@ def recent_desktop_interaction_receipts( path = self.path.parent / "desktop-interaction-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_post_action_verification_receipt( self, @@ -1157,9 +1073,7 @@ def append_post_action_verification_receipt( """Append one immutable post-action verification receipt.""" path = self.path.parent / "post-action-verification-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_post_action_verification_receipts( self, @@ -1178,8 +1092,7 @@ def recent_post_action_verification_receipts( path = self.path.parent / "post-action-verification-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_ghostwalk_state_snapshot( self, @@ -1188,9 +1101,7 @@ def append_ghostwalk_state_snapshot( """Append one immutable before/after Ghost-Walk UI state snapshot.""" path = self.path.parent / "ghostwalk-ui-state-snapshots.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(snapshot.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, snapshot.to_dict()) def ghostwalk_state_snapshots( self, @@ -1203,8 +1114,8 @@ def ghostwalk_state_snapshots( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if action_observation_sha256 is None: return rows @@ -1222,9 +1133,7 @@ def append_transition_inference_receipt( """Append one immutable Ghost-Walk transition inference receipt.""" path = self.path.parent / "transition-inference-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_transition_inference_receipts( self, @@ -1243,8 +1152,7 @@ def recent_transition_inference_receipts( path = self.path.parent / "transition-inference-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def transition_inference_receipt( self, @@ -1256,8 +1164,7 @@ def transition_inference_receipt( path = self.path.parent / "transition-inference-receipts.jsonl" if not path.exists(): return None - for line in reversed(path.read_text(encoding="utf-8").splitlines()): - row = json.loads(line) + for row in reversed(read_jsonl(path)): if row.get("receipt_sha256") == receipt_sha256: return row return None @@ -1269,9 +1176,7 @@ def append_uia_state_observation_receipt( """Append one immutable bounded UIA state-observer receipt.""" path = self.path.parent / "uia-state-observer-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_uia_state_observation_receipts( self, @@ -1290,8 +1195,7 @@ def recent_uia_state_observation_receipts( path = self.path.parent / "uia-state-observer-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_transition_coordinator_receipt( self, @@ -1300,9 +1204,7 @@ def append_transition_coordinator_receipt( """Append one immutable Ghost-Walk transition coordinator receipt.""" path = self.path.parent / "transition-coordinator-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_transition_coordinator_receipts( self, @@ -1321,8 +1223,7 @@ def recent_transition_coordinator_receipts( path = self.path.parent / "transition-coordinator-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_baseline_refresh_receipt( self, @@ -1331,9 +1232,7 @@ def append_baseline_refresh_receipt( """Append one immutable Ghost-Walk baseline refresh receipt.""" path = self.path.parent / "baseline-refresh-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def baseline_refresh_receipts( self, @@ -1346,8 +1245,8 @@ def baseline_refresh_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if service_id is None: return rows @@ -1413,9 +1312,7 @@ def append_ghostwalk_host_receipt( """Append one immutable Ghost-Walk host lifecycle receipt.""" path = self.path.parent / "ghostwalk-host-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def ghostwalk_host_receipts( self, @@ -1428,8 +1325,8 @@ def ghostwalk_host_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if host_id is None: return rows @@ -1495,9 +1392,7 @@ def append_ghostwalk_control_receipt( """Append one immutable Ghost-Walk control-surface receipt.""" path = self.path.parent / "ghostwalk-control-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def ghostwalk_control_receipts( self, @@ -1510,8 +1405,8 @@ def ghostwalk_control_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if surface_id is None: return rows @@ -1581,9 +1476,7 @@ def append_reconciliation( """Append one immutable reconciliation receipt beside execution history.""" path = self.path.parent / "execution-reconciliations.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_reconciliations( self, @@ -1598,15 +1491,14 @@ def recent_reconciliations( path = self.path.parent / "execution-reconciliations.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def claim_binding(self, binding_sha256: str) -> bool: """Atomically reserve one governed binding for an execution attempt.""" self._validate_binding_sha256(binding_sha256) claim_dir = self.path.parent / "binding-claims" - claim_dir.mkdir(parents=True, exist_ok=True) + claim_dir.mkdir(mode=0o700, parents=True, exist_ok=True) claim_path = claim_dir / f"{binding_sha256}.claim" try: fd = os.open( @@ -1618,6 +1510,9 @@ def claim_binding(self, binding_sha256: str) -> bool: return False with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(binding_sha256 + "\n") + handle.flush() + os.fsync(handle.fileno()) + sync_directory(claim_dir) return True def release_binding_claim(self, binding_sha256: str) -> None: @@ -1630,14 +1525,15 @@ def release_binding_claim(self, binding_sha256: str) -> None: / f"{binding_sha256}.claim" ) claim_path.unlink(missing_ok=True) + if claim_path.parent.exists(): + sync_directory(claim_path.parent) def has_consumed_binding(self, binding_sha256: str) -> bool: """Return true once a bound action reached an allowed executor attempt.""" if not self.path.exists(): return False - for line in self.path.read_text(encoding="utf-8").splitlines(): - entry = json.loads(line) + for entry in read_jsonl(self.path): provenance = entry.get("governed_provenance") if not isinstance(provenance, dict): continue @@ -1654,7 +1550,7 @@ def claim_action_lease(self, lease_sha256: str) -> bool: self._validate_sha256(lease_sha256, "lease_sha256") claim_dir = self.path.parent / "action-lease-claims" - claim_dir.mkdir(parents=True, exist_ok=True) + claim_dir.mkdir(mode=0o700, parents=True, exist_ok=True) claim_path = claim_dir / f"{lease_sha256}.claim" try: fd = os.open( @@ -1666,6 +1562,9 @@ def claim_action_lease(self, lease_sha256: str) -> bool: return False with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(lease_sha256 + "\n") + handle.flush() + os.fsync(handle.fileno()) + sync_directory(claim_dir) return True def release_action_lease_claim(self, lease_sha256: str) -> None: @@ -1678,6 +1577,8 @@ def release_action_lease_claim(self, lease_sha256: str) -> None: / f"{lease_sha256}.claim" ) claim_path.unlink(missing_ok=True) + if claim_path.parent.exists(): + sync_directory(claim_path.parent) def has_consumed_action_lease(self, lease_sha256: str) -> bool: """Return true once an ActionLease reached an allowed executor attempt.""" @@ -1685,8 +1586,7 @@ def has_consumed_action_lease(self, lease_sha256: str) -> bool: self._validate_sha256(lease_sha256, "lease_sha256") if not self.path.exists(): return False - for line in self.path.read_text(encoding="utf-8").splitlines(): - entry = json.loads(line) + for entry in read_jsonl(self.path): provenance = entry.get("governed_provenance") if not isinstance(provenance, dict): continue diff --git a/phios/spine/runtime.py b/phios/spine/runtime.py index c33038dd..0bd2b205 100644 --- a/phios/spine/runtime.py +++ b/phios/spine/runtime.py @@ -62,6 +62,7 @@ SomaPerceptionService, TesseractOcrProvider, ) +from phios.state_paths import configured_state_root from .api_keys import ApiKeyBoundary from .collaborator import PhiVesselAdapter @@ -94,7 +95,7 @@ def __init__( allowed_permissions: Iterable[str] = (), task_id: str | None = None, ) -> None: - self.state_root = (state_root or Path.home() / ".phios" / "spine-v0.1").expanduser() + self.state_root = (state_root or configured_state_root() / "spine-v0.1").expanduser() allowed = tuple(dict.fromkeys(allowed_permissions)) self.registry = CapabilityRegistry() self.api_keys = ApiKeyBoundary() diff --git a/phios/state_io.py b/phios/state_io.py new file mode 100644 index 00000000..be8568fb --- /dev/null +++ b/phios/state_io.py @@ -0,0 +1,209 @@ +"""Durable JSONL I/O; receipt content and authority remain caller-owned. + +Writers serialize on the file inode, sync before acknowledging an append and +refuse corrupt/truncated history. Recovery is never an implicit read side effect. +""" +from __future__ import annotations + +import json +import importlib +import os +import stat +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Iterator, Mapping + +MAX_RECORD_BYTES = 16 * 1024 * 1024 + + +def sync_directory(path: Path) -> None: + if os.name == "posix": + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + + +class StateIntegrityError(ValueError): + """State is unsafe or incomplete; preserve it for explicit recovery.""" + + +def _encode(payload: Mapping[str, Any]) -> bytes: + data = (json.dumps(dict(payload), sort_keys=True, ensure_ascii=False, + allow_nan=False) + "\n").encode("utf-8") + if len(data) > MAX_RECORD_BYTES: + raise ValueError("state record exceeds 16 MiB") + return data + + +def _object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise StateIntegrityError("duplicate JSON object key") + result[key] = value + return result + + +def _reject_constant(value: str) -> None: + raise StateIntegrityError(f"non-finite JSON value: {value}") + + +def _prefix(handle: Any, *, preserve_tail: bool) -> tuple[list[dict[str, Any]], bytes]: + handle.seek(0) + result: list[dict[str, Any]] = [] + number = 0 + while line := handle.readline(MAX_RECORD_BYTES + 1): + number += 1 + if len(line) > MAX_RECORD_BYTES: + raise StateIntegrityError(f"oversize state record at line {number}") + if not line.endswith(b"\n"): + if preserve_tail: + return result, line + raise StateIntegrityError(f"incomplete state record at line {number}") + try: + row = json.loads(line, object_pairs_hook=_object, parse_constant=_reject_constant) + except (ValueError, UnicodeError) as exc: + raise StateIntegrityError(f"invalid state record at line {number}: {exc}") from exc + if not isinstance(row, dict): + raise StateIntegrityError(f"state record at line {number} must be an object") + result.append(row) + return result, b"" + + +def _rows(handle: Any) -> list[dict[str, Any]]: + return _prefix(handle, preserve_tail=False)[0] + + +@contextmanager +def _parent(path: Path, *, create: bool) -> Iterator[int | None]: + """Walk POSIX parents without following symlinks, including ancestors.""" + if os.name != "posix": + for ancestor in (path, *path.parents): + if ancestor.is_symlink(): + raise StateIntegrityError("state paths cannot contain symlinks") + if create: + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + yield None + return + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + parent = os.open(path.anchor, flags) + try: + for part in path.parts[1:-1]: + if create: + try: + os.mkdir(part, mode=0o700, dir_fd=parent) + except FileExistsError: + pass + else: + os.fsync(parent) + child = os.open(part, flags, dir_fd=parent) + os.close(parent) + parent = child + yield parent + finally: + os.close(parent) + + +@contextmanager +def _locked(path: Path, *, write: bool) -> Iterator[tuple[Any, int | None]]: + path = path.expanduser().absolute() + with _parent(path, create=write) as parent: + flags = os.O_RDWR if write or os.name == "nt" else os.O_RDONLY + flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) + location: str | Path = path.name if parent is not None else path + options = {"dir_fd": parent} if parent is not None else {} + if write: + try: + fd = os.open(location, flags | os.O_CREAT | os.O_EXCL, 0o600, **options) + except FileExistsError: + fd = os.open(location, flags, **options) + else: + fd = os.open(location, flags, **options) + with os.fdopen(fd, "r+b" if write or os.name == "nt" else "rb", buffering=0) as handle: + info = os.fstat(handle.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: + raise StateIntegrityError("state must be a regular file with one link") + if os.name == "posix": + if info.st_uid != os.getuid() or info.st_mode & 0o022: + raise StateIntegrityError("state owner or write permissions are unsafe") + import fcntl + fcntl.flock(fd, fcntl.LOCK_EX if write else fcntl.LOCK_SH) + else: + msvcrt = importlib.import_module("msvcrt") + msvcrt.locking(fd, msvcrt.LK_LOCK, 1) + try: + yield handle, parent + finally: + if os.name == "posix": + fcntl.flock(fd, fcntl.LOCK_UN) + else: + handle.seek(0) + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + try: + with _locked(path, write=False) as (handle, _parent_fd): + return _rows(handle) + except FileNotFoundError: + return [] + + +def prepare_state_file(path: Path) -> None: + """Create a private regular file or validate an existing owned file.""" + with _locked(path, write=True) as (handle, parent): + os.fsync(handle.fileno()) + if parent is not None: + os.fsync(parent) + + +def recoverable_jsonl_prefix(path: Path) -> tuple[list[dict[str, Any]], bytes]: + """Read an intact prefix and a final incomplete row; never modify/replay it. + + Malformed complete rows still fail. Only explicit recovery tooling should + call this, with the original bytes archived outside active runtime paths. + """ + try: + with _locked(path, write=False) as (handle, _parent_fd): + return _prefix(handle, preserve_tail=True) + except FileNotFoundError: + return [], b"" + + +def append_jsonl( + path: Path, payload: Mapping[str, Any], *, identity_field: str | None = None, +) -> bool: + data = _encode(payload) + if identity_field is not None and not isinstance(payload.get(identity_field), str): + raise ValueError("idempotent append requires a string identity") + with _locked(path, write=True) as (handle, parent): + history = _rows(handle) + if identity_field is not None: + matches = [row for row in history + if row.get(identity_field) == payload[identity_field]] + if matches: + if len(matches) != 1 or _encode(matches[0]) != data: + raise StateIntegrityError("receipt identity collision or duplicate history") + return False + handle.seek(0, os.SEEK_END) + start = handle.tell() + try: + remaining = memoryview(data) + while remaining: + written = os.write(handle.fileno(), remaining) + if written <= 0: + raise OSError("state write made no progress") + remaining = remaining[written:] + os.fsync(handle.fileno()) + if parent is not None: + os.fsync(parent) + except BaseException: + # A caught I/O failure must not poison previously committed history. + # A killed process cannot reach this cleanup; its incomplete tail is + # instead detected and held by every later reader/writer. + os.ftruncate(handle.fileno(), start) + os.fsync(handle.fileno()) + raise + return True diff --git a/phios/state_paths.py b/phios/state_paths.py new file mode 100644 index 00000000..d21fddb3 --- /dev/null +++ b/phios/state_paths.py @@ -0,0 +1,24 @@ +"""Packaged Linux state location, with explicit legacy compatibility.""" +from __future__ import annotations + +import os +from pathlib import Path + + +def configured_state_root() -> Path: + value = os.environ.get("PHIOS_STATE_ROOT") + if value is None: + return Path.home() / ".phios" + path = Path(value).expanduser() + if not value.strip() or not path.is_absolute() or path == Path(path.anchor): + raise ValueError("PHIOS_STATE_ROOT must be an explicit absolute state directory") + return path + + +def memory_config_path() -> Path: + if "PHIOS_STATE_ROOT" not in os.environ: + return Path.home() / ".phios/memory/config.json" + value = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))).expanduser() + if not value.is_absolute(): + raise ValueError("XDG_CONFIG_HOME must be absolute") + return value / "phios/memory.json" diff --git a/phios/state_recovery.py b/phios/state_recovery.py new file mode 100644 index 00000000..998f2b6b --- /dev/null +++ b/phios/state_recovery.py @@ -0,0 +1,307 @@ +"""Verified data-only backup/restore into a fresh operator-owned state root.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import sqlite3 +import uuid +from contextlib import closing +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from phios.memory.models import MemoryRecord +from phios.memory.publisher import _receipt_from_payload +from phios.memory.store import SCHEMA_VERSION +from phios.curiosity_store import CuriosityStore +from phios.state_io import ( + StateIntegrityError, _locked, append_jsonl, prepare_state_file, read_jsonl, + recoverable_jsonl_prefix, sync_directory, +) +from phios.state_paths import configured_state_root + +FORMAT = "phios.data-backup.v1" +CANONICAL = "memory/canonical.sqlite3" +MEMORY_LEDGER = "spine-v0.1/ledger/mandala-receipts.jsonl" +DATA_FILES = {CANONICAL, MEMORY_LEDGER, "curiosity/artifacts.jsonl", "curiosity/return-pointers.jsonl"} + + +def _safe_root(root: Path) -> Path: + root = root.expanduser().absolute() + if not root.is_dir(): + raise ValueError("an existing owned state directory is required") + # A nonexistent child lets the shared directory walker check every ancestor. + try: + with _locked(root / "manifest.json", write=False): + pass + except FileNotFoundError: + pass + if os.name == "posix" and (root.stat().st_uid != os.getuid() or root.stat().st_mode & 0o022): + raise StateIntegrityError("state root owner or write permissions are unsafe") + return root + + +def _hash(path: Path) -> dict[str, Any]: + digest = hashlib.sha256() + with _locked(path, write=False) as (handle, _parent): + size = os.fstat(handle.fileno()).st_size + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return {"sha256": digest.hexdigest(), "size": size} + + +def _copy(source: Path, destination: Path) -> None: + with _locked(source, write=False) as (reader, _source_parent): + with _locked(destination, write=True) as (writer, parent): + for chunk in iter(lambda: reader.read(1024 * 1024), b""): + remaining = memoryview(chunk) + while remaining: + count = writer.write(remaining) + if not count: + raise OSError("backup copy made no progress") + remaining = remaining[count:] + os.fsync(writer.fileno()) + if parent is not None: + os.fsync(parent) + + +def _database(path: Path) -> list[tuple[dict[str, Any], bool]]: + # Validate both SQLite structural integrity and the domain's content hashes. + with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as conn: + conn.row_factory = sqlite3.Row + version = conn.execute("SELECT value FROM store_metadata WHERE key='schema_version'").fetchone() + if version is None or version[0] != str(SCHEMA_VERSION): + raise StateIntegrityError("unsupported canonical memory schema; no implicit migration") + if [row[0] for row in conn.execute("PRAGMA integrity_check")] != ["ok"]: + raise StateIntegrityError("canonical database integrity check failed") + if conn.execute("PRAGMA foreign_key_check").fetchone() is not None: + raise StateIntegrityError("canonical database foreign-key check failed") + for row in conn.execute("SELECT * FROM records"): + payload = json.loads(row["payload_json"]) + kwargs = dict(payload) + kwargs.pop("record_sha256") + kwargs.pop("content_sha256") + for field in ("provenance_refs", "derived_from", "transformation_lineage_sha256s", + "taint_labels", "contradicts"): + if field in kwargs: + kwargs[field] = tuple(kwargs[field]) + record = MemoryRecord.build(**kwargs) + if (record.to_dict() != payload or record.record_sha256 != row["record_sha256"] or + record.record_id != row["record_id"] or record.revision != row["revision"] or + record.source_id != row["source_id"] or record.scope_id != row["scope_id"] or + record.classification != row["classification"] or record.expires_at != row["expires_at"]): + raise StateIntegrityError("canonical record content or identity hash mismatch") + receipts: list[tuple[dict[str, Any], bool]] = [] + for row in conn.execute("SELECT * FROM receipt_outbox ORDER BY rowid"): + payload = json.loads(row["receipt_json"]) + receipt = _receipt_from_payload(payload).to_dict() + if (receipt["operation_id"] != row["operation_id"] or + receipt["action_authority"] is not False or receipt["execution_authority"] is not False): + raise StateIntegrityError("backup can restore only zero-authority memory receipts") + receipts.append((receipt, bool(row["published"]))) + return receipts + + +def _write_json(path: Path, payload: dict[str, Any]) -> None: + prepare_state_file(path) + with _locked(path, write=True) as (handle, parent): + data = json.dumps(payload, indent=2, sort_keys=True, allow_nan=False).encode() + b"\n" + remaining = memoryview(data) + while remaining: + written = handle.write(remaining) + if not written: + raise OSError("metadata write made no progress") + remaining = remaining[written:] + os.fsync(handle.fileno()) + if parent is not None: + os.fsync(parent) + + +def backup(source: Path, destination: Path, *, preserve_incomplete_tail: bool = False) -> dict[str, Any]: + source = _safe_root(source) + destination = destination.expanduser().absolute() + if destination.is_relative_to(source): + raise ValueError("backup destination must be outside the active state root") + destination.mkdir(mode=0o700) # no overwrite, including an empty existing directory + started = datetime.now(UTC).isoformat() + files: list[str] = [] + incomplete: list[str] = [] + + def capture_rows(path: Path, name: str) -> list[dict[str, Any]]: + rows, tail = recoverable_jsonl_prefix(path) + if tail and not preserve_incomplete_tail: + raise StateIntegrityError(f"incomplete audit tail in {name}; explicit preservation required") + if tail: + raw = "audit/" + name.replace("/", "-") + ".bin" + if raw not in files: + _copy(path, destination / raw) + files.append(raw) + incomplete.append(raw) + return rows + + db = source / CANONICAL + if db.exists(): + # Validate path custody, then use SQLite's online snapshot API rather + # than copying database/WAL bytes from a running process. + _hash(db) + target = destination / CANONICAL + prepare_state_file(target) + with closing(sqlite3.connect(db.as_uri() + "?mode=ro", uri=True, timeout=30)) as original: + with closing(sqlite3.connect(target)) as snapshot: + original.backup(snapshot) + with _locked(target, write=True) as (handle, parent): + os.fsync(handle.fileno()) + if parent is not None: + os.fsync(parent) + receipts = _database(target) + originals = capture_rows(source / MEMORY_LEDGER, "spine-ledger-mandala-receipts.jsonl") + for receipt, published in receipts: + matches = [row for row in originals if row.get("receipt_id") == receipt["receipt_id"]] + if published and (len(matches) != 1 or matches[0] != receipt): + raise StateIntegrityError("published canonical data lacks its exact durable receipt") + if matches and (len(matches) != 1 or matches[0] != receipt): + raise StateIntegrityError("canonical memory receipt collision") + if published: + append_jsonl(destination / MEMORY_LEDGER, receipt, identity_field="receipt_id") + prepare_state_file(destination / MEMORY_LEDGER) + files.extend([CANONICAL, MEMORY_LEDGER]) + for name in ["curiosity/artifacts.jsonl", "curiosity/return-pointers.jsonl"]: + path = source / name + if path.exists(): + rows = capture_rows(path, name) + prepare_state_file(destination / name) + for row in rows: + append_jsonl(destination / name, row) + files.append(name) + # All effect, decision, binding, lease and session evidence is archived + # outside active runtime paths. Claim markers and credentials are excluded. + ledger = source / "spine-v0.1/ledger" + if ledger.exists(): + for path in sorted(ledger.glob("*.jsonl")): + if re.fullmatch(r"[a-z0-9][a-z0-9-]{0,100}\.jsonl", path.name) is None: + raise StateIntegrityError("unexpected ledger filename") + name = "audit/" + path.name + rows = capture_rows(path, "spine-ledger-" + path.name) + prepare_state_file(destination / name) + for row in rows: + append_jsonl(destination / name, row) + files.append(name) + manifest = { + "schema_version": FORMAT, "canonical_schema_version": SCHEMA_VERSION, + "backup_id": str(uuid.uuid4()), "capture_started_at": started, + "capture_finished_at": datetime.now(UTC).isoformat(), + "authority_restored": False, "configuration_restored": False, + "derived_indexes_restored": False, "encrypted": False, + "incomplete_audit_files": sorted(set(incomplete)), + "files": {name: _hash(destination / name) for name in sorted(files)}, + } + _write_json(destination / "manifest.json", manifest) + sync_directory(destination.parent) + verify_backup(destination) + return manifest + + +def verify_backup(source: Path) -> dict[str, Any]: + source = _safe_root(source) + with _locked(source / "manifest.json", write=False) as (handle, _parent): + manifest = json.load(handle) + expected = {"schema_version", "canonical_schema_version", "backup_id", "capture_started_at", + "capture_finished_at", "authority_restored", "configuration_restored", + "derived_indexes_restored", "encrypted", "incomplete_audit_files", "files"} + if (not isinstance(manifest, dict) or set(manifest) != expected or + manifest["schema_version"] != FORMAT or manifest["canonical_schema_version"] != SCHEMA_VERSION or + any(manifest[key] is not False for key in ["authority_restored", "configuration_restored", + "derived_indexes_restored", "encrypted"])): + raise StateIntegrityError("unsupported or authority-bearing backup format") + files = manifest["files"] + if not isinstance(files, dict) or len(files) > 512: + raise StateIntegrityError("invalid backup inventory") + for name, identity in files.items(): + if not isinstance(name, str) or not (name in DATA_FILES or + re.fullmatch(r"audit/[a-z0-9][a-z0-9-]{0,150}\.jsonl(?:\.bin)?", name)): + raise StateIntegrityError("unexpected backup path") + if not isinstance(identity, dict) or set(identity) != {"sha256", "size"}: + raise StateIntegrityError("invalid backup file identity") + if (not isinstance(identity["sha256"], str) or + re.fullmatch(r"[0-9a-f]{64}", identity["sha256"]) is None or + type(identity["size"]) is not int or identity["size"] < 0): + raise StateIntegrityError("invalid backup hash or size") + if _hash(source / name) != identity: + raise StateIntegrityError(f"backup hash or size mismatch: {name}") + if name.endswith(".jsonl"): + read_jsonl(source / name) + if CANONICAL in files: + receipts = _database(source / CANONICAL) + expected_receipts = [receipt for receipt, published in receipts if published] + if MEMORY_LEDGER not in files or read_jsonl(source / MEMORY_LEDGER) != expected_receipts: + raise StateIntegrityError("active restored ledger must contain only exact published memory receipts") + elif MEMORY_LEDGER in files: + raise StateIntegrityError("a restored memory ledger requires its canonical database") + incomplete = manifest["incomplete_audit_files"] + if (not isinstance(incomplete, list) or + any(not isinstance(name, str) or not name.endswith(".jsonl.bin") or name not in files + for name in incomplete) or len(incomplete) != len(set(incomplete))): + raise StateIntegrityError("invalid incomplete-audit inventory") + curiosity = CuriosityStore(source / "curiosity") + targets = {item.curiosity_artifact_sha256 for item in curiosity.artifacts()} + if any(pointer.artifact_sha256 not in targets for pointer in curiosity.return_pointers()): + raise StateIntegrityError("curiosity return pointer has no verified artifact") + return manifest + + +def restore(source: Path, destination: Path) -> dict[str, Any]: + source = source.expanduser().absolute() + destination = destination.expanduser().absolute() + manifest = verify_backup(source) # no destination writes until all input checks pass + if destination.is_relative_to(source): + raise ValueError("restore destination must be outside the backup") + destination.mkdir(mode=0o700) + for name in manifest["files"]: + target = "recovered-" + name if name.startswith("audit/") else name + _copy(source / name, destination / target) + if CANONICAL in manifest["files"]: + _database(destination / CANONICAL) + receipt = {"schema_version": "phios.data-restore.v1", "backup_id": manifest["backup_id"], + "restore_id": str(uuid.uuid4()), "authority_restored": False, + "configuration_restored": False, "derived_indexes_restored": False, + "incomplete_audit_files": manifest["incomplete_audit_files"], + "canonical_schema_version": SCHEMA_VERSION, "release_ready": False} + _write_json(destination / "restored-state.json", receipt) + sync_directory(destination.parent) + return receipt + + +def main() -> int: + parser = argparse.ArgumentParser(prog="phi-state", description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + create = commands.add_parser("backup", help="Create a private data-only backup in a new directory") + create.add_argument("--state-root", type=Path, default=configured_state_root()) + create.add_argument("--output", type=Path, required=True) + create.add_argument("--preserve-incomplete-tail", action="store_true", + help="Archive incomplete final audit rows outside active paths; source stays held") + inspect = commands.add_parser("verify", help="Verify all backup hashes and canonical integrity") + inspect.add_argument("backup", type=Path) + recover = commands.add_parser("restore", help="Restore data into a fresh state root; authority stays held") + recover.add_argument("backup", type=Path) + recover.add_argument("--new-state-root", type=Path, required=True) + args = parser.parse_args() + try: + if args.command == "backup": + result = backup(args.state_root, args.output, + preserve_incomplete_tail=args.preserve_incomplete_tail) + elif args.command == "verify": + result = verify_backup(args.backup) + else: + result = restore(args.backup, args.new_state_root) + print(json.dumps(result, indent=2)) + return 0 + except (OSError, ValueError, TypeError, KeyError, sqlite3.Error) as exc: + print(f"State operation failed; preserve any partial destination for review: {exc}") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/phishell/contracts/package-observation.schema.json b/phishell/contracts/package-observation.schema.json index cceaa1e9..86930874 100644 --- a/phishell/contracts/package-observation.schema.json +++ b/phishell/contracts/package-observation.schema.json @@ -1 +1,129 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"phios.package-observation.v1","type":"object","required":["schemaVersion","source","capturedAt","availability","reason","adapter","packageLimit","readOnly","executionAuthority","effectPerformed","distro","totalInstalledPackageCount","packages"],"properties":{"schemaVersion":{"const":"phios.package-observation.v1"},"source":{"const":"dpkg-status-file"},"capturedAt":{"type":"string","format":"date-time"},"availability":{"enum":["available","unavailable"]},"reason":{"type":["string","null"]},"adapter":{"const":"debian-dpkg-status"},"packageLimit":{"const":64},"readOnly":{"const":true},"executionAuthority":{"const":false},"effectPerformed":{"const":false},"distro":{"type":["object","null"]},"totalInstalledPackageCount":{"type":"integer","minimum":0},"packages":{"type":"array","maxItems":64,"items":{"type":"object","required":["name","version","architecture","essential"],"properties":{"name":{"type":"string","maxLength":128},"version":{"type":"string","maxLength":256},"architecture":{"type":"string","maxLength":64},"essential":{"type":"boolean"}},"additionalProperties":false}}},"additionalProperties":false} \ No newline at end of file +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "phios.package-observation.v1", + "type": "object", + "required": [ + "schemaVersion", + "source", + "capturedAt", + "availability", + "reason", + "adapter", + "packageLimit", + "readOnly", + "executionAuthority", + "effectPerformed", + "distro", + "totalInstalledPackageCount", + "packages" + ], + "properties": { + "schemaVersion": { + "const": "phios.package-observation.v1" + }, + "source": { + "enum": [ + "dpkg-status-file", + "pacman-local-desc" + ] + }, + "capturedAt": { + "type": "string", + "format": "date-time" + }, + "availability": { + "enum": [ + "available", + "unavailable" + ] + }, + "reason": { + "type": [ + "string", + "null" + ] + }, + "adapter": { + "enum": [ + "debian-dpkg-status", + "arch-pacman-local" + ] + }, + "packageLimit": { + "const": 64 + }, + "readOnly": { + "const": true + }, + "executionAuthority": { + "const": false + }, + "effectPerformed": { + "const": false + }, + "distro": { + "type": [ + "object", + "null" + ] + }, + "totalInstalledPackageCount": { + "type": "integer", + "minimum": 0 + }, + "packages": { + "type": "array", + "maxItems": 64, + "items": { + "type": "object", + "required": [ + "name", + "version", + "architecture", + "essential" + ], + "properties": { + "name": { + "type": "string", + "maxLength": 128 + }, + "version": { + "type": "string", + "maxLength": 256 + }, + "architecture": { + "type": "string", + "maxLength": 64 + }, + "essential": { + "type": "boolean" + } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "source": { + "const": "dpkg-status-file" + }, + "adapter": { + "const": "debian-dpkg-status" + } + } + }, + { + "properties": { + "source": { + "const": "pacman-local-desc" + }, + "adapter": { + "const": "arch-pacman-local" + } + } + } + ] +} diff --git a/phishell/host/bundledInventory.d.mts b/phishell/host/bundledInventory.d.mts new file mode 100644 index 00000000..a0bb17b4 --- /dev/null +++ b/phishell/host/bundledInventory.d.mts @@ -0,0 +1,2 @@ +import type { Plugin } from "vite"; +export function bundledInventory(): Plugin; diff --git a/phishell/host/bundledInventory.mjs b/phishell/host/bundledInventory.mjs new file mode 100644 index 00000000..d48dafbb --- /dev/null +++ b/phishell/host/bundledInventory.mjs @@ -0,0 +1,75 @@ +import { createHash } from "node:crypto"; +import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +const sha = (bytes) => createHash("sha256").update(bytes).digest("hex"); + +// Record actual Rollup chunk participants before npm pruning removes build +// inputs. Virtual Vite runtime helpers retain their actual supplier identity. +export function bundledInventory() { + return { + name: "phios-bundled-inventory", + enforce: "post", + writeBundle(options, bundle) { + const root = realpathSync(join(process.cwd(), "node_modules")); + const output = resolve(options.dir ?? "dist"); + const packages = new Map(); + const chunks = []; + for (const chunk of Object.values(bundle)) { + if (chunk.type !== "chunk") continue; + if (isAbsolute(chunk.fileName) || chunk.fileName.split("/").includes("..")) throw new Error("Unsafe chunk path"); + const bytes = readFileSync(join(output, chunk.fileName)); + chunks.push({ filename: chunk.fileName, sha256: sha(bytes), size: bytes.length }); + for (const id of Object.keys(chunk.modules)) { + const virtual = id.startsWith("\0vite/"); + const clean = id.replace(/^\0/, "").split("?", 1)[0]; + let path; + let actual; + if (virtual) path = join(root, "vite"); + else { + if (!isAbsolute(clean) || !existsSync(clean)) continue; + actual = realpathSync(clean); + if (!actual.startsWith(root + sep)) continue; + path = dirname(actual); + } + while (path.startsWith(root + sep) && !existsSync(join(path, "package.json"))) path = dirname(path); + if (!path.startsWith(root + sep)) throw new Error("Bundled supplier identity missing"); + const metadata = readFileSync(join(path, "package.json")); + const info = JSON.parse(metadata); + if (typeof info.name !== "string" || typeof info.version !== "string") throw new Error("Bundled package identity missing"); + const origin = relative(root, path).split(sep).join("/"); + if (!packages.has(origin)) packages.set(origin, { name: info.name, version: info.version, + license: typeof info.license === "string" ? info.license : null, + package_json_sha256: sha(metadata), package_path: "node_modules/" + origin, + modules: [], notices: [], _path: path }); + packages.get(origin).modules.push({ id: virtual ? clean : relative(path, actual).split(sep).join("/"), + chunk: chunk.fileName, role: virtual ? "injected-runtime-helper" : "chunk-module" }); + } + } + if (packages.size === 0 || packages.size > 2000) throw new Error("Bounded nonempty bundled inventory required"); + mkdirSync(join(output, "bundled-notices"), { recursive: true }); + const rows = [...packages.values()].sort((a, b) => a.package_path.localeCompare(b.package_path)); + for (const row of rows) { + for (const name of readdirSync(row._path).sort()) { + if (!/license|copying|notice|copyright/i.test(name)) continue; + const target = realpathSync(join(row._path, name)); + if (!target.startsWith(root + sep)) throw new Error("Notice escaped dependency root"); + const info = lstatSync(target); + if (!info.isFile()) continue; + if (info.size > 1024 * 1024) throw new Error("Bundled notice exceeds its bound"); + const bytes = readFileSync(target); + const digest = sha(bytes); + const filename = "bundled-notices/" + digest + ".txt"; + writeFileSync(join(output, filename), bytes); + row.notices.push({ filename, original_name: name, sha256: digest, size: bytes.length }); + } + row.modules.sort((a, b) => a.chunk.localeCompare(b.chunk) || a.id.localeCompare(b.id)); + delete row._path; + } + writeFileSync(join(output, "bundled-js-inventory.json"), JSON.stringify({ + schema_version: "phios.phishell-bundle.v1", packages: rows, + chunks: chunks.sort((a, b) => a.filename.localeCompare(b.filename)), + license_compliance_reviewed: false }, null, 2) + "\n"); + }, + }; +} diff --git a/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs b/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs index ea9e81f8..16535b3c 100644 --- a/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs +++ b/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs @@ -1,75 +1,49 @@ import test from "node:test"; import assert from "node:assert/strict"; - import { createLocalObservationServer } from "./localTransport.mjs"; -const SHA = (char) => char.repeat(64); - -test("local transport forwards human decision without widening it", async () => { - const seen = []; - const transport = createLocalObservationServer({ - port: 0, - serveShell: false, - ghostWalkAuthorizationDecisionRecorder: async (payload) => { - seen.push(payload); - return { kind: "conflict" }; - }, - }); - const address = await transport.listen(); - try { - const body = { - target_inference_receipt_sha256: SHA("a"), - expected_authority_request_sha256: SHA("b"), - expected_previous_decision_sha256: null, - decision: "APPROVE", - decision_note: "human approval", - }; - const response = await fetch( - `http://${address.host}:${address.port}/api/v1/ghostwalk/authorization-console/decisions`, - { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(body), - }, - ); - assert.equal(response.status, 409); - assert.deepEqual(seen, [body]); - } finally { - await transport.close(); +for (const endpoint of ["decisions", "bindings", "leases"]) { + for (const [label, headers] of [ + ["local agent", { "content-type": "application/json" }], + ["foreign webpage", { "origin": "https://attacker.invalid", "content-type": "text/plain", "sec-fetch-site": "cross-site" }], + ["foreign Host and agent session", { "host": "attacker.invalid", "authorization": "Bearer agent-session", "content-type": "application/json" }], + ]) { + test(`${label} cannot use HTTP ${endpoint}`, async () => { + const transport = createLocalObservationServer({ port: 0, serveShell: false }); + const address = await transport.listen(); + try { + const response = await fetch(`http://${address.host}:${address.port}/api/v1/ghostwalk/authorization-console/${endpoint}`, { + method: "POST", headers, + body: JSON.stringify({ + target_inference_receipt_sha256: "a".repeat(64), + expected_authority_request_sha256: "b".repeat(64), + expected_previous_decision_sha256: null, + decision: "APPROVE", decision_note: "forged human approval", + }), + }); + assert.equal(response.status, 403); + const result = await response.json(); + assert.equal(result.error, "operator_channel_required"); + assert.equal(result.actionAuthority, false); + assert.equal(result.executionAuthority, false); + assert.equal(result.effectPerformed, false); + } finally { await transport.close(); } + }); } -}); +} -test("local transport rejects browser-supplied lease duration", async () => { - const seen = []; - const transport = createLocalObservationServer({ - port: 0, - serveShell: false, - ghostWalkActionLeaseIssuer: async (payload) => { - seen.push(payload); - return { kind: "conflict" }; - }, +test("foreign browser write is refused before proposal dispatch", async () => { + let dispatched = false; + const transport = createLocalObservationServer({ port: 0, serveShell: false, + ghostWalkAuthorityRequestCreator: async () => { dispatched = true; return { kind: "conflict" }; }, }); const address = await transport.listen(); try { - const response = await fetch( - `http://${address.host}:${address.port}/api/v1/ghostwalk/authorization-console/leases`, - { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ - target_inference_receipt_sha256: SHA("a"), - expected_executable_binding_sha256: SHA("b"), - expected_policy_sha256: SHA("c"), - expected_policy_set_sha256: SHA("d"), - expected_enforcement_profile_sha256: SHA("e"), - expected_authority_epoch_sha256: SHA("f"), - lease_seconds: 300, - }), - }, - ); - assert.equal(response.status, 400); - assert.deepEqual(seen, []); - } finally { - await transport.close(); - } + const response = await fetch(`http://${address.host}:${address.port}/api/v1/ghostwalk/authority-request/requests`, { + method: "POST", headers: { origin: "https://attacker.invalid", "content-type": "text/plain" }, + body: JSON.stringify({target_inference_receipt_sha256: "a".repeat(64), expected_admission_receipt_sha256: "b".repeat(64)}), + }); + assert.equal(response.status, 403); + assert.equal(dispatched, false); + } finally { await transport.close(); } }); diff --git a/phishell/host/localTransport.mjs b/phishell/host/localTransport.mjs index 668dec83..d85f9dcf 100644 --- a/phishell/host/localTransport.mjs +++ b/phishell/host/localTransport.mjs @@ -42,15 +42,7 @@ import { fetchGhostWalkAuthorityRequestStatus, validateGhostWalkAuthorityRequestCreatePayload, } from "./ghostWalkAuthorityRequestProxy.mjs"; -import { - createGhostWalkExecutableBinding, - fetchGhostWalkAuthorizationConsole, - issueGhostWalkActionLease, - recordGhostWalkAuthorizationDecision, - validateAuthorizationDecisionPayload, - validateBindingCreatePayload, - validateLeaseIssuePayload, -} from "./ghostWalkAuthorizationConsoleProxy.mjs"; +import { fetchGhostWalkAuthorizationConsole } from "./ghostWalkAuthorizationConsoleProxy.mjs"; import { createPersistRequest, fetchBrokerHealth, @@ -157,11 +149,6 @@ export function createLocalObservationServer({ ghostWalkAuthorityRequestCreator = createGhostWalkAuthorityRequest, ghostWalkAuthorizationConsoleFetcher = fetchGhostWalkAuthorizationConsole, - ghostWalkAuthorizationDecisionRecorder = - recordGhostWalkAuthorizationDecision, - ghostWalkExecutableBindingCreator = - createGhostWalkExecutableBinding, - ghostWalkActionLeaseIssuer = issueGhostWalkActionLease, } = {}) { if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new Error("local observation port must be an integer between 0 and 65535"); @@ -171,172 +158,49 @@ export function createLocalObservationServer({ try { const url = new URL(request.url ?? "/", `http://${LOOPBACK_HOST}`); - if ( - request.method === "POST" && - url.pathname === "/api/v1/ghostwalk/authorization-console/decisions" - ) { - let payload; - try { - payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); - } catch { - jsonResponse(response, 400, { - error: "invalid_ghostwalk_authorization_decision_body", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - if (!validateAuthorizationDecisionPayload(payload)) { - jsonResponse(response, 400, { - error: "invalid_ghostwalk_authorization_decision_request", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - const result = await ghostWalkAuthorizationDecisionRecorder(payload); - if (result?.kind === "conflict") { - jsonResponse(response, 409, { - error: "ghostwalk_authorization_decision_conflict", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - if (!result || result.kind !== "applied") { - jsonResponse(response, 503, { - error: "ghostwalk_authorization_console_unavailable", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - jsonResponse(response, 200, result.envelope); + // Observation/agent HTTP callers never become the operator channel. + if (request.method === "POST" && [ + "/api/v1/ghostwalk/authorization-console/decisions", + "/api/v1/ghostwalk/authorization-console/bindings", + "/api/v1/ghostwalk/authorization-console/leases", + ].includes(url.pathname)) { + jsonResponse(response, 403, { + error: "operator_channel_required", + operatorChannel: "local-terminal", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); return; } - if ( - request.method === "POST" && - url.pathname === "/api/v1/ghostwalk/authorization-console/bindings" - ) { - let payload; - try { - payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); - } catch { - jsonResponse(response, 400, { - error: "invalid_ghostwalk_binding_body", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - if (!validateBindingCreatePayload(payload)) { - jsonResponse(response, 400, { - error: "invalid_ghostwalk_binding_request", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - const result = await ghostWalkExecutableBindingCreator(payload); - if (result?.kind === "conflict") { - jsonResponse(response, 409, { - error: "ghostwalk_binding_conflict", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - if (!result || result.kind !== "applied") { - jsonResponse(response, 503, { - error: "ghostwalk_authorization_console_unavailable", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - jsonResponse(response, 200, result.envelope); + const expectedHost = `${LOOPBACK_HOST}:${request.socket.localPort}`; + const expectedOrigin = `http://${expectedHost}`; + if (request.headers.host !== expectedHost || + (url.origin !== `http://${LOOPBACK_HOST}` && url.origin !== expectedOrigin)) { + jsonResponse(response, 403, { error: "invalid_local_host", effectPerformed: false }); return; } - - if ( - request.method === "POST" && - url.pathname === "/api/v1/ghostwalk/authorization-console/leases" - ) { - let payload; - try { - payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); - } catch { - jsonResponse(response, 400, { - error: "invalid_ghostwalk_lease_body", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - if (!validateLeaseIssuePayload(payload)) { - jsonResponse(response, 400, { - error: "invalid_ghostwalk_lease_request", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - const result = await ghostWalkActionLeaseIssuer(payload); - if (result?.kind === "conflict") { - jsonResponse(response, 409, { - error: "ghostwalk_lease_conflict", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); - return; - } - if (!result || result.kind !== "applied") { - jsonResponse(response, 503, { - error: "ghostwalk_authorization_console_unavailable", - policyAuthority: false, - operationalAuthority: false, - actionAuthority: false, - executionAuthority: false, - effectPerformed: false, - }); + if (request.method === "POST" && [ + "/api/v1/ghostwalk/authority-request/requests", + "/api/v1/ghostwalk/policy-admission/evaluations", + "/api/v1/ghostwalk/accepted-intent/revisions", + "/api/v1/ghostwalk/operator-log/revisions", + "/api/v1/ghostwalk/actions", + "/api/v1/curiosity/persist-requests", + "/api/v1/curiosity/artifacts", + ].includes(url.pathname)) { + const origin = request.headers.origin; + const fetchSite = request.headers["sec-fetch-site"]; + const mime = request.headers["content-type"] ?? ""; + if ((origin !== undefined && origin !== expectedOrigin) || + (fetchSite !== undefined && !["same-origin", "none"].includes(fetchSite)) || + !/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(mime)) { + jsonResponse(response, 403, { error: "invalid_local_write_origin", effectPerformed: false }); return; } - jsonResponse(response, 200, result.envelope); - return; } if ( diff --git a/phishell/host/localTransportBuiltCheck.mjs b/phishell/host/localTransportBuiltCheck.mjs index d5de00b5..d84ec884 100644 --- a/phishell/host/localTransportBuiltCheck.mjs +++ b/phishell/host/localTransportBuiltCheck.mjs @@ -126,8 +126,12 @@ try { assert.equal(packageEnvelope.readOnly, true); assert.equal(packageEnvelope.executionAuthority, false); assert.equal(packageEnvelope.effectPerformed, false); - assert.equal(packageEnvelope.observation.source, "dpkg-status-file"); - assert.equal(packageEnvelope.observation.adapter, "debian-dpkg-status"); + assert.ok( + (packageEnvelope.observation.source === "dpkg-status-file" && + packageEnvelope.observation.adapter === "debian-dpkg-status") || + (packageEnvelope.observation.source === "pacman-local-desc" && + packageEnvelope.observation.adapter === "arch-pacman-local"), + ); assert.ok(packageEnvelope.observation.packages.length <= 64); const deviceObservation = await fetch(`${base}/api/v1/device-observation`); diff --git a/phishell/host/packageObservationContract.mjs b/phishell/host/packageObservationContract.mjs index 4a0bc820..afe37e25 100644 --- a/phishell/host/packageObservationContract.mjs +++ b/phishell/host/packageObservationContract.mjs @@ -13,8 +13,7 @@ export function validatePackageObservation(o){ const errors=[]; if(!exactKeys(o,TOP_LEVEL_KEYS)) return {ok:false,errors:["top-level package fields invalid"]}; if(o.schemaVersion!=="phios.package-observation.v1") errors.push("schemaVersion"); - if(o.source!=="dpkg-status-file") errors.push("source"); - if(o.adapter!=="debian-dpkg-status") errors.push("adapter"); + if(!((o.source==="dpkg-status-file"&&o.adapter==="debian-dpkg-status")||(o.source==="pacman-local-desc"&&o.adapter==="arch-pacman-local"))) errors.push("source/adapter"); if(!bounded(o.capturedAt,64)||Number.isNaN(Date.parse(o.capturedAt))) errors.push("capturedAt"); if(!["available","unavailable"].includes(o.availability)) errors.push("availability"); if(o.reason!==null&&!["non-linux-host","os-release-unavailable","unsupported-package-database","package-database-unavailable"].includes(o.reason)) errors.push("reason"); diff --git a/phishell/host/packageObserver.mjs b/phishell/host/packageObserver.mjs index 8cd4f426..3ee5568a 100644 --- a/phishell/host/packageObserver.mjs +++ b/phishell/host/packageObserver.mjs @@ -1,4 +1,4 @@ -import { readFile } from "node:fs/promises"; +import { readFile, readdir, open } from "node:fs/promises"; import { pathToFileURL } from "node:url"; const DPKG_STATUS_PATH = "/var/lib/dpkg/status"; @@ -7,6 +7,7 @@ const PACKAGE_LIMIT = 64; const MAX_NAME = 128; const MAX_VERSION = 256; const MAX_ARCH = 64; +const MAX_DESC_BYTES = 64 * 1024; function boundedText(value, max) { if (typeof value !== "string") return ""; @@ -88,128 +89,100 @@ export function parseDpkgStatus(text) { return packages; } -export async function collectPackageObservation({ - readText = async (path) => readFile(path, "utf8"), -} = {}) { - const capturedAt = new Date().toISOString(); - - if (process.platform !== "linux") { - return { - schemaVersion: "phios.package-observation.v1", - source: "dpkg-status-file", - capturedAt, - availability: "unavailable", - reason: "non-linux-host", - adapter: "debian-dpkg-status", - packageLimit: PACKAGE_LIMIT, - readOnly: true, - executionAuthority: false, - effectPerformed: false, - distro: null, - totalInstalledPackageCount: 0, - packages: [], - }; +const PACMAN_LOCAL_PATH = "/var/lib/pacman/local"; +const DATABASE_ENTRY_LIMIT = 20000; + +export function parsePacmanDescription(text) { + if (typeof text !== "string" || Buffer.byteLength(text) > MAX_DESC_BYTES) return null; + const fields = new Map(); + const lines = text.split("\n"); + for (let i = 0; i < lines.length; i++) { + if (!["%NAME%", "%VERSION%", "%ARCH%"].includes(lines[i])) continue; + if (fields.has(lines[i])) return null; + fields.set(lines[i], lines[i + 1] ?? ""); } + const name = fields.get("%NAME%"); + const version = fields.get("%VERSION%"); + const architecture = fields.get("%ARCH%"); + if (!name || !/^[a-z0-9@+_.-]+$/.test(name) || name.length > MAX_NAME || + !version || version.length > MAX_VERSION || /[\x00-\x1f\x7f]/.test(version) || + !architecture || architecture.length > MAX_ARCH || !/^[a-z0-9_]+$/.test(architecture)) return null; + // Pacman has no Debian Essential flag. Never infer importance from a name. + return { name, version, architecture, essential: false }; +} - let osReleaseText; +async function readBoundedDescription(path) { + const file = await open(path, "r"); try { - osReleaseText = await readText(OS_RELEASE_PATH); - } catch { - return { - schemaVersion: "phios.package-observation.v1", - source: "dpkg-status-file", - capturedAt, - availability: "unavailable", - reason: "os-release-unavailable", - adapter: "debian-dpkg-status", - packageLimit: PACKAGE_LIMIT, - readOnly: true, - executionAuthority: false, - effectPerformed: false, - distro: null, - totalInstalledPackageCount: 0, - packages: [], - }; - } + const buffer = Buffer.alloc(MAX_DESC_BYTES + 1); + const { bytesRead } = await file.read(buffer, 0, buffer.length, 0); + if (bytesRead > MAX_DESC_BYTES) throw new Error("package description too large"); + return buffer.subarray(0, bytesRead).toString("utf8"); + } finally { await file.close(); } +} - const osRelease = parseOsRelease(osReleaseText); - const distro = { +export async function collectPackageObservation({ + readText = async (path) => readFile(path, "utf8"), + listPacmanEntries = async () => (await readdir(PACMAN_LOCAL_PATH, { withFileTypes: true })) + .filter(entry => entry.isDirectory()).map(entry => entry.name), + readPacmanText = readBoundedDescription, +} = {}) { + const observation = { + schemaVersion: "phios.package-observation.v1", + source: "dpkg-status-file", capturedAt: new Date().toISOString(), + availability: "unavailable", reason: "non-linux-host", adapter: "debian-dpkg-status", + packageLimit: PACKAGE_LIMIT, readOnly: true, executionAuthority: false, + effectPerformed: false, distro: null, totalInstalledPackageCount: 0, packages: [], + }; + if (process.platform !== "linux") return observation; + let osRelease; + try { osRelease = parseOsRelease(await readText(OS_RELEASE_PATH)); } + catch { return { ...observation, reason: "os-release-unavailable" }; } + observation.distro = { id: boundedText(String(osRelease.ID ?? "unknown"), 64) || "unknown", - name: - boundedText(String(osRelease.PRETTY_NAME ?? osRelease.NAME ?? osRelease.ID ?? "Linux"), 160) || - "Linux", + name: boundedText(String(osRelease.PRETTY_NAME ?? osRelease.NAME ?? osRelease.ID ?? "Linux"), 160) || "Linux", }; - - if (!distroSupportsDpkg(osRelease)) { - return { - schemaVersion: "phios.package-observation.v1", - source: "dpkg-status-file", - capturedAt, - availability: "unavailable", - reason: "unsupported-package-database", - adapter: "debian-dpkg-status", - packageLimit: PACKAGE_LIMIT, - readOnly: true, - executionAuthority: false, - effectPerformed: false, - distro, - totalInstalledPackageCount: 0, - packages: [], - }; + const family = [osRelease.ID, ...String(osRelease.ID_LIKE ?? "").split(/\s+/)]; + const usePacman = family.includes("arch"); + if (!usePacman && !distroSupportsDpkg(osRelease)) { + return { ...observation, reason: "unsupported-package-database" }; } - - let statusText; - try { - statusText = await readText(DPKG_STATUS_PATH); - } catch { - return { - schemaVersion: "phios.package-observation.v1", - source: "dpkg-status-file", - capturedAt, - availability: "unavailable", - reason: "package-database-unavailable", - adapter: "debian-dpkg-status", - packageLimit: PACKAGE_LIMIT, - readOnly: true, - executionAuthority: false, - effectPerformed: false, - distro, - totalInstalledPackageCount: 0, - packages: [], - }; + if (usePacman) { + observation.source = "pacman-local-desc"; + observation.adapter = "arch-pacman-local"; } - - const installed = parseDpkgStatus(statusText).sort( - (a, b) => - Number(b.essential) - Number(a.essential) || - a.name.localeCompare(b.name) || - a.architecture.localeCompare(b.architecture), - ); - - return { - schemaVersion: "phios.package-observation.v1", - source: "dpkg-status-file", - capturedAt: new Date().toISOString(), - availability: "available", - reason: null, - adapter: "debian-dpkg-status", - packageLimit: PACKAGE_LIMIT, - readOnly: true, - executionAuthority: false, - effectPerformed: false, - distro, - totalInstalledPackageCount: installed.length, - packages: installed.slice(0, PACKAGE_LIMIT), - }; + let installed; + try { + if (usePacman) { + const entries = await listPacmanEntries(); + if (!Array.isArray(entries) || entries.length > DATABASE_ENTRY_LIMIT) throw new Error("database entry limit exceeded"); + installed = []; + for (const entry of entries.sort()) { + if (typeof entry !== "string" || !/^[a-zA-Z0-9@+_.:~-]{1,512}$/.test(entry) || [".", ".."].includes(entry)) { + throw new Error("invalid database entry"); + } + const pkg = parsePacmanDescription(await readPacmanText(`${PACMAN_LOCAL_PATH}/${entry}/desc`)); + if (!pkg) throw new Error("invalid package description"); + installed.push(pkg); + } + } else { + installed = parseDpkgStatus(await readText(DPKG_STATUS_PATH)); + } + } catch { return { ...observation, reason: "package-database-unavailable" }; } + installed.sort((a, b) => Number(b.essential) - Number(a.essential) || + a.name.localeCompare(b.name) || a.architecture.localeCompare(b.architecture)); + return { ...observation, availability: "available", reason: null, + capturedAt: new Date().toISOString(), totalInstalledPackageCount: installed.length, + packages: installed.slice(0, PACKAGE_LIMIT) }; } async function main() { const observation = await collectPackageObservation(); - if (process.argv.includes("--require-debian") && observation.availability !== "available") { + if ((process.argv.includes("--require-debian") || process.argv.includes("--require-native")) && observation.availability !== "available") { throw new Error(`package observation unavailable: ${observation.reason}`); } - if (process.argv.includes("--check") || process.argv.includes("--require-debian")) { + if (process.argv.includes("--check") || process.argv.includes("--require-debian") || process.argv.includes("--require-native")) { return; } diff --git a/phishell/host/packageObserver.test.mjs b/phishell/host/packageObserver.test.mjs index 586ac770..b49eec12 100644 --- a/phishell/host/packageObserver.test.mjs +++ b/phishell/host/packageObserver.test.mjs @@ -5,7 +5,53 @@ import { collectPackageObservation, parseDpkgStatus, parseOsRelease, + parsePacmanDescription, } from "./packageObserver.mjs"; +import { validatePackageObservation } from "./packageObservationContract.mjs"; + +test("Arch inventory reads exact installed identities with a bounded projection", async () => { + const observation = await collectPackageObservation({ + readText: async () => 'ID=phios\nID_LIKE=arch\nPRETTY_NAME="PhiOS Preview"\n', + listPacmanEntries: async () => Array.from({length: 70}, (_, i) => `pkg${i}-1.0-1`), + readPacmanText: async path => `%NAME%\n${path.split("/").at(-2).split("-")[0]}\n\n%VERSION%\n1.0-1\n\n%ARCH%\nx86_64\n\n%DESC%\nPrivate description\n`, + }); + assert.equal(observation.adapter, "arch-pacman-local"); + assert.equal(observation.availability, "available"); + assert.equal(observation.totalInstalledPackageCount, 70); + assert.equal(observation.packages.length, 64); + assert.equal(observation.packages[0].essential, false); + assert.equal(JSON.stringify(observation).includes("Private description"), false); + assert.equal(validatePackageObservation(observation).ok, true); + assert.equal(validatePackageObservation({...observation, source: "dpkg-status-file"}).ok, false); +}); + +test("Arch corrupt or changing database never reports a partial inventory as available", async () => { + for (const entry of ["../escape", "bad-1-1"]) { + const result = await collectPackageObservation({ + readText: async () => "ID=arch\n", + listPacmanEntries: async () => [entry], + readPacmanText: async () => "%NAME%\nbad\n%NAME%\nother\n", + }); + assert.equal(result.availability, "unavailable"); + assert.equal(result.reason, "package-database-unavailable"); + assert.deepEqual(result.packages, []); + } + assert.equal(parsePacmanDescription("x".repeat(65537)), null); + assert.equal(parsePacmanDescription("%NAME%\nlarge\n%VERSION%\n1.0\n%ARCH%\nany\n%DESC%\n" + "x".repeat(31000)).name, "large"); +}); + +test("Arch epoch versions use colons in the local database directory", async () => { + const result = await collectPackageObservation({ + readText: async () => "ID=arch\n", + listPacmanEntries: async () => ["python-setuptools-1:84.0.0-1"], + readPacmanText: async path => { + assert.equal(path, "/var/lib/pacman/local/python-setuptools-1:84.0.0-1/desc"); + return "%NAME%\npython-setuptools\n\n%VERSION%\n1:84.0.0-1\n\n%ARCH%\nany\n"; + }, + }); + assert.equal(result.availability, "available"); + assert.equal(result.packages[0].version, "1:84.0.0-1"); +}); test("dpkg parser keeps installed package identity only", () => { const parsed = parseDpkgStatus(` diff --git a/phishell/host/systemStateComposer.test.mjs b/phishell/host/systemStateComposer.test.mjs index 14d727b5..c679ae9a 100644 --- a/phishell/host/systemStateComposer.test.mjs +++ b/phishell/host/systemStateComposer.test.mjs @@ -10,6 +10,37 @@ import { import { collectLinuxHostObservation } from "./linuxProbe.mjs"; import { assertValidSystemStateReceipt } from "./systemStateContract.mjs"; +test("native Arch package observation survives unified composition without extending other planes", async () => { + const receipt = await composeSystemStateReceipt({ + collectPackages: async () => ({ + schemaVersion: "phios.package-observation.v1", + source: "pacman-local-desc", + capturedAt: new Date().toISOString(), + availability: "available", + reason: null, + adapter: "arch-pacman-local", + packageLimit: 64, + readOnly: true, + executionAuthority: false, + effectPerformed: false, + distro: { id: "phios", name: "PhiOS" }, + totalInstalledPackageCount: 1, + packages: [{ name: "phios", version: "1.0.0-1", architecture: "any", essential: false }], + }), + }); + assert.equal(receipt.components[3].source, "pacman-local-desc"); + assert.equal(receipt.summary.installedPackageCount, 1); + assert.equal(assertValidSystemStateReceipt(receipt), receipt); + const wrongPlane = structuredClone(receipt); + wrongPlane.components[0].source = "pacman-local-desc"; + wrongPlane.receiptDigest = recomputeSystemStateReceiptDigest(wrongPlane); + assert.throws(() => assertValidSystemStateReceipt(wrongPlane), /component source host/); + const unknownSource = structuredClone(receipt); + unknownSource.components[3].source = "unknown-package-source"; + unknownSource.receiptDigest = recomputeSystemStateReceiptDigest(unknownSource); + assert.throws(() => assertValidSystemStateReceipt(unknownSource), /component source packages/); +}); + test( "system state composer produces one bounded read-only receipt over all observation planes", { skip: process.platform !== "linux" }, diff --git a/phishell/host/systemStateContract.mjs b/phishell/host/systemStateContract.mjs index 3721ab41..342a90e5 100644 --- a/phishell/host/systemStateContract.mjs +++ b/phishell/host/systemStateContract.mjs @@ -145,7 +145,10 @@ export function validateSystemStateReceipt(receipt) { if (component.schemaVersion !== expected.schemaVersion) { errors.push(`component schema ${expectedId}`); } - if (component.source !== expected.source) errors.push(`component source ${expectedId}`); + if ( + component.source !== expected.source && + !(expectedId === "packages" && component.source === "pacman-local-desc") + ) errors.push(`component source ${expectedId}`); if (!validTimestamp(component.capturedAt)) errors.push(`component time ${expectedId}`); if (!["available", "unavailable"].includes(component.availability)) { errors.push(`component availability ${expectedId}`); diff --git a/phishell/package-lock.json b/phishell/package-lock.json new file mode 100644 index 00000000..618d97c1 --- /dev/null +++ b/phishell/package-lock.json @@ -0,0 +1,1839 @@ +{ + "name": "phishell", + "version": "0.16.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "phishell", + "version": "0.16.0", + "dependencies": { + "@jellybrick/dbus-next": "0.11.3", + "react": "19.1.1", + "react-dom": "19.1.1" + }, + "devDependencies": { + "@types/react": "19.1.12", + "@types/react-dom": "19.1.9", + "typescript": "5.9.2", + "vite": "7.1.5", + "vitest": "3.2.4" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jellybrick/dbus-next": { + "version": "0.11.3", + "resolved": "https://registry.npmjs.org/@jellybrick/dbus-next/-/dbus-next-0.11.3.tgz", + "integrity": "sha512-XaLIXFuG6YWmqmucY0/amh3VQpHXCOJ9mJMnwvvEOPdFFE6hQ3ZjdvkaWQuDWrN1qIfOoR9xTAGqFc3iWRpYbg==", + "license": "MIT", + "dependencies": { + "fast-xml-builder": "^1.3.0", + "fast-xml-parser": "^5.10.1" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@nodable/entities": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.1.0.tgz", + "integrity": "sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/nodable" + } + ], + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.5.tgz", + "integrity": "sha512-J25QJU+B78T4FhhBsNpLJyVWOi31mwtpcMwywHmOKH65Q9IWGA81gPj+dnwlhU8wktVriYE+tFAaQgrnJRzAZg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.5.tgz", + "integrity": "sha512-LDopB3zuZM5Ux9TT2luNEBJW/tYbGU2g1d+VpKk6I+gSKDb+/7sYE6M225gRQt4RbMX6MSwMsVR/phdjVUgRLg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.5.tgz", + "integrity": "sha512-wlJEERGfeuHeBavCL2qVnNacOK43NDoZM4sjkeRPymd04OAE9T1zBqDJgmZ+CIsPTYKwdzpUC8vmOw84dwY4Tg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.5.tgz", + "integrity": "sha512-4nJJGg5jbo2wwPP4JP+LfEBA3bvP8rU9CLuhp7jWvq9sxEyhjQFTFdrqi+/dHEin/pd8jpT0vcehIpnZtmEdcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.5.tgz", + "integrity": "sha512-DrZbyCDF1hneuO6jRbvZ2D7+PIBM6yIwYnJpg2vIk58T+wuFpiaGZrfUr59lDWw45bg+IrpTGLPiNi/Fk4w3Cg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.5.tgz", + "integrity": "sha512-gqfUVMJMB3mehqywxp6hTBFfgtMQykZY19+cfiaYP0toIJLb/1DZRJHVkQQGP13W4TAwfZDWeg1qBcheTRioXQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.5.tgz", + "integrity": "sha512-CFmhpvAwzSaWMlN3VN7UtmoTihlZNzoP0juQib5TQRnYUyDV8dXeWOp29sobWAT6gXl/hQgAClLlEiYozQG3OQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.5.tgz", + "integrity": "sha512-Uc9H8eXCOayV6JLTH5bXKMId6qbhNHa818/BgYjm4jrlq3vZquC9cqyvHBw17xy5Mnj5f+I3gFK5JcEf3hSqrw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.5.tgz", + "integrity": "sha512-VcPr/szv/1BFw112Kt//fxulXt/JPqzzidU84iW68L2DdjnOO8QFUv2zTSYBEPHD6movBD4z+bbr5y60GYM7Jw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.5.tgz", + "integrity": "sha512-BnxtJ5/91BrIHYIkGrmjz/lbMhqEHt1dPFqIxIFR+jPn0xVc/oUSCtIT089zfp5ufwGDlYz2UC+Fe1SRBpYFbQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.5.tgz", + "integrity": "sha512-LrYcHZwF+fAMNKHYTOQ5osWM4AZF7YF6D+XtsjDyEvljtt11twc+zHVXBLNEjxVSUnKYsOhvVz4Z213eW02COQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.5.tgz", + "integrity": "sha512-nj7QKQePAAUpCpJHtg0pR0W/b92A9NO17JS3BAQmHDn/yhmkir2p8llrKY9TOhleKIaSzy1JhxS3T9FVld6coA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.5.tgz", + "integrity": "sha512-5ylkX6dWMeBKge9nTU+Rxfb+ZfaCIJ9lRqIFaK0eAMcWp7OJbYnLveLgXmm0VrvuLKb8qIK+mHyH0qu88RM+iA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.5.tgz", + "integrity": "sha512-oHK4ZHYFDKjZviK34I+NwgfbGxgI7ztrNxj2hPTSSNFgeq1a/lEd7dHV2fdGAuTH4Iym3RHJg+vAbWaWG4B7Zg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.5.tgz", + "integrity": "sha512-UcetmHZ6XOXuUByiKZyQmb55ZPr0LABr3Ec/HB9wKZn6CEAFWZkE+hsJErJ9hbPBC7nI0dKuELx7CoV6IM7TMg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.5.tgz", + "integrity": "sha512-C5CmDPQBtvjVo8cgQsBs+w6WB0JLkiixhgi6hVLV11hERWdn/p0XcPU2OUcZzac9BPOFq7SbaHFa8r3SWEysCQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.5.tgz", + "integrity": "sha512-lHVQHJFKsuuxLMi3MQO9XVL8Tje3JR82CzB+QDKC5NWBcsIWuwsn9uIM5e3lBhI+fF1/s63qnyYqsg65+8rV/w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.5.tgz", + "integrity": "sha512-3W9bTFcQNJn71cSJVM9RKIiZOy8DO/XLDii8Uv/Pm6WKqDRj7JV3ZfuXIEfyuy5LXpIzAbB/1M4Ukp9GKNa7nA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.5.tgz", + "integrity": "sha512-VDC7rRJlee/scpki96GZ27Omf6yU87s1YXwVTpjE5841faVlDYYT565rgfmoR1U0sqL7z5ivQSDjcsF6VRXyBA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.5.tgz", + "integrity": "sha512-z86Ok2p4pTdv5xqCKZsTooO7yBEiaJR/HzU3Wx8RmWsPoLppnMKROhJusQob8B3IE1ghC343kUW9rC2r+Wf3ig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.5.tgz", + "integrity": "sha512-IzQmj+xXwQFGhMAMKMQVXkMwMZN3TqkJgAE0nSsqvVwWWciP4AIPMmWRqOQ2GfX7TUDZr+xqGFcBS36CRPGw0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.5.tgz", + "integrity": "sha512-F6qpTaPc9bwBH85kjy0/BLmLSW1uv7AoOXCoRIkg2arlgCYlWYcAbiMkvZuAcaWk9TpCRG//okznLAqLGshkMw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.5.tgz", + "integrity": "sha512-igoDsTFhhwECBeGbUuLeIk7t8Y1apa+cs6mDWpx2EZ0ch7oEQgzHbFUXN9euoHekCAQzXdXApAGkV6jznS7tWw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.5.tgz", + "integrity": "sha512-U3teMeMbXFmaM5D+OTJpsOXd+wV/qftIeYF9kBKL4v73641qyJmoXFtA28DQLsnmlyayEsTe72xpLHrArq6vHw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.5.tgz", + "integrity": "sha512-ypfC34F3RKXvCXBglGqGMsUSMKlgwd1HX9AOAlx9RoZZ6GaI42YHVeKpzg3JG+wpBUJYTG+NNZhqbDWL8tBZkw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.1.12", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.12.tgz", + "integrity": "sha512-cMoR+FoAf/Jyq6+Df2/Z41jISvGZZ2eTlnsaJRptmZ76Caldwy1odD4xTr/gNV9VLj0AWgg/nmkevIyUfIIq5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.1.9", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.1.9.tgz", + "integrity": "sha512-qXRuZaOsAdXKFyOhRBg6Lqqc0yay13vN7KrIg4L7N4aaHN68ma9OK3NE1BoDFgFOTfM7zg+3/8+2n8rLUH3OKQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.0.0" + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz", + "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.4.tgz", + "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.4", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.4.tgz", + "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.4", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.4.tgz", + "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot/node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.4.tgz", + "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.4.tgz", + "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils/node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/anynum": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/anynum/-/anynum-1.0.1.tgz", + "integrity": "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-xml-builder": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.1.tgz", + "integrity": "sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "path-expression-matcher": "^1.6.2", + "xml-naming": "^0.3.0" + } + }, + "node_modules/fast-xml-parser": { + "version": "5.11.2", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.11.2.tgz", + "integrity": "sha512-R9iDuNrQYeQut46cn2r2wHKn4HYzVDvDm5J1wW+koZewykv0yuO2HChTYeZtrULyHIDM9cj9TUXloCsueCQUog==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "@nodable/entities": "^3.0.1", + "fast-xml-builder": "^1.2.0", + "is-unsafe": "^2.0.0", + "path-expression-matcher": "^1.6.2", + "strnum": "^2.4.2", + "xml-naming": "^0.3.0" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/is-unsafe": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.2.tgz", + "integrity": "sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/path-expression-matcher": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.6.2.tgz", + "integrity": "sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.1.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.1.1.tgz", + "integrity": "sha512-w8nqGImo45dmMIfljjMwOGtbmC/mk4CMYhWIicdSflH91J9TyCyczcPFXJzrZ/ZXcgGRFeP6BU0BEJTw6tZdfQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.1.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.1.tgz", + "integrity": "sha512-Dlq/5LAZgF0Gaz6yiqZCf6VCcZs1ghAJyrsu84Q/GT0gV+mCxbfmKNoGRKBYMJ8IEdGPqu49YWXD02GCknEDkw==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.26.0" + }, + "peerDependencies": { + "react": "^19.1.1" + } + }, + "node_modules/rollup": { + "version": "4.63.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.5.tgz", + "integrity": "sha512-KRWwmNLlPw5M7HcdYfm15oBv9n9LPtjzpzCIxS/phwqvPyxHSoKX6Y2YU3pxSPfy0CLquVgsx/j/hBi6OvH1Nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.63.5", + "@rollup/rollup-android-arm64": "4.63.5", + "@rollup/rollup-darwin-arm64": "4.63.5", + "@rollup/rollup-darwin-x64": "4.63.5", + "@rollup/rollup-freebsd-arm64": "4.63.5", + "@rollup/rollup-freebsd-x64": "4.63.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.63.5", + "@rollup/rollup-linux-arm-musleabihf": "4.63.5", + "@rollup/rollup-linux-arm64-gnu": "4.63.5", + "@rollup/rollup-linux-arm64-musl": "4.63.5", + "@rollup/rollup-linux-loong64-gnu": "4.63.5", + "@rollup/rollup-linux-loong64-musl": "4.63.5", + "@rollup/rollup-linux-ppc64-gnu": "4.63.5", + "@rollup/rollup-linux-ppc64-musl": "4.63.5", + "@rollup/rollup-linux-riscv64-gnu": "4.63.5", + "@rollup/rollup-linux-riscv64-musl": "4.63.5", + "@rollup/rollup-linux-s390x-gnu": "4.63.5", + "@rollup/rollup-linux-x64-gnu": "4.63.5", + "@rollup/rollup-linux-x64-musl": "4.63.5", + "@rollup/rollup-openbsd-x64": "4.63.5", + "@rollup/rollup-openharmony-arm64": "4.63.5", + "@rollup/rollup-win32-arm64-msvc": "4.63.5", + "@rollup/rollup-win32-ia32-msvc": "4.63.5", + "@rollup/rollup-win32-x64-gnu": "4.63.5", + "@rollup/rollup-win32-x64-msvc": "4.63.5", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", + "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==", + "license": "MIT" + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/strnum": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.4.2.tgz", + "integrity": "sha512-rDG3Ah4TV0k1hWvLSzkZtMmLN9+eS+h3knq4MP6A42Y3Yh5qGNnOUs1jJkoSr8FG5dsL28c7KgkIBzSEykqtuw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "anynum": "^1.0.1" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/typescript": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", + "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vite": { + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.5.tgz", + "integrity": "sha512-4cKBO9wR75r0BeIWWWId9XK9Lj6La5X846Zw9dFfzMRw38IlTk2iCcUt6hsyiDRcPidc55ZParFYDXi0nXOeLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", + "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.4", + "@vitest/mocker": "3.2.4", + "@vitest/pretty-format": "^3.2.4", + "@vitest/runner": "3.2.4", + "@vitest/snapshot": "3.2.4", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.4", + "@vitest/ui": "3.2.4", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/xml-naming": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz", + "integrity": "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + } + } +} diff --git a/phishell/src/PhiShell.tsx b/phishell/src/PhiShell.tsx index 51182176..2a30a92b 100644 --- a/phishell/src/PhiShell.tsx +++ b/phishell/src/PhiShell.tsx @@ -1,4 +1,5 @@ import { useEffect, useMemo, useReducer, useRef, useState } from "react"; +import packageMetadata from "../package.json"; import { HostObservationPanel } from "./components/HostObservationPanel"; import { GhostWalkControlPanel } from "./components/GhostWalkControlPanel"; import { GhostWalkVesselContextCard } from "./components/GhostWalkVesselContextCard"; @@ -230,13 +231,13 @@ function Home() {
-
SYSTEM STATUS
+
CAPABILITY OBSERVATIONS
{[ - ["PhiVessel", "Online"], - ["Models", "Ready"], - ["Memory", "Nominal"], - ["SOMA", "Active"], - ["Ledger", "Recording"], + ["PhiVessel", "Advisory"], + ["Models", "Not observed"], + ["Memory", "Not observed"], + ["SOMA", "Not observed"], + ["Ledger", "Read only"], ["Linux Effects", "Blocked"], ].map(([a, b]) => (
@@ -247,7 +248,7 @@ function Home() {
-
RECENT PROJECTS
+
EXAMPLE PROJECTS
{projects.map(([name, type, when]) => (
@@ -593,7 +594,7 @@ function PhiVessel() {
{mode.toUpperCase()} MODE · ADVISORY -

Governed runtime context online.

+

Runtime context · advisory.

PhiVessel can read a stripped Ghost Walk explanation projection without receiving its lifecycle controls or execution primitives.

The intelligence layer may propose an action. Proposal is still not authority. @@ -855,7 +856,7 @@ export function PhiShell() {

{title} - PhiShell v0.13 · canonical history comparison · execution authority false + PhiShell v{packageMetadata.version} · canonical history comparison · execution authority false
diff --git a/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx b/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx index 3f2348d7..c992e461 100644 --- a/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx +++ b/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx @@ -1,7 +1,6 @@ import { useCallback, useEffect, useState } from "react"; import { ghostWalkAuthorizationConsoleClient, - type AuthorizationDecisionKind, type GhostWalkAuthorizationConsoleSnapshot, } from "../ghostwalk/authorizationConsole"; @@ -18,10 +17,6 @@ export function GhostWalkAuthorizationConsoleCard({ }) { const [snapshot, setSnapshot] = useState(null); - const [note, setNote] = useState(""); - const [busy, setBusy] = useState< - "DECISION" | "BINDING" | "LEASE" | null - >(null); const [message, setMessage] = useState(null); const load = useCallback(async () => { @@ -43,141 +38,6 @@ export function GhostWalkAuthorizationConsoleCard({ void load(); }, [load]); - const recordDecision = useCallback( - async (decision: AuthorizationDecisionKind) => { - if ( - !snapshot?.authorization_readiness.ready || - !snapshot.authorization_readiness.authority_request_sha256 - ) { - return; - } - setBusy("DECISION"); - setMessage(null); - try { - const result = - await ghostWalkAuthorizationConsoleClient.recordDecision({ - targetSha256, - expectedAuthorityRequestSha256: - snapshot.authorization_readiness.authority_request_sha256, - expectedPreviousDecisionSha256: - snapshot.authorization_readiness.latest_decision_sha256, - decision, - decisionNote: note.trim() || null, - }); - if (result.kind === "conflict") { - setMessage( - "Authorization conflict: the request or decision history " + - "changed. Reload before deciding again.", - ); - return; - } - if (result.kind === "unavailable") { - setMessage( - "Authorization decision was rejected or could not be validated.", - ); - return; - } - setSnapshot(result.snapshot); - setNote(""); - setMessage( - `${decision} recorded. This decision did not create an ActionLease or execute an effect.`, - ); - } finally { - setBusy(null); - } - }, - [note, snapshot, targetSha256], - ); - - const createBinding = useCallback(async () => { - const readiness = snapshot?.binding_readiness; - if ( - !readiness?.ready || - !readiness.authorization_decision_sha256 || - !readiness.selected_mapping_sha256 - ) { - return; - } - setBusy("BINDING"); - setMessage(null); - try { - const result = - await ghostWalkAuthorizationConsoleClient.createBinding({ - targetSha256, - expectedAuthorizationDecisionSha256: - readiness.authorization_decision_sha256, - expectedMappingSha256: readiness.selected_mapping_sha256, - expectedMappingSetSha256: readiness.mapping_set_sha256, - }); - if (result.kind === "conflict") { - setMessage( - "Binding conflict: authorization or trusted mapping state changed. Reload first.", - ); - return; - } - if (result.kind === "unavailable") { - setMessage( - "Executable binding is unavailable. Trusted local execution " + - "configuration may be absent or invalid.", - ); - return; - } - setSnapshot(result.snapshot); - setMessage( - "Exact executable binding created. It still carries zero action and execution authority.", - ); - } finally { - setBusy(null); - } - }, [snapshot, targetSha256]); - - const issueLease = useCallback(async () => { - const readiness = snapshot?.lease_readiness; - if ( - !readiness?.ready || - !readiness.executable_binding_sha256 || - !readiness.policy_sha256 || - !readiness.enforcement_profile_sha256 || - !readiness.authority_epoch_sha256 - ) { - return; - } - setBusy("LEASE"); - setMessage(null); - try { - const result = await ghostWalkAuthorizationConsoleClient.issueLease({ - targetSha256, - expectedExecutableBindingSha256: - readiness.executable_binding_sha256, - expectedPolicySha256: readiness.policy_sha256, - expectedPolicySetSha256: readiness.policy_set_sha256, - expectedEnforcementProfileSha256: - readiness.enforcement_profile_sha256, - expectedAuthorityEpochSha256: - readiness.authority_epoch_sha256, - }); - if (result.kind === "conflict") { - setMessage( - "Lease conflict: binding, policy, enforcement, or authority state changed. Reload first.", - ); - return; - } - if (result.kind === "unavailable") { - setMessage( - "ActionLease issuance is unavailable or failed current authority checks.", - ); - return; - } - setSnapshot(result.snapshot); - setMessage( - "Single-use ActionLease issued. The lease carries bounded action " + - "authority; this console still cannot execute it.", - ); - } finally { - setBusy(null); - } - }, [snapshot, targetSha256]); - if (!snapshot) { return (
@@ -235,39 +95,9 @@ export function GhostWalkAuthorizationConsoleCard({
)} - {auth.ready && ( - <> -