Full Code of lachlan2k/phatcrack for AI

main cfa969e3b2bd cached
264 files
3.8 MB
1.0M tokens
938 symbols
1 requests
Download .txt
Showing preview only (4,070K chars total). Download the full file or copy to clipboard to get everything.
Repository: lachlan2k/phatcrack
Branch: main
Commit: cfa969e3b2bd
Files: 264
Total size: 3.8 MB

Directory structure:
gitextract_umi_osjx/

├── .dockerignore
├── .github/
│   └── workflows/
│       ├── build-agent-and-release.yml
│       ├── codeql.yml
│       ├── docker-publish.yml
│       ├── e2e.yml
│       ├── go-lint.yml
│       └── lint.yaml
├── .gitignore
├── Caddyfile
├── Dockerfile.agent
├── Dockerfile.api
├── Dockerfile.frontend
├── LICENSE
├── README.md
├── agent/
│   ├── .gitignore
│   ├── build.sh
│   ├── example_config.json
│   ├── go.mod
│   ├── go.sum
│   ├── install.sh
│   ├── internal/
│   │   ├── config/
│   │   │   └── config.go
│   │   ├── handler/
│   │   │   ├── file.go
│   │   │   ├── handler.go
│   │   │   ├── heartbeat.go
│   │   │   ├── job.go
│   │   │   ├── run.go
│   │   │   └── run_windows.go
│   │   ├── hashcat/
│   │   │   ├── constants.go
│   │   │   ├── constants_windows.go
│   │   │   └── hashcat.go
│   │   ├── installer/
│   │   │   ├── hashcat_install.go
│   │   │   ├── installer.go
│   │   │   ├── register.go
│   │   │   ├── template.service
│   │   │   ├── utils.go
│   │   │   └── utils_windows.go
│   │   ├── lockfile/
│   │   │   ├── lockfile.go
│   │   │   └── lockfile_dummy.go
│   │   ├── util/
│   │   │   ├── backoff.go
│   │   │   └── util.go
│   │   ├── version/
│   │   │   └── version.go
│   │   └── wswrapper/
│   │       └── wswrapper.go
│   └── main.go
├── api/
│   ├── .air.toml
│   ├── .dockerignore
│   ├── Dockerfile.dev
│   ├── build.sh
│   ├── go.mod
│   ├── go.sum
│   ├── internal/
│   │   ├── accesscontrol/
│   │   │   └── accesscontrol.go
│   │   ├── attacksharder/
│   │   │   └── attacksharder.go
│   │   ├── auth/
│   │   │   ├── header_auth_middleware.go
│   │   │   ├── mfa.go
│   │   │   ├── mfa_webauthn.go
│   │   │   ├── middleware.go
│   │   │   ├── session.go
│   │   │   └── session_inmemory.go
│   │   ├── config/
│   │   │   ├── config.go
│   │   │   └── config_migration.go
│   │   ├── controllers/
│   │   │   ├── account.go
│   │   │   ├── admin.go
│   │   │   ├── agent.go
│   │   │   ├── agent_handler.go
│   │   │   ├── attack.go
│   │   │   ├── attack_template.go
│   │   │   ├── attackjob.go
│   │   │   ├── auth.go
│   │   │   ├── auth_credentials.go
│   │   │   ├── auth_oidc.go
│   │   │   ├── config.go
│   │   │   ├── controllers.go
│   │   │   ├── e2e.go
│   │   │   ├── hashcat.go
│   │   │   ├── hashlist.go
│   │   │   ├── listfiles.go
│   │   │   ├── listfiles_upload.go
│   │   │   ├── potfile.go
│   │   │   ├── project.go
│   │   │   └── users.go
│   │   ├── db/
│   │   │   ├── agent.go
│   │   │   ├── attack_template.go
│   │   │   ├── config.go
│   │   │   ├── db.go
│   │   │   ├── job.go
│   │   │   ├── keyspace_cache.go
│   │   │   ├── listfiles.go
│   │   │   ├── potfile.go
│   │   │   ├── project.go
│   │   │   └── user.go
│   │   ├── filerepo/
│   │   │   └── filerepo.go
│   │   ├── fleet/
│   │   │   ├── agent.go
│   │   │   ├── fleet.go
│   │   │   ├── handle_jobs_events.go
│   │   │   └── state_reconcilition.go
│   │   ├── hashcathelpers/
│   │   │   └── hashcathelpers.go
│   │   ├── resources/
│   │   │   ├── gen_hash_info.sh
│   │   │   ├── hash_info.json
│   │   │   └── resources.go
│   │   ├── roles/
│   │   │   └── roles.go
│   │   ├── util/
│   │   │   ├── password_strength.go
│   │   │   ├── request_validator.go
│   │   │   └── util.go
│   │   ├── version/
│   │   │   └── version.go
│   │   └── webserver/
│   │       ├── logger.go
│   │       └── webserver.go
│   └── main.go
├── common/
│   ├── go.mod
│   ├── go.sum
│   └── pkg/
│       ├── apitypes/
│       │   ├── account.go
│       │   ├── admin.go
│       │   ├── admin_config.go
│       │   ├── agent.go
│       │   ├── agent_handler.go
│       │   ├── apitypes.go
│       │   ├── attack.go
│       │   ├── attack_template.go
│       │   ├── auth.go
│       │   ├── config.go
│       │   ├── hashcat.go
│       │   ├── hashlist.go
│       │   ├── job.go
│       │   ├── listfiles.go
│       │   ├── potfile.go
│       │   ├── project.go
│       │   └── user.go
│       ├── hashcattypes/
│       │   ├── attackmode.go
│       │   ├── hashcattypes.go
│       │   └── hashinfo.go
│       └── wstypes/
│           ├── job.go
│           └── wstypes.go
├── docker-compose.dev.yml
├── docker-compose.prod.yml
├── e2e/
│   ├── api/
│   │   ├── .gitignore
│   │   ├── .prettierrc.json
│   │   ├── jest.config.js
│   │   ├── package.json
│   │   ├── tests/
│   │   │   ├── _api.spec.ts
│   │   │   ├── _helpers.ts
│   │   │   ├── admin_authz.ts
│   │   │   ├── dummyRequests.ts
│   │   │   ├── hashlists.ts
│   │   │   ├── projects.ts
│   │   │   ├── setup.ts
│   │   │   ├── unauth.ts
│   │   │   └── user_provisioning_auth.ts
│   │   └── tsconfig.json
│   ├── browser/
│   │   ├── .gitignore
│   │   ├── package.json
│   │   ├── playwright.config.ts
│   │   └── tests/
│   │       ├── adduser.spec.ts
│   │       ├── auth.config.ts
│   │       ├── auth.setup.ts
│   │       └── initial.setup.ts
│   └── docker-compose.test.yml
├── frontend/
│   ├── .gitignore
│   ├── .prettierrc.json
│   ├── .vscode/
│   │   └── extensions.json
│   ├── Dockerfile.dev
│   ├── README.md
│   ├── env.d.ts
│   ├── eslint.config.ts
│   ├── index.html
│   ├── package.json
│   ├── postcss.config.js
│   ├── src/
│   │   ├── App.vue
│   │   ├── api/
│   │   │   ├── account.ts
│   │   │   ├── admin.ts
│   │   │   ├── agent.ts
│   │   │   ├── attackTemplate.ts
│   │   │   ├── auth.ts
│   │   │   ├── config.ts
│   │   │   ├── hashcat.ts
│   │   │   ├── index.ts
│   │   │   ├── listfiles.ts
│   │   │   ├── potfile.ts
│   │   │   ├── project.ts
│   │   │   ├── types.ts
│   │   │   └── users.ts
│   │   ├── components/
│   │   │   ├── Admin/
│   │   │   │   ├── AgentConfig.vue
│   │   │   │   ├── AuthConfig.vue
│   │   │   │   ├── GeneralConfig.vue
│   │   │   │   └── UsersTable.vue
│   │   │   ├── AttackConfigDetails.vue
│   │   │   ├── AttackDetailsModal/
│   │   │   │   ├── Overview.vue
│   │   │   │   └── index.vue
│   │   │   ├── AttackTemplateCreator.vue
│   │   │   ├── AttackTemplateEditor.vue
│   │   │   ├── AttackTemplateSetCreator.vue
│   │   │   ├── AttackTemplateSetEditor.vue
│   │   │   ├── CheckboxSet.vue
│   │   │   ├── ConfirmModal.vue
│   │   │   ├── EmptyTable.vue
│   │   │   ├── FileUpload.vue
│   │   │   ├── HashesInput.vue
│   │   │   ├── HrOr.vue
│   │   │   ├── IconButton.vue
│   │   │   ├── InfoTip.vue
│   │   │   ├── Modal.vue
│   │   │   ├── PageLoading.vue
│   │   │   ├── PaginationControls.vue
│   │   │   ├── ProjectShare.vue
│   │   │   ├── SearchableDropdown.vue
│   │   │   ├── TimeSinceDisplay.vue
│   │   │   └── Wizard/
│   │   │       ├── AttackSettings.vue
│   │   │       ├── HashlistInputs.vue
│   │   │       ├── JobWizard.vue
│   │   │       ├── ListSelect.vue
│   │   │       └── MaskInput.vue
│   │   ├── composables/
│   │   │   ├── useApi.ts
│   │   │   ├── useAttackSettings.ts
│   │   │   ├── useHashesInput.ts
│   │   │   ├── usePagination.ts
│   │   │   ├── useToastError.ts
│   │   │   └── useWizardHashDetect.ts
│   │   ├── layouts/
│   │   │   └── default.vue
│   │   ├── main.ts
│   │   ├── pages/
│   │   │   ├── Account.vue
│   │   │   ├── Agents.vue
│   │   │   ├── AttackTemplates.vue
│   │   │   ├── HashSearch.vue
│   │   │   ├── Hashlist.vue
│   │   │   ├── Listfiles.vue
│   │   │   ├── Login.vue
│   │   │   ├── LoginOIDCCallback.vue
│   │   │   ├── Utilisation.vue
│   │   │   ├── Wizard.vue
│   │   │   ├── admin/
│   │   │   │   ├── Agents.vue
│   │   │   │   ├── Configuration.vue
│   │   │   │   └── Users.vue
│   │   │   └── projects/
│   │   │       ├── index.vue
│   │   │       └── project.vue
│   │   ├── router/
│   │   │   └── index.ts
│   │   ├── stores/
│   │   │   ├── activeAttacks.ts
│   │   │   ├── adminConfig.ts
│   │   │   ├── agents.ts
│   │   │   ├── attackTemplates.ts
│   │   │   ├── auth.ts
│   │   │   ├── config.ts
│   │   │   ├── listfiles.ts
│   │   │   ├── projects.ts
│   │   │   ├── resources.ts
│   │   │   └── users.ts
│   │   ├── styles.css
│   │   └── util/
│   │       ├── decodeHex.ts
│   │       ├── exportHashlist.ts
│   │       ├── formatDeviceName.ts
│   │       ├── hashcat.ts
│   │       ├── icons.ts
│   │       ├── sleep.ts
│   │       ├── units.ts
│   │       └── util.ts
│   ├── tailwind.config.js
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   └── vite.config.ts
├── go.work
├── go.work.sum
├── hack/
│   ├── cloc.sh
│   ├── dev.sh
│   ├── static_check.sh
│   ├── tag_release.sh
│   └── ts_types_codegen.sh
├── install_server.sh
└── renovate.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .dockerignore
================================================
frontend/node_modules/
.git/config
filerepo/

================================================
FILE: .github/workflows/build-agent-and-release.yml
================================================
name: Build Agent and Create Release

on:
  push:
    tags: [ 'v*.*.*' ]
  pull_request:
    branches: [ "main" ]

jobs:

  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v6
      with:
        fetch-depth: 0
        fetch-tags: true

    - name: Set up Go
      uses: actions/setup-go@v6
      with:
        go-version: '1.25'

    - name: Build Agent
      run: cd agent; bash build.sh

    - name: Upload artifact
      uses: actions/upload-artifact@v6
      with:
        name: phatcrack-agent
        path: ./agent/phatcrack-agent

    - id: get_version
      if: github.event_name != 'pull_request'
      uses: battila7/get-version-action@v2

    - name: Create Release
      if: github.event_name != 'pull_request'
      id: create_release
      uses: actions/create-release@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
      with:
        tag_name: ${{ github.ref }}
        release_name: ${{ github.ref }}
        body: |
          Release
        draft: false
        prerelease: false

    - name: Upload Agent as Release Asset
      if: github.event_name != 'pull_request'
      id: upload-agent-asset 
      uses: actions/upload-release-asset@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps 
        asset_path: ./agent/phatcrack-agent
        asset_name: phatcrack-agent
        asset_content_type: application/octet-stream

    # Replace :latest with specific version tag for release
    - run: sed -i 's/:-latest/:-${{ steps.get_version.outputs.version }}/' docker-compose.prod.yml
    
    - name: Upload Docker Compose as Release Asset
      if: github.event_name != 'pull_request'
      id: upload-docker-compose-asset 
      uses: actions/upload-release-asset@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps 
        asset_path: ./docker-compose.prod.yml
        asset_name: docker-compose.yml
        asset_content_type: application/x-yaml

    - name: Upload all-in-one install script as Release Asset
      if: github.event_name != 'pull_request'
      id: upload-install-script-asset
      uses: actions/upload-release-asset@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps 
        asset_path: ./install_server.sh
        asset_name: install_server.sh
        asset_content_type: text/x-shellscript

================================================
FILE: .github/workflows/codeql.yml
================================================
name: "CodeQL"

on:
  push:
    branches: [ "main" ]
  pull_request:
    # The branches below must be a subset of the branches above
    branches: [ "main" ]
  schedule:
    - cron: '20 14 * * 4'

jobs:
  analyze:
    name: Analyze
    # Runner size impacts CodeQL analysis time. To learn more, please see:
    #   - https://gh.io/recommended-hardware-resources-for-running-codeql
    #   - https://gh.io/supported-runners-and-hardware-resources
    #   - https://gh.io/using-larger-runners
    # Consider using larger runners for possible analysis time improvements.
    runs-on: ubuntu-latest
    timeout-minutes: 10
    permissions:
      actions: read
      contents: read
      security-events: write

    strategy:
      fail-fast: false
      matrix:
        language: [ 'go', 'javascript' ]


    steps:
    - name: Checkout repository
      uses: actions/checkout@v6

    - name: Setup Go
      uses: actions/setup-go@v6
      with:
        go-version: '^1.24.0' 

    # Initializes the CodeQL tools for scanning.
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v4
      with:
        languages: ${{ matrix.language }}
        # If you wish to specify custom queries, you can do so here or in a config file.
        # By default, queries listed here will override any specified in a config file.
        # Prefix the list here with "+" to use these queries and those in the config file.

        # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
        # queries: security-extended,security-and-quality


    # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift).
    # If this step fails, then you should remove it and run the build manually (see below)
    - name: Autobuild
      uses: github/codeql-action/autobuild@v4


    # ℹ️ Command-line programs to run using the OS shell.
    # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun

    #   If the Autobuild fails above, remove it and uncomment the following three lines.
    #   modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.

    # - run: |
    #     echo "Run, Build Application using script"
    #     ./location_of_script_within_repo/buildscript.sh

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v4
      with:
        category: "/language:${{matrix.language}}"


================================================
FILE: .github/workflows/docker-publish.yml
================================================
name: Docker Build & Publish API and Frontend

on:
  schedule:
    - cron: '0 0 * * 0'
  push:
    branches: [ "main" ]
    tags: [ 'v*.*.*' ]
  pull_request:
    branches: [ "main" ]

env:
  REGISTRY: ghcr.io
  API_IMAGE_NAME: ${{ github.repository }}/api
  FRONTEND_IMAGE_NAME: ${{ github.repository }}/frontend
  AGENT_SERVER_IMAGE_NAME: ${{ github.repository }}/agent-server


jobs:
  build:

    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      # This is used to complete the identity challenge
      # with sigstore/fulcio when running outside of PRs.
      id-token: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          fetch-tags: true

      - name: Install cosign
        if: github.event_name != 'pull_request'
        uses: sigstore/cosign-installer@v4.0.0
        with:
          cosign-release: 'v2.2.2'

      - name: Setup Docker buildx
        uses: docker/setup-buildx-action@c7c4c00f3eef127be487a50899a220e44c6bcc87

      - name: Log into registry ${{ env.REGISTRY }}
        if: github.event_name != 'pull_request'
        uses: docker/login-action@916386b00027d425839f8da46d302dab33f5875b
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      #####
      ### API
      #####
      - name: Extract Docker API metadata
        id: meta-api
        uses: docker/metadata-action@ed95091677497158a9ff38b314264cd965388d5e
        with:
          images: ${{ env.REGISTRY }}/${{ env.API_IMAGE_NAME }}

      - name: Build and push API Docker image
        id: build-and-push-api
        uses: docker/build-push-action@64c9b141502b80dbbd71e008a0130ad330f480f8
        with:
          context: .
          file: Dockerfile.api
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta-api.outputs.tags }}
          labels: ${{ steps.meta-api.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Sign the published API Docker image
        if: ${{ github.event_name != 'pull_request' }}
        env:
          TAGS: ${{ steps.meta-api.outputs.tags }}
          DIGEST: ${{ steps.build-and-push-api.outputs.digest }}
        run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}

        
      #####
      ### Frontend
      #####
      - name: Extract Docker frontend metadata
        id: meta-frontend
        uses: docker/metadata-action@ed95091677497158a9ff38b314264cd965388d5e
        with:
          images: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}

      - name: Build and push frontend Docker image
        id: build-and-push-frontend
        uses: docker/build-push-action@64c9b141502b80dbbd71e008a0130ad330f480f8
        with:
          context: .
          file: Dockerfile.frontend
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta-frontend.outputs.tags }}
          labels: ${{ steps.meta-frontend.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Sign the published frontend Docker image
        if: ${{ github.event_name != 'pull_request' }}
        env:
          TAGS: ${{ steps.meta-frontend.outputs.tags }}
          DIGEST: ${{ steps.build-and-push-frontend.outputs.digest }}
        run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}


      #####
      ### Agent Server
      #####
      - name: Extract Docker agent server metadata
        id: meta-agent
        uses: docker/metadata-action@ed95091677497158a9ff38b314264cd965388d5e
        with:
          images: ${{ env.REGISTRY }}/${{ env.AGENT_SERVER_IMAGE_NAME }}

      - name: Build and push agent server Docker image
        id: build-and-push-agent
        uses: docker/build-push-action@64c9b141502b80dbbd71e008a0130ad330f480f8
        with:
          context: .
          file: Dockerfile.agent
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta-agent.outputs.tags }}
          labels: ${{ steps.meta-agent.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Sign the published agent Docker image
        if: ${{ github.event_name != 'pull_request' }}
        env:
          TAGS: ${{ steps.meta-agent.outputs.tags }}
          DIGEST: ${{ steps.build-and-push-agent.outputs.digest }}
        run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}


================================================
FILE: .github/workflows/e2e.yml
================================================
name: E2E Tests
on:
  push:
    branches: ["main"]

jobs:
  tests:
    name: "E2E Tests"
    runs-on: ubuntu-24.04
    defaults:
      run:
        working-directory: ./e2e

    steps:
      - uses: actions/checkout@v6

      - uses: actions/setup-node@v6
        with:
          node-version: 24

      - name: Start application
        run: docker compose -f docker-compose.test.yml up -d --wait --build --force-recreate

      ##
      ## Playwright E2E Browser Tests
      ##
      - name: Install Playwright test dependencies
        run: |
          cd browser
          npm ci
          npx playwright install --with-deps

      - name: Run Playwright E2E tests
        run: |
          cd browser
          npx playwright test --trace on

      - name: Upload Playwright Test Results
        uses: actions/upload-artifact@v6
        with:
          name: playwright-test-results
          path: e2e/browser/playwright-report
          retention-days: 7

      ##
      ## Jest API Tests
      ##
      - name: Install Jest API test dependencies
        run: |
          cd api
          npm ci
          cd ../../frontend
          npm ci

      - name: Run Jest API tests
        run: |
          cd api
          npm test


================================================
FILE: .github/workflows/go-lint.yml
================================================
name: golangci-lint

on:
  pull_request:
  push:
    branches:
      - main

env:
  GO_VERSION: stable
  GOLANGCI_LINT_VERSION: v2.1

jobs:
  detect-modules:
    runs-on: ubuntu-latest
    outputs:
      modules: ${{ steps.set-modules.outputs.modules }}
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-go@v6
        with:
          go-version: ${{ env.GO_VERSION }}
      - id: set-modules
        run: echo "modules=$(go list -m -json | jq -s '.' | jq -c '[.[].Dir]')" >> $GITHUB_OUTPUT

  golangci-lint:
    needs: detect-modules
    runs-on: ubuntu-latest
    strategy:
      matrix:
        modules: ${{ fromJSON(needs.detect-modules.outputs.modules) }}
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-go@v6
        with:
          go-version: ${{ env.GO_VERSION }}
      - name: golangci-lint ${{ matrix.modules }}
        uses: golangci/golangci-lint-action@v9
        with:
          version: ${{ env.GOLANGCI_LINT_VERSION }}
          working-directory: ${{ matrix.modules }}
          args: '--disable errcheck'

================================================
FILE: .github/workflows/lint.yaml
================================================
name: Run lint checks

on:
  pull_request:
  push:
    branches:
      - main

jobs:
  frontend_lint:
    name: Frontend Lint
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./frontend

    steps:
    - name: Checkout repository
      uses: actions/checkout@v6

    - name: Setup Node.js
      uses: actions/setup-node@v6

    - name: Install dependencies
      run: npm ci

    - name: Run linter
      run: npm run lint


================================================
FILE: .gitignore
================================================
.env
.dev.env
certs/cert.pem
certs/key.pem
filerepo/*
*/tmp
agent/phatcrack-agent
agent/phatcrack-agent.exe

================================================
FILE: Caddyfile
================================================
{$HOST_NAME} {
    # This technically allows any caddy entry to be added here
    # But we'll just use it for TLS
    {$TLS_OPTS}

    encode gzip

    header {
        Strict-Transport-Security max-age=31536000;
        X-Content-Type-Options nosniff
        X-Frame-Options DENY
        Referrer-Policy no-referrer-when-downgrade
    }

    handle /agent-assets/* {
        reverse_proxy http://agent-server
    }

    handle /api/* {
        header Content-Security-Policy "default-src 'none'"
        reverse_proxy http://api:3000
    }

    handle {
        header Content-Security-Policy "default-src 'self'; object-src 'none'; script-src 'self' 'unsafe-eval'; img-src 'self' data:; style-src 'self' data: 'unsafe-inline'"
        root * /srv
        try_files {path} /index.html
        file_server
    }
}

================================================
FILE: Dockerfile.agent
================================================
# This Dockerfile builds and serves the agent
FROM golang:1.26 AS builder


COPY agent /app/agent
COPY common /app/common
COPY .git /app/.git

WORKDIR /app/common
RUN go mod download -x

WORKDIR /app/agent
RUN bash build.sh linux
RUN bash build.sh windows

FROM caddy:2-alpine
ENV HASHCAT_VERSION=6.2.6

WORKDIR /usr/share/caddy
RUN rm index.html
WORKDIR /usr/share/caddy/agent-assets
RUN wget -O hashcat.7z https://github.com/hashcat/hashcat/releases/download/v$HASHCAT_VERSION/hashcat-$HASHCAT_VERSION.7z \ 
    && apk add --update --no-cache p7zip                                                                                  \
    && 7z x hashcat.7z                                                                                                    \
    && tar czvf hashcat.tar.gz hashcat-$HASHCAT_VERSION                                                                    \
    && rm -r hashcat.7z hashcat-$HASHCAT_VERSION

COPY agent/install.sh install.sh    

COPY --from=builder /app/agent/phatcrack-agent.exe /usr/share/caddy/agent-assets/phatcrack-agent.exe
COPY --from=builder /app/agent/phatcrack-agent /usr/share/caddy/agent-assets/phatcrack-agent

================================================
FILE: Dockerfile.api
================================================
# This Dockerfile is for building the API server

# Builder
FROM golang:1.26 AS builder

WORKDIR /opt/

RUN wget https://github.com/hashcat/hashcat/releases/download/v6.2.6/hashcat-6.2.6.7z -q -O hashcat.7z
RUN apt update -y
RUN apt install -y p7zip-full
RUN 7z x hashcat.7z

# Before copying all the source, first copy the dependency files
# This lets us download these and cache the downloads
COPY api/go.mod api/go.sum /app/api/
COPY common/go.mod common/go.sum /app/common/

WORKDIR /app/common
RUN go mod download -x

WORKDIR /app/api
RUN go mod download -x

# Now copy over the source code
COPY common /app/common/
COPY api /app/api/
COPY .git /app/.git/

RUN bash build.sh

# Runtime
FROM redhat/ubi9-minimal AS runtime

WORKDIR /app
COPY --from=builder /app/api/phatcrack-api .
COPY --from=builder /opt/hashcat-6.2.6 /opt/hashcat/
RUN chmod 777 /opt/hashcat/

ENV HC_PATH=/opt/hashcat/hashcat.bin
ENTRYPOINT [ "/app/phatcrack-api" ]

================================================
FILE: Dockerfile.frontend
================================================
# The Dockerfile builds and packages the frontend, and serves it with the Caddy web server.
# Caddy also proxies to the API for production delpoyments.

FROM node:lts AS builder

WORKDIR /app

# Dependencies first to cache
COPY ./frontend/package.json ./frontend/package-lock.json ./
RUN npm install

COPY ./frontend ./
RUN npm run build-only

FROM caddy:2-alpine

COPY --from=builder /app/dist /srv
COPY Caddyfile /etc/caddy/Caddyfile

================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
# Phatcrack

Phatcrack is a modern solution for distributed hash cracking, designed for hackers and other information security professionals.

Key features include:
* Built on [Hashcat](https://hashcat.net), supporting most common Hashcat attacks and almost all hash types.
* Excellent UX for managing projects, configuring attack settings, and viewing results.
* Distributes attacks, allowing both dictionary-based and mask-based attacks to be split across multiple workers.
* Automatically synchronises wordlists & rulefiles to all workers. Low-privileged users can be granted permission to upload wordlists & rulefiles.
* Modern web-interface, with multi-user support and project-based access control.

![image](https://github.com/lachlan2k/phatcrack/assets/4683714/b10df9ec-ed5a-4678-9442-89003636bbce)

### Deployment

#### Server
Docker is the only supported deployment method for the server. The following instructions assume you already have [Docker installed on your server](https://docs.docker.com/engine/install/), and are logged in as root (`sudo su`).

```sh
# Ideally the container processes should be run rootless, so we'll create an unprivileged user.
useradd --system --create-home --home-dir /opt/phatcrack-server phatcrack-server

cd /opt/phatcrack-server

wget https://github.com/lachlan2k/phatcrack/releases/download/v0.7.0/docker-compose.yml

# Update your hostname here:
echo "HOST_NAME=phatcrack.lan" >> .env
echo "DB_PASS=$(openssl rand -hex 16)" >> .env
echo "PHATCRACK_USER=$(id -u phatcrack-server):$(id -g phatcrack-server)" >> .env
chmod 600 .env

# If you chose a hostname that is publicly accessible and expose this to the world (not recommended), Caddy will automatically deploy TLS.

## Otherwise, use the following for self-signed TLS
# echo "TLS_OPTS=tls internal" >> .env

## If you want to supply custom certificates, place them in a directory called `certs`
## And add ./certs:/etc/caddy/certs:ro as a mount in docker-compose.prod.yml for 
# echo "TLS_OPTS=tls /etc/caddy/certs/cert.pem /etc/caddy/certs/key.pem" >> .env

# Make a directory to persist files in
mkdir filerepo
chown phatcrack-server:phatcrack-server filerepo

docker compose up -d
```

You can then visit your local installation. The default credentials are `admin:changeme`.

#### Agents

To enroll an agent, visit the admin GUI, and click "Register Agent". The web interface will provide a script that you can run on the agent to enroll it.

However, if you want to set up an agent manually, you can do so with the following commands. You will need to replace `REGISTRATION_KEY_FROM_SERVER_HERE` with the key from the server.

```sh
# Create a user for the phatcrack agent
useradd --system --create-home --home-dir /opt/phatcrack-agent phatcrack-agent

# Depending on your distro, you may need to the phatcrack-agent to a group
usermod -aG video phatcrack-agent

cd /opt/phatcrack-agent

# Download the phatcrack-agent program from the local server
wget https://phatcrack.lan/agent-assets/phatcrack-agent
# Or, you can download from https://github.com/lachlan2k/phatcrack/releases/download/v0.7.0/phatcrack-agent

chmod +x ./phatcrack-agent
# Optionally add -disable-tls-verification if you are using self-signed certs
./phatcrack-agent install -defaults -api-endpoint https://phatcrack.lan/api/v1 -registration-key REGISTRATION_KEY_FROM_SERVER_HERE 

systemctl enable phatcrack-agent
systemctl start phatcrack-agent
```

================================================
FILE: agent/.gitignore
================================================
config.json
auth.key

================================================
FILE: agent/build.sh
================================================
#!/bin/bash

VERSION_STR=$(git describe --tags)

echo "Building version ${VERSION_STR}"

GOOS=${1:-linux}
FILENAME="phatcrack-agent"
if [ "$GOOS" = "windows" ]; then
    FILENAME="phatcrack-agent.exe"
fi

GOOS=$GOOS CGO_ENABLED=0 go build -ldflags="-X github.com/lachlan2k/phatcrack/agent/internal/version.version=${VERSION_STR}" -o $FILENAME main.go

================================================
FILE: agent/example_config.json
================================================
{
    "auth_key_file": "/opt/phatcrack-agent/auth-key",
    "hashcat_binary": "/opt/hashcat/hashcat.bin",
    "listfile_directory": "/opt/phatcrack-phatcrack/listfiles",
    "api_endpoint": "http://phatcrack.lan/api/v1",
    "additional_hashcat_args": ["-w3"]
}

================================================
FILE: agent/go.mod
================================================
module github.com/lachlan2k/phatcrack/agent

go 1.24.0

replace github.com/lachlan2k/phatcrack/common v0.0.0 => ../common

replace gopkg.in/fsnotify.v1 => github.com/fsnotify/fsnotify v1.9.0

require (
	github.com/google/uuid v1.6.0
	github.com/gorilla/websocket v1.5.3
	github.com/lachlan2k/phatcrack/common v0.0.0
	github.com/nxadm/tail v1.4.11
	golang.org/x/sys v0.41.0
)

require (
	github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef4dfa // indirect
	github.com/fsnotify/fsnotify v1.7.0 // indirect
	github.com/fxamacker/cbor/v2 v2.6.0 // indirect
	github.com/go-webauthn/x v0.1.27 // indirect
	github.com/golang-jwt/jwt/v5 v5.2.3 // indirect
	github.com/google/go-tpm v0.9.8 // indirect
	github.com/mitchellh/mapstructure v1.5.0 // indirect
	github.com/x448/float16 v0.8.4 // indirect
	golang.org/x/crypto v0.46.0 // indirect
	gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
)


================================================
FILE: agent/go.sum
================================================
github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef4dfa h1:z8Lo9+R9h4ZF5qvq2NTrWGVjL8gE92cPUv9J4i4yYKg=
github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef4dfa/go.mod h1:WfTnekCrJZ8MTDSlOeFACJTeGFvQnLInNzbZLRpoqTU=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/fxamacker/cbor/v2 v2.6.0 h1:sU6J2usfADwWlYDAFhZBQ6TnLFBHxgesMrQfQgk1tWA=
github.com/fxamacker/cbor/v2 v2.6.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
github.com/go-webauthn/x v0.1.27 h1:CLyuB8JGn9xvw0etBl4fnclcbPTwhKpN4Xg32zaSYnI=
github.com/go-webauthn/x v0.1.27/go.mod h1:KGYJQAPPgbpDKi4N7zKMGL+Iz6WgxKg3OlhVbPtuJXI=
github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0=
github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY=
github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JXXHc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=


================================================
FILE: agent/install.sh
================================================
#!/bin/sh

set -e

if [ -z "$PHATCRACK_HOST" ]; then
  echo "PHATCRACK_HOST is not set. Exiting."
  exit 1
fi

if [ -z "$PHATCRACK_REGISTRATION_KEY" ]; then
  echo "PHATCRACK_REGISTRATION_KEY is not set. Exiting."
  exit 1
fi

if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root. Exiting."
  exit 1
fi

if [[ $PHATCRACK_HOST != https://* ]]; then
  PHATCRACK_HOST=https://$PHATCRACK_HOST
fi

download_file() {
    local url="$1"
    local output="$2"
    
    if command -v curl &> /dev/null; then
        if [[ -n "$DISABLE_TLS_VERIFICATION" ]]; then
            curl -k "$url" -o "$output"
        else
            curl "$url" -o "$output"
        fi
    elif command -v wget &> /dev/null; then
        if [[ -n "$DISABLE_TLS_VERIFICATION" ]]; then
            wget --no-check-certificate "$url" -O "$output"
        else
            wget "$url" -O "$output"
        fi
    else
        echo "Neither curl nor wget is installed. Cannot download file."
        return 1
    fi
}

echo "Adding phatcrack-agent user..."
useradd --system --create-home --home-dir /opt/phatcrack-agent phatcrack-agent || true

echo "Adding phatcrack-agent user to video group (might error if it doesn't exist)"
usermod -aG video phatcrack-agent || true

cd /opt/phatcrack-agent

echo "Downloading agent"
download_file $PHATCRACK_HOST/agent-assets/phatcrack-agent phatcrack-agent
chmod +x ./phatcrack-agent

tls_arg=""
if [[ -n "$DISABLE_TLS_VERIFICATION" ]]; then
    tls_arg="-disable-tls-verification"
fi

./phatcrack-agent install -defaults -api-endpoint $PHATCRACK_HOST/api/v1 -registration-key $PHATCRACK_REGISTRATION_KEY $tls_arg

echo "Starting service..."

systemctl daemon-reload
systemctl enable --now phatcrack-agent

================================================
FILE: agent/internal/config/config.go
================================================
package config

import (
	"encoding/json"
	"os"
	"strings"

	"log"
)

type Config struct {
	AuthKeyFile             string `json:"auth_key_file"`
	AuthKey                 string `json:"auth_key"`
	HashcatPath             string `json:"hashcat_binary"`
	ListfileDirectory       string `json:"listfile_directory"`
	APIEndpoint             string `json:"api_endpoint"`
	DisableDownloadLockfile bool   `json:"disable_download_lockfile"`

	DisableTLSVerification bool `json:"disable_tls_verification"`
}

func LoadConfig(configPath string) (config Config) {
	configJSON, err := os.ReadFile(configPath)
	if err != nil {
		log.Fatalf("couldn't read config file (%q): %v", configPath, err)
	}

	err = json.Unmarshal(configJSON, &config)
	if err != nil {
		log.Fatalf("error when unmarshalling config json: %v", err)
	}

	if config.AuthKey == "" {
		if config.AuthKeyFile == "" {
			log.Fatalf("Neither auth_key nor auth_key_file was provided")
		}

		authKeyBytes, err := os.ReadFile(config.AuthKeyFile)
		if err != nil {
			log.Fatalf("couldn't read provided auth key file (%q): %v", config.AuthKeyFile, err)
		}

		config.AuthKey = strings.TrimSpace(string(authKeyBytes))
	}

	return
}


================================================
FILE: agent/internal/handler/file.go
================================================
package handler

import (
	"crypto/tls"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"log"

	"github.com/lachlan2k/phatcrack/agent/internal/util"
	"github.com/lachlan2k/phatcrack/common/pkg/wstypes"
)

type Lockfile interface {
	AcquireWithTimeout(time.Duration) error
	Unlock()
}

func (h *Handler) getFilePath(fileID string) (string, error) {
	filename := filepath.Base(filepath.Clean(fileID))
	if filename == "." || filename == ".." || filename == "/" {
		return "", fmt.Errorf("couldn't form a valid path from file ID: %v", fileID)
	}

	return filepath.Join(h.conf.ListfileDirectory, filename), nil
}

func (h *Handler) downloadFile(fileID string) error {
	writePath, err := h.getFilePath(fileID)
	if err != nil {
		return err
	}

	outFile, err := os.OpenFile(writePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}
	defer outFile.Close()

	tr := &http.Transport{}
	if h.conf.DisableTLSVerification {
		tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
	}
	client := &http.Client{Transport: tr}

	request, err := http.NewRequest("GET", fmt.Sprintf("%s/agent-handler/download-file/%s", h.conf.APIEndpoint, fileID), nil)
	if err != nil {
		return err
	}

	request.Header.Add("Authorization", h.conf.AuthKey)

	log.Printf("Downloading file from %q", request.URL.String())
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	if response == nil {
		return errors.New("response was nil")
	}

	if response.StatusCode != http.StatusOK {
		return fmt.Errorf("expected response code 200 when downloading file, got %d", response.StatusCode)
	}

	_, err = io.Copy(outFile, response.Body)
	if err != nil {
		return err
	}
	log.Printf("Downloaded file %q", fileID)
	return nil
}

func (h *Handler) handleDownloadFileRequest(msg *wstypes.Message) error {
	if h.isDownloadingFile {
		// Silently fail if we're already doing a download
		// We'll be instructed to complete the download at a later time, so this is all good
		return nil
	}

	h.fileDownloadLock.Lock()
	defer h.fileDownloadLock.Unlock()

	err := h.downloadLockfile.AcquireWithTimeout(10 * time.Second)
	if err != nil {
		return err
	}
	defer h.downloadLockfile.Unlock()

	h.isDownloadingFile = true
	defer func() {
		h.isDownloadingFile = false
	}()

	payload, err := util.UnmarshalJSON[wstypes.DownloadFileRequestDTO](msg.Payload)
	if err != nil {
		return fmt.Errorf("couldn't unmarshal %v to download file request dto: %v", msg.Payload, err)
	}

	for _, file := range payload.FileIDs {
		err := h.downloadFile(file)
		if err != nil {
			return err
		}
	}

	return nil
}

func (h *Handler) handleDeleteFileRequest(msg *wstypes.Message) error {
	// To avoid weird races, to be safe, let's make sure we're not downloading any files at the same time
	h.fileDownloadLock.Lock()
	defer h.fileDownloadLock.Unlock()

	payload, err := util.UnmarshalJSON[wstypes.DeleteFileRequestDTO](msg.Payload)
	if err != nil {
		return fmt.Errorf("couldn't unmarshal %v to delete file request dto: %v", msg.Payload, err)
	}

	filepath, err := h.getFilePath(payload.FileID)
	if err != nil {
		return err
	}

	err = os.Remove(filepath)
	if err != nil {
		return fmt.Errorf("failed to remove file: %v", err)
	}
	return nil
}


================================================
FILE: agent/internal/handler/handler.go
================================================
package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"runtime"
	"sync"
	"time"

	"log"
	"path"

	"github.com/lachlan2k/phatcrack/agent/internal/config"
	"github.com/lachlan2k/phatcrack/agent/internal/hashcat"
	"github.com/lachlan2k/phatcrack/agent/internal/lockfile"
	"github.com/lachlan2k/phatcrack/agent/internal/wswrapper"
	"github.com/lachlan2k/phatcrack/common/pkg/wstypes"
)

type ActiveJob struct {
	job        wstypes.JobStartDTO
	stopReason string
	sess       *hashcat.HashcatSession
}

type Handler struct {
	conn              *wswrapper.WSWrapper
	conf              *config.Config
	jobsLock          sync.Mutex
	fileDownloadLock  sync.Mutex
	isDownloadingFile bool
	activeJobs        map[string]*ActiveJob
	downloadLockfile  Lockfile
}

func (h *Handler) sendMessage(msgType string, payload interface{}) error {
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	return h.conn.WriteJSON(wstypes.Message{
		Type:    msgType,
		Payload: string(payloadBytes),
	})
}

func (h *Handler) sendMessageUnbuffered(msgType string, payload interface{}) error {
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	h.conn.WriteJSONUnbuffered(wstypes.Message{
		Type:    msgType,
		Payload: string(payloadBytes),
	})
	return nil
}

func (h *Handler) handleMessage(msg *wstypes.Message) error {
	switch msg.Type {
	case wstypes.JobStartType:
		return h.handleJobStart(msg)

	case wstypes.JobKillType:
		return h.handleJobKill(msg)

	case wstypes.DownloadFileRequestType:
		return h.handleDownloadFileRequest(msg)

	case wstypes.DeleteFileRequestType:
		return h.handleDeleteFileRequest(msg)

	default:
		return fmt.Errorf("unrecognized message type: %q", msg.Type)
	}
}

func (h *Handler) readLoop(ctx context.Context) error {
	for {
		var msg wstypes.Message
		err := h.conn.ReadJSON(&msg)
		if err != nil {
			time.Sleep(time.Second)
			continue
		}

		log.Printf("Received: %v", msg.Type)

		go func() {
			err := h.handleMessage(&msg)
			if err != nil {
				log.Printf("Error when handling %s message: %v", msg.Type, err)
			}
		}()

		select {
		case <-ctx.Done():
			return nil
		default:
		}
	}
}

func (h *Handler) writeLoop(ctx context.Context) error {
	for {
		if err := h.sendHeartbeat(); err != nil {
			return fmt.Errorf("failed to send heartbeat: %v", err)
		}

		select {
		case <-ctx.Done():
			return nil
		case <-time.After(30 * time.Second):
		}
	}
}

func (h *Handler) Handle() error {
	errs := make(chan error, 2)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		errs <- h.readLoop(ctx)
	}()

	go func() {
		errs <- h.writeLoop(ctx)
	}()

	err := <-errs
	return err
}

func apiEndpointToWSEndpoint(apiEndpoint string) (string, error) {
	wsUrl, err := url.Parse(apiEndpoint)
	if err != nil {
		return "", err
	}

	switch wsUrl.Scheme {
	case "http":
		wsUrl.Scheme = "ws"
	case "https":
		wsUrl.Scheme = "wss"
	}

	wsUrl.Path += "/agent-handler/ws"
	return wsUrl.String(), nil
}

func run(conf *config.Config) error {
	headers := http.Header{
		"Authorization": []string{conf.AuthKey},
	}

	wsEndpoint, err := apiEndpointToWSEndpoint(conf.APIEndpoint)
	if err != nil {
		return fmt.Errorf("invalid API endpoint (%q): %w", conf.APIEndpoint, err)
	}

	conn := &wswrapper.WSWrapper{
		Endpoint:               wsEndpoint,
		Headers:                headers,
		MaximumDropoutTime:     time.Minute * 5,
		DisableTLSVerification: conf.DisableTLSVerification,
	}

	var downloadLockfile Lockfile
	if conf.DisableDownloadLockfile || runtime.GOOS == "windows" {
		downloadLockfile = lockfile.NewDummy()
	} else {
		downloadLockfile = lockfile.New(path.Join(conf.ListfileDirectory, "agent.lock"))
	}

	h := &Handler{
		conn:             conn,
		conf:             conf,
		activeJobs:       make(map[string]*ActiveJob),
		downloadLockfile: downloadLockfile,
	}

	conn.Setup()

	errs := make(chan error)

	signalFirstConn := sync.NewCond(&sync.Mutex{})

	go func() {
		err := conn.Run(signalFirstConn)

		if err != nil {
			errs <- fmt.Errorf("unrecoverable connection error: %v", err)
		}
	}()

	signalFirstConn.L.Lock()
	signalFirstConn.Wait()

	go func() {
		err := h.Handle()

		if err != nil {
			errs <- fmt.Errorf("unrecoverable handler error: %v", err)
		}
	}()

	return <-errs
}


================================================
FILE: agent/internal/handler/heartbeat.go
================================================
package handler

import (
	"os"
	"time"

	"github.com/lachlan2k/phatcrack/agent/internal/version"
	"github.com/lachlan2k/phatcrack/common/pkg/wstypes"
)

func getFileDTOs(dir string) ([]wstypes.FileDTO, error) {
	if dir == "" {
		return []wstypes.FileDTO{}, nil
	}

	files, err := os.ReadDir(dir)
	if err != nil {
		return nil, err
	}

	dtos := make([]wstypes.FileDTO, 0)
	for _, file := range files {
		if file.IsDir() {
			continue
		}
		info, err := file.Info()
		if err != nil {
			continue
		}
		dtos = append(dtos, wstypes.FileDTO{
			Name: file.Name(),
			Size: info.Size(),
		})
	}

	return dtos, nil
}

var startTime = time.Now()

func (h *Handler) sendHeartbeat() error {
	h.jobsLock.Lock()
	defer h.jobsLock.Unlock()

	payload := wstypes.HeartbeatDTO{
		Time:           time.Now().Unix(),
		Version:        version.Version(),
		AgentStartTime: startTime.Unix(),
		ActiveJobIDs:   make([]string, 0),
	}

	for id := range h.activeJobs {
		payload.ActiveJobIDs = append(payload.ActiveJobIDs, id)
	}

	listFiles, err := getFileDTOs(h.conf.ListfileDirectory)
	if err != nil {
		return err
	}
	payload.Listfiles = listFiles

	return h.sendMessageUnbuffered(wstypes.HeartbeatType, payload)
}


================================================
FILE: agent/internal/handler/job.go
================================================
package handler

import (
	"fmt"
	"time"

	"log"

	"github.com/lachlan2k/phatcrack/agent/internal/hashcat"
	"github.com/lachlan2k/phatcrack/agent/internal/util"
	"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes"
	"github.com/lachlan2k/phatcrack/common/pkg/wstypes"
)

func (h *Handler) handleJobStart(msg *wstypes.Message) error {
	payload, err := util.UnmarshalJSON[wstypes.JobStartDTO](msg.Payload)
	if err != nil {
		return fmt.Errorf("couldn't unmarshal %v to job start dto: %v", msg.Payload, err)
	}

	return h.runJob(payload)
}

func (h *Handler) handleJobKill(msg *wstypes.Message) error {
	payload, err := util.UnmarshalJSON[wstypes.JobKillDTO](msg.Payload)
	if err != nil {
		return fmt.Errorf("couldn't unmarshal %v to job start dto: %v", msg.Payload, err)
	}

	return h.killJob(payload)
}

func (h *Handler) sendJobStarted(jobId string, hashcatCommand string) {
	h.sendMessage(wstypes.JobStartedType, wstypes.JobStartedDTO{
		JobID:          jobId,
		HashcatCommand: hashcatCommand,
		Time:           time.Now(),
	})
}

func (h *Handler) sendJobStdoutLine(jobId, line string) {
	h.sendMessage(wstypes.JobStdLineType, wstypes.JobStdLineDTO{
		JobID:  jobId,
		Line:   line,
		Stream: wstypes.JobStdLineStreamStdout,
	})
}

func (h *Handler) sendJobStderrLine(jobId, line string) {
	h.sendMessage(wstypes.JobStdLineType, wstypes.JobStdLineDTO{
		JobID:  jobId,
		Line:   line,
		Stream: wstypes.JobStdLineStreamStderr,
	})
}

func (h *Handler) sendJobExited(jobId string, reason string, err error) {
	errStr := ""
	if err != nil {
		errStr = err.Error()
	}

	// Hashcat gives exit code of 1 when a wordlist is exhausted
	// But not when a mask doesn't crack everything
	// So, we're just gonna silently ignore this?
	// I hate it
	if errStr == "exit status 1" {
		errStr = ""
	}

	h.sendMessage(wstypes.JobExitedType, wstypes.JobExitedDTO{
		JobID:      jobId,
		Error:      errStr,
		StopReason: reason,
		Time:       time.Now(),
	})
}

func (h *Handler) sendJobCrackedHash(jobId string, result hashcattypes.HashcatResult) {
	h.sendMessage(wstypes.JobCrackedHashType, wstypes.JobCrackedHashDTO{
		JobID:  jobId,
		Result: result,
	})
}

func (h *Handler) sendJobStatusUpdate(jobId string, status hashcattypes.HashcatStatus) {
	h.sendMessage(wstypes.JobStatusUpdateType, wstypes.JobStatusUpdateDTO{
		JobID:  jobId,
		Status: status,
	})
}

func (h *Handler) sendJobFailedToStart(jobId string, err error) {
	h.sendMessage(wstypes.JobFailedToStartType, wstypes.JobFailedToStartDTO{
		JobID: jobId,
		Time:  time.Now(),
		Error: err.Error(),
	})
}

var backoffTable = []util.BackoffEntry{
	{
		AfterTime: time.Duration(0),
		TimeApart: time.Duration(0),
	},
	{
		AfterTime: time.Minute,
		TimeApart: 10 * time.Second,
	},
	{
		AfterTime: 10 * time.Minute,
		TimeApart: 30 * time.Second,
	},
	{
		AfterTime: time.Hour,
		TimeApart: time.Minute,
	},
	{
		AfterTime: 8 * time.Hour,
		TimeApart: 5 * time.Minute,
	},
}

func (h *Handler) runJob(job wstypes.JobStartDTO) error {
	h.jobsLock.Lock()
	defer h.jobsLock.Unlock()

	_, alredyExists := h.activeJobs[job.ID]
	if alredyExists {
		return fmt.Errorf("job %q already exists", job.ID)
	}

	sess, err := hashcat.NewHashcatSession(job.ID, job.TargetHashes, hashcat.HashcatParams(job.HashcatParams), h.conf)
	if err != nil {
		h.sendJobFailedToStart(job.ID, err)
		return err
	}

	log.Printf("Starting job %q", job.ID)

	err = sess.Start()
	if err != nil {
		h.sendJobFailedToStart(job.ID, err)
		return err
	}

	activeJob := &ActiveJob{
		job:  job,
		sess: sess,
	}

	h.activeJobs[job.ID] = activeJob

	go func() {
		h.sendJobStarted(job.ID, sess.CmdLine())

		statusBackoff := util.Backoff{
			Entries: backoffTable,
		}
		stdoutBackoff := util.Backoff{
			Entries: backoffTable,
		}

		statusBackoff.Start()
		stdoutBackoff.Start()

	procLoop:
		for {
			select {
			case stdoutLine := <-sess.StdoutLines:
				// If it's a json status update, use our rate limit
				if len(stdoutLine) == 0 || stdoutLine[0] != '{' || stdoutBackoff.Ready() {
					h.sendJobStdoutLine(job.ID, stdoutLine)
				}

			case stderrLine := <-sess.StderrMessages:
				h.sendJobStderrLine(job.ID, stderrLine)

			case result := <-sess.CrackedHashes:
				h.sendJobCrackedHash(job.ID, hashcattypes.HashcatResult{
					Timestamp:    result.Timestamp,
					Hash:         result.Hash,
					PlaintextHex: result.PlaintextHex,
				})

			case status := <-sess.StatusUpdates:
				if statusBackoff.Ready() {
					h.sendJobStatusUpdate(job.ID, status)
				}

			case err := <-sess.DoneChan:
				h.sendJobExited(job.ID, activeJob.stopReason, err)
				break procLoop
			}
		}

		sess.Kill()
		sess.Cleanup()

		h.jobsLock.Lock()
		defer h.jobsLock.Unlock()

		delete(h.activeJobs, job.ID)
	}()

	return nil
}

func (h *Handler) killJob(jobMsg wstypes.JobKillDTO) error {
	h.jobsLock.Lock()
	defer h.jobsLock.Unlock()

	job, ok := h.activeJobs[jobMsg.JobID]
	if !ok {
		// We aren't running it so alg
		return nil
	}

	job.stopReason = jobMsg.StopReason

	return job.sess.Kill()
}


================================================
FILE: agent/internal/handler/run.go
================================================
//go:build !windows

package handler

import "github.com/lachlan2k/phatcrack/agent/internal/config"

func Run(conf *config.Config) error {
	// No op on linux as we dont need to keep informing systemd that we're alive
	return run(conf)
}


================================================
FILE: agent/internal/handler/run_windows.go
================================================
//go:build windows

package handler

import (
	"fmt"
	"os"
	"time"

	"github.com/lachlan2k/phatcrack/agent/internal/config"
	"github.com/lachlan2k/phatcrack/agent/internal/installer"
	"golang.org/x/sys/windows/svc"
	"golang.org/x/sys/windows/svc/debug"
	"golang.org/x/sys/windows/svc/eventlog"
)

var elog debug.Log

func Run(conf *config.Config) error {

	//https://github.com/NHAS/reverse_ssh/blob/e7c52e54622168a737c5592894d85bec3758b0bd/cmd/client/detach_windows.go#L1
	isService, err := svc.IsWindowsService()
	if err != nil || isService {
		return run(conf)
	}

	return run(conf)
}

type agentService struct {
	conf config.Config
}

func runService(c config.Config) {
	var err error

	elog, err := eventlog.Open(installer.ServiceName)
	if err != nil {
		return
	}

	defer elog.Close()

	elog.Info(1, fmt.Sprintf("starting %s service", installer.ServiceName))
	err = svc.Run("phatcrack-agent", &agentService{
		c,
	})
	if err != nil {
		elog.Error(1, fmt.Sprintf("%s service failed: %v", installer.ServiceName, err))
		return
	}
	elog.Info(1, fmt.Sprintf("%s service stopped", installer.ServiceName))
}

func (m *agentService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
	const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
	changes <- svc.Status{State: svc.StartPending}

	go run(&m.conf)
	changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}

Outer:
	for c := range r {
		switch c.Cmd {
		case svc.Interrogate:
			changes <- c.CurrentStatus
			// Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4
			time.Sleep(100 * time.Millisecond)
			changes <- c.CurrentStatus
		case svc.Stop, svc.Shutdown:
			break Outer
		default:
			elog.Error(1, fmt.Sprintf("unexpected control request #%d", c))
		}
	}

	changes <- svc.Status{State: svc.StopPending}
	changes <- svc.Status{State: svc.Stopped}

	os.Exit(0)
	return
}


================================================
FILE: agent/internal/hashcat/constants.go
================================================
//go:build !windows

package hashcat

const Hashcat = "hashcat.bin"


================================================
FILE: agent/internal/hashcat/constants_windows.go
================================================
//go:build windows

package hashcat

const Hashcat = "hashcat.exe"


================================================
FILE: agent/internal/hashcat/hashcat.go
================================================
package hashcat

import (
	"bufio"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"log"

	"github.com/google/uuid"
	"github.com/lachlan2k/phatcrack/agent/internal/config"
	"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes"

	"github.com/nxadm/tail"
)

type HashcatParams hashcattypes.HashcatParams

type HashcatStatusGuess hashcattypes.HashcatStatusGuess

type HashcatStatusDevice hashcattypes.HashcatStatusDevice

type HashcatStatus = hashcattypes.HashcatStatus

type HashcatResult hashcattypes.HashcatResult

const (
	AttackModeDictionary = 0
	AttackModeCombinator = 1
	AttackModeMask       = 3
	AttackModeHybridDM   = 6
	AttackModeHybridMD   = 7
)

func (params HashcatParams) Validate() error {
	switch params.AttackMode {
	case AttackModeDictionary:
		if len(params.WordlistFilenames) != 1 {
			return fmt.Errorf("expected 1 wordlist for dictionary attack (%d), but %d given", AttackModeDictionary, len(params.WordlistFilenames))
		}

	case AttackModeCombinator:
		if len(params.WordlistFilenames) != 2 {
			return fmt.Errorf("expected 2 wordlists for combinator attack (%d), but %d given", AttackModeCombinator, len(params.WordlistFilenames))
		}

	case AttackModeMask:
		if params.Mask == "" {
			return fmt.Errorf("using mask attack (%d), but no mask was given", AttackModeMask)
		}

	case AttackModeHybridDM, AttackModeHybridMD:
		if params.Mask == "" {
			return fmt.Errorf("using hybrid attack (%d), but no mask was given", params.AttackMode)
		}
		if len(params.WordlistFilenames) != 1 {
			return fmt.Errorf("using hybrid attack (%d), but %d wordlist were given", params.AttackMode, len(params.WordlistFilenames))
		}

	default:
		return fmt.Errorf("unsupported attack mode %d", params.AttackMode)
	}

	return nil
}

type uintIf interface {
	uint | uint8 | uint16 | uint32 | uint64
}

func fmtUint[T uintIf](x T) string {
	return strconv.FormatUint(uint64(x), 10)
}

func (params HashcatParams) maskArgs() ([]string, error) {
	maxCharsets := 4
	if params.MaskShardedCharset != "" {
		maxCharsets = 3
	}
	if len(params.MaskCustomCharsets) > maxCharsets {
		return nil, fmt.Errorf("too many custom charsets supplied (%d), the max is %d", len(params.MaskCustomCharsets), maxCharsets)
	}

	args := []string{}

	if len(params.MaskCustomCharsets) > 0 || params.MaskShardedCharset != "" {
		// This allows us to pass nullbytes etc
		args = append(args, "--hex-charset")
	}

	for i, charset := range params.MaskCustomCharsets {
		// Hashcat accepts paramters --custom-charset1 to --custom-charset4
		args = append(args, fmt.Sprintf("--custom-charset%d", i+1), charset)
	}

	// 4 is the "magic" charset used when sharding attacks
	if params.MaskShardedCharset != "" {
		args = append(args, "--custom-charset4", params.MaskShardedCharset)
	}

	if params.MaskIncrement {
		args = append(args, "--increment")

		if params.MaskIncrementMin > 0 {
			args = append(args, "--increment-min", fmtUint(params.MaskIncrementMin))
		}

		if params.MaskIncrementMax > 0 {
			args = append(args, "--increment-max", fmtUint(params.MaskIncrementMax))
		}
	}

	return args, nil
}

func (params HashcatParams) ToCmdArgs(conf *config.Config, session, tempHashFile string, outFile string) (args []string, err error) {
	if err = params.Validate(); err != nil {
		return
	}

	args = append(
		args,
		"--quiet",
		"--session", "sess-"+session+"_"+uuid.New().String(),
		"--outfile-format", "1,3,5",
		"--outfile", outFile,
		"--status",
		"--status-json",
		"--status-timer", "3",
		"--potfile-disable",
		"-a", fmtUint(params.AttackMode),
		"-m", fmtUint(params.HashType),
	)

	args = append(args, params.AdditionalArgs...)

	if params.EnableLoopback {
		args = append(args, "--loopback")
	}

	if params.OptimizedKernels {
		args = append(args, "-O")
	}

	if params.SlowCandidates {
		args = append(args, "-S")
	}

	if params.Skip > 0 {
		args = append(args, "--skip", strconv.FormatInt(params.Skip, 10))
	}

	if params.Limit > 0 {
		args = append(args, "--limit", strconv.FormatInt(params.Limit, 10))
	}

	wordlists := make([]string, len(params.WordlistFilenames))
	for i, list := range params.WordlistFilenames {
		wordlists[i] = filepath.Join(conf.ListfileDirectory, filepath.Clean(list))
		if _, err = os.Stat(wordlists[i]); err != nil {
			err = fmt.Errorf("provided wordlist %q couldn't be opened on filesystem", wordlists[i])
			return
		}
	}

	rules := make([]string, len(params.RulesFilenames))
	for i, rule := range params.RulesFilenames {
		rules[i] = filepath.Join(conf.ListfileDirectory, filepath.Clean(rule))
		if _, err = os.Stat(rules[i]); err != nil {
			err = fmt.Errorf("provided rules file %q couldn't be opened on filesystem", wordlists[i])
			return
		}
	}

	args = append(args, tempHashFile)

	switch params.AttackMode {
	case AttackModeDictionary:
		for _, rule := range rules {
			args = append(args, "-r", rule)
		}
		args = append(args, wordlists[0])

	case AttackModeCombinator:
		args = append(args, wordlists[0], wordlists[1])

	case AttackModeMask:
		args = append(args, params.Mask)

	case AttackModeHybridDM:
		args = append(args, wordlists[0], params.Mask)

	case AttackModeHybridMD:
		args = append(args, params.Mask, wordlists[0])
	}

	switch params.AttackMode {
	case AttackModeMask, AttackModeHybridDM, AttackModeHybridMD:
		maskArgs, err := params.maskArgs()
		if err != nil {
			return nil, err
		}
		args = append(args, maskArgs...)
	}

	return
}

func findBinary(conf *config.Config) (path string, err error) {
	path = conf.HashcatPath
	if path != "" {
		_, err = os.Stat(path)
		if err != nil {
			err = fmt.Errorf("failed to stat the specified hashcat binary (%q): %v (check path and permissions?)", path, err)
			path = ""
		}
		return
	}

	path, err = exec.LookPath("hashcat")
	if err != nil {
		path, err = exec.LookPath(Hashcat)
		if err != nil {
			err = errors.New("couldn't find hashcat or " + Hashcat + " in path, and hashcat_binary was not specified")
			return
		}
	}

	return
}

type HashcatSession struct {
	proc               *exec.Cmd
	hashFile           *os.File
	outFile            *os.File
	charsetFiles       []*os.File
	shardedCharsetFile *os.File
	CrackedHashes      chan HashcatResult
	StatusUpdates      chan HashcatStatus
	StderrMessages     chan string
	StdoutLines        chan string
	DoneChan           chan error
}

func (sess *HashcatSession) Start() error {
	pStdout, err := sess.proc.StdoutPipe()
	if err != nil {
		return fmt.Errorf("couldn't attach stdout to hashcat: %w", err)
	}

	pStderr, err := sess.proc.StderrPipe()
	if err != nil {
		return fmt.Errorf("couldn't attach stderr to hashcat: %w", err)
	}

	log.Printf("Running hashcat command: %q", sess.proc.String())

	// Hashcat on windows (or perhaps where hashcat is not in PATH) fails to load its resources
	sess.proc.Dir = filepath.Dir(sess.proc.Path)

	err = sess.proc.Start()
	if err != nil {
		return fmt.Errorf("couldn't start hashcat: %w", err)
	}

	tailer, err := tail.TailFile(sess.outFile.Name(), tail.Config{Follow: true})
	if err != nil {
		sess.Kill()
		return fmt.Errorf("couldn't tail outfile %q: %w", sess.outFile.Name(), err)
	}

	go func() {
		for tLine := range tailer.Lines {
			line := tLine.Text
			values := strings.Split(line, ":")
			if len(values) < 3 {
				log.Printf("unexpected line contents: %q", line)
				continue
			}

			// First
			timestamp := values[0]
			// Last
			plainHex := values[len(values)-1]

			// Everything in the middle
			hashParts := values[1 : len(values)-1]
			hash := strings.Join(hashParts, ":")

			timestampI, err := strconv.ParseInt(timestamp, 10, 64)
			if err != nil {
				log.Printf("couldn't parse hashcat timestamp %q: %v", timestamp, err)
				continue
			}

			sess.CrackedHashes <- HashcatResult{
				Timestamp:    time.Unix(timestampI, 0),
				Hash:         hash,
				PlaintextHex: plainHex,
			}
		}
	}()

	go func() {
		scanner := bufio.NewScanner(pStdout)
		for scanner.Scan() {
			line := scanner.Text()
			sess.StdoutLines <- line

			if len(line) == 0 {
				continue
			}

			switch line[0] {
			case '{':
				var status HashcatStatus
				err := json.Unmarshal([]byte(line), &status)
				if err != nil {
					log.Printf("WARN: couldn't unmarshal hashcat status: %v", err)
					continue
				}
				sess.StatusUpdates <- status

			default:
				log.Printf("Unexpected stdout line: %v", line)
			}
		}

		done := sess.proc.Wait()
		// Give us a hot moment to read any cracked hashes that are still being written to disk
		time.Sleep(time.Second)
		sess.DoneChan <- done

		tailer.Kill(nil)
	}()

	go func() {
		scanner := bufio.NewScanner(pStderr)
		for scanner.Scan() {
			log.Printf("read stderr: %q", scanner.Text())
			sess.StderrMessages <- scanner.Text()
		}
	}()

	return nil
}

func (sess *HashcatSession) Kill() error {
	if sess.proc == nil || sess.proc.Process == nil {
		return nil
	}

	err := sess.proc.Process.Kill()

	if errors.Is(err, os.ErrProcessDone) {
		return nil
	}

	return err
}

func (sess *HashcatSession) Cleanup() {
	if sess.hashFile != nil {
		os.Remove(sess.hashFile.Name())
		sess.hashFile = nil
	}

	if sess.outFile != nil {
		os.Remove(sess.outFile.Name())
		sess.outFile = nil
	}

	for _, f := range sess.charsetFiles {
		if f != nil {
			os.Remove(f.Name())
		}
	}

	if sess.shardedCharsetFile != nil {
		os.Remove(sess.shardedCharsetFile.Name())
	}
}

func (sess *HashcatSession) CmdLine() string {
	return sess.proc.String()
}

func NewHashcatSession(id string, hashes []string, params HashcatParams, conf *config.Config) (*HashcatSession, error) {
	var err error

	var hashFile *os.File
	var outFile *os.File
	var shardedCharsetFile *os.File
	charsetFiles := []*os.File{}

	defer func() {
		if err == nil {
			return
		}
		// We returned because of an error, clean up temp files
		if hashFile != nil {
			os.Remove(hashFile.Name())
		}
		if outFile != nil {
			os.Remove(outFile.Name())
		}
		if shardedCharsetFile != nil {
			os.Remove(shardedCharsetFile.Name())
		}
		for _, f := range charsetFiles {
			if f != nil {
				os.Remove(f.Name())
			}
		}
	}()

	binaryPath, err := findBinary(conf)
	if err != nil {
		return nil, err
	}

	hashFile, err = os.CreateTemp(os.TempDir(), "phatcrack-hashes")
	if err != nil {
		return nil, fmt.Errorf("couldn't make a temp file to store hashes: %v", err)
	}
	hashFile.Chmod(0600)

	outFile, err = os.CreateTemp(os.TempDir(), "phatcrack-output")
	if err != nil {
		return nil, fmt.Errorf("couldn't make a temp file to store output: %v", err)
	}
	outFile.Chmod(0600)

	charsetFiles = []*os.File{}
	for i, charset := range params.MaskCustomCharsets {
		charsetFile, err := os.CreateTemp(os.TempDir(), "phatcrack-charset")
		if err != nil {
			return nil, fmt.Errorf("couldn't make a temp file to store charset")
		}
		_, err = charsetFile.Write([]byte(charset))
		if err != nil {
			return nil, err
		}

		params.MaskCustomCharsets[i] = charsetFile.Name()
		charsetFiles = append(charsetFiles, charsetFile)
	}

	if params.MaskShardedCharset != "" {
		shardedCharsetFile, err = os.CreateTemp(os.TempDir(), "phatcrack-charset")
		if err != nil {
			return nil, fmt.Errorf("couldn't make a temp file to store charset")
		}
		outFile.Chmod(0600)
		_, err = shardedCharsetFile.Write([]byte(params.MaskShardedCharset))
		if err != nil {
			return nil, err
		}

		params.MaskShardedCharset = shardedCharsetFile.Name()
	}

	args, err := params.ToCmdArgs(conf, id, hashFile.Name(), outFile.Name())
	if err != nil {
		return nil, err
	}

	for _, hash := range hashes {
		_, err = hashFile.WriteString(hash + "\n")
		if err != nil {
			return nil, fmt.Errorf("couldn't write hash to file: %v", err)
		}
	}

	return &HashcatSession{
		proc:               exec.Command(binaryPath, args...),
		hashFile:           hashFile,
		outFile:            outFile,
		charsetFiles:       charsetFiles,
		shardedCharsetFile: shardedCharsetFile,
		CrackedHashes:      make(chan HashcatResult, 5),
		StatusUpdates:      make(chan HashcatStatus, 5),
		StderrMessages:     make(chan string, 5),
		StdoutLines:        make(chan string, 5),
		DoneChan:           make(chan error),
	}, nil
}


================================================
FILE: agent/internal/installer/hashcat_install.go
================================================
package installer

import (
	"archive/tar"
	"compress/gzip"
	"fmt"
	"io"
	"io/fs"
	"log"
	"net/url"
	"os"
	"path/filepath"
	"strings"

	"github.com/lachlan2k/phatcrack/agent/internal/hashcat"
)

func installHashcat(installConf InstallConfig) {
	log.Println("Installing hashcat...")

	if _, err := os.Stat(installConf.HashcatPath); err == nil {
		log.Printf("hashcat binary was already found at %q, skipping install", installConf.HashcatPath)
		return
	}

	if installConf.Defaults {
		os.MkdirAll(DefaultPathJoin("hashcat"), 0755)
	}

	installDirectory := filepath.Dir(installConf.HashcatPath)

	fi, err := os.Stat(installDirectory)
	if err != nil {
		log.Fatalf("directory %q does not exist (or is not readable) for hashcat installation, determined from -hashcat-path", installDirectory)
	}

	if !fi.IsDir() {
		log.Fatalf("%q is not a directory, cannot install hashcat there, path determined from -hashcat-path", installDirectory)
	}

	u, err := url.Parse(installConf.APIEndpoint)
	if err != nil {
		log.Fatal("failed to parse API endpoint to determine asset server location: ", err)
	}

	u.Path = "/agent-assets/hashcat.tar.gz"

	resp, err := makeHttpClient(installConf.DisableTLSVerification).Get(u.String())
	if err != nil {
		log.Fatalf("failed to get hashcat.tar.gz from download server %q: %s", u.String(), err)
	}
	defer resp.Body.Close()

	err = extractTarGz(installDirectory, resp.Body)
	if err != nil {
		log.Fatal("failed to extract hashcat.tar.gz: ", err)
	}

	_, err = os.Stat(filepath.Join(installDirectory, hashcat.Hashcat))
	if err != nil {
		log.Fatalf("did not find hashcat.bin within install directory %q, invalid tar.gz has been passed", installDirectory)
	}
}

// https://stackoverflow.com/questions/57639648/how-to-decompress-tar-gz-file-in-go
func extractTarGz(targetDirectory string, stream io.Reader) error {
	uncompressedStream, err := gzip.NewReader(stream)
	if err != nil {
		return fmt.Errorf("failed to decode gzip stream: %s", err)
	}

	tarReader := tar.NewReader(uncompressedStream)

	for {
		header, err := tarReader.Next()
		if err == io.EOF {
			break
		}

		if err != nil {
			return fmt.Errorf("reading next tar header failed: %s", err)
		}

		safePath := filepath.Join("/", filepath.Clean(header.Name))
		// Split off the hashcat-x.x.x parent directory so we're installing hashcat binary directly to the folder
		excludingHashcatFolder := strings.SplitN(safePath, string(os.PathSeparator), 3)
		safePath = filepath.Join(targetDirectory, excludingHashcatFolder[len(excludingHashcatFolder)-1])

		switch header.Typeflag {
		case tar.TypeDir:
			if err := os.Mkdir(safePath, fs.FileMode(header.Mode)); err != nil {
				return fmt.Errorf("failed to create directory %q: %s", safePath, err)
			}
		case tar.TypeReg:

			outFile, err := os.OpenFile(safePath, os.O_CREATE|os.O_RDWR, fs.FileMode(header.Mode))
			if err != nil {
				return fmt.Errorf("failed to create file %q: %s", safePath, err)
			}
			if _, err := io.Copy(outFile, tarReader); err != nil {
				return fmt.Errorf("failed to write file %q: %s", safePath, err)
			}
			outFile.Close()

		default:
			return fmt.Errorf("unsupported tar entry: %q (%c)", header.Name, header.Typeflag)
		}

	}

	return nil
}


================================================
FILE: agent/internal/installer/installer.go
================================================
package installer

import (
	"crypto/tls"
	_ "embed"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/lachlan2k/phatcrack/agent/internal/config"
	"github.com/lachlan2k/phatcrack/agent/internal/hashcat"
)

type InstallConfig struct {
	Defaults bool

	AgentUser    string
	AgentGroup   string
	AgentBinPath string

	Name string

	AuthKey         string
	AuthKeyFile     string
	RegistrationKey string
	ConfigPath      string

	HashcatPath            string
	ListfileDirectory      string
	APIEndpoint            string
	DisableTLSVerification bool
	InstallHashcat         bool
}

//go:embed template.service
var serviceFileTemplateString string

const serviceUnitFilePath = "/etc/systemd/system/phatcrack-agent.service"

func writeAuthKeyFile(installConf InstallConfig) {
	f, err := os.OpenFile(installConf.AuthKeyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		log.Fatalf("Couldn't open auth key file for writing: %v", err)
	}

	defer f.Close()
	_, err = f.Write([]byte(installConf.AuthKey))
	if err != nil {
		log.Fatalf("Couldn't write key to auth key file: %v", err)
	}

	adjustPerms(f, installConf)
}

func writeConfigFile(installConf InstallConfig) {

	marshalled, err := json.MarshalIndent(config.Config{
		AuthKeyFile:            installConf.AuthKeyFile,
		AuthKey:                "",
		HashcatPath:            installConf.HashcatPath,
		ListfileDirectory:      installConf.ListfileDirectory,
		APIEndpoint:            installConf.APIEndpoint,
		DisableTLSVerification: installConf.DisableTLSVerification,
	}, "", "  ")
	if err != nil {
		log.Fatalf("Couldn't marshal config file: %v", err)
	}

	f, err := os.OpenFile(installConf.ConfigPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640)
	if err != nil {
		log.Fatalf("Couldn't open config path for writing")
	}
	defer f.Close()

	_, err = f.Write(marshalled)
	if err != nil {
		log.Fatalf("Failed to write config file: %v", err)
	}

	adjustPerms(f, installConf)
}

func setupPaths(installConf InstallConfig) {

	if installConf.Defaults {
		os.MkdirAll(DefaultPathJoin(), 0700)
		adjustPermsPath(DefaultPathJoin(), installConf)
	}

	os.MkdirAll(installConf.ListfileDirectory, 0700)
	adjustPermsPath(installConf.ListfileDirectory, installConf)
}

func Run(installConf InstallConfig) {

	if err := isElevated(); err != nil {
		log.Fatal(err)
	}

	log.Println("Setting up paths...")
	setupPaths(installConf)

	log.Println("Writing config file...")
	writeConfigFile(installConf)

	log.Println("Writing key file...")
	writeAuthKeyFile(installConf)

	if installConf.InstallHashcat {
		installHashcat(installConf)
	}

	log.Println("Installing service...")
	installService(installConf)

	if runtime.GOOS != "windows" {
		log.Println("Done! Run 'systemctl enable --now phatcrack-agent' to start the agent")
	} else {
		log.Println("Done! Execute agent binary as administrator to start agent")

	}

}

func applyDefaults(installConf *InstallConfig) {
	if installConf.AgentUser == "" {
		u, err := user.Lookup("phatcrack-agent")
		if err != nil || u == nil {

			installConf.AgentUser = "root"
			if runtime.GOOS == "windows" {
				// On windows we dont have the concept of a root user, so just use the current user. We check that the binary has been elevated before doing any of the actual install stuff
				user, _ := user.Current()
				installConf.AgentUser = user.Uid
			}

		} else {
			installConf.AgentUser = "phatcrack-agent"
		}
	}

	installConf.InstallHashcat = true

	if installConf.AgentGroup == "" {
		g, err := user.LookupGroup("phatcrack-agent")
		if err != nil || g == nil {
			installConf.AgentGroup = "root"
			if runtime.GOOS == "windows" {
				user, _ := user.Current()
				installConf.AgentGroup = user.Gid
			}
		} else {
			installConf.AgentGroup = "phatcrack-agent"
		}
	}

	if installConf.AgentBinPath == "" {
		exe, err := os.Executable()
		if err == nil {
			installConf.AgentBinPath = exe
		}
	}

	if installConf.Name == "" {
		installConf.Name, _ = os.Hostname()
		if installConf.Name == "" {
			installConf.Name = "unknown"
		}
	}

	if installConf.AuthKeyFile == "" {
		installConf.AuthKeyFile = DefaultPathJoin("auth.key")
	}

	if installConf.ConfigPath == "" {
		installConf.ConfigPath = DefaultPathJoin("config.json")
	}

	if installConf.HashcatPath == "" {
		path, err := exec.LookPath("hashcat")
		if err != nil || path == "" {
			path, err = exec.LookPath(hashcat.Hashcat)
			if err != nil || path == "" {
				path = DefaultPathJoin("hashcat/" + hashcat.Hashcat)
			}
		}
		installConf.HashcatPath = path
	}

	if installConf.ListfileDirectory == "" {
		installConf.ListfileDirectory = DefaultPathJoin("listfiles/")
	}

}

func input(p string, a ...any) string {
	var res string
	fmt.Printf(p, a...)
	fmt.Scanln(&res)
	return strings.TrimSuffix(strings.TrimSpace(res), "\n")
}

func getOptionsInteractive(installConf *InstallConfig) {
	fmt.Println("You will be prompted to enter anything that hasn't been configured. Press enter for default.")

	if installConf.AgentUser == "" {
		installConf.AgentUser = input("Which user do you want to run Phatcrack as? (default: phatcrack-agent if present, else root): ")
	}

	if installConf.AgentGroup == "" {
		installConf.AgentGroup = input("Which user group do you want to run Phatcrack as? (default: phatcrack-agent if present, else root): ")
	}

	if installConf.AgentBinPath == "" {
		installConf.AgentBinPath = input("Where is the phatcrack agent binary? (default: current binary): ")
	}

	if installConf.Name == "" {
		installConf.Name = input("What name do you want to give the agent? (default: hostname): ")
	}

	if installConf.AuthKey == "" && installConf.RegistrationKey == "" {
		installConf.RegistrationKey = input("Registration key from server (leave blank to specify an auth key): ")
		if installConf.RegistrationKey == "" {
			installConf.AuthKey = input("Auth key from server (this is okay to leave blank for now): ")
		}
	}

	if installConf.AuthKeyFile == "" {
		installConf.AuthKeyFile = input("Auth key file to write (default: %s): ", DefaultPathJoin("auth.key"))
	}

	if installConf.ConfigPath == "" {
		installConf.ConfigPath = input("Config file to write (default: %s): ", DefaultPathJoin("config.json"))
	}

	if installConf.HashcatPath == "" {
		installConf.HashcatPath = input("Path to hashcat executable (default: searches PATH): ")
	}

	if installConf.ListfileDirectory == "" {
		installConf.ListfileDirectory = input("Directory to store listfiles (default: %s): ", DefaultPathJoin("listfiles/"))
	}

	if installConf.APIEndpoint == "" {
		installConf.APIEndpoint = input("API Endpoint (format: https://phatcrack.lan/api/v1): ")
	}
}

func checkConf(installConf InstallConfig) error {
	if installConf.AgentUser == "" {
		return errors.New("agent user is not set")
	}

	if installConf.AgentGroup == "" {
		return errors.New("agent group is not set")
	}

	if installConf.AgentBinPath == "" {
		return errors.New("agent bin path could not be determined")
	}

	// blank Authkey is fine

	if installConf.AuthKeyFile == "" {
		return errors.New("auth key file path is not set")
	}

	if installConf.ConfigPath == "" {
		return errors.New("config file path is not set")
	}

	if installConf.HashcatPath == "" {
		return errors.New("hashcat path could not be determined: either add to PATH, or specify")
	}

	if installConf.ListfileDirectory == "" {
		return errors.New("listfile directory is not set")
	}

	// Blank API Endpoint is fine, assuming user is maybe setting up agents before server, but if they're looking for us to install hashcat we have to be up and running
	if installConf.APIEndpoint == "" && installConf.InstallHashcat {
		return errors.New("install hashcat was selected, but no download (api endpoint) server was specified")
	}

	return nil
}

func RunInteractive() {
	flagSet := flag.NewFlagSet("install", flag.ExitOnError)

	useDefaultsP := flagSet.Bool("defaults", false, "Use basic defaults for intallation? (stores everything in "+DefaultPathJoin()+")")

	userP := flagSet.String("user", "", "Which user to run the agent as")
	groupP := flagSet.String("group", "", "Which user group to run the agent as")
	agentBinPathP := flagSet.String("agent-bin", "", "Path to agent (defaults to running executable)")
	nameP := flagSet.String("name", "", "Name of the agent (defaults to hostname)")
	registrationKeyP := flagSet.String("registration-key", "", "Registration key for agent")
	authKeyFileP := flagSet.String("auth-keyfile", "", "Path to file containing agent key")
	authKeyP := flagSet.String("auth-key", "", "Path to file containing agent key")
	configPathP := flagSet.String("config-path", "", "Path to config json file to install")
	hashcatPathP := flagSet.String("hashcat-path", "", "Path to hashcat executable")
	listfilePathP := flagSet.String("listfile-directory", "", "Path to directory to hold listfiles")
	apiEndpointP := flagSet.String("api-endpoint", "", "API endpoint (format: https://phatcrack.lan/api/v1)")

	autoInstallHashcatP := flagSet.Bool("download-hashcat", false, "Install hashcat from agent asset server (requires api endpoint to be set)")

	disableTLSVerificationP := flagSet.Bool("disable-tls-verification", false, "Whether to disable TLS Verification")

	flagSet.Parse(os.Args[2:])

	installConf := InstallConfig{
		Defaults: *useDefaultsP,

		AgentUser:    *userP,
		AgentGroup:   *groupP,
		AgentBinPath: *agentBinPathP,

		Name: *nameP,

		RegistrationKey: *registrationKeyP,
		AuthKey:         *authKeyP,
		AuthKeyFile:     *authKeyFileP,
		ConfigPath:      *configPathP,

		HashcatPath:            *hashcatPathP,
		ListfileDirectory:      *listfilePathP,
		APIEndpoint:            *apiEndpointP,
		DisableTLSVerification: *disableTLSVerificationP,
		InstallHashcat:         *autoInstallHashcatP,
	}

	if installConf.RegistrationKey != "" && installConf.AuthKey != "" {
		log.Fatal("Registration key and auth key cannot be set at the same time")
	}

	if installConf.Defaults {
		applyDefaults(&installConf)
	} else {
		getOptionsInteractive(&installConf)
		applyDefaults(&installConf)
	}

	registerIfRequired(&installConf)

	err := checkConf(installConf)
	if err != nil {
		log.Fatal("config was invalid: ", err)
	}

	Run(installConf)
}

func DefaultPathJoin(parts ...string) string {
	path := "/opt/phatcrack-agent"
	if runtime.GOOS == "windows" {
		var err error
		path, err = os.Getwd()
		if err != nil {
			panic(err)
		}
	}

	parts = append([]string{path}, parts...)
	return filepath.Join(parts...)

}

func adjustPermsPath(path string, installConf InstallConfig) {
	// No op on windows
	f, _ := os.OpenFile(path, os.O_WRONLY, 0700)
	adjustPerms(f, installConf)
}

func makeHttpClient(disableTlsVerification bool) *http.Client {
	tr := &http.Transport{}
	if disableTlsVerification {
		tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
	}
	client := &http.Client{Transport: tr}
	return client
}


================================================
FILE: agent/internal/installer/register.go
================================================
package installer

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"path"

	"github.com/lachlan2k/phatcrack/common/pkg/apitypes"
)

func RegisterWithKey(conf *InstallConfig) (*apitypes.AgentRegisterResponseDTO, error) {
	u, err := url.Parse(conf.APIEndpoint)
	if err != nil {
		return nil, fmt.Errorf("failed to parse API endpoint to register agent: %v", err)
	}

	if conf.Name == "" {
		name, err := os.Hostname()
		if err != nil || name == "" {
			log.Printf("Warn: couldn't get hostname for agent registration: %v\n", err)
			name = "unknown"
		}
		conf.Name = name
	}

	reqBody := apitypes.AgentRegisterRequestDTO{
		Name: conf.Name,
	}

	reqBodyBytes, err := json.Marshal(reqBody)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal agent registration request: %v", err)
	}

	u.Path = path.Join(u.Path, "/agent-handler/register")

	req, err := http.NewRequest("POST", u.String(), bytes.NewReader(reqBodyBytes))
	if err != nil {
		return nil, fmt.Errorf("failed to create agent registration request: %v", err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", conf.RegistrationKey)

	resp, err := makeHttpClient(conf.DisableTLSVerification).Do(req)
	if err != nil {
		return nil, fmt.Errorf("failed to register agent: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("failed to register agent: got status code %d", resp.StatusCode)
	}

	var respBody apitypes.AgentRegisterResponseDTO
	err = json.NewDecoder(resp.Body).Decode(&respBody)
	if err != nil {
		return nil, fmt.Errorf("failed to decode agent registration response: %v", err)
	}

	log.Print("Registered agent with server as " + respBody.Name + " with ID " + respBody.ID)
	conf.AuthKey = respBody.Key
	return &respBody, nil
}

func registerIfRequired(installConf *InstallConfig) {
	if installConf.RegistrationKey != "" {
		_, err := RegisterWithKey(installConf)
		if err != nil {
			log.Fatalf("failed to register agent: %v", err)
		}
	}
}

================================================
FILE: agent/internal/installer/template.service
================================================
[Unit]
Description=Phatcrack Agent
After=network.target

[Service]
User={{.AgentUser}}
Group={{.AgentGroup}}
Restart=on-failure
RestartSec=5s
ExecStart={{.AgentBinPath}} -config {{.ConfigPath}}

[Install]
WantedBy=multi-user.target

================================================
FILE: agent/internal/installer/utils.go
================================================
//go:build !windows

package installer

import (
	"fmt"
	"log"
	"os"
	"os/user"
	"strconv"
	"text/template"
)

func isElevated() error {
	user, err := user.Current()
	if err != nil {
		return fmt.Errorf("couldn't get current user for installation: %v", err)
	}

	if user.Uid != "0" || user.Gid != "0" {
		return fmt.Errorf("agent installer must be run as root")
	}

	return nil
}

func adjustPerms(f *os.File, installConf InstallConfig) {
	uid, gid := getUidAndGid(installConf)
	f.Chown(uid, gid)
}

func getUidAndGid(installConf InstallConfig) (int, int) {
	runningUser, err := user.Lookup(installConf.AgentUser)
	if runningUser == nil || err != nil {
		log.Fatalf("Couldn't look up user %q for installation: %v", installConf.AgentUser, err)
	}

	runningGroup, err := user.LookupGroup(installConf.AgentGroup)
	if runningGroup == nil || err != nil {
		log.Fatalf("Couldn't look up user group %q for installation: %v", installConf.AgentGroup, err)
	}

	uid, _ := strconv.Atoi(runningUser.Uid)
	gid, _ := strconv.Atoi(runningGroup.Gid)
	return uid, gid
}

func installService(installConf InstallConfig) {
	serviceFileTmpl, err := template.New("Service File").Parse(serviceFileTemplateString)
	if err != nil {
		log.Fatalf("Couldn't compile template: %v", err)
	}

	f, err := os.OpenFile(serviceUnitFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		log.Fatalf("Couldn't open systemd unit file for writing: %v", err)
	}
	defer f.Close()

	err = serviceFileTmpl.Execute(f, installConf)
	if err != nil {
		log.Fatalf("Failed to write service file: %v", err)
	}

	f.Chown(0, 0)
}


================================================
FILE: agent/internal/installer/utils_windows.go
================================================
//go:build windows

package installer

import (
	"errors"
	"log"
	"os"

	"golang.org/x/sys/windows"
	"golang.org/x/sys/windows/svc/eventlog"
	"golang.org/x/sys/windows/svc/mgr"
)

const ServiceName = "phatcrack-agent"

func isElevated() error {
	if !windows.GetCurrentProcessToken().IsElevated() {
		return errors.New("Agent installer must be run as administrator")
	}

	return nil
}

func adjustPerms(f *os.File, installConf InstallConfig) {
	// Windows is no op
}

func installService(installConf InstallConfig) {
	m, err := mgr.Connect()
	if err != nil {
		log.Fatal("failed to connect to windows service manager: ", err)
	}
	defer m.Disconnect()

	newService, err := m.OpenService(ServiceName)
	if err == nil {
		newService.Close()
		log.Fatalf("service %q already exists", ServiceName)
	}

	newService, err = m.CreateService(ServiceName, installConf.AgentBinPath, mgr.Config{DisplayName: "phatcrack-agent", StartType: mgr.StartAutomatic})
	if err != nil {
		log.Fatalf("failed to create service %q: %s", ServiceName, err)
	}
	defer newService.Close()
	err = eventlog.InstallAsEventCreate(ServiceName, eventlog.Error|eventlog.Warning|eventlog.Info)
	if err != nil {
		newService.Delete()
		log.Fatalf("SetupEventLogSource() failed: %s", err)
	}

	err = newService.Start()
	if err != nil {
		log.Fatalf("Starting phatcrack-agent has failed: %s", err)
	}
}


================================================
FILE: agent/internal/lockfile/lockfile.go
================================================
package lockfile

import (
	"context"
	"encoding/json"
	"errors"
	"os"
	"sync"
	"time"

	"log"

	"github.com/google/uuid"
)

type Lockfile struct {
	path string

	id          string
	mu          sync.Mutex
	stopWriting context.CancelFunc
	created     time.Time
}

const (
	writeInterval = time.Second

	// If a lockfile hasn't been updated in this long, consider the owner dead
	staleAge = 10 * time.Second

	// Time to wait after we delete a stale lockfile
	// This prevents the race condition where we have 2 writers who both delete the lockfile, and writer B deletes writer A's new lockfile
	afterStaleDelay = 3 * time.Second
)

type lockdata struct {
	Created int64
	Updated int64
	ID      string
}

func (data lockdata) isStale() bool {
	updatedT := time.Unix(data.Updated, 0)

	return time.Since(updatedT) > staleAge
}

func New(path string) *Lockfile {
	return &Lockfile{
		path: path,
	}
}

func (l *Lockfile) MyID() string {
	return l.id
}

func (l *Lockfile) Acquire(ctx context.Context) error {
	for {
		err := l.tryAcquire()
		if err == nil {
			// success
			return nil
		}

		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(time.Second):
		}
	}
}

func (l *Lockfile) AcquireWithTimeout(timeout time.Duration) error {
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(timeout))
	defer cancel()
	return l.Acquire(ctx)
}

func (l *Lockfile) tryAcquire() error {
	// Check if there's already a lockfile we can read
	data, err := l.readData()
	if err == nil {
		// Remove if stale, or exit if its live
		if data.isStale() {
			os.Remove(l.path)
			// Sleep to prevent the race condition of 2 writers deleting simultaneously, then write B deletes writer A's lockfile
			time.Sleep(afterStaleDelay)
		} else {
			return errors.New("lock is held by another process")
		}
	}
	// If we fail to read it that probably means the lockfile doesn't exist, in which case let's proceed

	l.mu.Lock()
	defer l.mu.Unlock()

	l.id = uuid.NewString()
	l.created = time.Now()

	// Try to claim the lockfile
	// Write, read it back to make sure we have the lock
	err = l.write(true)
	if err != nil {
		l.id = ""
		return err
	}
	err = l.ensureHeld()
	if err != nil {
		l.id = ""
		return err
	}

	// Lockfile obtained
	l.startWriting()
	return nil
}

func (l *Lockfile) readData() (*lockdata, error) {
	buff, err := os.ReadFile(l.path)
	if err != nil {
		return nil, err
	}

	data := &lockdata{
		Created: 0,
		Updated: 0,
		ID:      "",
	}
	// If it fails, that's fine (such as corrupt content of lockfile)
	json.Unmarshal(buff, &data)
	return data, nil
}

func (l *Lockfile) ensureHeld() error {
	// If someone else is writing, their write will appear in N seconds, so we check after N+1
	time.Sleep(writeInterval + time.Second)
	data, err := l.readData()
	if err != nil {
		return err
	}
	if l.id != data.ID {
		return errors.New("ID in lockfile doesn't match our ID")
	}
	return nil
}

func (l *Lockfile) write(create bool) error {
	flags := os.O_WRONLY
	if create {
		flags |= os.O_CREATE | os.O_EXCL
	}

	f, err := os.OpenFile(l.path, flags, 0644)
	if err != nil {
		return err
	}
	defer f.Close()

	d := lockdata{
		Created: l.created.Unix(),
		Updated: time.Now().Unix(),
		ID:      l.id,
	}

	err = json.NewEncoder(f).Encode(d)
	if err != nil {
		return err
	}

	return f.Sync()
}

func (l *Lockfile) startWriting() {
	ctx, cancel := context.WithCancel(context.Background())
	l.stopWriting = cancel
	go l.writeLoop(ctx)
}

func (l *Lockfile) writeLoop(ctx context.Context) {
	for {
		l.mu.Lock()
		err := l.write(false)
		if err != nil {
			log.Printf("Unexpected problem when writing lockfile: %v", err)
		}
		l.mu.Unlock()

		select {
		case <-ctx.Done():
			return
		case <-time.After(writeInterval):
		}
	}
}

func (l *Lockfile) Unlock() {
	l.mu.Lock()
	defer l.mu.Unlock()

	l.stopWriting()
	l.delete()

	l.stopWriting = nil
}

func (l *Lockfile) delete() error {
	return os.Remove(l.path)
}


================================================
FILE: agent/internal/lockfile/lockfile_dummy.go
================================================
package lockfile

import "time"

type LockfileDummy struct{}

func (l *LockfileDummy) AcquireWithTimeout(timeout time.Duration) error {
	return nil
}

func (l *LockfileDummy) Unlock() {
	// nop
}

func NewDummy() *LockfileDummy {
	return &LockfileDummy{}
}


================================================
FILE: agent/internal/util/backoff.go
================================================
package util

import "time"

type BackoffEntry struct {
	AfterTime time.Duration
	TimeApart time.Duration
}

type Backoff struct {
	Entries     []BackoffEntry
	activeEntry int
	startTime   time.Time
	lastTime    time.Time
}

func (b *Backoff) Start() {
	b.startTime = time.Now()
	b.activeEntry = 0
	b.lastTime = b.startTime
}

func (b *Backoff) Ready() bool {
	now := time.Now()
	sinceStart := now.Sub(b.startTime)
	sinceLast := now.Sub(b.lastTime)

	if b.activeEntry+1 < len(b.Entries) {
		nextEntry := b.Entries[b.activeEntry+1]
		if sinceStart >= nextEntry.AfterTime {
			b.activeEntry++
			b.lastTime = now
			return true
		}
	}

	return sinceLast >= b.Entries[b.activeEntry].TimeApart
}


================================================
FILE: agent/internal/util/util.go
================================================
package util

import "encoding/json"

func UnmarshalJSON[T interface{}](jsonBlob string) (out T, err error) {
	err = json.Unmarshal([]byte(jsonBlob), &out)
	return
}


================================================
FILE: agent/internal/version/version.go
================================================
package version

var version string = "vx.x.x-unknown"

func Version() string {
	return version
}


================================================
FILE: agent/internal/wswrapper/wswrapper.go
================================================
package wswrapper

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"sync"
	"time"

	"log"

	"github.com/gorilla/websocket"
)

// The WSWrapper adds a buffer layer to the underlying websocket connection
// It gracefully handles connection dropouts/reconnects in a manner that is transparent to the handler
type WSWrapper struct {
	DisableTLSVerification bool
	Endpoint               string
	Headers                http.Header
	MaximumDropoutTime     time.Duration

	writeChan chan interface{}
	readChan  chan []byte

	conn       *websocket.Conn
	errs       chan error
	lock       sync.Mutex
	msgToWrite interface{}
}

func (w *WSWrapper) WriteJSON(v interface{}) error {
	w.writeChan <- v
	return nil
}

// For heartbeats, as there's no reason to buffer them
func (w *WSWrapper) WriteJSONUnbuffered(v interface{}) error {
	w.lock.Lock()
	defer w.lock.Unlock()

	if w.conn == nil {
		return errors.New("couldn't write json, connection was nil")
	}

	return w.conn.WriteJSON(v)
}

func (w *WSWrapper) ReadJSON(v interface{}) error {
	bytes := <-w.readChan
	return json.Unmarshal(bytes, v)
}

func (w *WSWrapper) handle() error {
	w.errs = make(chan error, 2)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		for {
			select {
			case <-ctx.Done():
				return
			case w.msgToWrite = <-w.writeChan:
				w.lock.Lock()
				err := w.conn.WriteJSON(w.msgToWrite)
				w.lock.Unlock()
				if err != nil {
					w.errs <- err
				}

				w.msgToWrite = nil
			}
		}
	}()

	go func() {
		for {
			_, b, err := w.conn.ReadMessage()
			if err != nil {
				w.errs <- err
				return
			}

			w.readChan <- b

			if ctx.Err() != nil {
				return
			}
		}
	}()

	err := <-w.errs
	return err
}

func (w *WSWrapper) Setup() {
	w.writeChan = make(chan interface{}, 1000)
	w.readChan = make(chan []byte, 10)
}

func (w *WSWrapper) Run(notifyFirstConn *sync.Cond) error {
	lastValidConnectonTime := time.Now()
	first := true

	dialer := *websocket.DefaultDialer

	if w.DisableTLSVerification {
		dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
	}

	for {
		log.Printf("Dialing %s...", w.Endpoint)
		w.lock.Lock()

		conn, resp, err := dialer.Dial(w.Endpoint, w.Headers)
		if err != nil {
			if resp != nil && resp.StatusCode == 401 {
				log.Printf("Connection denied, status %q", resp.Status)
			} else {
				log.Printf("failed to dial ws endpoint (status %q): %v, %v", resp.Status, conn, err)
			}

			if time.Since(lastValidConnectonTime) > w.MaximumDropoutTime {
				w.lock.Unlock()
				return fmt.Errorf("couldn't re-establish connection after %v seconds", w.MaximumDropoutTime.Seconds())
			}

			time.Sleep(time.Second)
			w.lock.Unlock()
			continue
		}

		if w.msgToWrite != nil {
			// We died trying to write a message before, lets write it again
			err := conn.WriteJSON(w.msgToWrite)
			if err != nil {
				log.Printf("Failed to write previous message: %v", err)
				time.Sleep(time.Second)
				w.lock.Unlock()
				continue
			}
		}

		w.conn = conn
		w.lock.Unlock()

		if first {
			notifyFirstConn.Signal()
			first = false
		}

		log.Printf("Agent connected")

		err = w.handle()
		if err != nil {
			log.Printf("Error when running ws wrapper, reconnecting: %v", err)
		}

		w.lock.Lock()
		w.conn = nil
		w.lock.Unlock()

		lastValidConnectonTime = time.Now()
		time.Sleep(5 * time.Second)
	}
}


================================================
FILE: agent/main.go
================================================
package main

import (
	"flag"
	"fmt"
	"os"

	"log"

	"github.com/lachlan2k/phatcrack/agent/internal/config"
	"github.com/lachlan2k/phatcrack/agent/internal/handler"
	"github.com/lachlan2k/phatcrack/agent/internal/installer"
	"github.com/lachlan2k/phatcrack/agent/internal/version"
)

func main() {

	if len(os.Args) >= 2 {
		switch os.Args[1] {
		case "install":
			{
				installer.RunInteractive()
				return
			}

		case "register":
			{
				flagSet := flag.NewFlagSet("register", flag.ExitOnError)
				keyP := flagSet.String("key", "", "Registration key (to exchange for auth key)")
				apiEndpointP := flagSet.String("api-endpoint", "", "API endpoint (format: https://phatcrack.lan/api/v1)")
				disableTLSVerificationP := flagSet.Bool("disable-tls-verification", false, "Whether to disable TLS Verification")
				nameP := flagSet.String("name", "", "Name of the agent (defaults to hostname)")

				flagSet.Parse(os.Args[2:])

				if *keyP == "" {
					log.Fatal("No key provided")
				}
				if *apiEndpointP == "" {
					log.Fatal("No API endpoint provided")
				}

				conf := installer.InstallConfig{
					RegistrationKey: *keyP,
					APIEndpoint: *apiEndpointP,
					DisableTLSVerification: *disableTLSVerificationP,
					Name: *nameP,
				}

				resp, err := installer.RegisterWithKey(&conf)
				if err != nil {
					log.Fatalf("failed to register agent: %v", err)
				}

				fmt.Printf("\nAgent registered!\n\nID: %s\nName: %s\nAuth key: %s\n\n", resp.ID, resp.Name, resp.Key)

				return
			}

		default:
			{
				run()
			}
		}
	}

}

func run() {
	configPath := flag.String("config", installer.DefaultPathJoin("config.json"), "Location of config file")
	versionP := flag.Bool("version", false, "Print version")
	flag.Parse()

	if *versionP {
		fmt.Printf("Phatcrack Agent version %s", version.Version())
		return
	}

	conf := config.LoadConfig(*configPath)

	log.Printf("Starting phatcrack-agent %s", version.Version())
	err := handler.Run(&conf)

	if err != nil {
		log.Fatalf("%v", err)
	}
}


================================================
FILE: api/.air.toml
================================================
root = "."
tmp_dir = "/tmp/air/"

[build]
  bin = "/tmp/air/main"
  cmd = "go build -buildvcs=false -ldflags=\"-X github.com/lachlan2k/phatcrack/api/internal/version.version=$(git describe --tags)-DEV\" -o /tmp/air/main ."
  include_ext = ["go"]


================================================
FILE: api/.dockerignore
================================================
Dockerfile
Dockerfile.dev
.git
docker-compose.yml
docker-compose.dev.yml
tmp/

================================================
FILE: api/Dockerfile.dev
================================================
FROM golang:1.26

RUN apt-get update -y
RUN apt-get upgrade -y
RUN apt-get install -y p7zip-full

WORKDIR /opt/

RUN wget https://github.com/hashcat/hashcat/releases/download/v6.2.6/hashcat-6.2.6.7z -q -O hashcat.7z
RUN 7z x hashcat.7z

WORKDIR /app

RUN go install github.com/air-verse/air@latest

WORKDIR /app/phatcrack/api

ENV HC_PATH=/opt/hashcat-6.2.6/hashcat.bin

ENTRYPOINT ["air"]


================================================
FILE: api/build.sh
================================================
#!/bin/bash

VERSION_STR=$(git describe --tags)

echo "Building version ${VERSION_STR}"

go build -buildvcs=false -ldflags="-X github.com/lachlan2k/phatcrack/api/internal/version.version=${VERSION_STR}" -o phatcrack-api main.go

================================================
FILE: api/go.mod
================================================
module github.com/lachlan2k/phatcrack/api

go 1.24.0

require (
	github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef4dfa
	github.com/coreos/go-oidc/v3 v3.17.0
	github.com/go-playground/locales v0.14.1
	github.com/go-playground/universal-translator v0.18.1
	github.com/go-playground/validator/v10 v10.30.1
	github.com/google/uuid v1.6.0
	github.com/gorilla/websocket v1.5.3
	github.com/labstack/echo/v4 v4.15.0
	github.com/lachlan2k/phatcrack/common v0.0.0
	github.com/lib/pq v1.11.2
	github.com/sirupsen/logrus v1.9.4
	golang.org/x/crypto v0.47.0
	golang.org/x/oauth2 v0.35.0
	gorm.io/datatypes v1.2.7
	gorm.io/driver/postgres v1.6.0
	gorm.io/gorm v1.31.1
)

require (
	filippo.io/edwards25519 v1.1.0 // indirect
	github.com/fxamacker/cbor/v2 v2.7.1 // indirect
	github.com/gabriel-vasile/mimetype v1.4.12 // indirect
	github.com/go-jose/go-jose/v4 v4.1.3 // indirect
	github.com/go-sql-driver/mysql v1.8.1 // indirect
	github.com/go-webauthn/x v0.1.27 // indirect
	github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
	github.com/golang-jwt/jwt/v5 v5.2.3 // indirect
	github.com/google/go-tpm v0.9.8 // indirect
	github.com/jackc/pgpassfile v1.0.0 // indirect
	github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
	github.com/jackc/pgx/v5 v5.7.6 // indirect
	github.com/jackc/puddle/v2 v2.2.2 // indirect
	github.com/jinzhu/inflection v1.0.0 // indirect
	github.com/jinzhu/now v1.1.5 // indirect
	github.com/labstack/gommon v0.4.2 // indirect
	github.com/leodido/go-urn v1.4.0 // indirect
	github.com/mattn/go-colorable v0.1.14 // indirect
	github.com/mattn/go-isatty v0.0.20 // indirect
	github.com/mitchellh/mapstructure v1.5.0 // indirect
	github.com/valyala/bytebufferpool v1.0.0 // indirect
	github.com/valyala/fasttemplate v1.2.2 // indirect
	github.com/x448/float16 v0.8.4 // indirect
	golang.org/x/net v0.48.0 // indirect
	golang.org/x/sync v0.19.0 // indirect
	golang.org/x/sys v0.40.0 // indirect
	golang.org/x/text v0.33.0 // indirect
	golang.org/x/time v0.14.0 // indirect
	gorm.io/driver/mysql v1.5.7 // indirect
)

replace github.com/lachlan2k/phatcrack/common v0.0.0 => ../common


================================================
FILE: api/go.sum
================================================
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef4dfa h1:z8Lo9+R9h4ZF5qvq2NTrWGVjL8gE92cPUv9J4i4yYKg=
github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef4dfa/go.mod h1:WfTnekCrJZ8MTDSlOeFACJTeGFvQnLInNzbZLRpoqTU=
github.com/coreos/go-oidc/v3 v3.11.0 h1:Ia3MxdwpSw702YW0xgfmP1GVCMA9aEFWu12XUZ3/OtI=
github.com/coreos/go-oidc/v3 v3.11.0/go.mod h1:gE3LgjOgFoHi9a4ce4/tJczr0Ai2/BoDhf0r5lltWI0=
github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk=
github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU=
github.com/coreos/go-oidc/v3 v3.15.0 h1:R6Oz8Z4bqWR7VFQ+sPSvZPQv4x8M+sJkDO5ojgwlyAg=
github.com/coreos/go-oidc/v3 v3.15.0/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU=
github.com/coreos/go-oidc/v3 v3.17.0 h1:hWBGaQfbi0iVviX4ibC7bk8OKT5qNr4klBaCHVNvehc=
github.com/coreos/go-oidc/v3 v3.17.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=
github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
github.com/fxamacker/cbor/v2 v2.7.1 h1:e41dNILEDbsGj2nl/I0WrHszwH2p7UZLuANfMRfhGxc=
github.com/fxamacker/cbor/v2 v2.7.1/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE=
github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA=
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA=
github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-webauthn/x v0.1.14 h1:1wrB8jzXAofojJPAaRxnZhRgagvLGnLjhCAwg3kTpT0=
github.com/go-webauthn/x v0.1.14/go.mod h1:UuVvFZ8/NbOnkDz3y1NaxtUN87pmtpC1PQ+/5BBQRdc=
github.com/go-webauthn/x v0.1.27 h1:CLyuB8JGn9xvw0etBl4fnclcbPTwhKpN4Xg32zaSYnI=
github.com/go-webauthn/x v0.1.27/go.mod h1:KGYJQAPPgbpDKi4N7zKMGL+Iz6WgxKg3OlhVbPtuJXI=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0=
github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-tpm v0.9.1 h1:0pGc4X//bAlmZzMKf8iz6IsDo1nYTbYJ6FZN/rg4zdM=
github.com/google/go-tpm v0.9.1/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs=
github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA=
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=
github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
github.com/labstack/echo/v4 v4.14.0 h1:+tiMrDLxwv6u0oKtD03mv+V1vXXB3wCqPHJqPuIe+7M=
github.com/labstack/echo/v4 v4.14.0/go.mod h1:xmw1clThob0BSVRX1CRQkGQ/vjwcpOMjQZSZa9fKA/c=
github.com/labstack/echo/v4 v4.15.0 h1:hoRTKWcnR5STXZFe9BmYun9AMTNeSbjHi2vtDuADJ24=
github.com/labstack/echo/v4 v4.15.0/go.mod h1:xmw1clThob0BSVRX1CRQkGQ/vjwcpOMjQZSZa9fKA/c=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lib/pq v1.11.0 h1:aJpnw24caDH5XfSwI/tSUnN8RJRNqbNyArYazaGulzw=
github.com/lib/pq v1.11.0/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/lib/pq v1.11.1 h1:wuChtj2hfsGmmx3nf1m7xC2XpK6OtelS2shMY+bGMtI=
github.com/lib/pq v1.11.1/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/lib/pq v1.11.2 h1:x6gxUeu39V0BHZiugWe8LXZYZ+Utk7hSJGThs8sdzfs=
github.com/lib/pq v1.11.2/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/microsoft/go-mssqldb v0.17.0 h1:Fto83dMZPnYv1Zwx5vHHxpNraeEaUlQ/hhHLgZiaenE=
github.com/microsoft/go-mssqldb v0.17.0/go.mod h1:OkoNGhGEs8EZqchVTtochlXruEhEOaO4S0d2sB5aeGQ=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/time v0.6.0 h1:eTDhh4ZXt5Qf0augr54TN6suAUudPcawVZeIAPU7D4U=
golang.org/x/time v0.6.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/datatypes v1.2.1 h1:r+g0bk4LPCW2v4+Ls7aeNgGme7JYdNDQ2VtvlNUfBh0=
gorm.io/datatypes v1.2.1/go.mod h1:hYK6OTb/1x+m96PgoZZq10UXJ6RvEBb9kRDQ2yyhzGs=
gorm.io/datatypes v1.2.6 h1:KafLdXvFUhzNeL2ncm03Gl3eTLONQfNKZ+wJ+9Y4Nck=
gorm.io/datatypes v1.2.6/go.mod h1:M2iO+6S3hhi4nAyYe444Pcb0dcIiOMJ7QHaUXxyiNZY=
gorm.io/datatypes v1.2.7 h1:ww9GAhF1aGXZY3EB3cJPJ7//JiuQo7DlQA7NNlVaTdk=
gorm.io/datatypes v1.2.7/go.mod h1:M2iO+6S3hhi4nAyYe444Pcb0dcIiOMJ7QHaUXxyiNZY=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU=
gorm.io/driver/sqlite v1.4.3/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
gorm.io/driver/sqlserver v1.4.1 h1:t4r4r6Jam5E6ejqP7N82qAJIJAht27EGT41HyPfXRw0=
gorm.io/driver/sqlserver v1.4.1/go.mod h1:DJ4P+MeZbc5rvY58PnmN1Lnyvb5gw5NPzGshHDnJLig=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
gorm.io/gorm v1.30.1 h1:lSHg33jJTBxs2mgJRfRZeLDG+WZaHYCk3Wtfl6Ngzo4=
gorm.io/gorm v1.30.1/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
gorm.io/gorm v1.30.2 h1:f7bevlVoVe4Byu3pmbWPVHnPsLoWaMjEb7/clyr9Ivs=
gorm.io/gorm v1.30.2/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
gorm.io/gorm v1.30.3 h1:QiG8upl0Sg9ba2Zatfjy0fy4It2iNBL2/eMdvEkdXNs=
gorm.io/gorm v1.30.3/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
gorm.io/gorm v1.30.5 h1:dvEfYwxL+i+xgCNSGGBT1lDjCzfELK8fHZxL3Ee9X0s=
gorm.io/gorm v1.30.5/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=


================================================
FILE: api/internal/accesscontrol/accesscontrol.go
================================================
package accesscontrol

import (
	"fmt"

	"github.com/lachlan2k/phatcrack/api/internal/db"
	"github.com/lachlan2k/phatcrack/api/internal/roles"
)

func HasOwnershipRightsToProject(user *db.User, project *db.Project) bool {
	return project.OwnerUserID == user.ID || user.HasRole(roles.UserRoleAdmin)
}

func HasRightsToProject(user *db.User, project *db.Project) bool {
	if project.OwnerUserID == user.ID {
		return true
	}

	if user.HasRole(roles.UserRoleAdmin) {
		return true
	}

	for _, share := range project.ProjectShare {
		if share.UserID == user.ID {
			return true
		}
	}

	return false
}

func HasRightsToProjectID(user *db.User, projId string) (bool, error) {
	if user.HasRole(roles.UserRoleAdmin) {
		return true, nil
	}

	proj, err := db.GetProjectForUser(projId, user)
	if proj == nil || err == db.ErrNotFound {
		return false, nil
	}
	if err != nil {
		return false, fmt.Errorf("failed to get underlying project to check access control: %w", err)
	}
	return HasRightsToProject(user, proj), nil
}

func HasRightsToHashlistID(user *db.User, hashlistId string) (bool, error) {
	if user.HasRole(roles.UserRoleAdmin) {
		return true, nil
	}

	projId, err := db.GetHashlistProjID(hashlistId)
	if projId == "" || err == db.ErrNotFound {
		return false, nil
	}
	if err != nil {
		return false, err
	}

	return HasRightsToProjectID(user, projId)
}

func HasRightsToJobID(user *db.User, jobID string) (bool, error) {
	projId, err := db.GetJobProjID(jobID)
	if err == db.ErrNotFound {
		return false, nil
	}
	if err != nil {
		return false, fmt.Errorf("failed to get underlying job to check access control: %w", err)
	}
	return HasRightsToProjectID(user, projId)
}


================================================
FILE: api/internal/attacksharder/attacksharder.go
================================================
package attacksharder

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"

	"github.com/lachlan2k/phatcrack/api/internal/db"
	"github.com/lachlan2k/phatcrack/api/internal/hashcathelpers"
	"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes"
	"github.com/sirupsen/logrus"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

// Ref: https://hashcat.net/wiki/doku.php?id=mask_attack
var builtinCharset = map[byte][]byte{
	'l': []byte("abcdefghijklmnopqrstuvwxyz"),
	'u': []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),

	'd': []byte("0123456789"),
	'h': []byte("0123456789abcdef"),
	'H': []byte("0123456789ABCDEF"),

	's': []byte(" !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"),

	'a': []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"),
	'b': {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255},
}

func splitMask(inputMask string, numChunks int) (outputMask string, outputCharsets [][]byte, err error) {
	firstVariableIndex := -1
	for i := range inputMask {
		if inputMask[i] != '?' {
			continue
		}

		if i == len(inputMask)-1 {
			return "", nil, fmt.Errorf("'%q' is not a valid mask (unexpected ? at end)", inputMask)
		}

		firstVariableIndex = i
		break
	}

	// While a mask with no variables in it is dumb, its not *technically* wrong
	// But I'm going to throw a fit regardless
	if firstVariableIndex == -1 {
		return "", nil, fmt.Errorf("'%q' cannot be chunked as it contains no variables", inputMask)
	}

	maskChar := inputMask[firstVariableIndex+1]
	builtinCharset, ok := builtinCharset[maskChar]
	if !ok {
		return "", nil, fmt.Errorf("the first variable in the mask '%q' was not recognized", inputMask)
	}

	// Use ?4 as the "magic" custom charset dedicated to sharding
	outputMask = inputMask[:firstVariableIndex+1] + "4" + inputMask[firstVariableIndex+2:]
	outputCharsets = [][]byte{}

	for i := 0; i < numChunks; i++ {
		start := (i * len(builtinCharset) / numChunks)
		end := ((i + 1) * len(builtinCharset)) / numChunks

		outputCharsets = append(outputCharsets, builtinCharset[start:end])
	}

	return outputMask, outputCharsets, nil
}

func createSingleJobfromAttack(attack *db.Attack) (*db.Job, *db.Hashlist, error) {
	hashlist, err := db.GetHashlistWithHashes(attack.HashlistID.String())
	if err != nil {
		return nil, nil, err
	}

	targetHashes := []string{}
	for _, hash := range hashlist.Hashes {
		if !hash.IsCracked {
			targetHashes = append(targetHashes, hash.NormalizedHash)
		}
	}

	dbJob, err := db.CreateJob(&db.Job{
		HashlistVersion: hashlist.Version,
		AttackID:        &attack.ID,
		HashcatParams:   attack.HashcatParams,
		TargetHashes:    targetHashes,
		HashType:        hashlist.HashType,
	})

	if err != nil {
		return nil, nil, err
	}

	return dbJob, hashlist, err
}

func shardMaskAttack(attack *db.Attack, numJobs int) ([]*db.Job, *db.Hashlist, error) {
	params := attack.HashcatParams.Data()
	if len(params.MaskCustomCharsets) >= 4 {
		return nil, nil, fmt.Errorf("received %d custom character sets, maximum is 3", len(params.MaskCustomCharsets))
	}

	outputMask, shardedCharsets, err := splitMask(params.Mask, numJobs)
	if err != nil {
		return nil, nil, err
	}

	hashlist, err := db.GetHashlistWithHashes(attack.HashlistID.String())
	if err != nil {
		return nil, nil, err
	}

	targetHashes := []string{}
	for _, hash := range hashlist.Hashes {
		if !hash.IsCracked {
			targetHashes = append(targetHashes, hash.NormalizedHash)
		}
	}

	params.Mask = outputMask
	jobs := []*db.Job{}

	err = db.GetInstance().Transaction(func(tx *gorm.DB) error {
		for i := 0; i < numJobs; i++ {
			params.MaskShardedCharset = hex.EncodeToString(shardedCharsets[i])

			dbJob, err := db.CreateJobTx(&db.Job{
				HashlistVersion: hashlist.Version,
				AttackID:        &attack.ID,
				HashcatParams:   datatypes.NewJSONType(params),
				TargetHashes:    targetHashes,
				HashType:        hashlist.HashType,
			}, tx)

			jobs = append(jobs, dbJob)

			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return nil, nil, err
	}

	return jobs, hashlist, nil
}

// Returns a sha256sum of the hashcat settings so we can uniquely identify the settings for keyspace calaculation
func hashHashcatSettings(params hashcattypes.HashcatParams) (string, error) {
	settingsBytes, err := json.Marshal(params)
	if err != nil {
		return "", err
	}
	hash := sha256.Sum256(settingsBytes)
	return hex.EncodeToString(hash[:]), nil
}

func getKeyspace(params hashcattypes.HashcatParams) (int64, error) {
	hashedParams, err := hashHashcatSettings(params)
	if err == nil {
		keyspace, err := db.GetKeyspaceCacheEntry(hashedParams)
		if err == nil {
			// cache hit
			return keyspace, nil
		}
	}
	// cache miss
	keyspace, err := hashcathelpers.CalculateKeyspace(params)
	if err != nil {
		return 0, err
	}
	err = db.InsertKeyspaceCacheEntry(hashedParams, keyspace)
	if err != nil {
		// just log
		logrus.WithError(err).Warn("Failed to insert keyspace cache entry")
	}
	return keyspace, nil
}

func shardAttackByKeyspace(attack *db.Attack, numJobs int) ([]*db.Job, *db.Hashlist, error) {
	params := attack.HashcatParams.Data()
	hashlist, err := db.GetHashlistWithHashes(attack.HashlistID.String())
	if err != nil {
		return nil, nil, err
	}

	targetHashes := []string{}
	for _, hash := range hashlist.Hashes {
		if !hash.IsCracked {
			targetHashes = append(targetHashes, hash.NormalizedHash)
		}
	}

	keyspace, err := getKeyspace(params)
	if err != nil {
		return nil, nil, fmt.Errorf("couldn't calculate keyspace for sharding: %w", err)
	}

	limitPerJob := keyspace / int64(numJobs)
	jobs := []*db.Job{}

	err = db.GetInstance().Transaction(func(tx *gorm.DB) error {
		for i := 0; i < numJobs; i++ {
			params.Skip = limitPerJob * int64(i)

			if i == numJobs-1 {
				params.Limit = 0
			} else {
				params.Limit = limitPerJob
			}

			dbJob, err := db.CreateJobTx(&db.Job{
				HashlistVersion: hashlist.Version,
				AttackID:        &attack.ID,
				HashcatParams:   datatypes.NewJSONType(params),
				TargetHashes:    targetHashes,
				HashType:        hashlist.HashType,
			}, tx)

			jobs = append(jobs, dbJob)

			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return nil, nil, err
	}

	return jobs, hashlist, nil
}

func MakeJobs(attack *db.Attack, maxNumJobs int) ([]*db.Job, *db.Hashlist, error) {
	if !attack.IsDistributed || maxNumJobs <= 1 {
		job, h, err := createSingleJobfromAttack(attack)
		if err != nil {
			return nil, nil, err
		}
		jobs := []*db.Job{job}
		return jobs, h, err
	}

	switch attack.HashcatParams.Data().AttackMode {
	case hashcattypes.AttackModeDictionary, hashcattypes.AttackModeCombinator:
		return shardAttackByKeyspace(attack, maxNumJobs)

	case hashcattypes.AttackModeMask, hashcattypes.AttackModeHybridDM, hashcattypes.AttackModeHybridMD:
		return shardMaskAttack(attack, maxNumJobs)

	default:
		return nil, nil, fmt.Errorf("unrecognized attack mode: %d", attack.HashcatParams.Data().AttackMode)
	}
}


================================================
FILE: api/internal/auth/header_auth_middleware.go
================================================
package auth

import (
	"regexp"
	"slices"

	"github.com/labstack/echo/v4"
	"github.com/lachlan2k/phatcrack/api/internal/db"
	"github.com/lachlan2k/phatcrack/api/internal/roles"
	"github.com/lachlan2k/phatcrack/api/internal/util"
	log "github.com/sirupsen/logrus"
)

func CreateHeaderAuthMiddleware() echo.MiddlewareFunc {
	headerRe := regexp.MustCompile(`(?i)\s*bearer\s+(.+)\s*`)

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			// Another auth validator has already validated this request
			if AuthIsValid(c) {
				return next(c)
			}

			authHeader := c.Request().Header.Get("Authorization")
			match := headerRe.FindStringSubmatch(authHeader)
			if len(match) < 2 {
				return next(c)
			}

			token := match[1]
			user, err := db.GetServiceAccountByAPIKey(token)
			if err == db.ErrNotFound {
				return echo.ErrUnauthorized
			}
			if err != nil {
				return util.ServerError("Failed to check API key", err)
			}
			if !slices.Contains(user.Roles, roles.UserRoleServiceAccount) {
				log.WithField("user_dto", user.ToDTO()).Warn("Request sucessfully authorized by bearer token, but account isn't a service account")
				return echo.ErrUnauthorized
			}

			// Create dummy session entry
			c.Set(sessionContextKey, SessionData{
				UserID:              user.ID.String(),
				HasCompletedMFA:     false,
				WebAuthnSession:     nil,
				PendingWebAuthnUser: nil,
			})

			c.Set(sessionUserContextKey, user)
			c.Set(sessionAuthIsValidContextKey, true)

			return next(c)
		}
	}
}


================================================
FILE: api/internal/auth/mfa.go
================================================
package auth

const (
	MFATypeWebAuthn = "MFATypeWebAuthn"
)


================================================
FILE: api/internal/auth/mfa_webauthn.go
================================================
package auth

import (
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"net/url"

	"github.com/NHAS/webauthn/webauthn"
	"github.com/labstack/echo/v4"
	"github.com/lachlan2k/phatcrack/api/internal/db"
	"github.com/lachlan2k/phatcrack/api/internal/roles"
)

type webauthnUser struct {
	Username      string                          `json:"username"`
	WebauthnID    []byte                          `json:"webauthn_id"`
	CredentialMap map[string]*webauthn.Credential `json:"credential_map"`
}

func (w webauthnUser) WebAuthnID() []byte {
	return w.WebauthnID
}

func (w webauthnUser) WebAuthnName() string {
	return w.Username
}

func (w webauthnUser) WebAuthnDisplayName() string {
	return w.Username
}

func (w webauthnUser) WebAuthnCredentials() []*webauthn.Credential {
	creds := make([]*webauthn.Credential, 0)
	for _, cred := range w.CredentialMap {
		creds = append(creds, cred)
	}
	return creds
}

func (w webauthnUser) WebAuthnCredential(id []byte) *webauthn.Credential {
	return w.CredentialMap[hex.EncodeToString(id)]
}

func (w webauthnUser) WebAuthnIcon() string {
	return ""
}

func (w webauthnUser) PushCredential(c *webauthn.Credential) {
	w.CredentialMap[hex.EncodeToString(c.ID)] = c
}

var webauthnHandler webauthn.WebAuthn

func InitWebAuthn(baseURL url.URL) {
	webauthnHandler.Config = &webauthn.Config{
		RPDisplayName: "Phatcrack",
		RPID:          baseURL.Hostname(),
		RPOrigins:     []string{baseURL.String()},
	}
}

func IsWebAuthnAvailable() bool {
	return webauthnHandler.Config != nil
}

func MFAWebAuthnBeginRegister(c echo.Context, sessHandler SessionHandler) (marshalledJSONResponse []byte, userPresentableErr error, internalErr error) {
	if !IsWebAuthnAvailable() {
		userPresentableErr = errors.New("webauthn is not available")
		return
	}

	user, sessData := UserAndSessFromReq(c)
	if user == nil || sessData == nil {
		internalErr = errors.New("failed to get user from req")
		return
	}

	if user.HasRole(roles.UserRoleMFAEnrolled) {
		userPresentableErr = errors.New("user already enrolled in MFA")
		return
	}

	if sessData.PendingWebAuthnUser != nil || sessData.WebAuthnSession != nil {
		userPresentableErr = errors.New("MFA registration already in progress")
		return
	}

	wID := make([]byte, 64)
	_, err := rand.Read(wID)
	if err != nil {
		internalErr = fmt.Errorf("couldn't generated user id for webauthn: %w", err)
		return
	}

	wUser := &webauthnUser{
		Username:      user.Username,
		WebauthnID:    wID,
		CredentialMap: make(map[string]*webauthn.Credential),
	}

	creation, webauthnSession, err := webauthnHandler.BeginRegistration(wUser)
	if err != nil {
		internalErr = fmt.Errorf("couldn't begin registration: %w", err)
		return
	}

	marshalled, err := json.Marshal(creation)
	if err != nil {
		internalErr = fmt.Errorf("couldn't marshal webauthn creation data: %w", err)
		return
	}

	err = sessHandler.UpdateSessionData(c, func(sd *SessionData) error {
		sd.WebAuthnSession = webauthnSession
		sd.PendingWebAuthnUser = wUser
		return nil
	})
	if err != nil {
		internalErr = fmt.Errorf("couldn't save webauthn session data in session: %w", err)
		return
	}

	return marshalled, nil, nil
}

func MFAWebAuthnFinishRegister(c echo.Context, sessHandler SessionHandler) (userPresentableErr error, internalErr error) {
	if !IsWebAuthnAvailable() {
		userPresentableErr = errors.New("webauthn is not available")
		return
	}

	user, sessData := UserAndSessFromReq(c)
	if user == nil || sessData == nil {
		internalErr = fmt.Errorf("failed to get user from req")
		return
	}

	if user.HasRole(roles.UserRoleMFAEnrolled) {
		userPresentableErr = errors.New("user already enrolled in MFA")
		return
	}

	if sessData.PendingWebAuthnUser == nil || sessData.WebAuthnSession == nil {
		userPresentableErr = errors.New("registration process not started")
		return
	}

	credential, err := webauthnHandler.FinishRegistration(*sessData.PendingWebAuthnUser, *sessData.WebAuthnSession, c.Request())
	if err != nil {
		internalErr = fmt.Errorf("failed to finish webauthn registration: %w", err)
		return
	}

	sessData.PendingWebAuthnUser.PushCredential(credential)

	marshalledBytes, err := json.Marshal(sessData.PendingWebAuthnUser)
	if err != nil {
		internalErr = fmt.Errorf("failed to marshal webauthn user: %w", err)
		return
	}

	err = sessHandler.UpdateSessionData(c, func(sd *SessionData) error {
		sd.PendingWebAuthnUser = nil
		sd.WebAuthnSession = nil
		return nil
	})
	if err != nil {
		internalErr = fmt.Errorf("couldn't remove webauthn session data: %w", err)
		return
	}

	user.MFAType = MFATypeWebAuthn
	user.MFAData = marshalledBytes
	user.Roles = append(user.Roles, roles.UserRoleMFAEnrolled)

	err = db.GetInstance().Save(user).Error
	if err != nil {
		internalErr = fmt.Errorf("failed to save user in database with new MFA data: %w", err)
		return
	}

	return nil, nil
}

func MFAWebAuthnBeginLogin(c echo.Context, sessHandler SessionHandler) (marshalledJSONResponse []byte, userPresentableErr error, internalErr error) {
	if !IsWebAuthnAvailable() {
		userPresentableErr = errors.New("webauthn is not available")
		return
	}

	user := UserFromReq(c)
	if user == nil {
		internalErr = fmt.Errorf("failed to get user from req")
		return
	}

	if !user.HasRole(roles.UserRoleMFAEnrolled) {
		userPresentableErr = fmt.Errorf("user is not enrolled in MFA")
		return
	}

	var wUser = &webauthnUser{}
	err := json.Unmarshal(user.MFAData, wUser)
	if err != nil {
		internalErr = fmt.Errorf("couldn't unmarshal user's MFA data: %w", err)
		return
	}

	credentialAssertion, webauthnSession, err := webauthnHandler.BeginLogin(wUser)
	if err != nil {
		internalErr = fmt.Errorf("failed to begin webauthn login: %w", err)
		return
	}

	err = sessHandler.UpdateSessionData(c, func(sd *SessionData) error {
		sd.WebAuthnSession = webauthnSession
		sd.PendingWebAuthnUser = wUser
		return nil
	})
	if err != nil {
		internalErr = fmt.Errorf("couldn't save webauthn session data in session: %w", err)
		return
	}

	marshalledJSONResponse, err = json.Marshal(credentialAssertion)
	if err != nil {
		internalErr = fmt.Errorf("failed to marshal credential assertion: %w", err)
		return
	}

	return
}

func MFAWebAuthnFinishLogin(c echo.Context, sessHandler SessionHandler) (userPresentableErr error, internalErr error) {
	if !IsWebAuthnAvailable() {
		userPresentableErr = errors.New("webauthn is not available")
		return
	}

	user, sessData := UserAndSessFromReq(c)
	if user == nil || sessData == nil {
		internalErr = fmt.Errorf("failed to get user from req")
		return
	}

	if sessData.PendingWebAuthnUser == nil || sessData.WebAuthnSession == nil {
		userPresentableErr = fmt.Errorf("MFA verification process not started")
		return
	}

	credential, err := webauthnHandler.FinishLogin(*sessData.PendingWebAuthnUser, *sessData.WebAuthnSession, c.Request())
	if err != nil {
		userPresentableErr = fmt.Errorf("MFA verification failed")
		return
	}

	if credential.Authenticator.CloneWarning {
		userPresentableErr = fmt.Errorf("MFA verification failed (potential counter re-use)")
		return
	}

	return
}


================================================
FILE: api/internal/auth/middleware.go
================================================
package auth

import (
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/lachlan2k/phatcrack/api/internal/config"
	"github.com/lachlan2k/phatcrack/api/internal/roles"
)

func EnforceMFAMiddleware(s SessionHandler) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			user, sess := UserAndSessFromReq(c)
			if user == nil {
				return echo.ErrUnauthorized
			}

			userIsEnrolled := false
			for _, userRole := range user.Roles {
				if userRole == roles.UserRoleMFAEnrolled {
					userIsEnrolled = true
				}

				// Early exit if they're exempt
				if userRole == roles.UserRoleMFAExempt {
					return next(c)
				}
			}

			userHasCompleted := sess.HasCompletedMFA

			if config.Get().Auth.General.IsMFARequired {
				if !userIsEnrolled {
					return echo.NewHTTPError(http.StatusForbidden, "MFA not yet enrolled")
				}
			}

			// Even if we don't globally enforce MFA, we need to enforce it if the user has chosen to configure it themselves
			if userIsEnrolled {
				if !userHasCompleted {
					return echo.NewHTTPError(http.StatusForbidden, "MFA not yet completed")
				}
			}

			return next(c)
		}
	}
}

type EnforceAuthArgs struct {
	BypassPaths []string
}

func EnforceAuthMiddleware(args EnforceAuthArgs) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			path := c.Request().URL.Path
			for _, bypassPath := range args.BypassPaths {
				if path == bypassPath {
					return next(c)
				}
			}

			if !AuthIsValid(c) {
				return echo.NewHTTPError(http.StatusUnauthorized, "Login required")
			}

			return next(c)
		}
	}
}

func RoleRestrictedMiddleware(allowedRoles []string, disallowedRoles []string) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			user, _ := UserAndSessFromReq(c)

			if user == nil {
				return echo.ErrUnauthorized
			}

			for _, disallowedRole := range disallowedRoles {
				for _, userRole := range user.Roles {
					if disallowedRole == userRole {
						return echo.ErrUnauthorized
					}
				}
			}

			for _, allowedRole := range allowedRoles {
				for _, userRole := range user.Roles {
					if allowedRole == userRole {
						return next(c)
					}
				}
			}

			return echo.ErrUnauthorized
		}
	}
}

func AdminOnlyMiddleware(h SessionHandler) echo.MiddlewareFunc {
	return RoleRestrictedMiddleware([]string{"admin"}, nil)
}


================================================
FILE: api/internal/auth/session.go
================================================
package auth

import (
	log "github.com/sirupsen/logrus"

	"github.com/NHAS/webauthn/webauthn"
	"github.com/labstack/echo/v4"
	"github.com/lachlan2k/phatcrack/api/internal/db"
)

type SessionHandler interface {
	CreateMiddleware() echo.MiddlewareFunc

	Start(echo.Context, SessionData) error
	Destroy(echo.Context) error
	Refresh(echo.Context) error
	Rotate(echo.Context) error // Rotate session cookie, to mitigate session fixation
	UpdateSessionData(c echo.Context, updateFunc func(*SessionData) error) error

	LogoutAllSessionsForUser(id string) error
}

type SessionData struct {
	UserID          string
	HasCompletedMFA bool

	WebAuthnSession     *webauthn.SessionData
	PendingWebAuthnUser *webauthnUser
}

const sessionAuthIsValidContextKey = "sess-auth-valid"
const sessionContextKey = "sess-data"
const sessionUserContextKey = "sess-user"

func AuthIsValid(c echo.Context) bool {
	isValid, ok := c.Get(sessionAuthIsValidContextKey).(bool)
	return ok && isValid
}

func SessionDataFromReq(c echo.Context) *SessionData {
	data, ok := c.Get(sessionContextKey).(SessionData)
	if !ok {
		return nil
	}

	return &data
}

func UserAndSessFromReq(c echo.Context) (*db.User, *SessionData) {
	sess := SessionDataFromReq(c)
	if sess == nil {
		return nil, nil
	}

	// Incase we've already retrived it in this context, don't bother fetching again
	existingUser, ok := c.Get(sessionUserContextKey).(*db.User)
	if ok && existingUser != nil {
		return existingUser, sess
	}

	user, err := db.GetUserByID(sess.UserID)
	if err != nil || user == nil {
		log.WithError(err).WithField("user_id", sess.UserID).Error("Failed to retrieve user's information from DB for session")
		return nil, nil
	}

	c.Set(sessionUserContextKey, user)
	return user, sess
}

func UserFromReq(c echo.Context) *db.User {
	u, _ := UserAndSessFromReq(c)
	return u
}


================================================
FILE: api/internal/auth/session_inmemory.go
================================================
package auth

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"net/http"
	"sync"
	"time"

	"github.com/labstack/echo/v4"
)

type inMemoryStoreEntry struct {
	sess        SessionData
	timeoutTime time.Time
	maxEndTime  time.Time
}

type InMemorySessionHandler struct {
	CookieName         string
	SessionTimeout     time.Duration
	SessionMaxLifetime time.Duration

	store     map[string]*inMemoryStoreEntry
	storeLock sync.Mutex
}

func (s *InMemorySessionHandler) CreateMiddleware() echo.MiddlewareFunc {
	if s.CookieName == "" {
		s.CookieName = "auth"
	}

	s.store = make(map[string]*inMemoryStoreEntry)
	go s.janitor()

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			// Another auth validator has already validated this request
			if AuthIsValid(c) {
				return next(c)
			}

			s.storeLock.Lock()
			entry, err := s.getEntry(c)
			s.storeLock.Unlock()

			if err != nil || entry == nil {
				return next(c)
			}

			c.Set(sessionContextKey, entry.sess)
			c.Set(sessionAuthIsValidContextKey, true)

			return next(c)
		}
	}
}

func (s *InMemorySessionHandler) Start(c echo.Context, sess SessionData) error {
	s.storeLock.Lock()
	defer s.storeLock.Unlock()

	newCookie, err := s.genRandom()
	if err != nil {
		return err
	}

	timeout := time.Now().Add(s.SessionTimeout)
	endTime := time.Now().Add(s.SessionMaxLifetime)

	s.store[newCookie] = &inMemoryStoreEntry{
		sess:        sess,
		timeoutTime: timeout,
		maxEndTime:  endTime,
	}

	s.setCookie(c, newCookie, timeout)
	return err
}

func (s *InMemorySessionHandler) Destroy(c echo.Context) error {
	s.storeLock.Lock()
	defer s.storeLock.Unlock()

	cookie := s.getCookie(c)
	delete(s.store, cookie)
	return nil
}

func (s *InMemorySessionHandler) Refresh(c echo.Context) error {
	s.storeLock.Lock()
	defer s.storeLock.Unlock()

	cookie := s.getCookie(c)
	entry, err := s.getEntry(c)
	if err != nil {
		return err
	}

	// Require user to log in again
	if time.Now().After(entry.maxEndTime) {
		return nil
	}

	entry.timeoutTime = time.Now().Add(s.SessionTimeout)
	if entry.timeoutTime.After(entry.maxEndTime) {
		entry.timeoutTime = entry.maxEndTime
	}

	s.store[cookie] = entry
	s.setCookie(c, cookie, entry.timeoutTime)

	return nil
}

func (s *InMemorySessionHandler) Rotate(c echo.Context) error {
	s.storeLock.Lock()
	defer s.storeLock.Unlock()

	cookie := s.getCookie(c)

	newCookie, err := s.genRandom()
	if err != nil {
		return err
	}

	entry, err := s.getEntry(c)
	if err != nil {
		return err
	}

	s.store[newCookie] = entry
	delete(s.store, cookie)

	s.setCookie(c, newCookie, entry.timeoutTime)

	return nil
}

func (s *InMemorySessionHandler) UpdateSessionData(c echo.Context, updateFunc func(*SessionData) error) error {
	s.storeLock.Lock()
	defer s.storeLock.Unlock()

	entry, err := s.getEntry(c)
	if err != nil {
		return err
	}

	return updateFunc(&entry.sess)
}

func (s *InMemorySessionHandler) LogoutAllSessionsForUser(userId string) error {
	s.storeLock.Lock()
	defer s.storeLock.Unlock()

	for sessId, entry := range s.store {
		if entry.sess.UserID == userId {
			delete(s.store, sessId)
		}
	}

	return nil
}

func (s *InMemorySessionHandler) genRandom() (string, error) {
	bytes := make([]byte, 32)
	if _, err := rand.Read(bytes); err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

func (s *InMemorySessionHandler) getCookie(c echo.Context) string {
	cookie, err := c.Cookie(s.CookieName)
	if err != nil || cookie == nil {
		return ""
	}
	return cookie.Value
}

const sessionInMemoryEntryKey = "sess-inmem-entry"

// Unsafe: Caller must hold mutex
func (s *InMemorySessionHandler) getEntry(c echo.Context) (*inMemoryStoreEntry, error) {
	existingEntry, existingOk := c.Get(sessionInMemoryEntryKey).(*inMemoryStoreEntry)
	if existingOk && existingEntry != nil {
		return existingEntry, nil
	}

	cookie := s.getCookie(c)
	if len(cookie) != 64 {
		return nil, fmt.Errorf("%v is an invalid session length (expected 64 characters)", cookie)
	}

	entry, ok := s.store[cookie]
	if !ok {
		return nil, fmt.Errorf("%v is not a valid session", cookie)
	}

	if entry.timeoutTime.Before(time.Now()) {
		return nil, fmt.Errorf("%v session expired", cookie)
	}

	c.Set(sessionInMemoryEntryKey, entry)

	return entry, nil
}

func (s *InMemorySessionHandler) setCookie(c echo.Context, val string, expires time.Time) {
	c.SetCookie(&http.Cookie{
		Name:     s.CookieName,
		Value:    val,
		Expires:  expires,
		Path:     "/",
		HttpOnly: true,
		Secure:   c.Scheme() == "https",
		SameSite: http.SameSiteStrictMode,
	})
}

func (s *InMemorySessionHandler) cleanup() {
	s.storeLock.Lock()
	defer s.storeLock.Unlock()

	for sessId, entry := range s.store {
		if time.Now().After(entry.timeoutTime) {
			delete(s.store, sessId)
		}
	}
}

func (s *InMemorySessionHandler) janitor() {
	for {
		s.cleanup()
		time.Sleep(time.Minute)
	}
}


================================================
FILE: api/internal/config/config.go
================================================
package config

import (
	"errors"
	"fmt"
	"sync"

	"github.com/lachlan2k/phatcrack/api/internal/db"
	"github.com/lachlan2k/phatcrack/common/pkg/apitypes"
)

var lock sync.Mutex

const AuthMethodCredentials = "method_credentials"
const AuthMethodOIDC = "method_oidc"

type AuthOIDCConfig struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`

	IssuerURL   string `json:"issuer_url"`
	RedirectURL string `json:"redirect_url"`

	AutomaticUserCreation bool   `json:"automatic_user_creation"`
	UsernameClaim         string `json:"username_claim"`

	RolesClaim   string `json:"role_field"`
	RequiredRole string `json:"required_role"`
	Prompt       string `json:"prompt"`

	AdditionalScopes []string `json:"scopes"`
}

type AuthGeneralConfig struct {
	EnabledMethods                    []string `json:"enabled_methods"`
	IsMFARequired                     bool     `json:"is_mfa_required"`
	RequirePasswordChangeOnFirstLogin bool     `json:"require_password_change_on_first_login"`
}

type AuthConfig struct {
	General AuthGeneralConfig `json:"general"`
	OIDC    AuthOIDCConfig    `json:"oidc"`
}

type AgentConfig struct {
	AutomaticallySyncListfiles bool `json:"auto_sync_listfiles"`
	SplitJobsPerAgent          int  `json:"split_jobs_per_agent"`
}

type GeneralConfig struct {
	IsMaintenanceMode               bool  `json:"is_maintenance_mode"`
	MaximumUploadedFileSize         int64 `json:"maximum_uploaded_file_size"`
	MaximumUploadedFileLineScanSize int64 `json:"maximum_uploaded_file_line_scan_size"`
}

type RuntimeConfig struct {
	ConfigVersion int `json:"version"`

	IsSetupComplete bool `json:"is_setup_complete"`

	Auth    AuthConfig    `json:"auth"`
	Agent   AgentConfig   `json:"agent"`
	General GeneralConfig `json:"general"`
}

const latestConfigVersion = 2

func (conf RuntimeConfig) ToAdminDTO() apitypes.AdminConfigResponseDTO {
	oidcClientSecret := ""
	if len(conf.Auth.OIDC.ClientSecret) > 0 {
		oidcClientSecret = "redacted"
	}

	return apitypes.AdminConfigResponseDTO{
		Auth: apitypes.AuthConfigDTO{
			General: &apitypes.GeneralAuthConfigDTO{
				EnabledMethods:                    conf.Auth.General.EnabledMethods,
				IsMFARequired:                     conf.Auth.General.IsMFARequired,
				RequirePasswordChangeOnFirstLogin: conf.Auth.General.RequirePasswordChangeOnFirstLogin,
			},

			OIDC: &apitypes.AuthOIDCConfigDTO{
				ClientID:     conf.Auth.OIDC.ClientID,
				ClientSecret: oidcClientSecret,

				IssuerURL:   conf.Auth.OIDC.IssuerURL,
				RedirectURL: conf.Auth.OIDC.RedirectURL,

				AutomaticUserCreation: conf.Auth.OIDC.AutomaticUserCreation,
				UsernameClaim:         conf.Auth.OIDC.UsernameClaim,
				Prompt:                conf.Auth.OIDC.Prompt,

				RolesClaim:       conf.Auth.OIDC.RolesClaim,
				RequiredRole:     conf.Auth.OIDC.RequiredRole,
				AdditionalScopes: conf.Auth.OIDC.AdditionalScopes,
			},
		},

		Agent: apitypes.AgentConfigDTO{
			AutomaticallySyncListfiles: conf.Agent.AutomaticallySyncListfiles,
			SplitJobsPerAgent:          conf.Agent.SplitJobsPerAgent,
		},

		General: apitypes.GeneralConfigDTO{
			IsMaintenanceMode:               conf.General.IsMaintenanceMode,
			MaximumUploadedFileSize:         conf.General.MaximumUploadedFileSize,
			MaximumUploadedFileLineScanSize: conf.General.MaximumUploadedFileLineScanSize,
		},
	}
}

func (conf RuntimeConfig) ToPublicDTO() apitypes.PublicConfigDTO {
	return apitypes.PublicConfigDTO{
		Auth: apitypes.PublicAuthConfigDTO{
			EnabledMethods: conf.Auth.General.EnabledMethods,
			OIDC: apitypes.PublicOIDCConfigDTO{
				Prompt: conf.Auth.OIDC.Prompt,
			},
		},

		General: apitypes.PublicGeneralConfigDTO{
			IsMaintenanceMode:               conf.General.IsMaintenanceMode,
			MaximumUploadedFileSize:         conf.General.MaximumUploadedFileSize,
			MaximumUploadedFileLineScanSize: conf.General.MaximumUploadedFileLineScanSize,
		},
	}
}

var runningConf RuntimeConfig

func MakeDefaultConfig() RuntimeConfig {
	return RuntimeConfig{
		IsSetupComplete: true,
		ConfigVersion:   latestConfigVersion,

		Auth: AuthConfig{
			General: AuthGeneralConfig{
				EnabledMethods: []string{AuthMethodCredentials},

				IsMFARequired:                     false,
				RequirePasswordChangeOnFirstLogin: true,
			},

			OIDC: AuthOIDCConfig{
				AdditionalScopes:      []string{},
				AutomaticUserCreation: true,
				RolesClaim:            "groups",
				UsernameClaim:         "email",
			},
		},

		Agent: AgentConfig{
			AutomaticallySyncListfiles: true,
			SplitJobsPerAgent:          1,
		},

		General: GeneralConfig{
			IsMaintenanceMode:               false,
			MaximumUploadedFileSize:         10 * 1000 * 1000 * 1000, // 10GB,
			MaximumUploadedFileLineScanSize: 500 * 1000 * 1000,       // 100MB
		},
	}
}

func Reload() error {
	lock.Lock()
	defer lock.Unlock()

	var newConf *RuntimeConfig

	newConf, err := db.GetConfig[RuntimeConfig]()
	if err == db.ErrNotFound {
		err = db.SeedConfig[RuntimeConfig](MakeDefaultConfig())
		if err != nil {
			return err
		}

		newConf, err = db.GetConfig[RuntimeConfig]()
		if err != nil {
			return errors.New("failed to fetch configuration even after seeding: " + err.Error())
		}
	}
	if err != nil {
		return err
	}
	if newConf == nil {
		return errors.New("database config was nil")
	}

	if newConf.ConfigVersion < latestConfigVersion {
		configJsonStr, err := db.GetConfigJSONString()
		if err != nil {
			return fmt.Errorf("failed to get config string for migrations: %v", err)
		}

		migratedConfig, err := runMigrations(configJsonStr)
		if err != nil {
			return fmt.Errorf("failed to perform config migrations: %v", err)
		}

		newConf = migratedConfig
	}

	runningConf = *newConf
	return nil
}

func save(conf RuntimeConfig) error {
	return db.SetConfig[RuntimeConfig](conf)
}

func Save() error {
	lock.Lock()
	defer lock.Unlock()

	return save(runningConf)
}

func Update(updateFunc func(*RuntimeConfig) error) error {
	lock.Lock()
	defer lock.Unlock()

	newConf := runningConf
	err := updateFunc(&newConf)
	if err != nil {
		return err
	}

	err = save(newConf)
	if err != nil {
		return fmt.Errorf("failed to save new config in db: %w", err)
	}

	runningConf = newConf
	return nil
}

func Get() RuntimeConfig {
	return runningConf
}


================================================
FILE: api/internal/config/config_migration.go
================================================
package config

import (
	"encoding/json"
	"fmt"

	log "github.com/sirupsen/logrus"
)

type v1runtimeConfig struct {
	IsSetupComplete                   bool  `json:"is_setup_complete"`
	IsMFARequired                     bool  `json:"is_mfa_required"`
	IsMaintenanceMode                 bool  `json:"is_maintenance_mode"`
	AutomaticallySyncListfiles        bool  `json:"auto_sync_listfiles"`
	SplitJobsPerAgent                 int   `json:"split_jobs_per_agent"`
	RequirePasswordChangeOnFirstLogin bool  `json:"require_password_change_on_first_login"`
	MaximumUploadedFileSize           int64 `json:"maximum_uploaded_file_size"`
	MaximumUploadedFileLineScanSize   int64 `json:"maximum_uploaded_file_line_scan_size"`
}

func migrateV1ToV2(oldConfig v1runtimeConfig) RuntimeConfig {
	return RuntimeConfig{
		ConfigVersion:   2,
		IsSetupComplete: oldConfig.IsSetupComplete,

		Auth: AuthConfig{
			General: AuthGeneralConfig{
				EnabledMethods: []string{AuthMethodCredentials},

				IsMFARequired:                     oldConfig.IsMFARequired,
				RequirePasswordChangeOnFirstLogin: oldConfig.RequirePasswordChangeOnFirstLogin,
			},

			// all oidc fields are new, and can happily default to an empty string
			OIDC: AuthOIDCConfig{
				AdditionalScopes: []string{},
			},
		},

		Agent: AgentConfig{
			AutomaticallySyncListfiles: oldConfig.AutomaticallySyncListfiles,
			SplitJobsPerAgent:          oldConfig.SplitJobsPerAgent,
		},

		General: GeneralConfig{
			IsMaintenanceMode:               oldConfig.IsMaintenanceMode,
			MaximumUploadedFileSize:         oldConfig.MaximumUploadedFileSize,
			MaximumUploadedFileLineScanSize: oldConfig.MaximumUploadedFileLineScanSize,
		},
	}
}

// Currently only migrates from 1 -> 2
func runMigrations(configJsonStr string) (*RuntimeConfig, error) {
	var justVersion struct {
		ConfigVersion int `json:"version"`
	}

	err := json.Unmarshal([]byte(configJsonStr), &justVersion)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %v", err)
	}

	if justVersion.ConfigVersion >= latestConfigVersion {
		return nil, fmt.Errorf("no migrations to perform, version is %d", justVersion.ConfigVersion)
	}

	log.Warnf("Migrating from config version %d to %d", justVersion.ConfigVersion, latestConfigVersion)

	var oldConf v1runtimeConfig

	err = json.Unmarshal([]byte(configJsonStr), &oldConf)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal as old conf: %v", err)
	}

	newConf := migrateV1ToV2(oldConf)
	return &newConf, nil
}


================================================
FILE: api/internal/controllers/account.go
================================================
package controllers

import (
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/lachlan2k/phatcrack/api/internal/auth"
	"github.com/lachlan2k/phatcrack/api/internal/db"
	"github.com/lachlan2k/phatcrack/api/internal/util"
	"github.com/lachlan2k/phatcrack/common/pkg/apitypes"
	"golang.org/x/crypto/bcrypt"
)

func HookAccountEndpoints(api *echo.Group) {
	api.PUT("/change-password", handleChangePassword)
}

func handleChangePassword(c echo.Context) error {
	req, err := util.BindAndValidate[apitypes.AccountChangePasswordRequestDTO](c)
	if err != nil {
		return err
	}

	u := auth.UserFromReq(c)
	if u == nil {
		return echo.ErrUnauthorized
	}

	AuditLog(c, nil, "User is updating password")

	dbUser, err := db.GetUserByID(u.ID.String())
	if err != nil {
		return util.ServerError("Failed to update password", err)
	}

	if dbUser.IsPasswordLocked() {
		return echo.NewHTTPError(http.StatusBadRequest, "Password locked")
	}

	currentPasswordCheckErr := bcrypt.CompareHashAndPassword([]byte(dbUser.PasswordHash), []byte(req.CurrentPassword))
	if currentPasswordCheckErr == bcrypt.ErrMismatchedHashAndPassword {
		return echo.NewHTTPError(http.StatusBadRequest, "Incorrect current password")
	}
	if currentPasswordCheckErr != nil {
		return util.ServerError("Failed to update password", err)
	}

	newHash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
	if err != nil {
		return util.ServerError("Failed to update password", err)
	}

	dbUser.PasswordHash = string(newHash)
	err = db.Save(dbUser)
	if err != nil {
		return util.ServerError("Failed to update password", err)
	}

	AuditLog(c, nil, "User successfully updated their password")

	return c.JSON(http.StatusOK, "ok")
}


================================================
FILE: api/internal/controllers/admin.go
================================================
package controllers

import (
	"encoding/hex"
	"errors"
	"net/http"
	"regexp"
	"strconv"
	"strings"

	"crypto/rand"

	log "github.com/sirupsen/logrus"
	"golang.org/x/crypto/bcrypt"

	"github.com/labstack/echo/v4"
	"github.com/lachlan2k/phatcrack/api/internal/auth"
	"github.com/lachlan2k/phatcrack/api/internal/config"
	"github.com/lachlan2k/phatcrack/api/internal/db"
	"github.com/lachlan2k/phatcrack/api/internal/roles"
	"github.com/lachlan2k/phatcrack/api/internal/util"
	"github.com/lachlan2k/phatcrack/api/internal/version"
	"github.com/lachlan2k/phatcrack/common/pkg/apitypes"
)

func HookAdminEndpoints(api *echo.Group) {
	api.GET("/ping", func(c echo.Context) error {
		return c.String(http.StatusOK, "pong auth")
	})

	api.GET("/whoami", func(c echo.Context) error {
		user := c.Get("user")
		return c.JSON(http.StatusOK, user)
	})

	api.GET("/version", func(c echo.Context) error {
		return c.JSON(http.StatusOK, version.Version())
	})

	api.PUT("/config", func(c echo.Context) error {
		user := auth.UserFromReq(c)
		if user == nil {
			return echo.ErrForbidden
		}

		req, err := util.BindAndValidate[apitypes.AdminConfigRequestDTO](c)
		if err != nil {
			return err
		}

		err = config.Update(func(newConf *config.RuntimeConfig) error {
			if req.Agent != nil {
				a := *req.Agent

				newConf.Agent.AutomaticallySyncListfiles = a.AutomaticallySyncListfiles
				newConf.Agent.SplitJobsPerAgent = a.SplitJobsPerAgent
			}

			if req.Auth != nil {
				a := *req.Auth

				if a.General != nil {
					newConf.Auth.General.EnabledMethods = a.General.EnabledMethods
					newConf.Auth.General.IsMFARequired = a.General.IsMFARequired
					newConf.Auth.General.RequirePasswordChangeOnFirstLogin = a.General.RequirePasswordChangeOnFirstLogin
				}

				if a.OIDC != nil {
					newConf.Auth.OIDC.ClientID = a.OIDC.ClientID
					if a.OIDC.ClientSecret != "redacted" {
						newConf.Auth.OIDC.ClientSecret = a.OIDC.ClientSecret
					}
					newConf.Auth.OIDC.IssuerURL = a.OIDC.IssuerURL
					newConf.Auth.OIDC.RedirectURL = a.OIDC.RedirectURL
					newConf.Auth.OIDC.AutomaticUserCreation = a.OIDC.AutomaticUserCreation
					newConf.Auth.OIDC.UsernameClaim = a.OIDC.UsernameClaim
					newConf.Auth.OIDC.Prompt = a.OIDC.Prompt
					newConf.Auth.OIDC.RolesClaim = a.OIDC.RolesClaim
					newConf.Auth.OIDC.RequiredRole = a.OIDC.RequiredRole
					newConf.Auth.OIDC.AdditionalScopes = a.OIDC.AdditionalScopes
				}
			}

			if req.General != nil {
				g := *req.General

				newConf.General.IsMaintenanceMode = g.IsMaintenanceMode
				newConf.General.MaximumUploadedFileSize = g.MaximumUploadedFileSize
				newConf.General.MaximumUploadedFileLineScanSize = g.MaximumUploadedFileLineScanSize
			}

			return nil
		})

		if err != nil {
			return util.ServerError("Failed to update config", err)
		}

		AuditLog(c, nil, "Admin updated configurationv")

		return c.JSON(http.StatusOK, config.Get().ToAdminDTO())
	})

	api.GET("/config", func(c echo.Context) error {
		return c.JSON(http.StatusOK, config.Get().ToAdminDTO())
	})

	api.GET("/user/all", func(c echo.Context) error {
		users, err := db.GetAllUsers()
		if err != nil {
			return util.ServerError("Failed to get users", err)
		}

		userDTOs := make([]apitypes.AdminGetUserDTO, len(users))
		for i := range users {
			userDTOs[i] = users[i].ToAdminDTO()
		}

		return c.JSON(http.StatusOK, apitypes.AdminGetAllUsersResponseDTO{
			Users: userDTOs,
		})
	})

	api.POST("/user/create", handleCreateUser)
	api.POST("/user/create-service-account", handleCreateServiceAccount)
	api.POST("/agent/create", handleAgentCreate)
	api.PUT("/agent/:id/set-maintenance-mode", func(c echo.Context) error {
		id := c.Param("id")
		req, err := util.BindAndValidate[apitypes.AdminAgentSetMaintanceRequestDTO](c)
		if err != nil {
			return err
		}

		err = db.UpdateAgentMaintenanceMode(id, req.IsMaintenanceMode)
		if err != nil {
			return util.ServerError("Failed to set agent's maintenance mode", err)
		}

		return c.JSON(http.StatusOK, "ok")
	})

	api.POST("/agent-registration-key/create", handleAgentRegistrationKeyCreate)
	api.GET("/agent-registration-key/all", handleGetAllAgentRegistrationKeys)
	api.DELETE("/agent-registration-key/:id", handleDeleteAgentRegistrationKey)

	api.PUT("/user/:id", handleUpdateUser)
	api.PUT("/user/:id/password", handleUpdateUserPassword)

	api.DELETE("/user/:id", handleDeleteUser)
	api.DELETE("/agent/:id", handleDeleteAgent)
}

func handleCreateUser(c echo.Context) error {
	req, err := util.BindAndValidate[apitypes.AdminUserCreateRequestDTO](c)
	if err != nil {
		return err
	}

	if req.LockPassword {
		if req.Password != "" || req.GenPassword {
			return echo.NewHTTPError(http.StatusBadRequest, "Cannot set a password when password is locked")
		}
	}

	password := req.Password
	generatedPassword := ""

	if req.GenPassword {
		genBuff := make([]byte, 16)
		_, err := rand.Read(genBuff)
		if err != nil {
			return util.ServerError("Couldn't create user", err)
		}

		generatedPassword = hex.EncodeToString(genBuff)
		password = generatedPassword
	} else if !req.LockPassword {
		if pwordOk, pwordFb := util.ValidatePasswordStrength(password); !pwordOk {
			return echo.NewHTTPError(http.StatusBadRequest, "Password did not meet strength requirements: "+pwordFb)
		}
	}

	rolesOk := roles.AreRolesAssignable(req.Roles)
	if !rolesOk {
		return echo.NewHTTPError(http.StatusBadRequest, "One or more provided roles are not allowed on registration")
	}

	if config.Get().Auth.General.RequirePasswordChangeOnFirstLogin && !req.LockPassword {
		req.Roles = append(req.Roles, roles.UserRoleRequiresPasswordChange)
	}

	var newUser *db.User
	if req.LockPassword {
		newUser, err = db.RegisterUserWithoutPassword(req.Username, req.Roles)
	} else {
		newUser, err = db.RegisterUserWithCredentials(req.Username, password, req.Roles)
	}

	if err != nil {
		if strings.Contains(err.Error(), "duplicate key") {
			return echo.NewHTTPError(http.StatusConflict, "A user with that username already exists")
		}

		return util.ServerError("Couldn't create user", err)
	}

	AuditLog(c, log.Fields{
		"new_user": newUser.ToDTO(),
	}, "New user created")

	return c.JSON(http.StatusCreated, apitypes.AdminUserCreateResponseDTO{
		ID:                newUser.ID.String(),
		Username:          newUser.Username,
		Roles:             newUser.Roles,
		GeneratedPassword: generatedPassword,
	})
}

func handleCreateServiceAccount(c echo.Context) error {
	req, err := util.BindAndValidate[apitypes.AdminServiceAccountCreateRequestDTO](c)
	if err != nil {
		return err
	}

	rolesOk := roles.AreRolesAssignable(req.Roles)
	if !rolesOk {
		return echo.NewHTTPError(http.StatusBadRequest, "One or more provided roles are not allowed on registration")
	}

	apiKey, _, err := util.GenAPIKeyAndHash()
	if err != nil {
		return util.ServerError("Couldn't create service account", err)
	}

	var allRoles []string
	allRoles = append(allRoles, req.Roles...)
	allRoles = append(allRoles, roles.UserRoleMFAExempt, roles.UserRoleServiceAccount)

	newUser, err := db.RegisterServiceAccount(req.Username, apiKey, allRoles)
	if err != nil {
		return util.ServerError("Couldn't create service account", err)
	}

	AuditLog(c, log.Fields{
		"new_user": newUser.ToDTO(),
	}, "New service account created")

	return c.JSON(http.StatusCreated, apitypes.AdminServiceAccountCreateResponseDTO{
		ID:       newUser.ID.String(),
		Username: newUser.Username,
		Roles:    newUser.Roles,
		APIKey:   apiKey,
	})
}

func handleAgentCreate(c echo.Context) error {
	req, err := util.BindAndValidate[apitypes.AdminAgentCreateRequestDTO](c)
	if err != nil {
		return err
	}

	newAgent, key, err := db.CreateAgent(req.Name, req.Ephemeral)
	if err != nil {
		return util.ServerError("Failed to create agent", err)
	}

	AuditLog(c, log.Fields{
		"new_agent": newAgent.ToDTO(),
	}, "New agent created")

	return c.JSON(http.StatusCreated, apitypes.AdminAgentCreateResponseDTO{
		Name: req.Name,
		ID:   newAgent.ID.String(),
		Key:  key,
	})
}

func handleAgentRegistrationKeyCreate(c echo.Context) error {
	req, err := util.BindAndValidate[apitypes.AdminAgentRegistrationKeyCreateRequestDTO](c)
	if err != nil {
		return err
	}

	newRegKey, key, err := db.CreateAgentRegistrationKey(req.Name, req.ForEphemeralAgent)
	if err != nil {
		return util.ServerError("Failed to create agent registration key", err)
	}

	AuditLog(c, log.Fields{
		"key_id":   newRegKey.ID,
		"key_name": newRegKey.Name,
	}, "New agent registration key created")

	return c.JSON(http.StatusCreated, apitypes.AdminAgentRegistrationKeyCreateResponseDTO{
		ForEphemeralAgent: newRegKey.ForEphemeralAgent,
		Name:              newRegKey.Name,
		ID:                strconv.Itoa(int(newRegKey.ID)),
		Key:               key,
	})
}

func handleUpdateUser(c echo.Context) error {
	id := c.Param("id")
	if !util.AreValidUUIDs(id) {
		return echo.ErrBadRequest
	}

	req, err := util.BindAndValidate[apitypes.AdminUserUpdateRequestDTO](c)
	if err != nil {
		return err
	}

	user, err := db.GetUserByID(id)
	if err == db.ErrNotFound {
		return echo.NewHTTPError(http.StatusNotFound, "User does not exist")
	}
	if err != nil {
		return util.ServerError("Failed to retrieve user to update", err)
	}

	AuditLog(c, log.Fields{
		"user_id":      id,
		"new_username": req.Username,
		"new_roles":    req.Roles,
	}, "Admin is updating user")

	if req.Username != user.Username {
		_, err := db.GetUserByUsername(req.Username)
		if err == nil {
			// err is nil, i.e. we found a match
			return echo.NewHTTPError(http.StatusBadRequest, "Username already taken")
		}
		if err == db.ErrNotFound {
			// pass
		} else {
			return util.GenericServerError(err)
		}
	}

	// Already validated
	user.Username = req.Username
	user.Roles = req.Roles
	err = db.Save(user)
	if err != nil {
		return util.ServerError("Failed to save user", err)
	}

	return c.JSON(http.StatusOK, user.ToDTO())
}

func handleDeleteUser(c echo.Context) error {
	id := c.Param("id")
	if !util.AreValidUUIDs(id) {
		return echo.ErrBadRequest
	}

	user, err := db.GetUserByID(id)
	if err == db.ErrNotFound {
		return echo.NewHTTPError(http.StatusNotFound, "User does not exist")
	}
	if err != nil {
		return util.ServerError("Failed to retrieve user before deletion", err)
	}

	AuditLog(c, log.Fields{
		"user_to_delete": user.ToDTO(),
	}, "Admin is deleting user")

	err = db.HardDelete(user)
	if err != nil {
		return util.ServerError("Failed to delete user", err)
	}

	return c.JSON(http.StatusOK, "ok")
}

func handleDeleteAgent(c echo.Context) error {
	id := c.Param("id")

	agent, err := db.GetAgent(id)
	if err == db.ErrNotFound {
		return echo.NewHTTPError(http.StatusNotFound, "Agent does not exist")
	}
	if err != nil {
		return util.ServerError("Failed to retrieve agent before deletion", err)
	}

	AuditLog(c, log.Fields{
		"agent_to_delete": agent.ToDTO(),
	}, "Admin is deleting agent")

	err = db.HardDelete(agent)
	if err != nil {
		return util.ServerError("Failed to delete agent", err)
	}

	return c.JSON(http.StatusOK, "ok")
}

func handleUpdateUserPassword(c echo.Context) error {
	req, err := util.BindAndValidate[apitypes.AdminUserUp
Download .txt
gitextract_umi_osjx/

├── .dockerignore
├── .github/
│   └── workflows/
│       ├── build-agent-and-release.yml
│       ├── codeql.yml
│       ├── docker-publish.yml
│       ├── e2e.yml
│       ├── go-lint.yml
│       └── lint.yaml
├── .gitignore
├── Caddyfile
├── Dockerfile.agent
├── Dockerfile.api
├── Dockerfile.frontend
├── LICENSE
├── README.md
├── agent/
│   ├── .gitignore
│   ├── build.sh
│   ├── example_config.json
│   ├── go.mod
│   ├── go.sum
│   ├── install.sh
│   ├── internal/
│   │   ├── config/
│   │   │   └── config.go
│   │   ├── handler/
│   │   │   ├── file.go
│   │   │   ├── handler.go
│   │   │   ├── heartbeat.go
│   │   │   ├── job.go
│   │   │   ├── run.go
│   │   │   └── run_windows.go
│   │   ├── hashcat/
│   │   │   ├── constants.go
│   │   │   ├── constants_windows.go
│   │   │   └── hashcat.go
│   │   ├── installer/
│   │   │   ├── hashcat_install.go
│   │   │   ├── installer.go
│   │   │   ├── register.go
│   │   │   ├── template.service
│   │   │   ├── utils.go
│   │   │   └── utils_windows.go
│   │   ├── lockfile/
│   │   │   ├── lockfile.go
│   │   │   └── lockfile_dummy.go
│   │   ├── util/
│   │   │   ├── backoff.go
│   │   │   └── util.go
│   │   ├── version/
│   │   │   └── version.go
│   │   └── wswrapper/
│   │       └── wswrapper.go
│   └── main.go
├── api/
│   ├── .air.toml
│   ├── .dockerignore
│   ├── Dockerfile.dev
│   ├── build.sh
│   ├── go.mod
│   ├── go.sum
│   ├── internal/
│   │   ├── accesscontrol/
│   │   │   └── accesscontrol.go
│   │   ├── attacksharder/
│   │   │   └── attacksharder.go
│   │   ├── auth/
│   │   │   ├── header_auth_middleware.go
│   │   │   ├── mfa.go
│   │   │   ├── mfa_webauthn.go
│   │   │   ├── middleware.go
│   │   │   ├── session.go
│   │   │   └── session_inmemory.go
│   │   ├── config/
│   │   │   ├── config.go
│   │   │   └── config_migration.go
│   │   ├── controllers/
│   │   │   ├── account.go
│   │   │   ├── admin.go
│   │   │   ├── agent.go
│   │   │   ├── agent_handler.go
│   │   │   ├── attack.go
│   │   │   ├── attack_template.go
│   │   │   ├── attackjob.go
│   │   │   ├── auth.go
│   │   │   ├── auth_credentials.go
│   │   │   ├── auth_oidc.go
│   │   │   ├── config.go
│   │   │   ├── controllers.go
│   │   │   ├── e2e.go
│   │   │   ├── hashcat.go
│   │   │   ├── hashlist.go
│   │   │   ├── listfiles.go
│   │   │   ├── listfiles_upload.go
│   │   │   ├── potfile.go
│   │   │   ├── project.go
│   │   │   └── users.go
│   │   ├── db/
│   │   │   ├── agent.go
│   │   │   ├── attack_template.go
│   │   │   ├── config.go
│   │   │   ├── db.go
│   │   │   ├── job.go
│   │   │   ├── keyspace_cache.go
│   │   │   ├── listfiles.go
│   │   │   ├── potfile.go
│   │   │   ├── project.go
│   │   │   └── user.go
│   │   ├── filerepo/
│   │   │   └── filerepo.go
│   │   ├── fleet/
│   │   │   ├── agent.go
│   │   │   ├── fleet.go
│   │   │   ├── handle_jobs_events.go
│   │   │   └── state_reconcilition.go
│   │   ├── hashcathelpers/
│   │   │   └── hashcathelpers.go
│   │   ├── resources/
│   │   │   ├── gen_hash_info.sh
│   │   │   ├── hash_info.json
│   │   │   └── resources.go
│   │   ├── roles/
│   │   │   └── roles.go
│   │   ├── util/
│   │   │   ├── password_strength.go
│   │   │   ├── request_validator.go
│   │   │   └── util.go
│   │   ├── version/
│   │   │   └── version.go
│   │   └── webserver/
│   │       ├── logger.go
│   │       └── webserver.go
│   └── main.go
├── common/
│   ├── go.mod
│   ├── go.sum
│   └── pkg/
│       ├── apitypes/
│       │   ├── account.go
│       │   ├── admin.go
│       │   ├── admin_config.go
│       │   ├── agent.go
│       │   ├── agent_handler.go
│       │   ├── apitypes.go
│       │   ├── attack.go
│       │   ├── attack_template.go
│       │   ├── auth.go
│       │   ├── config.go
│       │   ├── hashcat.go
│       │   ├── hashlist.go
│       │   ├── job.go
│       │   ├── listfiles.go
│       │   ├── potfile.go
│       │   ├── project.go
│       │   └── user.go
│       ├── hashcattypes/
│       │   ├── attackmode.go
│       │   ├── hashcattypes.go
│       │   └── hashinfo.go
│       └── wstypes/
│           ├── job.go
│           └── wstypes.go
├── docker-compose.dev.yml
├── docker-compose.prod.yml
├── e2e/
│   ├── api/
│   │   ├── .gitignore
│   │   ├── .prettierrc.json
│   │   ├── jest.config.js
│   │   ├── package.json
│   │   ├── tests/
│   │   │   ├── _api.spec.ts
│   │   │   ├── _helpers.ts
│   │   │   ├── admin_authz.ts
│   │   │   ├── dummyRequests.ts
│   │   │   ├── hashlists.ts
│   │   │   ├── projects.ts
│   │   │   ├── setup.ts
│   │   │   ├── unauth.ts
│   │   │   └── user_provisioning_auth.ts
│   │   └── tsconfig.json
│   ├── browser/
│   │   ├── .gitignore
│   │   ├── package.json
│   │   ├── playwright.config.ts
│   │   └── tests/
│   │       ├── adduser.spec.ts
│   │       ├── auth.config.ts
│   │       ├── auth.setup.ts
│   │       └── initial.setup.ts
│   └── docker-compose.test.yml
├── frontend/
│   ├── .gitignore
│   ├── .prettierrc.json
│   ├── .vscode/
│   │   └── extensions.json
│   ├── Dockerfile.dev
│   ├── README.md
│   ├── env.d.ts
│   ├── eslint.config.ts
│   ├── index.html
│   ├── package.json
│   ├── postcss.config.js
│   ├── src/
│   │   ├── App.vue
│   │   ├── api/
│   │   │   ├── account.ts
│   │   │   ├── admin.ts
│   │   │   ├── agent.ts
│   │   │   ├── attackTemplate.ts
│   │   │   ├── auth.ts
│   │   │   ├── config.ts
│   │   │   ├── hashcat.ts
│   │   │   ├── index.ts
│   │   │   ├── listfiles.ts
│   │   │   ├── potfile.ts
│   │   │   ├── project.ts
│   │   │   ├── types.ts
│   │   │   └── users.ts
│   │   ├── components/
│   │   │   ├── Admin/
│   │   │   │   ├── AgentConfig.vue
│   │   │   │   ├── AuthConfig.vue
│   │   │   │   ├── GeneralConfig.vue
│   │   │   │   └── UsersTable.vue
│   │   │   ├── AttackConfigDetails.vue
│   │   │   ├── AttackDetailsModal/
│   │   │   │   ├── Overview.vue
│   │   │   │   └── index.vue
│   │   │   ├── AttackTemplateCreator.vue
│   │   │   ├── AttackTemplateEditor.vue
│   │   │   ├── AttackTemplateSetCreator.vue
│   │   │   ├── AttackTemplateSetEditor.vue
│   │   │   ├── CheckboxSet.vue
│   │   │   ├── ConfirmModal.vue
│   │   │   ├── EmptyTable.vue
│   │   │   ├── FileUpload.vue
│   │   │   ├── HashesInput.vue
│   │   │   ├── HrOr.vue
│   │   │   ├── IconButton.vue
│   │   │   ├── InfoTip.vue
│   │   │   ├── Modal.vue
│   │   │   ├── PageLoading.vue
│   │   │   ├── PaginationControls.vue
│   │   │   ├── ProjectShare.vue
│   │   │   ├── SearchableDropdown.vue
│   │   │   ├── TimeSinceDisplay.vue
│   │   │   └── Wizard/
│   │   │       ├── AttackSettings.vue
│   │   │       ├── HashlistInputs.vue
│   │   │       ├── JobWizard.vue
│   │   │       ├── ListSelect.vue
│   │   │       └── MaskInput.vue
│   │   ├── composables/
│   │   │   ├── useApi.ts
│   │   │   ├── useAttackSettings.ts
│   │   │   ├── useHashesInput.ts
│   │   │   ├── usePagination.ts
│   │   │   ├── useToastError.ts
│   │   │   └── useWizardHashDetect.ts
│   │   ├── layouts/
│   │   │   └── default.vue
│   │   ├── main.ts
│   │   ├── pages/
│   │   │   ├── Account.vue
│   │   │   ├── Agents.vue
│   │   │   ├── AttackTemplates.vue
│   │   │   ├── HashSearch.vue
│   │   │   ├── Hashlist.vue
│   │   │   ├── Listfiles.vue
│   │   │   ├── Login.vue
│   │   │   ├── LoginOIDCCallback.vue
│   │   │   ├── Utilisation.vue
│   │   │   ├── Wizard.vue
│   │   │   ├── admin/
│   │   │   │   ├── Agents.vue
│   │   │   │   ├── Configuration.vue
│   │   │   │   └── Users.vue
│   │   │   └── projects/
│   │   │       ├── index.vue
│   │   │       └── project.vue
│   │   ├── router/
│   │   │   └── index.ts
│   │   ├── stores/
│   │   │   ├── activeAttacks.ts
│   │   │   ├── adminConfig.ts
│   │   │   ├── agents.ts
│   │   │   ├── attackTemplates.ts
│   │   │   ├── auth.ts
│   │   │   ├── config.ts
│   │   │   ├── listfiles.ts
│   │   │   ├── projects.ts
│   │   │   ├── resources.ts
│   │   │   └── users.ts
│   │   ├── styles.css
│   │   └── util/
│   │       ├── decodeHex.ts
│   │       ├── exportHashlist.ts
│   │       ├── formatDeviceName.ts
│   │       ├── hashcat.ts
│   │       ├── icons.ts
│   │       ├── sleep.ts
│   │       ├── units.ts
│   │       └── util.ts
│   ├── tailwind.config.js
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   └── vite.config.ts
├── go.work
├── go.work.sum
├── hack/
│   ├── cloc.sh
│   ├── dev.sh
│   ├── static_check.sh
│   ├── tag_release.sh
│   └── ts_types_codegen.sh
├── install_server.sh
└── renovate.json
Download .txt
SYMBOL INDEX (938 symbols across 137 files)

FILE: agent/internal/config/config.go
  type Config (line 11) | type Config struct
  function LoadConfig (line 22) | func LoadConfig(configPath string) (config Config) {

FILE: agent/internal/handler/file.go
  type Lockfile (line 19) | type Lockfile interface
  method getFilePath (line 24) | func (h *Handler) getFilePath(fileID string) (string, error) {
  method downloadFile (line 33) | func (h *Handler) downloadFile(fileID string) error {
  method handleDownloadFileRequest (line 79) | func (h *Handler) handleDownloadFileRequest(msg *wstypes.Message) error {
  method handleDeleteFileRequest (line 115) | func (h *Handler) handleDeleteFileRequest(msg *wstypes.Message) error {

FILE: agent/internal/handler/handler.go
  type ActiveJob (line 23) | type ActiveJob struct
  type Handler (line 29) | type Handler struct
    method sendMessage (line 39) | func (h *Handler) sendMessage(msgType string, payload interface{}) err...
    method sendMessageUnbuffered (line 51) | func (h *Handler) sendMessageUnbuffered(msgType string, payload interf...
    method handleMessage (line 64) | func (h *Handler) handleMessage(msg *wstypes.Message) error {
    method readLoop (line 83) | func (h *Handler) readLoop(ctx context.Context) error {
    method writeLoop (line 109) | func (h *Handler) writeLoop(ctx context.Context) error {
    method Handle (line 123) | func (h *Handler) Handle() error {
  function apiEndpointToWSEndpoint (line 140) | func apiEndpointToWSEndpoint(apiEndpoint string) (string, error) {
  function run (line 157) | func run(conf *config.Config) error {

FILE: agent/internal/handler/heartbeat.go
  function getFileDTOs (line 11) | func getFileDTOs(dir string) ([]wstypes.FileDTO, error) {
  method sendHeartbeat (line 41) | func (h *Handler) sendHeartbeat() error {

FILE: agent/internal/handler/job.go
  method handleJobStart (line 15) | func (h *Handler) handleJobStart(msg *wstypes.Message) error {
  method handleJobKill (line 24) | func (h *Handler) handleJobKill(msg *wstypes.Message) error {
  method sendJobStarted (line 33) | func (h *Handler) sendJobStarted(jobId string, hashcatCommand string) {
  method sendJobStdoutLine (line 41) | func (h *Handler) sendJobStdoutLine(jobId, line string) {
  method sendJobStderrLine (line 49) | func (h *Handler) sendJobStderrLine(jobId, line string) {
  method sendJobExited (line 57) | func (h *Handler) sendJobExited(jobId string, reason string, err error) {
  method sendJobCrackedHash (line 79) | func (h *Handler) sendJobCrackedHash(jobId string, result hashcattypes.H...
  method sendJobStatusUpdate (line 86) | func (h *Handler) sendJobStatusUpdate(jobId string, status hashcattypes....
  method sendJobFailedToStart (line 93) | func (h *Handler) sendJobFailedToStart(jobId string, err error) {
  method runJob (line 124) | func (h *Handler) runJob(job wstypes.JobStartDTO) error {
  method killJob (line 209) | func (h *Handler) killJob(jobMsg wstypes.JobKillDTO) error {

FILE: agent/internal/handler/run.go
  function Run (line 7) | func Run(conf *config.Config) error {

FILE: agent/internal/handler/run_windows.go
  function Run (line 19) | func Run(conf *config.Config) error {
  type agentService (line 30) | type agentService struct
    method Execute (line 55) | func (m *agentService) Execute(args []string, r <-chan svc.ChangeReque...
  function runService (line 34) | func runService(c config.Config) {

FILE: agent/internal/hashcat/constants.go
  constant Hashcat (line 5) | Hashcat = "hashcat.bin"

FILE: agent/internal/hashcat/constants_windows.go
  constant Hashcat (line 5) | Hashcat = "hashcat.exe"

FILE: agent/internal/hashcat/hashcat.go
  type HashcatParams (line 24) | type HashcatParams
    method Validate (line 42) | func (params HashcatParams) Validate() error {
    method maskArgs (line 82) | func (params HashcatParams) maskArgs() ([]string, error) {
    method ToCmdArgs (line 123) | func (params HashcatParams) ToCmdArgs(conf *config.Config, session, te...
  type HashcatStatusGuess (line 26) | type HashcatStatusGuess
  type HashcatStatusDevice (line 28) | type HashcatStatusDevice
  type HashcatResult (line 32) | type HashcatResult
  constant AttackModeDictionary (line 35) | AttackModeDictionary = 0
  constant AttackModeCombinator (line 36) | AttackModeCombinator = 1
  constant AttackModeMask (line 37) | AttackModeMask       = 3
  constant AttackModeHybridDM (line 38) | AttackModeHybridDM   = 6
  constant AttackModeHybridMD (line 39) | AttackModeHybridMD   = 7
  type uintIf (line 74) | type uintIf interface
  function fmtUint (line 78) | func fmtUint[T uintIf](x T) string {
  function findBinary (line 216) | func findBinary(conf *config.Config) (path string, err error) {
  type HashcatSession (line 239) | type HashcatSession struct
    method Start (line 252) | func (sess *HashcatSession) Start() error {
    method Kill (line 355) | func (sess *HashcatSession) Kill() error {
    method Cleanup (line 369) | func (sess *HashcatSession) Cleanup() {
    method CmdLine (line 391) | func (sess *HashcatSession) CmdLine() string {
  function NewHashcatSession (line 395) | func NewHashcatSession(id string, hashes []string, params HashcatParams,...

FILE: agent/internal/installer/hashcat_install.go
  function installHashcat (line 18) | func installHashcat(installConf InstallConfig) {
  function extractTarGz (line 66) | func extractTarGz(targetDirectory string, stream io.Reader) error {

FILE: agent/internal/installer/installer.go
  type InstallConfig (line 23) | type InstallConfig struct
  constant serviceUnitFilePath (line 47) | serviceUnitFilePath = "/etc/systemd/system/phatcrack-agent.service"
  function writeAuthKeyFile (line 49) | func writeAuthKeyFile(installConf InstallConfig) {
  function writeConfigFile (line 64) | func writeConfigFile(installConf InstallConfig) {
  function setupPaths (line 92) | func setupPaths(installConf InstallConfig) {
  function Run (line 103) | func Run(installConf InstallConfig) {
  function applyDefaults (line 134) | func applyDefaults(installConf *InstallConfig) {
  function input (line 205) | func input(p string, a ...any) string {
  function getOptionsInteractive (line 212) | func getOptionsInteractive(installConf *InstallConfig) {
  function checkConf (line 259) | func checkConf(installConf InstallConfig) error {
  function RunInteractive (line 298) | func RunInteractive() {
  function DefaultPathJoin (line 363) | func DefaultPathJoin(parts ...string) string {
  function adjustPermsPath (line 378) | func adjustPermsPath(path string, installConf InstallConfig) {
  function makeHttpClient (line 384) | func makeHttpClient(disableTlsVerification bool) *http.Client {

FILE: agent/internal/installer/register.go
  function RegisterWithKey (line 16) | func RegisterWithKey(conf *InstallConfig) (*apitypes.AgentRegisterRespon...
  function registerIfRequired (line 71) | func registerIfRequired(installConf *InstallConfig) {

FILE: agent/internal/installer/utils.go
  function isElevated (line 14) | func isElevated() error {
  function adjustPerms (line 27) | func adjustPerms(f *os.File, installConf InstallConfig) {
  function getUidAndGid (line 32) | func getUidAndGid(installConf InstallConfig) (int, int) {
  function installService (line 48) | func installService(installConf InstallConfig) {

FILE: agent/internal/installer/utils_windows.go
  constant ServiceName (line 15) | ServiceName = "phatcrack-agent"
  function isElevated (line 17) | func isElevated() error {
  function adjustPerms (line 25) | func adjustPerms(f *os.File, installConf InstallConfig) {
  function installService (line 29) | func installService(installConf InstallConfig) {

FILE: agent/internal/lockfile/lockfile.go
  type Lockfile (line 16) | type Lockfile struct
    method MyID (line 54) | func (l *Lockfile) MyID() string {
    method Acquire (line 58) | func (l *Lockfile) Acquire(ctx context.Context) error {
    method AcquireWithTimeout (line 74) | func (l *Lockfile) AcquireWithTimeout(timeout time.Duration) error {
    method tryAcquire (line 80) | func (l *Lockfile) tryAcquire() error {
    method readData (line 119) | func (l *Lockfile) readData() (*lockdata, error) {
    method ensureHeld (line 135) | func (l *Lockfile) ensureHeld() error {
    method write (line 148) | func (l *Lockfile) write(create bool) error {
    method startWriting (line 174) | func (l *Lockfile) startWriting() {
    method writeLoop (line 180) | func (l *Lockfile) writeLoop(ctx context.Context) {
    method Unlock (line 197) | func (l *Lockfile) Unlock() {
    method delete (line 207) | func (l *Lockfile) delete() error {
  constant writeInterval (line 26) | writeInterval = time.Second
  constant staleAge (line 29) | staleAge = 10 * time.Second
  constant afterStaleDelay (line 33) | afterStaleDelay = 3 * time.Second
  type lockdata (line 36) | type lockdata struct
    method isStale (line 42) | func (data lockdata) isStale() bool {
  function New (line 48) | func New(path string) *Lockfile {

FILE: agent/internal/lockfile/lockfile_dummy.go
  type LockfileDummy (line 5) | type LockfileDummy struct
    method AcquireWithTimeout (line 7) | func (l *LockfileDummy) AcquireWithTimeout(timeout time.Duration) error {
    method Unlock (line 11) | func (l *LockfileDummy) Unlock() {
  function NewDummy (line 15) | func NewDummy() *LockfileDummy {

FILE: agent/internal/util/backoff.go
  type BackoffEntry (line 5) | type BackoffEntry struct
  type Backoff (line 10) | type Backoff struct
    method Start (line 17) | func (b *Backoff) Start() {
    method Ready (line 23) | func (b *Backoff) Ready() bool {

FILE: agent/internal/util/util.go
  function UnmarshalJSON (line 5) | func UnmarshalJSON[T interface{}](jsonBlob string) (out T, err error) {

FILE: agent/internal/version/version.go
  function Version (line 5) | func Version() string {

FILE: agent/internal/wswrapper/wswrapper.go
  type WSWrapper (line 20) | type WSWrapper struct
    method WriteJSON (line 35) | func (w *WSWrapper) WriteJSON(v interface{}) error {
    method WriteJSONUnbuffered (line 41) | func (w *WSWrapper) WriteJSONUnbuffered(v interface{}) error {
    method ReadJSON (line 52) | func (w *WSWrapper) ReadJSON(v interface{}) error {
    method handle (line 57) | func (w *WSWrapper) handle() error {
    method Setup (line 101) | func (w *WSWrapper) Setup() {
    method Run (line 106) | func (w *WSWrapper) Run(notifyFirstConn *sync.Cond) error {

FILE: agent/main.go
  function main (line 16) | func main() {
  function run (line 69) | func run() {

FILE: api/internal/accesscontrol/accesscontrol.go
  function HasOwnershipRightsToProject (line 10) | func HasOwnershipRightsToProject(user *db.User, project *db.Project) bool {
  function HasRightsToProject (line 14) | func HasRightsToProject(user *db.User, project *db.Project) bool {
  function HasRightsToProjectID (line 32) | func HasRightsToProjectID(user *db.User, projId string) (bool, error) {
  function HasRightsToHashlistID (line 47) | func HasRightsToHashlistID(user *db.User, hashlistId string) (bool, erro...
  function HasRightsToJobID (line 63) | func HasRightsToJobID(user *db.User, jobID string) (bool, error) {

FILE: api/internal/attacksharder/attacksharder.go
  function splitMask (line 32) | func splitMask(inputMask string, numChunks int) (outputMask string, outp...
  function createSingleJobfromAttack (line 73) | func createSingleJobfromAttack(attack *db.Attack) (*db.Job, *db.Hashlist...
  function shardMaskAttack (line 101) | func shardMaskAttack(attack *db.Attack, numJobs int) ([]*db.Job, *db.Has...
  function hashHashcatSettings (line 155) | func hashHashcatSettings(params hashcattypes.HashcatParams) (string, err...
  function getKeyspace (line 164) | func getKeyspace(params hashcattypes.HashcatParams) (int64, error) {
  function shardAttackByKeyspace (line 186) | func shardAttackByKeyspace(attack *db.Attack, numJobs int) ([]*db.Job, *...
  function MakeJobs (line 241) | func MakeJobs(attack *db.Attack, maxNumJobs int) ([]*db.Job, *db.Hashlis...

FILE: api/internal/auth/header_auth_middleware.go
  function CreateHeaderAuthMiddleware (line 14) | func CreateHeaderAuthMiddleware() echo.MiddlewareFunc {

FILE: api/internal/auth/mfa.go
  constant MFATypeWebAuthn (line 4) | MFATypeWebAuthn = "MFATypeWebAuthn"

FILE: api/internal/auth/mfa_webauthn.go
  type webauthnUser (line 17) | type webauthnUser struct
    method WebAuthnID (line 23) | func (w webauthnUser) WebAuthnID() []byte {
    method WebAuthnName (line 27) | func (w webauthnUser) WebAuthnName() string {
    method WebAuthnDisplayName (line 31) | func (w webauthnUser) WebAuthnDisplayName() string {
    method WebAuthnCredentials (line 35) | func (w webauthnUser) WebAuthnCredentials() []*webauthn.Credential {
    method WebAuthnCredential (line 43) | func (w webauthnUser) WebAuthnCredential(id []byte) *webauthn.Credenti...
    method WebAuthnIcon (line 47) | func (w webauthnUser) WebAuthnIcon() string {
    method PushCredential (line 51) | func (w webauthnUser) PushCredential(c *webauthn.Credential) {
  function InitWebAuthn (line 57) | func InitWebAuthn(baseURL url.URL) {
  function IsWebAuthnAvailable (line 65) | func IsWebAuthnAvailable() bool {
  function MFAWebAuthnBeginRegister (line 69) | func MFAWebAuthnBeginRegister(c echo.Context, sessHandler SessionHandler...
  function MFAWebAuthnFinishRegister (line 129) | func MFAWebAuthnFinishRegister(c echo.Context, sessHandler SessionHandle...
  function MFAWebAuthnBeginLogin (line 188) | func MFAWebAuthnBeginLogin(c echo.Context, sessHandler SessionHandler) (...
  function MFAWebAuthnFinishLogin (line 237) | func MFAWebAuthnFinishLogin(c echo.Context, sessHandler SessionHandler) ...

FILE: api/internal/auth/middleware.go
  function EnforceMFAMiddleware (line 11) | func EnforceMFAMiddleware(s SessionHandler) echo.MiddlewareFunc {
  type EnforceAuthArgs (line 51) | type EnforceAuthArgs struct
  function EnforceAuthMiddleware (line 55) | func EnforceAuthMiddleware(args EnforceAuthArgs) echo.MiddlewareFunc {
  function RoleRestrictedMiddleware (line 74) | func RoleRestrictedMiddleware(allowedRoles []string, disallowedRoles []s...
  function AdminOnlyMiddleware (line 104) | func AdminOnlyMiddleware(h SessionHandler) echo.MiddlewareFunc {

FILE: api/internal/auth/session.go
  type SessionHandler (line 11) | type SessionHandler interface
  type SessionData (line 23) | type SessionData struct
  constant sessionAuthIsValidContextKey (line 31) | sessionAuthIsValidContextKey = "sess-auth-valid"
  constant sessionContextKey (line 32) | sessionContextKey = "sess-data"
  constant sessionUserContextKey (line 33) | sessionUserContextKey = "sess-user"
  function AuthIsValid (line 35) | func AuthIsValid(c echo.Context) bool {
  function SessionDataFromReq (line 40) | func SessionDataFromReq(c echo.Context) *SessionData {
  function UserAndSessFromReq (line 49) | func UserAndSessFromReq(c echo.Context) (*db.User, *SessionData) {
  function UserFromReq (line 71) | func UserFromReq(c echo.Context) *db.User {

FILE: api/internal/auth/session_inmemory.go
  type inMemoryStoreEntry (line 14) | type inMemoryStoreEntry struct
  type InMemorySessionHandler (line 20) | type InMemorySessionHandler struct
    method CreateMiddleware (line 29) | func (s *InMemorySessionHandler) CreateMiddleware() echo.MiddlewareFunc {
    method Start (line 60) | func (s *InMemorySessionHandler) Start(c echo.Context, sess SessionDat...
    method Destroy (line 82) | func (s *InMemorySessionHandler) Destroy(c echo.Context) error {
    method Refresh (line 91) | func (s *InMemorySessionHandler) Refresh(c echo.Context) error {
    method Rotate (line 117) | func (s *InMemorySessionHandler) Rotate(c echo.Context) error {
    method UpdateSessionData (line 141) | func (s *InMemorySessionHandler) UpdateSessionData(c echo.Context, upd...
    method LogoutAllSessionsForUser (line 153) | func (s *InMemorySessionHandler) LogoutAllSessionsForUser(userId strin...
    method genRandom (line 166) | func (s *InMemorySessionHandler) genRandom() (string, error) {
    method getCookie (line 174) | func (s *InMemorySessionHandler) getCookie(c echo.Context) string {
    method getEntry (line 185) | func (s *InMemorySessionHandler) getEntry(c echo.Context) (*inMemorySt...
    method setCookie (line 210) | func (s *InMemorySessionHandler) setCookie(c echo.Context, val string,...
    method cleanup (line 222) | func (s *InMemorySessionHandler) cleanup() {
    method janitor (line 233) | func (s *InMemorySessionHandler) janitor() {
  constant sessionInMemoryEntryKey (line 182) | sessionInMemoryEntryKey = "sess-inmem-entry"

FILE: api/internal/config/config.go
  constant AuthMethodCredentials (line 14) | AuthMethodCredentials = "method_credentials"
  constant AuthMethodOIDC (line 15) | AuthMethodOIDC = "method_oidc"
  type AuthOIDCConfig (line 17) | type AuthOIDCConfig struct
  type AuthGeneralConfig (line 34) | type AuthGeneralConfig struct
  type AuthConfig (line 40) | type AuthConfig struct
  type AgentConfig (line 45) | type AgentConfig struct
  type GeneralConfig (line 50) | type GeneralConfig struct
  type RuntimeConfig (line 56) | type RuntimeConfig struct
    method ToAdminDTO (line 68) | func (conf RuntimeConfig) ToAdminDTO() apitypes.AdminConfigResponseDTO {
    method ToPublicDTO (line 112) | func (conf RuntimeConfig) ToPublicDTO() apitypes.PublicConfigDTO {
  constant latestConfigVersion (line 66) | latestConfigVersion = 2
  function MakeDefaultConfig (line 131) | func MakeDefaultConfig() RuntimeConfig {
  function Reload (line 165) | func Reload() error {
  function save (line 208) | func save(conf RuntimeConfig) error {
  function Save (line 212) | func Save() error {
  function Update (line 219) | func Update(updateFunc func(*RuntimeConfig) error) error {
  function Get (line 238) | func Get() RuntimeConfig {

FILE: api/internal/config/config_migration.go
  type v1runtimeConfig (line 10) | type v1runtimeConfig struct
  function migrateV1ToV2 (line 21) | func migrateV1ToV2(oldConfig v1runtimeConfig) RuntimeConfig {
  function runMigrations (line 54) | func runMigrations(configJsonStr string) (*RuntimeConfig, error) {

FILE: api/internal/controllers/account.go
  function HookAccountEndpoints (line 14) | func HookAccountEndpoints(api *echo.Group) {
  function handleChangePassword (line 18) | func handleChangePassword(c echo.Context) error {

FILE: api/internal/controllers/admin.go
  function HookAdminEndpoints (line 26) | func HookAdminEndpoints(api *echo.Group) {
  function handleCreateUser (line 153) | func handleCreateUser(c echo.Context) error {
  function handleCreateServiceAccount (line 219) | func handleCreateServiceAccount(c echo.Context) error {
  function handleAgentCreate (line 256) | func handleAgentCreate(c echo.Context) error {
  function handleAgentRegistrationKeyCreate (line 278) | func handleAgentRegistrationKeyCreate(c echo.Context) error {
  function handleUpdateUser (line 302) | func handleUpdateUser(c echo.Context) error {
  function handleDeleteUser (line 351) | func handleDeleteUser(c echo.Context) error {
  function handleDeleteAgent (line 377) | func handleDeleteAgent(c echo.Context) error {
  function handleUpdateUserPassword (line 400) | func handleUpdateUserPassword(c echo.Context) error {
  function handleGetAllAgentRegistrationKeys (line 462) | func handleGetAllAgentRegistrationKeys(c echo.Context) error {
  function handleDeleteAgentRegistrationKey (line 477) | func handleDeleteAgentRegistrationKey(c echo.Context) error {

FILE: api/internal/controllers/agent.go
  function HookAgentEndpoints (line 12) | func HookAgentEndpoints(api *echo.Group) {

FILE: api/internal/controllers/agent_handler.go
  function HookAgentHandlerEndpoints (line 18) | func HookAgentHandlerEndpoints(api *echo.Group) {
  function handleAgentDownloadFile (line 30) | func handleAgentDownloadFile(c echo.Context) error {
  function handleAgentWs (line 63) | func handleAgentWs(c echo.Context) error {
  function handleAgentRegister (line 99) | func handleAgentRegister(c echo.Context) error {

FILE: api/internal/controllers/attack.go
  function HookAttackEndpoints (line 24) | func HookAttackEndpoints(api *echo.Group) {
  function handleAttacksGetInitialising (line 41) | func handleAttacksGetInitialising(c echo.Context) error {
  function handleAttackGetAllForHashlist (line 62) | func handleAttackGetAllForHashlist(c echo.Context) error {
  function handleDeleteAttack (line 106) | func handleDeleteAttack(c echo.Context) error {
  function handleAttackStopAllJobs (line 162) | func handleAttackStopAllJobs(c echo.Context) error {
  function handleAttackJobGetAll (line 201) | func handleAttackJobGetAll(c echo.Context) error {
  function handleAttackGet (line 244) | func handleAttackGet(c echo.Context) error {
  function handleAttackCreate (line 280) | func handleAttackCreate(c echo.Context) error {
  function handleAttackStart (line 379) | func handleAttackStart(c echo.Context) error {
  function handleAttackRestartFailedJobs (line 533) | func handleAttackRestartFailedJobs(c echo.Context) error {

FILE: api/internal/controllers/attack_template.go
  function HookAttackTemplateEndpoints (line 16) | func HookAttackTemplateEndpoints(api *echo.Group) {
  function handleGetAllAttackTemplates (line 24) | func handleGetAllAttackTemplates(c echo.Context) error {
  function handleCreateAttackTemplate (line 49) | func handleCreateAttackTemplate(c echo.Context) error {
  function handleCreateAttackTemplateSet (line 72) | func handleCreateAttackTemplateSet(c echo.Context) error {
  function handleUpdateAttackTemplate (line 95) | func handleUpdateAttackTemplate(c echo.Context) error {
  function handleDeleteAttackTemplate (line 173) | func handleDeleteAttackTemplate(c echo.Context) error {

FILE: api/internal/controllers/attackjob.go
  function HookJobEndpoints (line 14) | func HookJobEndpoints(api *echo.Group) {
  function handleAttackJobGet (line 45) | func handleAttackJobGet(c echo.Context) error {
  function handleAttacksAndJobsForHashlist (line 87) | func handleAttacksAndJobsForHashlist(c echo.Context) error {

FILE: api/internal/controllers/auth.go
  function isOIDCAuthAllowed (line 19) | func isOIDCAuthAllowed() bool {
  function isCredentialAuthAllowed (line 23) | func isCredentialAuthAllowed() bool {
  function HookAuthEndpoints (line 27) | func HookAuthEndpoints(api *echo.Group, sessHandler auth.SessionHandler) {
  function handleRefresh (line 277) | func handleRefresh(sessHandler auth.SessionHandler) echo.HandlerFunc {

FILE: api/internal/controllers/auth_credentials.go
  function handleCredentialLogin (line 18) | func handleCredentialLogin(sessHandler auth.SessionHandler) echo.Handler...

FILE: api/internal/controllers/auth_oidc.go
  constant nonceCookieName (line 25) | nonceCookieName = "_oauth_state_nonce"
  type oidcUtils (line 27) | type oidcUtils struct
  type oauthState (line 33) | type oauthState struct
  function getOidcUtils (line 38) | func getOidcUtils(ctx context.Context) (*oidcUtils, error) {
  function handleOIDCStart (line 64) | func handleOIDCStart(_ auth.SessionHandler) echo.HandlerFunc {
  function handleOIDCCallback (line 110) | func handleOIDCCallback(sessHandler auth.SessionHandler) echo.HandlerFunc {
  function extractUsernameAndRoles (line 238) | func extractUsernameAndRoles(claims map[string]any, ac config.AuthConfig...

FILE: api/internal/controllers/config.go
  function HookConfigEndpoints (line 10) | func HookConfigEndpoints(api *echo.Group) {

FILE: api/internal/controllers/controllers.go
  function AuditLog (line 9) | func AuditLog(c echo.Context, fields log.Fields, format string, args ......

FILE: api/internal/controllers/e2e.go
  function HookE2EEndpoints (line 12) | func HookE2EEndpoints(g *echo.Group, apiKey string) {

FILE: api/internal/controllers/hashcat.go
  function HookHashcatEndpoints (line 13) | func HookHashcatEndpoints(api *echo.Group) {

FILE: api/internal/controllers/hashlist.go
  function HookHashlistEndpoints (line 19) | func HookHashlistEndpoints(api *echo.Group) {
  function handleHashlistGetAllForProj (line 32) | func handleHashlistGetAllForProj(c echo.Context) error {
  function handleHashlistGet (line 66) | func handleHashlistGet(c echo.Context) error {
  function handleHashlistDelete (line 96) | func handleHashlistDelete(c echo.Context) error {
  function handleHashlistCreate (line 146) | func handleHashlistCreate(c echo.Context) error {
  function handleHashlistAppend (line 228) | func handleHashlistAppend(c echo.Context) error {

FILE: api/internal/controllers/listfiles.go
  function HookListsEndpoints (line 17) | func HookListsEndpoints(api *echo.Group) {
  function handleListfileDelete (line 26) | func handleListfileDelete(c echo.Context) error {
  function handleGetListfile (line 69) | func handleGetListfile(c echo.Context) error {
  function handleGetAllListfiles (line 107) | func handleGetAllListfiles(c echo.Context) error {

FILE: api/internal/controllers/listfiles_upload.go
  type listfileUploadForm (line 30) | type listfileUploadForm struct
  function handleListfileUpload (line 42) | func handleListfileUpload(c echo.Context) error {
  function parseListfileUploadForm (line 155) | func parseListfileUploadForm(mpReader *multipart.Reader, tmpFile *os.Fil...
  function detectFileLineCount (line 258) | func detectFileLineCount(f *os.File) (int, error) {

FILE: api/internal/controllers/potfile.go
  function HookPotfileEndpoints (line 13) | func HookPotfileEndpoints(api *echo.Group) {
  function handlePotfileSearch (line 17) | func handlePotfileSearch(c echo.Context) error {

FILE: api/internal/controllers/project.go
  function HookProjectEndpoints (line 19) | func HookProjectEndpoints(api *echo.Group) {
  function handleProjectCreate (line 38) | func handleProjectCreate(c echo.Context) error {
  function handleProjectGet (line 66) | func handleProjectGet(c echo.Context) error {
  function handleProjectDelete (line 94) | func handleProjectDelete(c echo.Context) error {
  function handleProjectGetAll (line 144) | func handleProjectGetAll(c echo.Context) error {
  function handleProjectGetShares (line 175) | func handleProjectGetShares(c echo.Context) error {
  function handleProjectAddShare (line 210) | func handleProjectAddShare(c echo.Context) error {
  function handleProjectDeleteShare (line 258) | func handleProjectDeleteShare(c echo.Context) error {
  function handleProjectListfilesGet (line 299) | func handleProjectListfilesGet(c echo.Context) error {

FILE: api/internal/controllers/users.go
  function HookUserEndpoints (line 12) | func HookUserEndpoints(api *echo.Group) {

FILE: api/internal/db/agent.go
  constant AgentStatusHealthy (line 15) | AgentStatusHealthy                  = "AgentStatusHealthy"
  constant AgentStatusUnhealthyButConnected (line 16) | AgentStatusUnhealthyButConnected    = "AgentStatusUnhealthyButConnected"
  constant AgentStatusUnhealthyAndDisconnected (line 17) | AgentStatusUnhealthyAndDisconnected = "AgentStatusUnhealthyAndDisconnected"
  constant AgentStatusDead (line 18) | AgentStatusDead                     = "AgentStatusDead"
  type Agent (line 21) | type Agent struct
    method ToDTO (line 91) | func (a Agent) ToDTO() apitypes.AgentDTO {
  type AgentRegistrationKey (line 31) | type AgentRegistrationKey struct
    method ToDTO (line 41) | func (a AgentRegistrationKey) ToDTO() apitypes.AdminGetAgentRegistrati...
  type AgentFile (line 50) | type AgentFile struct
    method ToDTO (line 69) | func (a AgentFile) ToDTO() apitypes.AgentFileDTO {
  type AgentDeviceInfo (line 55) | type AgentDeviceInfo struct
  type AgentInfo (line 59) | type AgentInfo struct
    method ToDTO (line 76) | func (a AgentInfo) ToDTO() apitypes.AgentInfoDTO {
  function CreateAgent (line 101) | func CreateAgent(name string, ephemeral bool) (newAgent *Agent, plaintex...
  function CreateAgentRegistrationKey (line 122) | func CreateAgentRegistrationKey(name string, ephemeral bool) (newKey *Ag...
  function GetAllAgentRegistrationKeys (line 146) | func GetAllAgentRegistrationKeys() ([]AgentRegistrationKey, error) {
  function DeleteAgentRegistrationKey (line 155) | func DeleteAgentRegistrationKey(id string) error {
  function GetAgentRegistrationKeyByKey (line 159) | func GetAgentRegistrationKeyByKey(key string) (*AgentRegistrationKey, er...
  function GetAllAgents (line 169) | func GetAllAgents() ([]Agent, error) {
  function GetAllHealthyAgents (line 178) | func GetAllHealthyAgents() ([]Agent, error) {
  function GetAllSchedulableAgents (line 187) | func GetAllSchedulableAgents() ([]Agent, error) {
  function GetAgent (line 196) | func GetAgent(id string) (*Agent, error) {
  function FindAgentByAuthKey (line 205) | func FindAgentByAuthKey(authKey string) (*Agent, error) {
  function FindAgentIDByAuthKey (line 215) | func FindAgentIDByAuthKey(authKey string) (string, error) {
  function UpdateAgentDevices (line 230) | func UpdateAgentDevices(agentId string, devices []hashcattypes.HashcatSt...
  function UpdateAgentStatus (line 239) | func UpdateAgentStatus(agentId string, status string) error {
  function UpdateAgentInfo (line 249) | func UpdateAgentInfo(agentId string, info AgentInfo) error {
  function UpdateAgentMaintenanceMode (line 253) | func UpdateAgentMaintenanceMode(agentId string, isMaintenance bool) error {

FILE: api/internal/db/attack_template.go
  type AttackTemplate (line 10) | type AttackTemplate struct
    method ToDTO (line 33) | func (at AttackTemplate) ToDTO() apitypes.AttackTemplateDTO {
  type AttackTemplateSet (line 20) | type AttackTemplateSet struct
    method ToDTO (line 48) | func (at AttackTemplateSet) ToDTO() apitypes.AttackTemplateDTO {
  constant AttackTemplateType (line 30) | AttackTemplateType = "attack-template"
  constant AttackTemplateSetType (line 31) | AttackTemplateSetType = "attack-template-set"
  function CreateAttackTemplate (line 63) | func CreateAttackTemplate(attackTemplate *AttackTemplate) (*AttackTempla...
  function CreateAttackTemplateSet (line 67) | func CreateAttackTemplateSet(templateSet *AttackTemplateSet) (*AttackTem...
  function GetAllAttackTemplates (line 71) | func GetAllAttackTemplates() ([]AttackTemplate, error) {
  function GetAllAttackTemplateSets (line 75) | func GetAllAttackTemplateSets() ([]AttackTemplateSet, error) {
  function GetAttackTemplate (line 79) | func GetAttackTemplate(id string) (*AttackTemplate, error) {
  function GetAttackTemplateSet (line 83) | func GetAttackTemplateSet(id string) (*AttackTemplateSet, error) {
  function DeleteAttackTemplate (line 87) | func DeleteAttackTemplate(id string) error {
  function DeleteAttackTemplateSet (line 91) | func DeleteAttackTemplateSet(id string) error {

FILE: api/internal/db/config.go
  type Config (line 11) | type Config struct
    method TableName (line 16) | func (c Config) TableName() string {
  function GetConfigJSONString (line 20) | func GetConfigJSONString() (string, error) {
  function GetConfig (line 30) | func GetConfig[ConfigT interface{}]() (*ConfigT, error) {
  function SeedConfig (line 45) | func SeedConfig[ConfigT interface{}](defaultConfig ConfigT) error {
  function SetConfig (line 70) | func SetConfig[ConfigT interface{}](newConf ConfigT) error {

FILE: api/internal/db/db.go
  type UUIDBaseModel (line 21) | type UUIDBaseModel struct
  type SimpleBaseModel (line 28) | type SimpleBaseModel struct
  function HardDelete (line 32) | func HardDelete[T any](obj *T) error {
  function SoftDelete (line 36) | func SoftDelete[T any](obj *T) error {
  function Save (line 40) | func Save[T any](obj *T) error {
  function GetByID (line 44) | func GetByID[T any](id string) (*T, error) {
  function GetAll (line 53) | func GetAll[T any]() ([]T, error) {
  function Connect (line 66) | func Connect(dsn string) error {
  function seed (line 86) | func seed() error {
  function GetInstance (line 103) | func GetInstance() *gorm.DB {
  function runMigrations (line 107) | func runMigrations() {
  function WipeEverything (line 134) | func WipeEverything() error {
  type pgJSONBArray (line 155) | type pgJSONBArray struct
  method Init (line 160) | func (a *pgJSONBArray[T]) Init() {
  method Value (line 165) | func (a pgJSONBArray[T]) Value() (driver.Value, error) {
  method Unwrap (line 170) | func (a *pgJSONBArray[T]) Unwrap() []T {
  method Scan (line 179) | func (a *pgJSONBArray[T]) Scan(src interface{}) error {
  method GormDataType (line 185) | func (a *pgJSONBArray[T]) GormDataType() string {

FILE: api/internal/db/job.go
  constant JobStatusCreated (line 18) | JobStatusCreated       = "JobStatus-Created"
  constant JobStatusAwaitingStart (line 20) | JobStatusAwaitingStart = "JobStatus-AwaitingStart"
  constant JobStatusStarted (line 22) | JobStatusStarted       = "JobStatus-Started"
  constant JobStatusExited (line 24) | JobStatusExited        = "JobStatus-Exited"
  constant JobStopReasonFinished (line 29) | JobStopReasonFinished = "JobStopReason-Finished"
  constant JobStopReasonUserStopped (line 31) | JobStopReasonUserStopped = "JobStopReason-UserStopped"
  constant JobStopReasonFailedToStart (line 33) | JobStopReasonFailedToStart = "JobStopReason-FailedToStart"
  constant JobStopReasonFailed (line 35) | JobStopReasonFailed = "JobStopReason-Failed"
  constant JobStopReasonTimeout (line 37) | JobStopReasonTimeout = "JobStopReason-Timeout"
  type Job (line 40) | type Job struct
    method HasFailed (line 59) | func (j Job) HasFailed() bool {
    method ToDTO (line 92) | func (j Job) ToDTO() apitypes.JobDTO {
    method ToSimpleDTO (line 176) | func (j *Job) ToSimpleDTO() apitypes.JobSimpleDTO {
  type JobRuntimeData (line 63) | type JobRuntimeData struct
    method ToDTO (line 113) | func (r JobRuntimeData) ToDTO() apitypes.JobRuntimeDataDTO {
    method ToSummaryDTO (line 138) | func (r *JobRuntimeData) ToSummaryDTO() apitypes.JobRuntimeSummaryDTO {
  constant JobStdLineStreamStdout (line 83) | JobStdLineStreamStdout = "stdout"
  constant JobStdLineStreamStderr (line 84) | JobStdLineStreamStderr = "stderr"
  type JobRuntimeOutputLine (line 87) | type JobRuntimeOutputLine struct
  function GetJob (line 186) | func GetJob(jobId string, includeRuntimeData bool) (*Job, error) {
  function GetAllPendingJobs (line 201) | func GetAllPendingJobs(includeRuntimeData bool) ([]Job, error) {
  function GetAllIncompleteJobs (line 219) | func GetAllIncompleteJobs(includeRuntimeData bool) ([]Job, error) {
  type RunningJobForUser (line 237) | type RunningJobForUser struct
    method ToDTO (line 244) | func (j *RunningJobForUser) ToDTO() apitypes.RunningJobForUserDTO {
  type RunningJobsForUser (line 253) | type RunningJobsForUser
    method ToDTO (line 255) | func (jobs RunningJobsForUser) ToDTO() []apitypes.RunningJobForUserDTO {
  type RunningJobCountForUser (line 263) | type RunningJobCountForUser struct
  type RunningJobCountPerUserList (line 268) | type RunningJobCountPerUserList
    method ToDTO (line 270) | func (l RunningJobCountPerUserList) ToDTO() apitypes.RunningJobCountPe...
  function GetRunningJobCountPerUser (line 285) | func GetRunningJobCountPerUser() (RunningJobCountPerUserList, error) {
  function GetAllRunningJobsForUser (line 310) | func GetAllRunningJobsForUser(user *User) (RunningJobsForUser, error) {
  function GetJobProjID (line 335) | func GetJobProjID(jobId string) (string, error) {
  function CreateJob (line 353) | func CreateJob(job *Job) (*Job, error) {
  function GetJobsForHashlist (line 363) | func GetJobsForHashlist(hashlistId string) ([]Job, error) {
  function GetJobsForProject (line 377) | func GetJobsForProject(projectId string) ([]Job, error) {
  function CreateJobTx (line 392) | func CreateJobTx(job *Job, tx *gorm.DB) (*Job, error) {
  function SetJobStarted (line 402) | func SetJobStarted(jobId string, cmdLine string, startTime time.Time) er...
  function SetJobExited (line 418) | func SetJobExited(jobId string, reason string, errStr string, exitTime t...
  function SetJobScheduled (line 456) | func SetJobScheduled(jobId string, agentId string) error {
  function AddJobCrackedHash (line 487) | func AddJobCrackedHash(jobId string, hash string, plaintextHex string) e...
  constant MaxJobOutputs (line 534) | MaxJobOutputs = 10
  function AddJobStdline (line 536) | func AddJobStdline(jobId string, stream string, line string) error {
  function AddJobStatusUpdate (line 548) | func AddJobStatusUpdate(jobId string, status hashcattypes.HashcatStatus)...
  function GetJobHashtype (line 555) | func GetJobHashtype(jobId string) (uint, error) {
  function GetJobsForAttack (line 574) | func GetJobsForAttack(attackId string, includeRuntimeData bool, includeT...

FILE: api/internal/db/keyspace_cache.go
  type KeyspaceCache (line 3) | type KeyspaceCache struct
  function GetKeyspaceCacheEntry (line 10) | func GetKeyspaceCacheEntry(settingsHash string) (int64, error) {
  function InsertKeyspaceCacheEntry (line 19) | func InsertKeyspaceCacheEntry(settingsHash string, keyspace int64) error {

FILE: api/internal/db/listfiles.go
  constant ListfileTypeWordlist (line 9) | ListfileTypeWordlist = "Wordlist"
  constant ListfileTypeRulefile (line 10) | ListfileTypeRulefile = "Rulefile"
  constant ListfileTypeHashlist (line 11) | ListfileTypeHashlist = "Hashlist"
  constant ListfileTypeCharset (line 12) | ListfileTypeCharset  = "Charset"
  type Listfile (line 15) | type Listfile struct
    method Save (line 31) | func (l *Listfile) Save() error {
    method ToDTO (line 35) | func (w *Listfile) ToDTO() apitypes.ListfileDTO {
  function GetListfile (line 54) | func GetListfile(id string) (*Listfile, error) {
  function CreateListfile (line 63) | func CreateListfile(listfile *Listfile) (*Listfile, error) {
  function MarkListfileAsAvailable (line 67) | func MarkListfileAsAvailable(id string) error {
  function MarkListfileForDeletion (line 71) | func MarkListfileForDeletion(id string) error {
  function GetAllPublicRulefiles (line 76) | func GetAllPublicRulefiles() ([]Listfile, error) {
  function GetAllPublicWordlists (line 85) | func GetAllPublicWordlists() ([]Listfile, error) {
  function GetAllListfilesAvailableToProject (line 94) | func GetAllListfilesAvailableToProject(projectID string) ([]Listfile, er...
  function GetAllPublicListfiles (line 103) | func GetAllPublicListfiles() ([]Listfile, error) {
  function GetAllListfiles (line 112) | func GetAllListfiles() ([]Listfile, error) {
  function GetAllProjectSpecificListfiles (line 121) | func GetAllProjectSpecificListfiles(projectID string) ([]Listfile, error) {

FILE: api/internal/db/potfile.go
  type PotfileEntry (line 10) | type PotfileEntry struct
  type PotfileSearchResult (line 17) | type PotfileSearchResult struct
    method ToDTO (line 23) | func (r PotfileSearchResult) ToDTO() apitypes.PotfileSearchResultDTO {
  function AddPotfileEntry (line 37) | func AddPotfileEntry(newEntry *PotfileEntry) (*PotfileEntry, error) {
  function SearchPotfile (line 63) | func SearchPotfile(hashes []string) ([]PotfileSearchResult, error) {

FILE: api/internal/db/project.go
  type Project (line 15) | type Project struct
    method ToDTO (line 27) | func (p *Project) ToDTO() apitypes.ProjectDTO {
  function CreateProject (line 37) | func CreateProject(proj *Project) (*Project, error) {
  type ProjectShare (line 41) | type ProjectShare struct
  function CreateProjectShare (line 51) | func CreateProjectShare(share *ProjectShare) (*ProjectShare, error) {
  function DeleteProjectShare (line 55) | func DeleteProjectShare(projId string, userId string) error {
  type ProjectShares (line 59) | type ProjectShares
    method ToDTO (line 61) | func (shares ProjectShares) ToDTO() apitypes.ProjectSharesDTO {
  function GetProjectShares (line 71) | func GetProjectShares(projId string) (ProjectShares, error) {
  type Hashlist (line 80) | type Hashlist struct
    method ToDTO (line 94) | func (h *Hashlist) ToDTO(withHashes bool) apitypes.HashlistDTO {
  function CreateHashlist (line 115) | func CreateHashlist(hashlist *Hashlist) (*Hashlist, error) {
  function AppendToHashlist (line 136) | func AppendToHashlist(newHashes []HashlistHash) (int64, error) {
  function PopulateHashlistFromPotfile (line 168) | func PopulateHashlistFromPotfile(hashlistId string) (int64, error) {
  type HashlistHash (line 182) | type HashlistHash struct
    method ToDTO (line 193) | func (h *HashlistHash) ToDTO() apitypes.HashlistHashDTO {
  type Attack (line 205) | type Attack struct
    method ToDTO (line 219) | func (a *Attack) ToDTO() apitypes.AttackDTO {
  function CreateAttack (line 215) | func CreateAttack(attack *Attack) (*Attack, error) {
  function GetProject (line 229) | func GetProject(projId string) (*Project, error) {
  function GetProjectForUser (line 238) | func GetProjectForUser(projId string, user *User) (*Project, error) {
  function GetAllProjects (line 257) | func GetAllProjects() ([]Project, error) {
  function GetAllProjectsForUser (line 266) | func GetAllProjectsForUser(user *User) ([]Project, error) {
  function GetHashlist (line 291) | func GetHashlist(hashlistId string) (*Hashlist, error) {
  function GetHashlistWithHashes (line 300) | func GetHashlistWithHashes(hashlistId string) (*Hashlist, error) {
  function GetHashlistProjID (line 309) | func GetHashlistProjID(hashlistId string) (string, error) {
  function GetAllHashlistsForProject (line 322) | func GetAllHashlistsForProject(projId string) ([]Hashlist, error) {
  function GetAttack (line 331) | func GetAttack(attackId string) (*Attack, error) {
  function DeleteProject (line 341) | func DeleteProject(projectId string) error {
  function DeleteHashlist (line 374) | func DeleteHashlist(hashlistId string) error {
  function DeleteAttack (line 397) | func DeleteAttack(attackId string) error {
  function GetAllAttacksForHashlist (line 410) | func GetAllAttacksForHashlist(hashlistId string) ([]Attack, error) {
  function GetAttackProjID (line 419) | func GetAttackProjID(attackId string) (string, error) {
  type AttackIDTree (line 437) | type AttackIDTree struct
    method ToDTO (line 443) | func (a *AttackIDTree) ToDTO() apitypes.AttackIDTreeDTO {
  function GetAllAttacksWithProgressStringsForUser (line 451) | func GetAllAttacksWithProgressStringsForUser(user *User) ([]AttackIDTree...
  function SetAttackProgressString (line 474) | func SetAttackProgressString(attackId string, progressString string) err...

FILE: api/internal/db/user.go
  constant UserPasswordLocked (line 13) | UserPasswordLocked = "*"
  type User (line 15) | type User struct
    method ToDTO (line 26) | func (u *User) ToDTO() apitypes.UserDTO {
    method ToAdminDTO (line 34) | func (u *User) ToAdminDTO() apitypes.AdminGetUserDTO {
    method ToMinimalDTO (line 43) | func (u *User) ToMinimalDTO() apitypes.UserMinimalDTO {
    method IsPasswordLocked (line 50) | func (u *User) IsPasswordLocked() bool {
    method HasRole (line 54) | func (u *User) HasRole(roleToCheck string) bool {
  function NormalizeUsername (line 64) | func NormalizeUsername(username string) string {
  function GetAllUsers (line 68) | func GetAllUsers() ([]User, error) {
  function GetUserByID (line 77) | func GetUserByID(id string) (*User, error) {
  function GetUserByUsername (line 86) | func GetUserByUsername(username string) (*User, error) {
  function RegisterUserWithCredentials (line 95) | func RegisterUserWithCredentials(username, password string, roles []stri...
  function RegisterUserWithoutPassword (line 114) | func RegisterUserWithoutPassword(username string, roles []string) (*User...
  function RegisterServiceAccount (line 129) | func RegisterServiceAccount(username string, apiKey string, roles []stri...
  function GetServiceAccountByAPIKey (line 151) | func GetServiceAccountByAPIKey(key string) (*User, error) {

FILE: api/internal/filerepo/filerepo.go
  function SetPath (line 14) | func SetPath(pathToSet string) error {
  function GetPathToFile (line 28) | func GetPathToFile(id uuid.UUID) (string, error) {
  function Create (line 37) | func Create(id uuid.UUID) (io.WriteCloser, error) {
  function Delete (line 46) | func Delete(id uuid.UUID) error {
  function MakeTmp (line 55) | func MakeTmp() (*os.File, string, error) {
  function CreateFromTmp (line 66) | func CreateFromTmp(id uuid.UUID, tmpFilename string) error {

FILE: api/internal/fleet/agent.go
  type AgentConnection (line 20) | type AgentConnection struct
    method markDisconnected (line 27) | func (a *AgentConnection) markDisconnected() {
    method handleMessage (line 48) | func (a *AgentConnection) handleMessage(msg *wstypes.Message) error {
    method sendMessage (line 79) | func (a *AgentConnection) sendMessage(msgType string, payload interfac...
    method handleHeartbeat (line 98) | func (a *AgentConnection) handleHeartbeat(msg *wstypes.Message) error {
    method RequestFileDownload (line 178) | func (a *AgentConnection) RequestFileDownload(fileIDs ...uuid.UUID) er...
    method RequestFileDelete (line 193) | func (a *AgentConnection) RequestFileDelete(fileID string) error {
    method Handle (line 199) | func (a *AgentConnection) Handle() error {

FILE: api/internal/fleet/fleet.go
  function broadcastMessageUnsafe (line 25) | func broadcastMessageUnsafe(msgType string, message interface{}) {
  function RegisterAgentFromWebsocket (line 31) | func RegisterAgentFromWebsocket(conn *websocket.Conn, agentId string) *A...
  function RemoveAgentByID (line 60) | func RemoveAgentByID(projectId string) {
  function ScheduleJobs (line 67) | func ScheduleJobs(jobIds []string) ([]string, error) {
  function NumSchedulableAgents (line 74) | func NumSchedulableAgents() int {
  function scheduleJobUnsafe (line 83) | func scheduleJobUnsafe(jobIds []string) ([]string, error) {
  function StopJob (line 144) | func StopJob(job db.Job, reason string) {
  function RequestFileDownload (line 151) | func RequestFileDownload(fileIDs ...uuid.UUID) {

FILE: api/internal/fleet/handle_jobs_events.go
  method handleJobStarted (line 12) | func (a *AgentConnection) handleJobStarted(msg *wstypes.Message) error {
  method handleJobCrackedHash (line 28) | func (a *AgentConnection) handleJobCrackedHash(msg *wstypes.Message) err...
  method handleJobStdLine (line 52) | func (a *AgentConnection) handleJobStdLine(msg *wstypes.Message) error {
  method handleJobStatusUpdate (line 61) | func (a *AgentConnection) handleJobStatusUpdate(msg *wstypes.Message) er...
  method handleJobExited (line 74) | func (a *AgentConnection) handleJobExited(msg *wstypes.Message) error {
  method handleJobFailedToStart (line 92) | func (a *AgentConnection) handleJobFailedToStart(msg *wstypes.Message) e...

FILE: api/internal/fleet/state_reconcilition.go
  constant deadtimeToUnhealthy (line 19) | deadtimeToUnhealthy = 60 * time.Second
  constant deadtimetoDead (line 20) | deadtimetoDead = 120 * time.Second
  constant disconnectTimeToDead (line 21) | disconnectTimeToDead = 60 * time.Second
  constant acceptableJobStartTime (line 24) | acceptableJobStartTime = 30 * time.Second
  function tellAgentToKillJob (line 27) | func tellAgentToKillJob(agentId *uuid.UUID, jobId *uuid.UUID, reason str...
  function stateReconciliation (line 43) | func stateReconciliation() error {
  function stateReconciliationTask (line 384) | func stateReconciliationTask() {
  function QueueStateReconciliation (line 401) | func QueueStateReconciliation() {
  function LazyQueueStateReconciliation (line 414) | func LazyQueueStateReconciliation() {
  function Setup (line 425) | func Setup() error {

FILE: api/internal/hashcathelpers/hashcathelpers.go
  function findBinary (line 18) | func findBinary() (path string, err error) {
  function hashcatCommand (line 41) | func hashcatCommand(args ...string) (*exec.Cmd, error) {
  function hashcatCommandWithRandSession (line 51) | func hashcatCommandWithRandSession(args ...string) (*exec.Cmd, error) {
  function CalculateKeyspace (line 58) | func CalculateKeyspace(params hashcattypes.HashcatParams) (int64, error) {
  function IdentifyHashTypes (line 142) | func IdentifyHashTypes(exampleHash string, hasUsername bool) ([]int, err...
  constant usernameSeparator (line 195) | usernameSeparator = ":"
  function SplitUsername (line 197) | func SplitUsername(hash string) (string, string, error) {
  function NormalizeHashes (line 205) | func NormalizeHashes(hashes []string, hashType int, hasUsernames bool) (...

FILE: api/internal/resources/resources.go
  function init (line 16) | func init() {
  function GetHashTypeMap (line 27) | func GetHashTypeMap() hashcattypes.HashTypeMap {

FILE: api/internal/roles/roles.go
  constant UserRoleAdmin (line 3) | UserRoleAdmin = "admin"
  constant UserRoleStandard (line 4) | UserRoleStandard = "standard"
  constant UserRoleServiceAccount (line 5) | UserRoleServiceAccount = "service_account"
  constant UserRoleMFAExempt (line 6) | UserRoleMFAExempt = "mfa_exempt"
  constant UserRoleRequiresPasswordChange (line 7) | UserRoleRequiresPasswordChange = "requires_password_change"
  constant UserRoleMFAEnrolled (line 9) | UserRoleMFAEnrolled = "mfa_enrolled"
  function AreRolesAssignable (line 13) | func AreRolesAssignable(roles []string) bool {

FILE: api/internal/util/password_strength.go
  function ValidatePasswordStrength (line 3) | func ValidatePasswordStrength(password string) (ok bool, feedback string) {

FILE: api/internal/util/request_validator.go
  function BindAndValidate (line 16) | func BindAndValidate[DTO interface{}](c echo.Context) (DTO, error) {
  type RequestValidator (line 31) | type RequestValidator struct
    method Validate (line 91) | func (v *RequestValidator) Validate(i interface{}) error {
    method makeValidationError (line 98) | func (v *RequestValidator) makeValidationError(err error) string {
  function NewRequestValidator (line 36) | func NewRequestValidator() *RequestValidator {

FILE: api/internal/util/util.go
  type WrappedServerError (line 17) | type WrappedServerError struct
    method Error (line 22) | func (e WrappedServerError) Error() string {
    method Unwrap (line 26) | func (e WrappedServerError) Unwrap() error {
    method ID (line 30) | func (e WrappedServerError) ID() string {
  function ServerError (line 34) | func ServerError(message string, internal error) *echo.HTTPError {
  function GenericServerError (line 43) | func GenericServerError(internal error) *echo.HTTPError {
  function CleanPath (line 47) | func CleanPath(filePath string) string {
  function UnmarshalJSON (line 52) | func UnmarshalJSON[T interface{}](jsonBlob string) (out T, err error) {
  constant agentKeyLen (line 57) | agentKeyLen = 32
  function HashAgentKey (line 59) | func HashAgentKey(keyStr string) string {
  function CheckAgentKey (line 64) | func CheckAgentKey(keyStr string, hashStr string) bool {
  function GenAgentKeyAndHash (line 71) | func GenAgentKeyAndHash() (keyStr string, hashStr string, err error) {
  function HashAPIKey (line 86) | func HashAPIKey(keyStr string) string {
  function CheckAPIKey (line 91) | func CheckAPIKey(keyStr string, hashStr string) bool {
  constant apiKeyLen (line 95) | apiKeyLen = 32
  function GenAPIKeyAndHash (line 97) | func GenAPIKeyAndHash() (keyStr string, hashStr string, err error) {
  function isValidUUID (line 111) | func isValidUUID(id string) bool {
  function AreValidUUIDs (line 119) | func AreValidUUIDs(candidates ...string) bool {

FILE: api/internal/version/version.go
  function Version (line 5) | func Version() string {

FILE: api/internal/webserver/logger.go
  function makeLoggerMiddleware (line 13) | func makeLoggerMiddleware() echo.MiddlewareFunc {

FILE: api/internal/webserver/webserver.go
  function makeSessionHandler (line 18) | func makeSessionHandler() auth.SessionHandler {
  function Listen (line 25) | func Listen(baseURL string, insecureOrigin bool, port string) error {

FILE: api/main.go
  function main (line 17) | func main() {

FILE: common/pkg/apitypes/account.go
  type AccountChangePasswordRequestDTO (line 3) | type AccountChangePasswordRequestDTO struct

FILE: common/pkg/apitypes/admin.go
  type AdminAgentCreateRequestDTO (line 3) | type AdminAgentCreateRequestDTO struct
  type AdminAgentCreateResponseDTO (line 8) | type AdminAgentCreateResponseDTO struct
  type AdminAgentRegistrationKeyCreateRequestDTO (line 15) | type AdminAgentRegistrationKeyCreateRequestDTO struct
  type AdminAgentRegistrationKeyCreateResponseDTO (line 20) | type AdminAgentRegistrationKeyCreateResponseDTO struct
  type AdminGetAgentRegistrationKeyDTO (line 27) | type AdminGetAgentRegistrationKeyDTO struct
  type AdminGetAllAgentRegistrationKeysResponseDTO (line 34) | type AdminGetAllAgentRegistrationKeysResponseDTO struct
  type AdminUserCreateRequestDTO (line 38) | type AdminUserCreateRequestDTO struct
  type AdminUserCreateResponseDTO (line 46) | type AdminUserCreateResponseDTO struct
  type AdminUserUpdatePasswordRequestDTO (line 53) | type AdminUserUpdatePasswordRequestDTO struct
  type AdminUserUpdatePasswordResponseDTO (line 56) | type AdminUserUpdatePasswordResponseDTO struct
  type AdminUserUpdateRequestDTO (line 60) | type AdminUserUpdateRequestDTO struct
  type AdminServiceAccountCreateRequestDTO (line 65) | type AdminServiceAccountCreateRequestDTO struct
  type AdminServiceAccountCreateResponseDTO (line 69) | type AdminServiceAccountCreateResponseDTO struct
  type AdminGetAllUsersResponseDTO (line 76) | type AdminGetAllUsersResponseDTO struct
  type AdminGetUserDTO (line 80) | type AdminGetUserDTO struct
  type AdminAgentSetMaintanceRequestDTO (line 87) | type AdminAgentSetMaintanceRequestDTO struct

FILE: common/pkg/apitypes/admin_config.go
  type AuthOIDCConfigDTO (line 3) | type AuthOIDCConfigDTO struct
  type GeneralAuthConfigDTO (line 21) | type GeneralAuthConfigDTO struct
  type AuthConfigDTO (line 28) | type AuthConfigDTO struct
  type AgentConfigDTO (line 33) | type AgentConfigDTO struct
  type GeneralConfigDTO (line 38) | type GeneralConfigDTO struct
  type AdminConfigRequestDTO (line 44) | type AdminConfigRequestDTO struct
  type AdminConfigResponseDTO (line 50) | type AdminConfigResponseDTO struct

FILE: common/pkg/apitypes/agent.go
  type AgentDTO (line 5) | type AgentDTO struct
  type AgentFileDTO (line 13) | type AgentFileDTO struct
  type AgentInfoDTO (line 18) | type AgentInfoDTO struct
  type AgentGetAllResponseDTO (line 26) | type AgentGetAllResponseDTO struct

FILE: common/pkg/apitypes/agent_handler.go
  type AgentRegisterRequestDTO (line 3) | type AgentRegisterRequestDTO struct
  type AgentRegisterResponseDTO (line 7) | type AgentRegisterResponseDTO struct

FILE: common/pkg/apitypes/attack.go
  type AttackDTO (line 5) | type AttackDTO struct
  type AttackIDTreeDTO (line 13) | type AttackIDTreeDTO struct
  type AttackWithJobsDTO (line 19) | type AttackWithJobsDTO struct
  type AttackWithJobsMultipleDTO (line 24) | type AttackWithJobsMultipleDTO struct
  type AttackMultipleDTO (line 28) | type AttackMultipleDTO struct
  type AttackIDTreeMultipleDTO (line 32) | type AttackIDTreeMultipleDTO struct
  type AttackCreateRequestDTO (line 36) | type AttackCreateRequestDTO struct
  type AttackStartResponseDTO (line 42) | type AttackStartResponseDTO struct

FILE: common/pkg/apitypes/attack_template.go
  constant AttackTemplateType (line 7) | AttackTemplateType = "attack-template"
  constant AttackTemplateSetType (line 8) | AttackTemplateSetType = "attack-template-set"
  type AttackTemplateDTO (line 10) | type AttackTemplateDTO struct
  type AttackTemplateGetAllResponseDTO (line 22) | type AttackTemplateGetAllResponseDTO struct
  type AttackTemplateCreateRequestDTO (line 26) | type AttackTemplateCreateRequestDTO struct
  type AttackTemplateCreateSetRequestDTO (line 31) | type AttackTemplateCreateSetRequestDTO struct
  type AttackTemplateUpdateRequestDTO (line 36) | type AttackTemplateUpdateRequestDTO struct

FILE: common/pkg/apitypes/auth.go
  type AuthLoginRequestDTO (line 5) | type AuthLoginRequestDTO struct
  type AuthCurrentUserDTO (line 10) | type AuthCurrentUserDTO struct
  type AuthLoginResponseDTO (line 17) | type AuthLoginResponseDTO struct
  type AuthWhoamiResponseDTO (line 24) | type AuthWhoamiResponseDTO struct
  type AuthRefreshResponseDTO (line 31) | type AuthRefreshResponseDTO struct
  type AuthWebAuthnStartEnrollmentResponseDTO (line 38) | type AuthWebAuthnStartEnrollmentResponseDTO struct
  type AuthWebAuthnStartChallengeResponseDTO (line 42) | type AuthWebAuthnStartChallengeResponseDTO struct
  type AuthChangePasswordRequestDTO (line 46) | type AuthChangePasswordRequestDTO struct

FILE: common/pkg/apitypes/config.go
  type PublicOIDCConfigDTO (line 3) | type PublicOIDCConfigDTO struct
  type PublicAuthConfigDTO (line 7) | type PublicAuthConfigDTO struct
  type PublicGeneralConfigDTO (line 12) | type PublicGeneralConfigDTO struct
  type PublicConfigDTO (line 18) | type PublicConfigDTO struct

FILE: common/pkg/apitypes/hashcat.go
  type HashTypesDTO (line 5) | type HashTypesDTO struct
  type DetectHashTypeRequestDTO (line 9) | type DetectHashTypeRequestDTO struct
  type DetectHashTypeResponseDTO (line 14) | type DetectHashTypeResponseDTO struct
  type VerifyHashesRequestDTO (line 18) | type VerifyHashesRequestDTO struct
  type VerifyHashesResponseDTO (line 24) | type VerifyHashesResponseDTO struct
  type NormalizeHashesResponseDTO (line 30) | type NormalizeHashesResponseDTO struct

FILE: common/pkg/apitypes/hashlist.go
  type HashlistCreateRequestDTO (line 3) | type HashlistCreateRequestDTO struct
  type HashlistAppendRequestDTO (line 11) | type HashlistAppendRequestDTO struct
  type HashlistAppendResponseDTO (line 15) | type HashlistAppendResponseDTO struct
  type HashlistCreateResponseDTO (line 20) | type HashlistCreateResponseDTO struct
  type HashlistHashDTO (line 25) | type HashlistHashDTO struct
  type HashlistDTO (line 35) | type HashlistDTO struct
  type HashlistResponseMultipleDTO (line 46) | type HashlistResponseMultipleDTO struct

FILE: common/pkg/apitypes/job.go
  type JobCreateRequestDTO (line 9) | type JobCreateRequestDTO struct
  type JobCreateResponseDTO (line 17) | type JobCreateResponseDTO struct
  type JobStartResponseDTO (line 21) | type JobStartResponseDTO struct
  type JobRuntimeOutputLineDTO (line 25) | type JobRuntimeOutputLineDTO struct
  type JobRuntimeDataDTO (line 30) | type JobRuntimeDataDTO struct
  type JobRuntimeSummaryDTO (line 43) | type JobRuntimeSummaryDTO struct
  type JobDTO (line 52) | type JobDTO struct
  type JobSimpleDTO (line 64) | type JobSimpleDTO struct
  type JobMultipleDTO (line 72) | type JobMultipleDTO struct
  type RunningJobForUserDTO (line 76) | type RunningJobForUserDTO struct
  type RunningJobsForUserResponseDTO (line 83) | type RunningJobsForUserResponseDTO struct
  type RunningJobCountForUserDTO (line 87) | type RunningJobCountForUserDTO struct
  type RunningJobCountPerUsersDTO (line 92) | type RunningJobCountPerUsersDTO struct

FILE: common/pkg/apitypes/listfiles.go
  type ListfileDTO (line 3) | type ListfileDTO struct
  type GetAllWordlistsDTO (line 15) | type GetAllWordlistsDTO struct
  type GetAllRuleFilesDTO (line 19) | type GetAllRuleFilesDTO struct
  type GetAllListfilesDTO (line 23) | type GetAllListfilesDTO struct
  type ListfileUploadResponseDTO (line 27) | type ListfileUploadResponseDTO struct

FILE: common/pkg/apitypes/potfile.go
  type PotfileSearchRequestDTO (line 3) | type PotfileSearchRequestDTO struct
  type PotfileSearchResultDTO (line 7) | type PotfileSearchResultDTO struct
  type PotfileSearchResponseDTO (line 14) | type PotfileSearchResponseDTO struct

FILE: common/pkg/apitypes/project.go
  type ProjectCreateRequestDTO (line 3) | type ProjectCreateRequestDTO struct
  type ProjectDTO (line 8) | type ProjectDTO struct
  type ProjectResponseMultipleDTO (line 16) | type ProjectResponseMultipleDTO struct
  type ProjectAddShareRequestDTO (line 22) | type ProjectAddShareRequestDTO struct
  type ProjectSharesDTO (line 26) | type ProjectSharesDTO struct

FILE: common/pkg/apitypes/user.go
  type UserDTO (line 3) | type UserDTO struct
  type UserMinimalDTO (line 9) | type UserMinimalDTO struct
  type UsersGetAllResponseDTO (line 14) | type UsersGetAllResponseDTO struct
  constant UserRoleAdmin (line 18) | UserRoleAdmin = "admin"
  constant UserRoleStandard (line 19) | UserRoleStandard = "standard"
  constant UserRoleServiceAccount (line 20) | UserRoleServiceAccount = "service_account"
  constant UserRoleMFAExempt (line 21) | UserRoleMFAExempt = "mfa_exempt"
  constant UserRoleRequiresPasswordChange (line 22) | UserRoleRequiresPasswordChange = "requires_password_change"

FILE: common/pkg/hashcattypes/attackmode.go
  constant AttackModeDictionary (line 4) | AttackModeDictionary = 0
  constant AttackModeCombinator (line 5) | AttackModeCombinator = 1
  constant AttackModeMask (line 6) | AttackModeMask       = 3
  constant AttackModeHybridDM (line 7) | AttackModeHybridDM   = 6
  constant AttackModeHybridMD (line 8) | AttackModeHybridMD   = 7

FILE: common/pkg/hashcattypes/hashcattypes.go
  type HashcatParams (line 5) | type HashcatParams struct
  type HashcatStatusGuess (line 27) | type HashcatStatusGuess struct
  type HashcatStatusDevice (line 41) | type HashcatStatusDevice struct
  type HashcatStatus (line 50) | type HashcatStatus struct
  type HashcatResult (line 69) | type HashcatResult struct

FILE: common/pkg/hashcattypes/hashinfo.go
  type HashType (line 3) | type HashType struct
  type HashTypeMap (line 24) | type HashTypeMap

FILE: common/pkg/wstypes/job.go
  constant JobStartType (line 11) | JobStartType = "JobStart"
  constant JobKillType (line 12) | JobKillType  = "JobKill"
  constant JobStartedType (line 15) | JobStartedType       = "JobStarted"
  constant JobFailedToStartType (line 16) | JobFailedToStartType = "JobFailedToStart"
  constant JobCrackedHashType (line 17) | JobCrackedHashType   = "JobCrackedHash"
  constant JobStdLineType (line 18) | JobStdLineType       = "JobStdLine"
  constant JobExitedType (line 19) | JobExitedType        = "JobExited"
  constant JobStatusUpdateType (line 20) | JobStatusUpdateType  = "JobStatusUpdate"
  type JobStartDTO (line 24) | type JobStartDTO struct
  type JobFailedToStartDTO (line 31) | type JobFailedToStartDTO struct
  type JobStartedDTO (line 38) | type JobStartedDTO struct
  type JobKillDTO (line 44) | type JobKillDTO struct
  type JobCrackedHashDTO (line 50) | type JobCrackedHashDTO struct
  constant JobStdLineStreamStdout (line 57) | JobStdLineStreamStdout = "stdout"
  constant JobStdLineStreamStderr (line 58) | JobStdLineStreamStderr = "stderr"
  type JobStdLineDTO (line 61) | type JobStdLineDTO struct
  type JobExitedDTO (line 68) | type JobExitedDTO struct
  type JobStatusUpdateDTO (line 76) | type JobStatusUpdateDTO struct

FILE: common/pkg/wstypes/wstypes.go
  type Message (line 3) | type Message struct
  constant HeartbeatType (line 9) | HeartbeatType           = "Heartbeat"
  constant AgentErrorType (line 10) | AgentErrorType          = "AgentError"
  constant DownloadFileRequestType (line 11) | DownloadFileRequestType = "DownloadFileRequest"
  constant DeleteFileRequestType (line 12) | DeleteFileRequestType   = "DeleteFileRequest"
  type FileDTO (line 15) | type FileDTO struct
  type HeartbeatDTO (line 20) | type HeartbeatDTO struct
  type DownloadFileRequestDTO (line 29) | type DownloadFileRequestDTO struct
  type DeleteFileRequestDTO (line 33) | type DeleteFileRequestDTO struct
  type AgentErrorDTO (line 37) | type AgentErrorDTO struct

FILE: e2e/api/tests/_helpers.ts
  function setupClientWithCookieJar (line 40) | function setupClientWithCookieJar(_jar: tough.CookieJar | null = null) {
  function beforeAllSetupClientWithCookieJar (line 59) | function beforeAllSetupClientWithCookieJar() {
  function beforeAllSetupClientWithLogin (line 67) | function beforeAllSetupClientWithLogin({ username, password }: { usernam...

FILE: e2e/browser/tests/auth.config.ts
  function getAuthFilePath (line 30) | function getAuthFilePath(username: string): string {

FILE: e2e/browser/tests/auth.setup.ts
  function doAuth (line 4) | async function doAuth({ page, creds }) {

FILE: frontend/src/api/account.ts
  function accountChangePassword (line 5) | function accountChangePassword(body: AccountChangePasswordRequestDTO): P...

FILE: frontend/src/api/admin.ts
  function adminGetAllUsers (line 23) | function adminGetAllUsers(): Promise<AdminGetAllUsersResponseDTO> {
  function adminCreateUser (line 27) | function adminCreateUser(newUserData: AdminUserCreateRequestDTO): Promis...
  function adminUpdateUser (line 31) | function adminUpdateUser(id: string, userData: AdminUserUpdateRequestDTO...
  type AdminUserUpdatePasswordAction (line 35) | type AdminUserUpdatePasswordAction = 'remove' | 'generate'
  function adminUpdateUserPassword (line 37) | function adminUpdateUserPassword(id: string, action: AdminUserUpdatePass...
  function adminCreateServiceAccount (line 41) | function adminCreateServiceAccount(
  function adminDeleteUser (line 47) | function adminDeleteUser(id: string): Promise<string> {
  function adminDeleteAgent (line 51) | function adminDeleteAgent(id: string): Promise<string> {
  function adminCreateAgent (line 55) | function adminCreateAgent(newAgentData: AdminAgentCreateRequestDTO): Pro...
  function adminAgentSetMaintenance (line 59) | function adminAgentSetMaintenance(id: string, body: AdminAgentSetMaintan...
  function adminGetConfig (line 63) | function adminGetConfig(): Promise<AdminConfigResponseDTO> {
  function adminSetConfig (line 67) | function adminSetConfig(newConfig: AdminConfigRequestDTO): Promise<Admin...
  function adminGetVersion (line 71) | function adminGetVersion(): Promise<string> {
  function adminGetAgentRegistrationKeys (line 75) | function adminGetAgentRegistrationKeys(): Promise<AdminGetAllAgentRegist...
  function adminCreateAgentRegistrationKey (line 79) | function adminCreateAgentRegistrationKey(
  function adminDeleteAgentRegistrationKey (line 85) | function adminDeleteAgentRegistrationKey(id: string): Promise<string> {

FILE: frontend/src/api/agent.ts
  function getAllAgents (line 5) | function getAllAgents(): Promise<AgentGetAllResponseDTO> {

FILE: frontend/src/api/attackTemplate.ts
  function getAllAttackTemplates (line 14) | function getAllAttackTemplates(): Promise<AttackTemplateGetAllResponseDT...
  function deleteAttackTemplate (line 18) | function deleteAttackTemplate(id: string): Promise<string> {
  function createAttackTemplate (line 22) | function createAttackTemplate(newTemplate: AttackTemplateCreateRequestDT...
  function createAttackTemplateSet (line 26) | function createAttackTemplateSet(newTemplateSet: AttackTemplateCreateSet...
  function updateAttackTemplate (line 30) | function updateAttackTemplate(id: string, body: AttackTemplateUpdateRequ...

FILE: frontend/src/api/auth.ts
  function loginWithCredentials (line 11) | function loginWithCredentials(username: string, password: string): Promi...
  function loginWithOIDCCallback (line 20) | function loginWithOIDCCallback(querystring: string): Promise<AuthLoginRe...
  function urlSafeB64Encode (line 24) | function urlSafeB64Encode(value: ArrayBuffer) {
  function startMFAEnrollment (line 31) | function startMFAEnrollment(): Promise<AuthWebAuthnStartEnrollmentRespon...
  function finishMFAEnrollment (line 35) | function finishMFAEnrollment(cred: PublicKeyCredential): Promise<string> {
  function startMFAChallenge (line 51) | function startMFAChallenge(): Promise<AuthWebAuthnStartChallengeResponse...
  function finishMFAChallenge (line 55) | function finishMFAChallenge(cred: PublicKeyCredential): Promise<string> {
  function changeTemporaryPassword (line 73) | function changeTemporaryPassword(body: AuthChangePasswordRequestDTO): Pr...
  function refreshAuth (line 77) | function refreshAuth(): Promise<AuthWhoamiResponseDTO> {
  function logout (line 81) | function logout(): Promise<string> {

FILE: frontend/src/api/config.ts
  function getCurrentConfig (line 8) | function getCurrentConfig(): Promise<PublicConfigDTO> {

FILE: frontend/src/api/hashcat.ts
  function loadHashTypes (line 5) | function loadHashTypes(): Promise<HashTypesDTO> {
  function detectHashType (line 11) | async function detectHashType(exampleHash: string): Promise<DetectHashTy...

FILE: frontend/src/api/index.ts
  function setClient (line 5) | function setClient(newClient: AxiosInstance) {
  function ping (line 9) | function ping(): Promise<string> {
  function checkCors (line 13) | function checkCors(): Promise<string> {

FILE: frontend/src/api/listfiles.ts
  constant LISTFILE_TYPE_WORDLIST (line 7) | const LISTFILE_TYPE_WORDLIST = 'Wordlist'
  constant LISTFILE_TYPE_RULEFILE (line 8) | const LISTFILE_TYPE_RULEFILE = 'Rulefile'
  type ListfileTypeT (line 10) | type ListfileTypeT = 'Wordlist' | 'Rulefile'
  function getAllListfiles (line 12) | function getAllListfiles(): Promise<GetAllListfilesDTO> {
  function getListfilesForProject (line 16) | function getListfilesForProject(projectId: string): Promise<GetAllListfi...
  function deleteListfile (line 20) | function deleteListfile(id: string): Promise<string> {
  function uploadListfile (line 24) | function uploadListfile(body: FormData, onUploadProgress: (progress: Axi...

FILE: frontend/src/api/potfile.ts
  function searchPotfile (line 5) | function searchPotfile(hashes: string[]): Promise<PotfileSearchResponseD...

FILE: frontend/src/api/project.ts
  function createProject (line 25) | function createProject(name: string, description: string): Promise<Proje...
  function deleteProject (line 34) | function deleteProject(projId: string): Promise<string> {
  function getAllProjects (line 38) | function getAllProjects(): Promise<ProjectResponseMultipleDTO> {
  function getProject (line 42) | function getProject(projId: string): Promise<ProjectDTO> {
  function getProjectShares (line 46) | function getProjectShares(projId: string): Promise<ProjectSharesDTO> {
  function addProjectShare (line 50) | function addProjectShare(projId: string, body: ProjectAddShareRequestDTO...
  function deleteProjectShare (line 54) | function deleteProjectShare(projId: string, userId: string): Promise<Pro...
  function createHashlist (line 58) | function createHashlist(body: HashlistCreateRequestDTO): Promise<Hashlis...
  function appendToHashlist (line 62) | function appendToHashlist(hashlistId: string, hashes: string[]): Promise...
  function createAttack (line 70) | function createAttack(body: AttackCreateRequestDTO): Promise<AttackDTO> {
  function deleteAttack (line 74) | function deleteAttack(attackId: string): Promise<string> {
  function stopAttack (line 78) | function stopAttack(attackId: string): Promise<string> {
  function startAttack (line 82) | function startAttack(attackId: string): Promise<AttackStartResponseDTO> {
  function restartAttackFailedJobs (line 86) | function restartAttackFailedJobs(attackId: string): Promise<string> {
  function getHashlistsForProject (line 90) | function getHashlistsForProject(projId: string): Promise<HashlistRespons...
  function getHashlist (line 94) | function getHashlist(hashlistId: string): Promise<HashlistDTO> {
  function deleteHashlist (line 98) | function deleteHashlist(hashlistId: string): Promise<string> {
  function getAttacksForHashlist (line 102) | function getAttacksForHashlist(hashlistId: string): Promise<AttackMultip...
  function getAttacksWithJobsForHashlist (line 106) | function getAttacksWithJobsForHashlist(hashlistId: string, includeRuntim...
  function getAttacksInitialising (line 112) | function getAttacksInitialising(): Promise<AttackIDTreeMultipleDTO> {
  function getRunningJobs (line 116) | function getRunningJobs(): Promise<RunningJobsForUserResponseDTO> {
  function getJobCountPerUser (line 120) | function getJobCountPerUser(): Promise<RunningJobCountPerUsersDTO> {

FILE: frontend/src/api/types.ts
  type AccountChangePasswordRequestDTO (line 3) | interface AccountChangePasswordRequestDTO {
  type AuthOIDCConfigDTO (line 7) | interface AuthOIDCConfigDTO {
  type GeneralAuthConfigDTO (line 19) | interface GeneralAuthConfigDTO {
  type AuthConfigDTO (line 24) | interface AuthConfigDTO {
  type AgentConfigDTO (line 28) | interface AgentConfigDTO {
  type GeneralConfigDTO (line 32) | interface GeneralConfigDTO {
  type AdminConfigRequestDTO (line 37) | interface AdminConfigRequestDTO {
  type AdminConfigResponseDTO (line 42) | interface AdminConfigResponseDTO {
  type AdminAgentCreateRequestDTO (line 47) | interface AdminAgentCreateRequestDTO {
  type AdminAgentCreateResponseDTO (line 51) | interface AdminAgentCreateResponseDTO {
  type AdminAgentRegistrationKeyCreateRequestDTO (line 57) | interface AdminAgentRegistrationKeyCreateRequestDTO {
  type AdminAgentRegistrationKeyCreateResponseDTO (line 61) | interface AdminAgentRegistrationKeyCreateResponseDTO {
  type AdminGetAgentRegistrationKeyDTO (line 67) | interface AdminGetAgentRegistrationKeyDTO {
  type AdminGetAllAgentRegistrationKeysResponseDTO (line 73) | interface AdminGetAllAgentRegistrationKeysResponseDTO {
  type AdminUserCreateRequestDTO (line 76) | interface AdminUserCreateRequestDTO {
  type AdminUserCreateResponseDTO (line 83) | interface AdminUserCreateResponseDTO {
  type AdminUserUpdatePasswordRequestDTO (line 89) | interface AdminUserUpdatePasswordRequestDTO {
  type AdminUserUpdatePasswordResponseDTO (line 92) | interface AdminUserUpdatePasswordResponseDTO {
  type AdminUserUpdateRequestDTO (line 95) | interface AdminUserUpdateRequestDTO {
  type AdminServiceAccountCreateRequestDTO (line 99) | interface AdminServiceAccountCreateRequestDTO {
  type AdminServiceAccountCreateResponseDTO (line 103) | interface AdminServiceAccountCreateResponseDTO {
  type AdminGetUserDTO (line 109) | interface AdminGetUserDTO {
  type AdminGetAllUsersResponseDTO (line 115) | interface AdminGetAllUsersResponseDTO {
  type AdminAgentSetMaintanceRequestDTO (line 119) | interface AdminAgentSetMaintanceRequestDTO {
  type HashcatStatusDevice (line 122) | interface HashcatStatusDevice {
  type AgentFileDTO (line 130) | interface AgentFileDTO {
  type AgentInfoDTO (line 134) | interface AgentInfoDTO {
  type AgentDTO (line 141) | interface AgentDTO {
  type AgentGetAllResponseDTO (line 149) | interface AgentGetAllResponseDTO {
  type AgentRegisterRequestDTO (line 152) | interface AgentRegisterRequestDTO {
  type AgentRegisterResponseDTO (line 155) | interface AgentRegisterResponseDTO {
  type HashcatParams (line 160) | interface HashcatParams {
  type AttackDTO (line 178) | interface AttackDTO {
  type AttackIDTreeDTO (line 185) | interface AttackIDTreeDTO {
  type JobRuntimeSummaryDTO (line 190) | interface JobRuntimeSummaryDTO {
  type HashcatStatusGuess (line 198) | interface HashcatStatusGuess {
  type HashcatStatus (line 209) | interface HashcatStatus {
  type JobRuntimeOutputLineDTO (line 225) | interface JobRuntimeOutputLineDTO {
  type Time (line 229) | interface Time {}
  type JobRuntimeDataDTO (line 230) | interface JobRuntimeDataDTO {
  type JobDTO (line 241) | interface JobDTO {
  type AttackWithJobsDTO (line 252) | interface AttackWithJobsDTO {
  type AttackWithJobsMultipleDTO (line 260) | interface AttackWithJobsMultipleDTO {
  type AttackMultipleDTO (line 263) | interface AttackMultipleDTO {
  type AttackIDTreeMultipleDTO (line 266) | interface AttackIDTreeMultipleDTO {
  type AttackCreateRequestDTO (line 269) | interface AttackCreateRequestDTO {
  type AttackStartResponseDTO (line 274) | interface AttackStartResponseDTO {
  type AttackTemplateDTO (line 278) | interface AttackTemplateDTO {
  type AttackTemplateGetAllResponseDTO (line 286) | interface AttackTemplateGetAllResponseDTO {
  type AttackTemplateCreateRequestDTO (line 289) | interface AttackTemplateCreateRequestDTO {
  type AttackTemplateCreateSetRequestDTO (line 293) | interface AttackTemplateCreateSetRequestDTO {
  type AttackTemplateUpdateRequestDTO (line 297) | interface AttackTemplateUpdateRequestDTO {
  type AuthLoginRequestDTO (line 303) | interface AuthLoginRequestDTO {
  type AuthCurrentUserDTO (line 307) | interface AuthCurrentUserDTO {
  type AuthLoginResponseDTO (line 313) | interface AuthLoginResponseDTO {
  type AuthWhoamiResponseDTO (line 319) | interface AuthWhoamiResponseDTO {
  type AuthRefreshResponseDTO (line 325) | interface AuthRefreshResponseDTO {
  type AuthenticatorSelection (line 331) | interface AuthenticatorSelection {
  type CredentialDescriptor (line 337) | interface CredentialDescriptor {
  type CredentialParameter (line 342) | interface CredentialParameter {
  type UserEntity (line 346) | interface UserEntity {
  type RelyingPartyEntity (line 351) | interface RelyingPartyEntity {
  type PublicKeyCredentialCreationOptions (line 355) | interface PublicKeyCredentialCreationOptions {
  type AuthWebAuthnStartEnrollmentResponseDTO (line 368) | interface AuthWebAuthnStartEnrollmentResponseDTO {
  type PublicKeyCredentialRequestOptions (line 371) | interface PublicKeyCredentialRequestOptions {
  type AuthWebAuthnStartChallengeResponseDTO (line 380) | interface AuthWebAuthnStartChallengeResponseDTO {
  type AuthChangePasswordRequestDTO (line 383) | interface AuthChangePasswordRequestDTO {
  type PublicOIDCConfigDTO (line 387) | interface PublicOIDCConfigDTO {
  type PublicAuthConfigDTO (line 390) | interface PublicAuthConfigDTO {
  type PublicGeneralConfigDTO (line 394) | interface PublicGeneralConfigDTO {
  type PublicConfigDTO (line 399) | interface PublicConfigDTO {
  type HashType (line 403) | interface HashType {
  type HashTypesDTO (line 423) | interface HashTypesDTO {
  type DetectHashTypeRequestDTO (line 426) | interface DetectHashTypeRequestDTO {
  type DetectHashTypeResponseDTO (line 430) | interface DetectHashTypeResponseDTO {
  type VerifyHashesRequestDTO (line 433) | interface VerifyHashesRequestDTO {
  type VerifyHashesResponseDTO (line 438) | interface VerifyHashesResponseDTO {
  type NormalizeHashesResponseDTO (line 441) | interface NormalizeHashesResponseDTO {
  type HashlistCreateRequestDTO (line 445) | interface HashlistCreateRequestDTO {
  type HashlistAppendRequestDTO (line 452) | interface HashlistAppendRequestDTO {
  type HashlistAppendResponseDTO (line 455) | interface HashlistAppendResponseDTO {
  type HashlistCreateResponseDTO (line 459) | interface HashlistCreateResponseDTO {
  type HashlistHashDTO (line 463) | interface HashlistHashDTO {
  type HashlistDTO (line 472) | interface HashlistDTO {
  type HashlistResponseMultipleDTO (line 482) | interface HashlistResponseMultipleDTO {
  type JobCreateRequestDTO (line 485) | interface JobCreateRequestDTO {
  type JobCreateResponseDTO (line 492) | interface JobCreateResponseDTO {
  type JobStartResponseDTO (line 495) | interface JobStartResponseDTO {
  type JobSimpleDTO (line 499) | interface JobSimpleDTO {
  type JobMultipleDTO (line 506) | interface JobMultipleDTO {
  type RunningJobForUserDTO (line 509) | interface RunningJobForUserDTO {
  type RunningJobsForUserResponseDTO (line 515) | interface RunningJobsForUserResponseDTO {
  type RunningJobCountForUserDTO (line 518) | interface RunningJobCountForUserDTO {
  type RunningJobCountPerUsersDTO (line 522) | interface RunningJobCountPerUsersDTO {
  type ListfileDTO (line 525) | interface ListfileDTO {
  type GetAllWordlistsDTO (line 536) | interface GetAllWordlistsDTO {
  type GetAllRuleFilesDTO (line 539) | interface GetAllRuleFilesDTO {
  type GetAllListfilesDTO (line 542) | interface GetAllListfilesDTO {
  type ListfileUploadResponseDTO (line 545) | interface ListfileUploadResponseDTO {
  type PotfileSearchRequestDTO (line 548) | interface PotfileSearchRequestDTO {
  type PotfileSearchResultDTO (line 551) | interface PotfileSearchResultDTO {
  type PotfileSearchResponseDTO (line 557) | interface PotfileSearchResponseDTO {
  type ProjectCreateRequestDTO (line 560) | interface ProjectCreateRequestDTO {
  type ProjectDTO (line 564) | interface ProjectDTO {
  type ProjectResponseMultipleDTO (line 571) | interface ProjectResponseMultipleDTO {
  type ProjectAddShareRequestDTO (line 574) | interface ProjectAddShareRequestDTO {
  type ProjectSharesDTO (line 577) | interface ProjectSharesDTO {
  type UserDTO (line 580) | interface UserDTO {
  type UserMinimalDTO (line 585) | interface UserMinimalDTO {
  type UsersGetAllResponseDTO (line 589) | interface UsersGetAllResponseDTO {

FILE: frontend/src/api/users.ts
  type UserRole (line 5) | enum UserRole {
  function getAllUsers (line 18) | function getAllUsers(): Promise<UsersGetAllResponseDTO> {

FILE: frontend/src/composables/useApi.ts
  type UseAPIState (line 8) | interface UseAPIState<DTOType> {
  type UseAPIOptions (line 14) | interface UseAPIOptions {
  function useApi (line 21) | function useApi<DTOType>(apiFunc: () => Promise<DTOType>, options: UseAP...

FILE: frontend/src/composables/useHashesInput.ts
  function useHashesInput (line 3) | function useHashesInput() {

FILE: frontend/src/composables/usePagination.ts
  function usePagination (line 4) | function usePagination<ItemT>(items: Ref<ItemT[]>, itemsPerPage: number) {

FILE: frontend/src/composables/useToastError.ts
  function useToastError (line 4) | function useToastError() {

FILE: frontend/src/composables/useWizardHashDetect.ts
  function useWizardHashDetect (line 7) | function useWizardHashDetect(hashesArr: Ref<string[]>) {

FILE: frontend/src/router/index.ts
  function withDefaultLayout (line 5) | function withDefaultLayout(component: () => any, name: string) {
  function route (line 12) | function route(path: string, name: string, component: () => any) {

FILE: frontend/src/stores/activeAttacks.ts
  type ActiveAttacksStore (line 6) | type ActiveAttacksStore = {
  method load (line 21) | async load() {

FILE: frontend/src/stores/adminConfig.ts
  type ConfigStore (line 6) | type ConfigStore = {
  method load (line 15) | async load() {
  method update (line 29) | async update(newConfig: AdminConfigRequestDTO) {

FILE: frontend/src/stores/agents.ts
  type AgentsStore (line 6) | type AgentsStore = {
  method load (line 19) | async load(forceRefetch = false) {

FILE: frontend/src/stores/attackTemplates.ts
  type AttackTemplatesStore (line 18) | type AttackTemplatesStore = {
  method load (line 31) | async load(forceRefresh: boolean = false) {
  method delete (line 58) | async delete(templateId: string) {
  method create (line 64) | async create(newTemplate: AttackTemplateCreateRequestDTO) {
  method createSet (line 70) | async createSet(newTemplate: AttackTemplateCreateSetRequestDTO) {
  method update (line 76) | async update(id: string, body: AttackTemplateUpdateRequestDTO) {

FILE: frontend/src/stores/auth.ts
  type AuthState (line 6) | type AuthState = {
  method handleOIDCCallback (line 31) | async handleOIDCCallback(querystring: string) {
  method login (line 49) | async login(username: string, password: string): Promise<boolean> {
  method logout (line 66) | async logout() {
  method refreshAuth (line 76) | async refreshAuth() {

FILE: frontend/src/stores/config.ts
  type ConfigStore (line 6) | type ConfigStore = {
  method load (line 15) | async load() {

FILE: frontend/src/stores/listfiles.ts
  type ListfileStore (line 6) | type ListfileStore = {
  method load (line 23) | async load(forceRefetch = false) {
  method loadForProject (line 39) | async loadForProject(projectId: string) {

FILE: frontend/src/stores/projects.ts
  type ProjectsState (line 6) | type ProjectsState = {
  method load (line 19) | async load(forceRefetch: boolean = false) {

FILE: frontend/src/stores/resources.ts
  type ResourceStore (line 6) | type ResourceStore = {
  method loadHashTypes (line 19) | async loadHashTypes() {
  method loadAll (line 31) | loadAll() {

FILE: frontend/src/stores/users.ts
  type UsersState (line 6) | type UsersState = {
  method load (line 19) | async load(forceRefetch: boolean = false) {

FILE: frontend/src/util/decodeHex.ts
  function decodeHex (line 1) | function decodeHex(input: string): string {

FILE: frontend/src/util/exportHashlist.ts
  type ExportFormat (line 4) | enum ExportFormat {
  function getExportBlob (line 20) | function getExportBlob(hashes: HashlistHashDTO[], format: ExportFormat, ...
  function getExportFilename (line 51) | function getExportFilename(hashlist: HashlistDTO, format: ExportFormat) {
  function exportResults (line 62) | async function exportResults(hashlistId: string, format: ExportFormat, c...

FILE: frontend/src/util/formatDeviceName.ts
  function formatDeviceName (line 2) | function formatDeviceName(deviceName: string): string {

FILE: frontend/src/util/hashcat.ts
  type AttackMode (line 5) | enum AttackMode {
  function getAttackModeName (line 32) | function getAttackModeName(id: number): string {
  function modeHasMask (line 36) | function modeHasMask(value: number): boolean {
  type MaskInfo (line 40) | interface MaskInfo {
  function hashrateStr (line 59) | function hashrateStr(hashrate: number): string {
  function isLoopbackValid (line 71) | function isLoopbackValid(attackSettings: AttackSettingsT): boolean {
  function makeHashcatParams (line 76) | function makeHashcatParams(hashType: number, attackSettings: AttackSetti...

FILE: frontend/src/util/sleep.ts
  function sleep (line 1) | function sleep(ms: number) {

FILE: frontend/src/util/units.ts
  function timeSince (line 1) | function timeSince(timestamp: number): string {
  function timeBetween (line 25) | function timeBetween(startTime: number, endTime: number): string {
  function timeDurationToReadable (line 41) | function timeDurationToReadable(durationInSeconds: number): string {
  function bytesToReadable (line 60) | function bytesToReadable(bytes: number): string {

FILE: frontend/src/util/util.ts
  function pluralise (line 1) | function pluralise(count: number, singular: string, plural: string = sin...
Condensed preview — 264 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (4,117K chars).
[
  {
    "path": ".dockerignore",
    "chars": 44,
    "preview": "frontend/node_modules/\n.git/config\nfilerepo/"
  },
  {
    "path": ".github/workflows/build-agent-and-release.yml",
    "chars": 3369,
    "preview": "name: Build Agent and Create Release\n\non:\n  push:\n    tags: [ 'v*.*.*' ]\n  pull_request:\n    branches: [ \"main\" ]\n\njobs:"
  },
  {
    "path": ".github/workflows/codeql.yml",
    "chars": 2615,
    "preview": "name: \"CodeQL\"\n\non:\n  push:\n    branches: [ \"main\" ]\n  pull_request:\n    # The branches below must be a subset of the br"
  },
  {
    "path": ".github/workflows/docker-publish.yml",
    "chars": 4569,
    "preview": "name: Docker Build & Publish API and Frontend\n\non:\n  schedule:\n    - cron: '0 0 * * 0'\n  push:\n    branches: [ \"main\" ]\n"
  },
  {
    "path": ".github/workflows/e2e.yml",
    "chars": 1232,
    "preview": "name: E2E Tests\non:\n  push:\n    branches: [\"main\"]\n\njobs:\n  tests:\n    name: \"E2E Tests\"\n    runs-on: ubuntu-24.04\n    d"
  },
  {
    "path": ".github/workflows/go-lint.yml",
    "chars": 1070,
    "preview": "name: golangci-lint\n\non:\n  pull_request:\n  push:\n    branches:\n      - main\n\nenv:\n  GO_VERSION: stable\n  GOLANGCI_LINT_V"
  },
  {
    "path": ".github/workflows/lint.yaml",
    "chars": 453,
    "preview": "name: Run lint checks\n\non:\n  pull_request:\n  push:\n    branches:\n      - main\n\njobs:\n  frontend_lint:\n    name: Frontend"
  },
  {
    "path": ".gitignore",
    "chars": 107,
    "preview": ".env\n.dev.env\ncerts/cert.pem\ncerts/key.pem\nfilerepo/*\n*/tmp\nagent/phatcrack-agent\nagent/phatcrack-agent.exe"
  },
  {
    "path": "Caddyfile",
    "chars": 813,
    "preview": "{$HOST_NAME} {\n    # This technically allows any caddy entry to be added here\n    # But we'll just use it for TLS\n    {$"
  },
  {
    "path": "Dockerfile.agent",
    "chars": 1164,
    "preview": "# This Dockerfile builds and serves the agent\nFROM golang:1.26 AS builder\n\n\nCOPY agent /app/agent\nCOPY common /app/commo"
  },
  {
    "path": "Dockerfile.api",
    "chars": 940,
    "preview": "# This Dockerfile is for building the API server\n\n# Builder\nFROM golang:1.26 AS builder\n\nWORKDIR /opt/\n\nRUN wget https:/"
  },
  {
    "path": "Dockerfile.frontend",
    "chars": 435,
    "preview": "# The Dockerfile builds and packages the frontend, and serves it with the Caddy web server.\n# Caddy also proxies to the "
  },
  {
    "path": "LICENSE",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 3427,
    "preview": "# Phatcrack\n\nPhatcrack is a modern solution for distributed hash cracking, designed for hackers and other information se"
  },
  {
    "path": "agent/.gitignore",
    "chars": 20,
    "preview": "config.json\nauth.key"
  },
  {
    "path": "agent/build.sh",
    "chars": 350,
    "preview": "#!/bin/bash\n\nVERSION_STR=$(git describe --tags)\n\necho \"Building version ${VERSION_STR}\"\n\nGOOS=${1:-linux}\nFILENAME=\"phat"
  },
  {
    "path": "agent/example_config.json",
    "chars": 261,
    "preview": "{\n    \"auth_key_file\": \"/opt/phatcrack-agent/auth-key\",\n    \"hashcat_binary\": \"/opt/hashcat/hashcat.bin\",\n    \"listfile_"
  },
  {
    "path": "agent/go.mod",
    "chars": 903,
    "preview": "module github.com/lachlan2k/phatcrack/agent\n\ngo 1.24.0\n\nreplace github.com/lachlan2k/phatcrack/common v0.0.0 => ../commo"
  },
  {
    "path": "agent/go.sum",
    "chars": 3630,
    "preview": "github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef4dfa h1:z8Lo9+R9h4ZF5qvq2NTrWGVjL8gE92cPUv9J4i4yYKg=\ngithub.com/N"
  },
  {
    "path": "agent/install.sh",
    "chars": 1725,
    "preview": "#!/bin/sh\n\nset -e\n\nif [ -z \"$PHATCRACK_HOST\" ]; then\n  echo \"PHATCRACK_HOST is not set. Exiting.\"\n  exit 1\nfi\n\nif [ -z \""
  },
  {
    "path": "agent/internal/config/config.go",
    "chars": 1180,
    "preview": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n\t\"strings\"\n\n\t\"log\"\n)\n\ntype Config struct {\n\tAuthKeyFile             stri"
  },
  {
    "path": "agent/internal/handler/file.go",
    "chars": 3234,
    "preview": "package handler\n\nimport (\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"log\"\n\n\t\"git"
  },
  {
    "path": "agent/internal/handler/handler.go",
    "chars": 4314,
    "preview": "package handler\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n\n\t\"log\"\n\t"
  },
  {
    "path": "agent/internal/handler/heartbeat.go",
    "chars": 1196,
    "preview": "package handler\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/lachlan2k/phatcrack/agent/internal/version\"\n\t\"github.com/lachlan2k"
  },
  {
    "path": "agent/internal/handler/job.go",
    "chars": 5005,
    "preview": "package handler\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"log\"\n\n\t\"github.com/lachlan2k/phatcrack/agent/internal/hashcat\"\n\t\"github.com/"
  },
  {
    "path": "agent/internal/handler/run.go",
    "chars": 237,
    "preview": "//go:build !windows\n\npackage handler\n\nimport \"github.com/lachlan2k/phatcrack/agent/internal/config\"\n\nfunc Run(conf *conf"
  },
  {
    "path": "agent/internal/handler/run_windows.go",
    "chars": 1920,
    "preview": "//go:build windows\n\npackage handler\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/lachlan2k/phatcrack/agent/internal/conf"
  },
  {
    "path": "agent/internal/hashcat/constants.go",
    "chars": 68,
    "preview": "//go:build !windows\n\npackage hashcat\n\nconst Hashcat = \"hashcat.bin\"\n"
  },
  {
    "path": "agent/internal/hashcat/constants_windows.go",
    "chars": 67,
    "preview": "//go:build windows\n\npackage hashcat\n\nconst Hashcat = \"hashcat.exe\"\n"
  },
  {
    "path": "agent/internal/hashcat/hashcat.go",
    "chars": 12078,
    "preview": "package hashcat\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"stri"
  },
  {
    "path": "agent/internal/installer/hashcat_install.go",
    "chars": 3204,
    "preview": "package installer\n\nimport (\n\t\"archive/tar\"\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"log\"\n\t\"net/url\"\n\t\"os\"\n\t\"path/filepat"
  },
  {
    "path": "agent/internal/installer/installer.go",
    "chars": 10905,
    "preview": "package installer\n\nimport (\n\t\"crypto/tls\"\n\t_ \"embed\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n"
  },
  {
    "path": "agent/internal/installer/register.go",
    "chars": 2034,
    "preview": "package installer\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/l"
  },
  {
    "path": "agent/internal/installer/template.service",
    "chars": 231,
    "preview": "[Unit]\nDescription=Phatcrack Agent\nAfter=network.target\n\n[Service]\nUser={{.AgentUser}}\nGroup={{.AgentGroup}}\nRestart=on-"
  },
  {
    "path": "agent/internal/installer/utils.go",
    "chars": 1594,
    "preview": "//go:build !windows\n\npackage installer\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/user\"\n\t\"strconv\"\n\t\"text/template\"\n)\n\nfunc isEl"
  },
  {
    "path": "agent/internal/installer/utils_windows.go",
    "chars": 1359,
    "preview": "//go:build windows\n\npackage installer\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org/x/sys/windows\"\n\t\"golang.org/x/sys/w"
  },
  {
    "path": "agent/internal/lockfile/lockfile.go",
    "chars": 3942,
    "preview": "package lockfile\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"log\"\n\n\t\"github.com/google/uuid"
  },
  {
    "path": "agent/internal/lockfile/lockfile_dummy.go",
    "chars": 257,
    "preview": "package lockfile\n\nimport \"time\"\n\ntype LockfileDummy struct{}\n\nfunc (l *LockfileDummy) AcquireWithTimeout(timeout time.Du"
  },
  {
    "path": "agent/internal/util/backoff.go",
    "chars": 692,
    "preview": "package util\n\nimport \"time\"\n\ntype BackoffEntry struct {\n\tAfterTime time.Duration\n\tTimeApart time.Duration\n}\n\ntype Backof"
  },
  {
    "path": "agent/internal/util/util.go",
    "chars": 166,
    "preview": "package util\n\nimport \"encoding/json\"\n\nfunc UnmarshalJSON[T interface{}](jsonBlob string) (out T, err error) {\n\terr = jso"
  },
  {
    "path": "agent/internal/version/version.go",
    "chars": 98,
    "preview": "package version\n\nvar version string = \"vx.x.x-unknown\"\n\nfunc Version() string {\n\treturn version\n}\n"
  },
  {
    "path": "agent/internal/wswrapper/wswrapper.go",
    "chars": 3376,
    "preview": "package wswrapper\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"lo"
  },
  {
    "path": "agent/main.go",
    "chars": 2008,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"log\"\n\n\t\"github.com/lachlan2k/phatcrack/agent/internal/config\"\n\t\"github.co"
  },
  {
    "path": "api/.air.toml",
    "chars": 246,
    "preview": "root = \".\"\ntmp_dir = \"/tmp/air/\"\n\n[build]\n  bin = \"/tmp/air/main\"\n  cmd = \"go build -buildvcs=false -ldflags=\\\"-X github"
  },
  {
    "path": "api/.dockerignore",
    "chars": 77,
    "preview": "Dockerfile\nDockerfile.dev\n.git\ndocker-compose.yml\ndocker-compose.dev.yml\ntmp/"
  },
  {
    "path": "api/Dockerfile.dev",
    "chars": 390,
    "preview": "FROM golang:1.26\n\nRUN apt-get update -y\nRUN apt-get upgrade -y\nRUN apt-get install -y p7zip-full\n\nWORKDIR /opt/\n\nRUN wge"
  },
  {
    "path": "api/build.sh",
    "chars": 227,
    "preview": "#!/bin/bash\n\nVERSION_STR=$(git describe --tags)\n\necho \"Building version ${VERSION_STR}\"\n\ngo build -buildvcs=false -ldfla"
  },
  {
    "path": "api/go.mod",
    "chars": 2130,
    "preview": "module github.com/lachlan2k/phatcrack/api\n\ngo 1.24.0\n\nrequire (\n\tgithub.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef"
  },
  {
    "path": "api/go.sum",
    "chars": 18830,
    "preview": "filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=\nfilippo.io/edwards25519 v1.1.0/go.mod h1:"
  },
  {
    "path": "api/internal/accesscontrol/accesscontrol.go",
    "chars": 1668,
    "preview": "package accesscontrol\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lachlan2k/phatcrack/api/internal/db\"\n\t\"github.com/lachlan2k/phatcra"
  },
  {
    "path": "api/internal/attacksharder/attacksharder.go",
    "chars": 8067,
    "preview": "package attacksharder\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/lachlan2k/phatcra"
  },
  {
    "path": "api/internal/auth/header_auth_middleware.go",
    "chars": 1537,
    "preview": "package auth\n\nimport (\n\t\"regexp\"\n\t\"slices\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal"
  },
  {
    "path": "api/internal/auth/mfa.go",
    "chars": 61,
    "preview": "package auth\n\nconst (\n\tMFATypeWebAuthn = \"MFATypeWebAuthn\"\n)\n"
  },
  {
    "path": "api/internal/auth/mfa_webauthn.go",
    "chars": 7051,
    "preview": "package auth\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n\n\t\"github.com/NHAS/we"
  },
  {
    "path": "api/internal/auth/middleware.go",
    "chars": 2475,
    "preview": "package auth\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/config\""
  },
  {
    "path": "api/internal/auth/session.go",
    "chars": 1831,
    "preview": "package auth\n\nimport (\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/NHAS/webauthn/webauthn\"\n\t\"github.com/labstack/ech"
  },
  {
    "path": "api/internal/auth/session_inmemory.go",
    "chars": 4871,
    "preview": "package auth\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/labstack/echo/v4\""
  },
  {
    "path": "api/internal/config/config.go",
    "chars": 6234,
    "preview": "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com/lachlan2k/phatcrack/api/internal/db\"\n\t\"github.com/lachla"
  },
  {
    "path": "api/internal/config/config_migration.go",
    "chars": 2494,
    "preview": "package config\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\ntype v1runtimeConfig struct {\n\tIs"
  },
  {
    "path": "api/internal/controllers/account.go",
    "chars": 1716,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/"
  },
  {
    "path": "api/internal/controllers/admin.go",
    "chars": 13426,
    "preview": "package controllers\n\nimport (\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"crypto/rand\"\n\n\tlo"
  },
  {
    "path": "api/internal/controllers/agent.go",
    "chars": 749,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/"
  },
  {
    "path": "api/internal/controllers/agent_handler.go",
    "chars": 3496,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/gor"
  },
  {
    "path": "api/internal/controllers/attack.go",
    "chars": 14998,
    "preview": "package controllers\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.co"
  },
  {
    "path": "api/internal/controllers/attack_template.go",
    "chars": 5488,
    "preview": "package controllers\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api"
  },
  {
    "path": "api/internal/controllers/attackjob.go",
    "chars": 3544,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/"
  },
  {
    "path": "api/internal/controllers/auth.go",
    "chars": 9873,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\t\"slices\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/labstack/echo/v4\"\n\t"
  },
  {
    "path": "api/internal/controllers/auth_credentials.go",
    "chars": 2956,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/i"
  },
  {
    "path": "api/internal/controllers/auth_oidc.go",
    "chars": 7986,
    "preview": "package controllers\n\nimport (\n\t\"context\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"slices\""
  },
  {
    "path": "api/internal/controllers/config.go",
    "chars": 289,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/"
  },
  {
    "path": "api/internal/controllers/controllers.go",
    "chars": 531,
    "preview": "package controllers\n\nimport (\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/auth\"\n\tlog \"g"
  },
  {
    "path": "api/internal/controllers/e2e.go",
    "chars": 865,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/"
  },
  {
    "path": "api/internal/controllers/hashcat.go",
    "chars": 2122,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/"
  },
  {
    "path": "api/internal/controllers/hashlist.go",
    "chars": 8107,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/lab"
  },
  {
    "path": "api/internal/controllers/listfiles.go",
    "chars": 2984,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.co"
  },
  {
    "path": "api/internal/controllers/listfiles_upload.go",
    "chars": 7288,
    "preview": "package controllers\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime/multipart\"\n\t\"net/http\"\n\t\"os\"\n\t\"slices\"\n\t\"strconv\"\n\t"
  },
  {
    "path": "api/internal/controllers/potfile.go",
    "chars": 971,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/"
  },
  {
    "path": "api/internal/controllers/project.go",
    "chars": 8461,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\t\"slices\"\n\n\t\"github.com/google/uuid\"\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"gith"
  },
  {
    "path": "api/internal/controllers/users.go",
    "chars": 659,
    "preview": "package controllers\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/"
  },
  {
    "path": "api/internal/db/agent.go",
    "chars": 6528,
    "preview": "package db\n\nimport (\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/util\"\n\t"
  },
  {
    "path": "api/internal/db/attack_template.go",
    "chars": 2422,
    "preview": "package db\n\nimport (\n\t\"github.com/google/uuid\"\n\t\"github.com/lachlan2k/phatcrack/common/pkg/apitypes\"\n\t\"github.com/lachla"
  },
  {
    "path": "api/internal/db/config.go",
    "chars": 1678,
    "preview": "package db\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/lachlan2k/phatcrack/api/internal/util\"\n\t\"gorm.io/datatypes\"\n)"
  },
  {
    "path": "api/internal/db/db.go",
    "chars": 4105,
    "preview": "package db\n\nimport (\n\t\"database/sql/driver\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/lachlan2"
  },
  {
    "path": "api/internal/db/job.go",
    "chars": 14557,
    "preview": "package db\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/lachlan2k/phatcrack/api/internal/roles\"\n\t"
  },
  {
    "path": "api/internal/db/keyspace_cache.go",
    "chars": 544,
    "preview": "package db\n\ntype KeyspaceCache struct {\n\tSimpleBaseModel\n\n\tSettingsHash string `gorm:\"index\"`\n\tKeyspace int64\n}\n\nfunc Ge"
  },
  {
    "path": "api/internal/db/listfiles.go",
    "chars": 3499,
    "preview": "package db\n\nimport (\n\t\"github.com/google/uuid\"\n\t\"github.com/lachlan2k/phatcrack/common/pkg/apitypes\"\n)\n\nconst (\n\tListfil"
  },
  {
    "path": "api/internal/db/potfile.go",
    "chars": 2170,
    "preview": "package db\n\nimport (\n\t\"errors\"\n\n\t\"github.com/lachlan2k/phatcrack/common/pkg/apitypes\"\n\t\"gorm.io/gorm\"\n)\n\ntype PotfileEnt"
  },
  {
    "path": "api/internal/db/project.go",
    "chars": 11759,
    "preview": "package db\n\nimport (\n\t\"strconv\"\n\n\t\"github.com/google/uuid\"\n\t\"gorm.io/datatypes\"\n\t\"gorm.io/gorm\"\n\n\t\"github.com/lachlan2k/"
  },
  {
    "path": "api/internal/db/user.go",
    "chars": 3538,
    "preview": "package db\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"github.com/lachlan2k/phatcrack/api/internal/util\"\n\t\"github.com/lachlan2k/ph"
  },
  {
    "path": "api/internal/filerepo/filerepo.go",
    "chars": 1422,
    "preview": "package filerepo\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/google/uuid\"\n)\n\nvar basePath string\n\nfunc S"
  },
  {
    "path": "api/internal/fleet/agent.go",
    "chars": 5748,
    "preview": "package fleet\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\n\t\"github.c"
  },
  {
    "path": "api/internal/fleet/fleet.go",
    "chars": 4019,
    "preview": "package fleet\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/gorilla/websocket\"\n\t\"github.com"
  },
  {
    "path": "api/internal/fleet/handle_jobs_events.go",
    "chars": 3021,
    "preview": "package fleet\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/lachlan2k/phatcrack/api/internal/db\"\n\t\"github.com/lachlan2k/phatcrack/api/i"
  },
  {
    "path": "api/internal/fleet/state_reconcilition.go",
    "chars": 14621,
    "preview": "package fleet\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"time\"\n\n\tlog \"github.com/sirupsen/logrus\"\n\t\"gorm.io/datatypes"
  },
  {
    "path": "api/internal/hashcathelpers/hashcathelpers.go",
    "chars": 7121,
    "preview": "package hashcathelpers\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com"
  },
  {
    "path": "api/internal/resources/gen_hash_info.sh",
    "chars": 75,
    "preview": "#!bin/bash\n\nhashcat --hash-info --machine-readable --quiet > hash_info.json"
  },
  {
    "path": "api/internal/resources/hash_info.json",
    "chars": 3271465,
    "preview": "{ \"0\": { \"name\": \"MD5\", \"category\": \"Raw Hash\", \"slow_hash\": false, \"password_len_min\": 0, \"password_len_max\": 256, \"is_"
  },
  {
    "path": "api/internal/resources/resources.go",
    "chars": 508,
    "preview": "package resources\n\nimport (\n\t_ \"embed\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes"
  },
  {
    "path": "api/internal/roles/roles.go",
    "chars": 688,
    "preview": "package roles\n\nconst UserRoleAdmin = \"admin\"\nconst UserRoleStandard = \"standard\"\nconst UserRoleServiceAccount = \"service"
  },
  {
    "path": "api/internal/util/password_strength.go",
    "chars": 196,
    "preview": "package util\n\nfunc ValidatePasswordStrength(password string) (ok bool, feedback string) {\n\tif len(password) < 16 {\n\t\tret"
  },
  {
    "path": "api/internal/util/request_validator.go",
    "chars": 2737,
    "preview": "package util\n\nimport (\n\t\"net/http\"\n\t\"regexp\"\n\n\tenglish \"github.com/go-playground/locales/en\"\n\tut \"github.com/go-playgrou"
  },
  {
    "path": "api/internal/util/util.go",
    "chars": 2817,
    "preview": "package util\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"path\"\n\t\"str"
  },
  {
    "path": "api/internal/version/version.go",
    "chars": 98,
    "preview": "package version\n\nvar version string = \"vx.x.x-unknown\"\n\nfunc Version() string {\n\treturn version\n}\n"
  },
  {
    "path": "api/internal/webserver/logger.go",
    "chars": 2018,
    "preview": "package webserver\n\nimport (\n\t\"errors\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/labstack/echo/v4/middleware\"\n\t\"github"
  },
  {
    "path": "api/internal/webserver/webserver.go",
    "chars": 3551,
    "preview": "package webserver\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/labstack/echo/v4\"\n\t\"github.com/labstack/e"
  },
  {
    "path": "api/main.go",
    "chars": 2268,
    "preview": "package main\n\nimport (\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/lachlan2k/phatcrack/api/internal/auth\"\n\t\"github.com/lac"
  },
  {
    "path": "common/go.mod",
    "chars": 547,
    "preview": "module github.com/lachlan2k/phatcrack/common\n\ngo 1.24.0\n\nrequire github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef"
  },
  {
    "path": "common/go.sum",
    "chars": 3229,
    "preview": "github.com/NHAS/webauthn v0.0.0-20240606085832-ea3172ef4dfa h1:z8Lo9+R9h4ZF5qvq2NTrWGVjL8gE92cPUv9J4i4yYKg=\ngithub.com/N"
  },
  {
    "path": "common/pkg/apitypes/account.go",
    "chars": 217,
    "preview": "package apitypes\n\ntype AccountChangePasswordRequestDTO struct {\n\tNewPassword     string `json:\"new_password\" validate:\"r"
  },
  {
    "path": "common/pkg/apitypes/admin.go",
    "chars": 2873,
    "preview": "package apitypes\n\ntype AdminAgentCreateRequestDTO struct {\n\tName      string `json:\"name\" validate:\"required,min=4,max=6"
  },
  {
    "path": "common/pkg/apitypes/admin_config.go",
    "chars": 1614,
    "preview": "package apitypes\n\ntype AuthOIDCConfigDTO struct {\n\tClientID     string `json:\"client_id\"`\n\tClientSecret string `json:\"cl"
  },
  {
    "path": "common/pkg/apitypes/agent.go",
    "chars": 978,
    "preview": "package apitypes\n\nimport \"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes\"\n\ntype AgentDTO struct {\n\tID           "
  },
  {
    "path": "common/pkg/apitypes/agent_handler.go",
    "chars": 223,
    "preview": "package apitypes\n\ntype AgentRegisterRequestDTO struct {\n\tName string `json:\"name\" validate:\"max=64\"`\n}\n\ntype AgentRegist"
  },
  {
    "path": "common/pkg/apitypes/apitypes.go",
    "chars": 17,
    "preview": "package apitypes\n"
  },
  {
    "path": "common/pkg/apitypes/attack.go",
    "chars": 1321,
    "preview": "package apitypes\n\nimport \"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes\"\n\ntype AttackDTO struct {\n\tID          "
  },
  {
    "path": "common/pkg/apitypes/attack_template.go",
    "chars": 1405,
    "preview": "package apitypes\n\nimport (\n\t\"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes\"\n)\n\nconst AttackTemplateType = \"atta"
  },
  {
    "path": "common/pkg/apitypes/auth.go",
    "chars": 1753,
    "preview": "package apitypes\n\nimport \"github.com/NHAS/webauthn/protocol\"\n\ntype AuthLoginRequestDTO struct {\n\tUsername string `json:\""
  },
  {
    "path": "common/pkg/apitypes/config.go",
    "chars": 629,
    "preview": "package apitypes\n\ntype PublicOIDCConfigDTO struct {\n\tPrompt string `json:\"prompt\"`\n}\n\ntype PublicAuthConfigDTO struct {\n"
  },
  {
    "path": "common/pkg/apitypes/hashcat.go",
    "chars": 902,
    "preview": "package apitypes\n\nimport \"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes\"\n\ntype HashTypesDTO struct {\n\tHashTypes"
  },
  {
    "path": "common/pkg/apitypes/hashlist.go",
    "chars": 1708,
    "preview": "package apitypes\n\ntype HashlistCreateRequestDTO struct {\n\tProjectID    string   `json:\"project_id\" validate:\"required,uu"
  },
  {
    "path": "common/pkg/apitypes/job.go",
    "chars": 3148,
    "preview": "package apitypes\n\nimport (\n\t\"time\"\n\n\t\"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes\"\n)\n\ntype JobCreateRequestDT"
  },
  {
    "path": "common/pkg/apitypes/listfiles.go",
    "chars": 796,
    "preview": "package apitypes\n\ntype ListfileDTO struct {\n\tID                string `json:\"id\"`\n\tFileType          string `json:\"file_"
  },
  {
    "path": "common/pkg/apitypes/potfile.go",
    "chars": 379,
    "preview": "package apitypes\n\ntype PotfileSearchRequestDTO struct {\n\tHashes []string `json:\"hashes\"`\n}\n\ntype PotfileSearchResultDTO "
  },
  {
    "path": "common/pkg/apitypes/project.go",
    "chars": 729,
    "preview": "package apitypes\n\ntype ProjectCreateRequestDTO struct {\n\tName        string `json:\"name\" validate:\"required,standardname"
  },
  {
    "path": "common/pkg/apitypes/user.go",
    "chars": 684,
    "preview": "package apitypes\n\ntype UserDTO struct {\n\tID       string   `json:\"id\"`\n\tUsername string   `json:\"username\"`\n\tRoles    []"
  },
  {
    "path": "common/pkg/hashcattypes/attackmode.go",
    "chars": 162,
    "preview": "package hashcattypes\n\nconst (\n\tAttackModeDictionary = 0\n\tAttackModeCombinator = 1\n\tAttackModeMask       = 3\n\tAttackModeH"
  },
  {
    "path": "common/pkg/hashcattypes/hashcattypes.go",
    "chars": 2565,
    "preview": "package hashcattypes\n\nimport \"time\"\n\ntype HashcatParams struct {\n\tAttackMode uint8 `json:\"attack_mode\"`\n\tHashType   uint"
  },
  {
    "path": "common/pkg/hashcattypes/hashinfo.go",
    "chars": 999,
    "preview": "package hashcattypes\n\ntype HashType struct {\n\tID                int      `json:\"id\"`\n\tName              string   `json:\""
  },
  {
    "path": "common/pkg/wstypes/job.go",
    "chars": 1833,
    "preview": "package wstypes\n\nimport (\n\t\"time\"\n\n\t\"github.com/lachlan2k/phatcrack/common/pkg/hashcattypes\"\n)\n\nconst (\n\t// server -> ag"
  },
  {
    "path": "common/pkg/wstypes/wstypes.go",
    "chars": 920,
    "preview": "package wstypes\n\ntype Message struct {\n\tType    string `json:\"type\"`\n\tPayload string `json:\"payload\"` // json blob\n}\n\nco"
  },
  {
    "path": "docker-compose.dev.yml",
    "chars": 1066,
    "preview": "version: '3'\n\nservices:\n  webserver:\n    build:\n      context: ./frontend\n      dockerfile: Dockerfile.dev\n    restart: "
  },
  {
    "path": "docker-compose.prod.yml",
    "chars": 1323,
    "preview": "services:\n  frontend:\n    image: ghcr.io/lachlan2k/phatcrack/frontend:${PHATCRACK_VERSION_TAG:-latest}\n    restart: unle"
  },
  {
    "path": "e2e/api/.gitignore",
    "chars": 21,
    "preview": "node_modules\ncoverage"
  },
  {
    "path": "e2e/api/.prettierrc.json",
    "chars": 189,
    "preview": "{\n  \"$schema\": \"https://json.schemastore.org/prettierrc\",\n  \"semi\": false,\n  \"tabWidth\": 2,\n  \"singleQuote\": true,\n  \"pr"
  },
  {
    "path": "e2e/api/jest.config.js",
    "chars": 381,
    "preview": "/** @type {import('ts-jest').JestConfigWithTsJest} **/\nmodule.exports = {\n  testEnvironment: 'node',\n  transform: {\n    "
  },
  {
    "path": "e2e/api/package.json",
    "chars": 607,
    "preview": "{\n  \"name\": \"api\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"jest\",\n "
  },
  {
    "path": "e2e/api/tests/_api.spec.ts",
    "chars": 723,
    "preview": "import * as api from '../../../frontend/src/api'\nimport { dummyApiRequests } from './dummyRequests'\nimport {\n  beforeAll"
  },
  {
    "path": "e2e/api/tests/_helpers.ts",
    "chars": 1824,
    "preview": "import axios, { AxiosError } from 'axios'\nimport * as tough from 'tough-cookie'\nimport { HttpsCookieAgent } from 'http-c"
  },
  {
    "path": "e2e/api/tests/admin_authz.ts",
    "chars": 696,
    "preview": "import * as api from '../../../frontend/src/api'\nimport {\n  beforeAllSetupClientWithCookieJar,\n  beforeAllSetupClientWit"
  },
  {
    "path": "e2e/api/tests/dummyRequests.ts",
    "chars": 3283,
    "preview": "import * as api from '../../../frontend/src/api'\n\nconst t = (name: string, run: any) => ({ name, run })\n\nexport const du"
  },
  {
    "path": "e2e/api/tests/hashlists.ts",
    "chars": 12536,
    "preview": "import * as api from '../../../frontend/src/api'\nimport { dummyApiRequests } from './dummyRequests'\nimport {\n  beforeAll"
  },
  {
    "path": "e2e/api/tests/projects.ts",
    "chars": 2898,
    "preview": "import * as api from '../../../frontend/src/api'\nimport {\n  beforeAllSetupClientWithCookieJar,\n  beforeAllSetupClientWit"
  },
  {
    "path": "e2e/api/tests/setup.ts",
    "chars": 2788,
    "preview": "import * as api from '../../../frontend/src/api'\nimport {\n  beforeAllSetupClientWithCookieJar,\n  beforeAllSetupClientWit"
  },
  {
    "path": "e2e/api/tests/unauth.ts",
    "chars": 892,
    "preview": "import * as api from '../../../frontend/src/api'\nimport {\n  beforeAllSetupClientWithCookieJar,\n  beforeAllSetupClientWit"
  },
  {
    "path": "e2e/api/tests/user_provisioning_auth.ts",
    "chars": 9406,
    "preview": "import * as api from '../../../frontend/src/api'\nimport {\n  beforeAllSetupClientWithCookieJar,\n  beforeAllSetupClientWit"
  },
  {
    "path": "e2e/api/tsconfig.json",
    "chars": 12203,
    "preview": "{\n  \"compilerOptions\": {\n    /* Visit https://aka.ms/tsconfig to read more about this file */\n\n    /* Projects */\n    //"
  },
  {
    "path": "e2e/browser/.gitignore",
    "chars": 100,
    "preview": "node_modules\n/test-results/\n/playwright-report/\n/blob-report/\n/playwright/.cache/\n/playwright/.auth\n"
  },
  {
    "path": "e2e/browser/package.json",
    "chars": 248,
    "preview": "{\n  \"name\": \"e2e\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {},\n  \"keywords\": [],\n "
  },
  {
    "path": "e2e/browser/playwright.config.ts",
    "chars": 985,
    "preview": "import { defineConfig, devices } from '@playwright/test';\n\n/**\n * Read environment variables from file.\n * https://githu"
  },
  {
    "path": "e2e/browser/tests/adduser.spec.ts",
    "chars": 6336,
    "preview": "import { test, expect } from '@playwright/test';\nimport { credsMap, getAuthFilePath } from './auth.config';\n\nconst admin"
  },
  {
    "path": "e2e/browser/tests/auth.config.ts",
    "chars": 592,
    "preview": "export const credsMap = {\n    default: {\n        username: 'admin',\n        password: 'changeme'\n    },\n\n    admin: {\n  "
  },
  {
    "path": "e2e/browser/tests/auth.setup.ts",
    "chars": 691,
    "preview": "import { test as setup, expect } from '@playwright/test';\nimport { credsMap, getAuthFilePath } from './auth.config';\n\nas"
  },
  {
    "path": "e2e/browser/tests/initial.setup.ts",
    "chars": 1490,
    "preview": "import { test as setup, expect } from '@playwright/test'\nimport { credsMap } from './auth.config'\n\nconst defaultCreds = "
  },
  {
    "path": "e2e/docker-compose.test.yml",
    "chars": 1075,
    "preview": "services:\n  webserver:\n    build:\n      context: ../\n      dockerfile: Dockerfile.frontend\n    restart: unless-stopped\n "
  },
  {
    "path": "frontend/.gitignore",
    "chars": 302,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\n.DS_Stor"
  },
  {
    "path": "frontend/.prettierrc.json",
    "chars": 189,
    "preview": "{\n  \"$schema\": \"https://json.schemastore.org/prettierrc\",\n  \"semi\": false,\n  \"tabWidth\": 2,\n  \"singleQuote\": true,\n  \"pr"
  },
  {
    "path": "frontend/.vscode/extensions.json",
    "chars": 75,
    "preview": "{\n  \"recommendations\": [\"Vue.volar\", \"Vue.vscode-typescript-vue-plugin\"]\n}\n"
  },
  {
    "path": "frontend/Dockerfile.dev",
    "chars": 127,
    "preview": "FROM node:lts\n\nWORKDIR /app\n\nENV HOST 0.0.0.0\nENV PORT 3000\nENV NODE_ENV development\n\nCMD [ \"npm\", \"run\", \"docker-dev-en"
  },
  {
    "path": "frontend/README.md",
    "chars": 1679,
    "preview": "# frontend\n\nThis template should help get you started developing with Vue 3 in Vite.\n\n## Recommended IDE Setup\n\n[VSCode]"
  },
  {
    "path": "frontend/env.d.ts",
    "chars": 38,
    "preview": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "frontend/eslint.config.ts",
    "chars": 2171,
    "preview": "import { globalIgnores } from 'eslint/config'\nimport { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-ty"
  },
  {
    "path": "frontend/index.html",
    "chars": 332,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\">\n    <link rel=\"icon\" href=\"/favicon.ico\">\n    <meta"
  },
  {
    "path": "frontend/package.json",
    "chars": 1685,
    "preview": "{\n  \"name\": \"frontend\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"run-p t"
  },
  {
    "path": "frontend/postcss.config.js",
    "chars": 82,
    "preview": "module.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n"
  },
  {
    "path": "frontend/src/App.vue",
    "chars": 3486,
    "preview": "<script setup lang=\"ts\">\nimport { storeToRefs } from 'pinia'\nimport { useToast } from 'vue-toastification'\nimport { onBe"
  },
  {
    "path": "frontend/src/api/account.ts",
    "chars": 273,
    "preview": "import type { AccountChangePasswordRequestDTO } from './types'\n\nimport { client } from '.'\n\nexport function accountChang"
  },
  {
    "path": "frontend/src/api/admin.ts",
    "chars": 3519,
    "preview": "import type {\n  AdminAgentCreateRequestDTO,\n  AdminAgentCreateResponseDTO,\n  AdminAgentRegistrationKeyCreateRequestDTO,\n"
  },
  {
    "path": "frontend/src/api/agent.ts",
    "chars": 214,
    "preview": "import type { AgentGetAllResponseDTO } from './types'\n\nimport { client } from '.'\n\nexport function getAllAgents(): Promi"
  },
  {
    "path": "frontend/src/api/attackTemplate.ts",
    "chars": 1267,
    "preview": "import type {\n  AttackTemplateCreateRequestDTO,\n  AttackTemplateCreateSetRequestDTO,\n  AttackTemplateDTO,\n  AttackTempla"
  },
  {
    "path": "frontend/src/api/auth.ts",
    "chars": 2898,
    "preview": "import type {\n  AuthLoginResponseDTO,\n  AuthWhoamiResponseDTO,\n  AuthChangePasswordRequestDTO,\n  AuthWebAuthnStartEnroll"
  },
  {
    "path": "frontend/src/api/config.ts",
    "chars": 311,
    "preview": "import type { PublicConfigDTO } from './types'\n\nimport { client } from '.'\n\nexport const AuthMethodCredentials = 'method"
  },
  {
    "path": "frontend/src/api/hashcat.ts",
    "chars": 798,
    "preview": "import type { DetectHashTypeRequestDTO, DetectHashTypeResponseDTO, HashTypesDTO } from './types'\n\nimport { client } from"
  },
  {
    "path": "frontend/src/api/index.ts",
    "chars": 727,
    "preview": "import axios, { type AxiosInstance } from 'axios'\n\nexport let client = axios.create()\n\nexport function setClient(newClie"
  },
  {
    "path": "frontend/src/api/listfiles.ts",
    "chars": 1063,
    "preview": "import type { AxiosProgressEvent } from 'axios'\n\nimport type { GetAllListfilesDTO, ListfileDTO } from './types'\n\nimport "
  },
  {
    "path": "frontend/src/api/potfile.ts",
    "chars": 273,
    "preview": "import type { PotfileSearchResponseDTO } from './types'\n\nimport { client } from '.'\n\nexport function searchPotfile(hashe"
  },
  {
    "path": "frontend/src/api/project.ts",
    "chars": 5067,
    "preview": "import type {\n  AttackDTO,\n  AttackIDTreeMultipleDTO,\n  AttackMultipleDTO,\n  AttackStartResponseDTO,\n  AttackWithJobsMul"
  },
  {
    "path": "frontend/src/api/types.ts",
    "chars": 13636,
    "preview": "/* Do not change, this code is generated from Golang structs */\n\nexport interface AccountChangePasswordRequestDTO {\n  ne"
  },
  {
    "path": "frontend/src/api/users.ts",
    "chars": 660,
    "preview": "import type { UsersGetAllResponseDTO } from './types'\n\nimport { client } from '.'\n\nexport enum UserRole {\n  Standard = '"
  },
  {
    "path": "frontend/src/components/Admin/AgentConfig.vue",
    "chars": 2154,
    "preview": "<script setup lang=\"ts\">\nimport { reactive, watch } from 'vue'\nimport { useToast } from 'vue-toastification'\nimport { st"
  },
  {
    "path": "frontend/src/components/Admin/AuthConfig.vue",
    "chars": 10513,
    "preview": "<script setup lang=\"ts\">\nimport { computed, reactive, watch } from 'vue'\nimport { useToast } from 'vue-toastification'\ni"
  },
  {
    "path": "frontend/src/components/Admin/GeneralConfig.vue",
    "chars": 2864,
    "preview": "<script setup lang=\"ts\">\nimport { reactive, watch } from 'vue'\nimport { useToast } from 'vue-toastification'\nimport { st"
  },
  {
    "path": "frontend/src/components/Admin/UsersTable.vue",
    "chars": 13562,
    "preview": "<script setup lang=\"ts\">\nimport { useToast } from 'vue-toastification'\nimport { ref, computed, watch, reactive } from 'v"
  },
  {
    "path": "frontend/src/components/AttackConfigDetails.vue",
    "chars": 2004,
    "preview": "<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\nimport type { HashcatParams } from '@/api/types'\n\nimport { useL"
  },
  {
    "path": "frontend/src/components/AttackDetailsModal/Overview.vue",
    "chars": 6573,
    "preview": "<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { useToast } from 'vue-toastification'\n\nimport TimeSinceD"
  },
  {
    "path": "frontend/src/components/AttackDetailsModal/index.vue",
    "chars": 3873,
    "preview": "<script setup lang=\"ts\">\nimport { computed, ref } from 'vue'\n\nimport Overview from '@/components/AttackDetailsModal/Over"
  },
  {
    "path": "frontend/src/components/AttackTemplateCreator.vue",
    "chars": 2119,
    "preview": "<script setup lang=\"ts\">\nimport { computed, ref } from 'vue'\nimport { useToast } from 'vue-toastification'\n\nimport Attac"
  },
  {
    "path": "frontend/src/components/AttackTemplateEditor.vue",
    "chars": 2645,
    "preview": "<script setup lang=\"ts\">\nimport { computed, ref, watch } from 'vue'\nimport { useToast } from 'vue-toastification'\n\nimpor"
  },
  {
    "path": "frontend/src/components/AttackTemplateSetCreator.vue",
    "chars": 3022,
    "preview": "<script setup lang=\"ts\">\nimport { storeToRefs } from 'pinia'\nimport { computed, ref } from 'vue'\nimport { useToast } fro"
  },
  {
    "path": "frontend/src/components/AttackTemplateSetEditor.vue",
    "chars": 3391,
    "preview": "<script setup lang=\"ts\">\nimport { storeToRefs } from 'pinia'\nimport { computed, ref, watch } from 'vue'\nimport { useToas"
  },
  {
    "path": "frontend/src/components/CheckboxSet.vue",
    "chars": 929,
    "preview": "<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\nconst props = defineProps<{\n  modelValue: {\n    [key: string]: "
  },
  {
    "path": "frontend/src/components/ConfirmModal.vue",
    "chars": 1478,
    "preview": "<script setup lang=\"ts\">\nimport { ref } from 'vue'\n\nconst props = defineProps<{\n  title?: string\n  body?: string\n}>()\n\nc"
  },
  {
    "path": "frontend/src/components/EmptyTable.vue",
    "chars": 325,
    "preview": "<script setup lang=\"ts\">\nconst props = defineProps<{\n  text: string\n  icon?: string\n}>()\n</script>\n\n<template>\n  <div cl"
  },
  {
    "path": "frontend/src/components/FileUpload.vue",
    "chars": 6099,
    "preview": "<script setup lang=\"ts\">\nimport { ref, computed, watch } from 'vue'\nimport { useToast } from 'vue-toastification'\nimport"
  },
  {
    "path": "frontend/src/components/HashesInput.vue",
    "chars": 891,
    "preview": "<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\nconst props = defineProps<{\n  rows?: number\n  modelValue: strin"
  },
  {
    "path": "frontend/src/components/HrOr.vue",
    "chars": 181,
    "preview": "<template>\n  <div class=\"flex w-full items-center\">\n    <hr class=\"grow\" />\n    <span class=\"mx-2 pb-1 italic text-slate"
  },
  {
    "path": "frontend/src/components/IconButton.vue",
    "chars": 391,
    "preview": "<script setup lang=\"ts\">\nconst props = defineProps<{\n  color: string\n  icon: string\n  tooltip: string\n}>()\n\nconst hoverC"
  },
  {
    "path": "frontend/src/components/InfoTip.vue",
    "chars": 542,
    "preview": "<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\nimport { Icons } from '@/util/icons'\n\nexport type PlacementT = "
  },
  {
    "path": "frontend/src/components/Modal.vue",
    "chars": 995,
    "preview": "<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\nconst props = defineProps<{\n  isOpen: boolean\n}>()\n\nconst emit "
  },
  {
    "path": "frontend/src/components/PageLoading.vue",
    "chars": 143,
    "preview": "<template>\n  <div class=\"flex h-full w-full justify-center\">\n    <span class=\"loading loading-spinner loading-lg\"></span"
  },
  {
    "path": "frontend/src/components/PaginationControls.vue",
    "chars": 582,
    "preview": "<script setup lang=\"ts\">\nconst props = defineProps<{\n  currentPage: number\n  totalPages?: number\n}>()\n\nconst emit = defi"
  }
]

// ... and 64 more files (download for full content)

About this extraction

This page contains the full source code of the lachlan2k/phatcrack GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 264 files (3.8 MB), approximately 1.0M tokens, and a symbol index with 938 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!